repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
trustar/trustar-python | trustar/utils.py | normalize_timestamp | def normalize_timestamp(date_time):
"""
TODO: get rid of this function and all references to it / uses of it.
Attempt to convert a string timestamp in to a TruSTAR compatible format for submission.
Will return current time with UTC time zone if None
:param date_time: int that is seconds or milliseco... | python | def normalize_timestamp(date_time):
"""
TODO: get rid of this function and all references to it / uses of it.
Attempt to convert a string timestamp in to a TruSTAR compatible format for submission.
Will return current time with UTC time zone if None
:param date_time: int that is seconds or milliseco... | [
"def",
"normalize_timestamp",
"(",
"date_time",
")",
":",
"# if timestamp is null, just return the same null. ",
"if",
"not",
"date_time",
":",
"return",
"date_time",
"datetime_dt",
"=",
"datetime",
".",
"now",
"(",
")",
"# get current time in seconds-since-epoch",
"current... | TODO: get rid of this function and all references to it / uses of it.
Attempt to convert a string timestamp in to a TruSTAR compatible format for submission.
Will return current time with UTC time zone if None
:param date_time: int that is seconds or milliseconds since epoch, or string/datetime object conta... | [
"TODO",
":",
"get",
"rid",
"of",
"this",
"function",
"and",
"all",
"references",
"to",
"it",
"/",
"uses",
"of",
"it",
".",
"Attempt",
"to",
"convert",
"a",
"string",
"timestamp",
"in",
"to",
"a",
"TruSTAR",
"compatible",
"format",
"for",
"submission",
".... | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/utils.py#L17-L70 |
trustar/trustar-python | trustar/utils.py | parse_boolean | def parse_boolean(value):
"""
Coerce a value to boolean.
:param value: the value, could be a string, boolean, or None
:return: the value as coerced to a boolean
"""
if value is None:
return None
if isinstance(value, bool):
return value
if isinstance(value, string_type... | python | def parse_boolean(value):
"""
Coerce a value to boolean.
:param value: the value, could be a string, boolean, or None
:return: the value as coerced to a boolean
"""
if value is None:
return None
if isinstance(value, bool):
return value
if isinstance(value, string_type... | [
"def",
"parse_boolean",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=... | Coerce a value to boolean.
:param value: the value, could be a string, boolean, or None
:return: the value as coerced to a boolean | [
"Coerce",
"a",
"value",
"to",
"boolean",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/utils.py#L117-L138 |
trustar/trustar-python | trustar/trustar.py | TruStar.config_from_file | def config_from_file(config_file_path, config_role):
"""
Create a configuration dictionary from a config file section. This dictionary is what the TruStar
class constructor ultimately requires.
:param config_file_path: The path to the config file.
:param config_role: The sectio... | python | def config_from_file(config_file_path, config_role):
"""
Create a configuration dictionary from a config file section. This dictionary is what the TruStar
class constructor ultimately requires.
:param config_file_path: The path to the config file.
:param config_role: The sectio... | [
"def",
"config_from_file",
"(",
"config_file_path",
",",
"config_role",
")",
":",
"# read config file depending on filetype, parse into dictionary",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"config_file_path",
")",
"[",
"-",
"1",
"]",
"if",
"ext",
"in",
... | Create a configuration dictionary from a config file section. This dictionary is what the TruStar
class constructor ultimately requires.
:param config_file_path: The path to the config file.
:param config_role: The section within the file to use.
:return: The configuration dictionary. | [
"Create",
"a",
"configuration",
"dictionary",
"from",
"a",
"config",
"file",
"section",
".",
"This",
"dictionary",
"is",
"what",
"the",
"TruStar",
"class",
"constructor",
"ultimately",
"requires",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/trustar.py#L213-L257 |
trustar/trustar-python | trustar/trustar.py | TruStar.get_version | def get_version(self):
"""
Get the version number of the API.
Example:
>>> ts.get_version()
1.3
"""
result = self._client.get("version").content
if isinstance(result, bytes):
result = result.decode('utf-8')
return result.strip('\n'... | python | def get_version(self):
"""
Get the version number of the API.
Example:
>>> ts.get_version()
1.3
"""
result = self._client.get("version").content
if isinstance(result, bytes):
result = result.decode('utf-8')
return result.strip('\n'... | [
"def",
"get_version",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"version\"",
")",
".",
"content",
"if",
"isinstance",
"(",
"result",
",",
"bytes",
")",
":",
"result",
"=",
"result",
".",
"decode",
"(",
"'utf-8'",
... | Get the version number of the API.
Example:
>>> ts.get_version()
1.3 | [
"Get",
"the",
"version",
"number",
"of",
"the",
"API",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/trustar.py#L284-L299 |
trustar/trustar-python | trustar/trustar.py | TruStar.get_user_enclaves | def get_user_enclaves(self):
"""
Gets the list of enclaves that the user has access to.
:return: A list of |EnclavePermissions| objects, each representing an enclave and whether the requesting user
has read, create, and update access to it.
"""
resp = self._client.g... | python | def get_user_enclaves(self):
"""
Gets the list of enclaves that the user has access to.
:return: A list of |EnclavePermissions| objects, each representing an enclave and whether the requesting user
has read, create, and update access to it.
"""
resp = self._client.g... | [
"def",
"get_user_enclaves",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"enclaves\"",
")",
"return",
"[",
"EnclavePermissions",
".",
"from_dict",
"(",
"enclave",
")",
"for",
"enclave",
"in",
"resp",
".",
"json",
"(",
")... | Gets the list of enclaves that the user has access to.
:return: A list of |EnclavePermissions| objects, each representing an enclave and whether the requesting user
has read, create, and update access to it. | [
"Gets",
"the",
"list",
"of",
"enclaves",
"that",
"the",
"user",
"has",
"access",
"to",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/trustar.py#L301-L310 |
trustar/trustar-python | trustar/trustar.py | TruStar.get_request_quotas | def get_request_quotas(self):
"""
Gets the request quotas for the user's company.
:return: A list of |RequestQuota| objects.
"""
resp = self._client.get("request-quotas")
return [RequestQuota.from_dict(quota) for quota in resp.json()] | python | def get_request_quotas(self):
"""
Gets the request quotas for the user's company.
:return: A list of |RequestQuota| objects.
"""
resp = self._client.get("request-quotas")
return [RequestQuota.from_dict(quota) for quota in resp.json()] | [
"def",
"get_request_quotas",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"request-quotas\"",
")",
"return",
"[",
"RequestQuota",
".",
"from_dict",
"(",
"quota",
")",
"for",
"quota",
"in",
"resp",
".",
"json",
"(",
")",
... | Gets the request quotas for the user's company.
:return: A list of |RequestQuota| objects. | [
"Gets",
"the",
"request",
"quotas",
"for",
"the",
"user",
"s",
"company",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/trustar.py#L312-L320 |
trustar/trustar-python | trustar/logger.py | configure_logging | def configure_logging():
"""
Initialize logging configuration to defaults. If the environment variable DISABLE_TRUSTAR_LOGGING is set to true,
this will be ignored.
"""
if not parse_boolean(os.environ.get('DISABLE_TRUSTAR_LOGGING')):
# configure
dictConfig(DEFAULT_LOGGING_CONFIG)
... | python | def configure_logging():
"""
Initialize logging configuration to defaults. If the environment variable DISABLE_TRUSTAR_LOGGING is set to true,
this will be ignored.
"""
if not parse_boolean(os.environ.get('DISABLE_TRUSTAR_LOGGING')):
# configure
dictConfig(DEFAULT_LOGGING_CONFIG)
... | [
"def",
"configure_logging",
"(",
")",
":",
"if",
"not",
"parse_boolean",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'DISABLE_TRUSTAR_LOGGING'",
")",
")",
":",
"# configure",
"dictConfig",
"(",
"DEFAULT_LOGGING_CONFIG",
")",
"# construct error logger",
"error_logge... | Initialize logging configuration to defaults. If the environment variable DISABLE_TRUSTAR_LOGGING is set to true,
this will be ignored. | [
"Initialize",
"logging",
"configuration",
"to",
"defaults",
".",
"If",
"the",
"environment",
"variable",
"DISABLE_TRUSTAR_LOGGING",
"is",
"set",
"to",
"true",
"this",
"will",
"be",
"ignored",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/logger.py#L73-L92 |
trustar/trustar-python | trustar/models/enclave.py | Enclave.from_dict | def from_dict(cls, enclave):
"""
Create a enclave object from a dictionary.
:param enclave: The dictionary.
:return: The enclave object.
"""
return Enclave(id=enclave.get('id'),
name=enclave.get('name'),
type=EnclaveType.fro... | python | def from_dict(cls, enclave):
"""
Create a enclave object from a dictionary.
:param enclave: The dictionary.
:return: The enclave object.
"""
return Enclave(id=enclave.get('id'),
name=enclave.get('name'),
type=EnclaveType.fro... | [
"def",
"from_dict",
"(",
"cls",
",",
"enclave",
")",
":",
"return",
"Enclave",
"(",
"id",
"=",
"enclave",
".",
"get",
"(",
"'id'",
")",
",",
"name",
"=",
"enclave",
".",
"get",
"(",
"'name'",
")",
",",
"type",
"=",
"EnclaveType",
".",
"from_string",
... | Create a enclave object from a dictionary.
:param enclave: The dictionary.
:return: The enclave object. | [
"Create",
"a",
"enclave",
"object",
"from",
"a",
"dictionary",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/enclave.py#L34-L44 |
trustar/trustar-python | trustar/models/enclave.py | Enclave.to_dict | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the enclave.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the enclave.
"""
if remo... | python | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the enclave.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the enclave.
"""
if remo... | [
"def",
"to_dict",
"(",
"self",
",",
"remove_nones",
"=",
"False",
")",
":",
"if",
"remove_nones",
":",
"return",
"super",
"(",
")",
".",
"to_dict",
"(",
"remove_nones",
"=",
"True",
")",
"return",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'name'",
"... | Creates a dictionary representation of the enclave.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the enclave. | [
"Creates",
"a",
"dictionary",
"representation",
"of",
"the",
"enclave",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/enclave.py#L46-L61 |
trustar/trustar-python | trustar/models/enclave.py | EnclavePermissions.from_dict | def from_dict(cls, d):
"""
Create a enclave object from a dictionary.
:param d: The dictionary.
:return: The EnclavePermissions object.
"""
enclave = super(cls, EnclavePermissions).from_dict(d)
enclave_permissions = cls.from_enclave(enclave)
enclave_per... | python | def from_dict(cls, d):
"""
Create a enclave object from a dictionary.
:param d: The dictionary.
:return: The EnclavePermissions object.
"""
enclave = super(cls, EnclavePermissions).from_dict(d)
enclave_permissions = cls.from_enclave(enclave)
enclave_per... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"enclave",
"=",
"super",
"(",
"cls",
",",
"EnclavePermissions",
")",
".",
"from_dict",
"(",
"d",
")",
"enclave_permissions",
"=",
"cls",
".",
"from_enclave",
"(",
"enclave",
")",
"enclave_permissions",
".... | Create a enclave object from a dictionary.
:param d: The dictionary.
:return: The EnclavePermissions object. | [
"Create",
"a",
"enclave",
"object",
"from",
"a",
"dictionary",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/enclave.py#L87-L102 |
trustar/trustar-python | trustar/models/enclave.py | EnclavePermissions.to_dict | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the enclave.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the EnclavePermissions object.
""... | python | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the enclave.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the EnclavePermissions object.
""... | [
"def",
"to_dict",
"(",
"self",
",",
"remove_nones",
"=",
"False",
")",
":",
"d",
"=",
"super",
"(",
")",
".",
"to_dict",
"(",
"remove_nones",
"=",
"remove_nones",
")",
"d",
".",
"update",
"(",
"{",
"'read'",
":",
"self",
".",
"read",
",",
"'create'",... | Creates a dictionary representation of the enclave.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the EnclavePermissions object. | [
"Creates",
"a",
"dictionary",
"representation",
"of",
"the",
"enclave",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/enclave.py#L104-L120 |
trustar/trustar-python | trustar/models/enclave.py | EnclavePermissions.from_enclave | def from_enclave(cls, enclave):
"""
Create an |EnclavePermissions| object from an |Enclave| object.
:param enclave: the Enclave object
:return: an EnclavePermissions object
"""
return EnclavePermissions(id=enclave.id,
name=enclave.name,... | python | def from_enclave(cls, enclave):
"""
Create an |EnclavePermissions| object from an |Enclave| object.
:param enclave: the Enclave object
:return: an EnclavePermissions object
"""
return EnclavePermissions(id=enclave.id,
name=enclave.name,... | [
"def",
"from_enclave",
"(",
"cls",
",",
"enclave",
")",
":",
"return",
"EnclavePermissions",
"(",
"id",
"=",
"enclave",
".",
"id",
",",
"name",
"=",
"enclave",
".",
"name",
",",
"type",
"=",
"enclave",
".",
"type",
")"
] | Create an |EnclavePermissions| object from an |Enclave| object.
:param enclave: the Enclave object
:return: an EnclavePermissions object | [
"Create",
"an",
"|EnclavePermissions|",
"object",
"from",
"an",
"|Enclave|",
"object",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/enclave.py#L123-L133 |
trustar/trustar-python | trustar/tag_client.py | TagClient.get_enclave_tags | def get_enclave_tags(self, report_id, id_type=None):
"""
Retrieves all enclave tags present in a specific report.
:param report_id: the ID of the report
:param id_type: indicates whether the ID internal or an external ID provided by the user
:return: A list of |Tag| objects.
... | python | def get_enclave_tags(self, report_id, id_type=None):
"""
Retrieves all enclave tags present in a specific report.
:param report_id: the ID of the report
:param id_type: indicates whether the ID internal or an external ID provided by the user
:return: A list of |Tag| objects.
... | [
"def",
"get_enclave_tags",
"(",
"self",
",",
"report_id",
",",
"id_type",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'idType'",
":",
"id_type",
"}",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"reports/%s/tags\"",
"%",
"report_id",
",",
"par... | Retrieves all enclave tags present in a specific report.
:param report_id: the ID of the report
:param id_type: indicates whether the ID internal or an external ID provided by the user
:return: A list of |Tag| objects. | [
"Retrieves",
"all",
"enclave",
"tags",
"present",
"in",
"a",
"specific",
"report",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L20-L31 |
trustar/trustar-python | trustar/tag_client.py | TagClient.add_enclave_tag | def add_enclave_tag(self, report_id, name, enclave_id, id_type=None):
"""
Adds a tag to a specific report, for a specific enclave.
:param report_id: The ID of the report
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added... | python | def add_enclave_tag(self, report_id, name, enclave_id, id_type=None):
"""
Adds a tag to a specific report, for a specific enclave.
:param report_id: The ID of the report
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added... | [
"def",
"add_enclave_tag",
"(",
"self",
",",
"report_id",
",",
"name",
",",
"enclave_id",
",",
"id_type",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'idType'",
":",
"id_type",
",",
"'name'",
":",
"name",
",",
"'enclaveId'",
":",
"enclave_id",
"}",
"resp"... | Adds a tag to a specific report, for a specific enclave.
:param report_id: The ID of the report
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added
:param id_type: indicates whether the ID internal or an external ID provided by t... | [
"Adds",
"a",
"tag",
"to",
"a",
"specific",
"report",
"for",
"a",
"specific",
"enclave",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L33-L50 |
trustar/trustar-python | trustar/tag_client.py | TagClient.delete_enclave_tag | def delete_enclave_tag(self, report_id, tag_id, id_type=None):
"""
Deletes a tag from a specific report, in a specific enclave.
:param string report_id: The ID of the report
:param string tag_id: ID of the tag to delete
:param string id_type: indicates whether the ID internal or... | python | def delete_enclave_tag(self, report_id, tag_id, id_type=None):
"""
Deletes a tag from a specific report, in a specific enclave.
:param string report_id: The ID of the report
:param string tag_id: ID of the tag to delete
:param string id_type: indicates whether the ID internal or... | [
"def",
"delete_enclave_tag",
"(",
"self",
",",
"report_id",
",",
"tag_id",
",",
"id_type",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'idType'",
":",
"id_type",
"}",
"self",
".",
"_client",
".",
"delete",
"(",
"\"reports/%s/tags/%s\"",
"%",
"(",
"report_i... | Deletes a tag from a specific report, in a specific enclave.
:param string report_id: The ID of the report
:param string tag_id: ID of the tag to delete
:param string id_type: indicates whether the ID internal or an external ID provided by the user
:return: The response body. | [
"Deletes",
"a",
"tag",
"from",
"a",
"specific",
"report",
"in",
"a",
"specific",
"enclave",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L52-L65 |
trustar/trustar-python | trustar/tag_client.py | TagClient.get_all_enclave_tags | def get_all_enclave_tags(self, enclave_ids=None):
"""
Retrieves all tags present in the given enclaves. If the enclave list is empty, the tags returned include all
tags for all enclaves the user has access to.
:param (string) list enclave_ids: list of enclave IDs
:return: The li... | python | def get_all_enclave_tags(self, enclave_ids=None):
"""
Retrieves all tags present in the given enclaves. If the enclave list is empty, the tags returned include all
tags for all enclaves the user has access to.
:param (string) list enclave_ids: list of enclave IDs
:return: The li... | [
"def",
"get_all_enclave_tags",
"(",
"self",
",",
"enclave_ids",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'enclaveIds'",
":",
"enclave_ids",
"}",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"reports/tags\"",
",",
"params",
"=",
"params",
")",... | Retrieves all tags present in the given enclaves. If the enclave list is empty, the tags returned include all
tags for all enclaves the user has access to.
:param (string) list enclave_ids: list of enclave IDs
:return: The list of |Tag| objects. | [
"Retrieves",
"all",
"tags",
"present",
"in",
"the",
"given",
"enclaves",
".",
"If",
"the",
"enclave",
"list",
"is",
"empty",
"the",
"tags",
"returned",
"include",
"all",
"tags",
"for",
"all",
"enclaves",
"the",
"user",
"has",
"access",
"to",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L67-L78 |
trustar/trustar-python | trustar/tag_client.py | TagClient.add_indicator_tag | def add_indicator_tag(self, indicator_value, name, enclave_id):
"""
Adds a tag to a specific indicator, for a specific enclave.
:param indicator_value: The value of the indicator
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will... | python | def add_indicator_tag(self, indicator_value, name, enclave_id):
"""
Adds a tag to a specific indicator, for a specific enclave.
:param indicator_value: The value of the indicator
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will... | [
"def",
"add_indicator_tag",
"(",
"self",
",",
"indicator_value",
",",
"name",
",",
"enclave_id",
")",
":",
"data",
"=",
"{",
"'value'",
":",
"indicator_value",
",",
"'tag'",
":",
"{",
"'name'",
":",
"name",
",",
"'enclaveId'",
":",
"enclave_id",
"}",
"}",
... | Adds a tag to a specific indicator, for a specific enclave.
:param indicator_value: The value of the indicator
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added
:return: A |Tag| object representing the tag that was created. | [
"Adds",
"a",
"tag",
"to",
"a",
"specific",
"indicator",
"for",
"a",
"specific",
"enclave",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L95-L114 |
trustar/trustar-python | trustar/tag_client.py | TagClient.delete_indicator_tag | def delete_indicator_tag(self, indicator_value, tag_id):
"""
Deletes a tag from a specific indicator, in a specific enclave.
:param indicator_value: The value of the indicator to delete the tag from
:param tag_id: ID of the tag to delete
"""
params = {
'valu... | python | def delete_indicator_tag(self, indicator_value, tag_id):
"""
Deletes a tag from a specific indicator, in a specific enclave.
:param indicator_value: The value of the indicator to delete the tag from
:param tag_id: ID of the tag to delete
"""
params = {
'valu... | [
"def",
"delete_indicator_tag",
"(",
"self",
",",
"indicator_value",
",",
"tag_id",
")",
":",
"params",
"=",
"{",
"'value'",
":",
"indicator_value",
"}",
"self",
".",
"_client",
".",
"delete",
"(",
"\"indicators/tags/%s\"",
"%",
"tag_id",
",",
"params",
"=",
... | Deletes a tag from a specific indicator, in a specific enclave.
:param indicator_value: The value of the indicator to delete the tag from
:param tag_id: ID of the tag to delete | [
"Deletes",
"a",
"tag",
"from",
"a",
"specific",
"indicator",
"in",
"a",
"specific",
"enclave",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L116-L128 |
trustar/trustar-python | trustar/models/tag.py | Tag.from_dict | def from_dict(cls, tag):
"""
Create a tag object from a dictionary. This method is intended for internal use, to construct a
:class:`Tag` object from the body of a response json. It expects the keys of the dictionary to match those
of the json that would be found in a response to an AP... | python | def from_dict(cls, tag):
"""
Create a tag object from a dictionary. This method is intended for internal use, to construct a
:class:`Tag` object from the body of a response json. It expects the keys of the dictionary to match those
of the json that would be found in a response to an AP... | [
"def",
"from_dict",
"(",
"cls",
",",
"tag",
")",
":",
"return",
"Tag",
"(",
"name",
"=",
"tag",
".",
"get",
"(",
"'name'",
")",
",",
"id",
"=",
"tag",
".",
"get",
"(",
"'guid'",
")",
",",
"enclave_id",
"=",
"tag",
".",
"get",
"(",
"'enclaveId'",
... | Create a tag object from a dictionary. This method is intended for internal use, to construct a
:class:`Tag` object from the body of a response json. It expects the keys of the dictionary to match those
of the json that would be found in a response to an API call such as ``GET /enclave-tags``.
... | [
"Create",
"a",
"tag",
"object",
"from",
"a",
"dictionary",
".",
"This",
"method",
"is",
"intended",
"for",
"internal",
"use",
"to",
"construct",
"a",
":",
"class",
":",
"Tag",
"object",
"from",
"the",
"body",
"of",
"a",
"response",
"json",
".",
"It",
"... | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/tag.py#L34-L46 |
trustar/trustar-python | trustar/models/tag.py | Tag.to_dict | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the tag.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the tag.
"""
if remove_nones... | python | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the tag.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the tag.
"""
if remove_nones... | [
"def",
"to_dict",
"(",
"self",
",",
"remove_nones",
"=",
"False",
")",
":",
"if",
"remove_nones",
":",
"d",
"=",
"super",
"(",
")",
".",
"to_dict",
"(",
"remove_nones",
"=",
"True",
")",
"else",
":",
"d",
"=",
"{",
"'name'",
":",
"self",
".",
"name... | Creates a dictionary representation of the tag.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the tag. | [
"Creates",
"a",
"dictionary",
"representation",
"of",
"the",
"tag",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/tag.py#L48-L65 |
openvax/topiary | topiary/rna/common.py | infer_delimiter | def infer_delimiter(filename, comment_char="#", n_lines=3):
"""
Given a file which contains data separated by one of the following:
- commas
- tabs
- spaces
Return the most likely separator by sniffing the first few lines
of the file's contents.
"""
lines = []
with op... | python | def infer_delimiter(filename, comment_char="#", n_lines=3):
"""
Given a file which contains data separated by one of the following:
- commas
- tabs
- spaces
Return the most likely separator by sniffing the first few lines
of the file's contents.
"""
lines = []
with op... | [
"def",
"infer_delimiter",
"(",
"filename",
",",
"comment_char",
"=",
"\"#\"",
",",
"n_lines",
"=",
"3",
")",
":",
"lines",
"=",
"[",
"]",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line... | Given a file which contains data separated by one of the following:
- commas
- tabs
- spaces
Return the most likely separator by sniffing the first few lines
of the file's contents. | [
"Given",
"a",
"file",
"which",
"contains",
"data",
"separated",
"by",
"one",
"of",
"the",
"following",
":",
"-",
"commas",
"-",
"tabs",
"-",
"spaces",
"Return",
"the",
"most",
"likely",
"separator",
"by",
"sniffing",
"the",
"first",
"few",
"lines",
"of",
... | train | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/rna/common.py#L19-L46 |
openvax/topiary | topiary/rna/common.py | check_required_columns | def check_required_columns(df, filename, required_columns):
"""
Ensure that all required columns are present in the given dataframe,
otherwise raise an exception.
"""
available_columns = set(df.columns)
for column_name in required_columns:
if column_name not in available_columns:
... | python | def check_required_columns(df, filename, required_columns):
"""
Ensure that all required columns are present in the given dataframe,
otherwise raise an exception.
"""
available_columns = set(df.columns)
for column_name in required_columns:
if column_name not in available_columns:
... | [
"def",
"check_required_columns",
"(",
"df",
",",
"filename",
",",
"required_columns",
")",
":",
"available_columns",
"=",
"set",
"(",
"df",
".",
"columns",
")",
"for",
"column_name",
"in",
"required_columns",
":",
"if",
"column_name",
"not",
"in",
"available_col... | Ensure that all required columns are present in the given dataframe,
otherwise raise an exception. | [
"Ensure",
"that",
"all",
"required",
"columns",
"are",
"present",
"in",
"the",
"given",
"dataframe",
"otherwise",
"raise",
"an",
"exception",
"."
] | train | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/rna/common.py#L49-L59 |
gabrielelanaro/chemview | chemview/contrib.py | topology_mdtraj | def topology_mdtraj(traj):
'''Generate topology spec for the MolecularViewer from mdtraj.
:param mdtraj.Trajectory traj: the trajectory
:return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj.
'''
import mdtraj as md
top = {}
top['atom_types'] = [a.elemen... | python | def topology_mdtraj(traj):
'''Generate topology spec for the MolecularViewer from mdtraj.
:param mdtraj.Trajectory traj: the trajectory
:return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj.
'''
import mdtraj as md
top = {}
top['atom_types'] = [a.elemen... | [
"def",
"topology_mdtraj",
"(",
"traj",
")",
":",
"import",
"mdtraj",
"as",
"md",
"top",
"=",
"{",
"}",
"top",
"[",
"'atom_types'",
"]",
"=",
"[",
"a",
".",
"element",
".",
"symbol",
"for",
"a",
"in",
"traj",
".",
"topology",
".",
"atoms",
"]",
"top... | Generate topology spec for the MolecularViewer from mdtraj.
:param mdtraj.Trajectory traj: the trajectory
:return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj. | [
"Generate",
"topology",
"spec",
"for",
"the",
"MolecularViewer",
"from",
"mdtraj",
"."
] | train | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/contrib.py#L3-L20 |
gabrielelanaro/chemview | chemview/utils.py | encode_numpy | def encode_numpy(array):
'''Encode a numpy array as a base64 encoded string, to be JSON serialized.
:return: a dictionary containing the fields:
- *data*: the base64 string
- *type*: the array type
- *shape*: the array shape
'''
return {'data' : base64.... | python | def encode_numpy(array):
'''Encode a numpy array as a base64 encoded string, to be JSON serialized.
:return: a dictionary containing the fields:
- *data*: the base64 string
- *type*: the array type
- *shape*: the array shape
'''
return {'data' : base64.... | [
"def",
"encode_numpy",
"(",
"array",
")",
":",
"return",
"{",
"'data'",
":",
"base64",
".",
"b64encode",
"(",
"array",
".",
"data",
")",
".",
"decode",
"(",
"'utf8'",
")",
",",
"'type'",
":",
"array",
".",
"dtype",
".",
"name",
",",
"'shape'",
":",
... | Encode a numpy array as a base64 encoded string, to be JSON serialized.
:return: a dictionary containing the fields:
- *data*: the base64 string
- *type*: the array type
- *shape*: the array shape | [
"Encode",
"a",
"numpy",
"array",
"as",
"a",
"base64",
"encoded",
"string",
"to",
"be",
"JSON",
"serialized",
"."
] | train | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/utils.py#L7-L18 |
openvax/topiary | topiary/rna/cufflinks.py | load_cufflinks_dataframe | def load_cufflinks_dataframe(
filename,
id_column=ID_COLUMN,
fpkm_column=FPKM_COLUMN,
status_column=STATUS_COLUMN,
locus_column=LOCUS_COLUMN,
gene_names_column=GENE_NAMES_COLUMN,
drop_failed=True,
drop_lowdata=False,
drop_hidata=True,
repla... | python | def load_cufflinks_dataframe(
filename,
id_column=ID_COLUMN,
fpkm_column=FPKM_COLUMN,
status_column=STATUS_COLUMN,
locus_column=LOCUS_COLUMN,
gene_names_column=GENE_NAMES_COLUMN,
drop_failed=True,
drop_lowdata=False,
drop_hidata=True,
repla... | [
"def",
"load_cufflinks_dataframe",
"(",
"filename",
",",
"id_column",
"=",
"ID_COLUMN",
",",
"fpkm_column",
"=",
"FPKM_COLUMN",
",",
"status_column",
"=",
"STATUS_COLUMN",
",",
"locus_column",
"=",
"LOCUS_COLUMN",
",",
"gene_names_column",
"=",
"GENE_NAMES_COLUMN",
",... | Loads a Cufflinks tracking file, which contains expression levels
(in FPKM: Fragments Per Kilobase of transcript per Million fragments)
for transcript isoforms or whole genes. These transcripts/genes may be
previously known (in which case they have an Ensembl ID) or a novel
assembly from the RNA-Seq dat... | [
"Loads",
"a",
"Cufflinks",
"tracking",
"file",
"which",
"contains",
"expression",
"levels",
"(",
"in",
"FPKM",
":",
"Fragments",
"Per",
"Kilobase",
"of",
"transcript",
"per",
"Million",
"fragments",
")",
"for",
"transcript",
"isoforms",
"or",
"whole",
"genes",
... | train | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/rna/cufflinks.py#L45-L212 |
openvax/topiary | topiary/rna/cufflinks.py | load_cufflinks_dict | def load_cufflinks_dict(*args, **kwargs):
"""
Returns dictionary mapping feature identifier (either transcript or gene ID)
to a DataFrame row with fields:
id : str
novel : bool
fpkm : float
chr : str
start : int
end : int
gene_names : str list
"""
... | python | def load_cufflinks_dict(*args, **kwargs):
"""
Returns dictionary mapping feature identifier (either transcript or gene ID)
to a DataFrame row with fields:
id : str
novel : bool
fpkm : float
chr : str
start : int
end : int
gene_names : str list
"""
... | [
"def",
"load_cufflinks_dict",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"{",
"row",
".",
"id",
":",
"row",
"for",
"(",
"_",
",",
"row",
")",
"in",
"load_cufflinks_dataframe",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",... | Returns dictionary mapping feature identifier (either transcript or gene ID)
to a DataFrame row with fields:
id : str
novel : bool
fpkm : float
chr : str
start : int
end : int
gene_names : str list | [
"Returns",
"dictionary",
"mapping",
"feature",
"identifier",
"(",
"either",
"transcript",
"or",
"gene",
"ID",
")",
"to",
"a",
"DataFrame",
"row",
"with",
"fields",
":",
"id",
":",
"str",
"novel",
":",
"bool",
"fpkm",
":",
"float",
"chr",
":",
"str",
"sta... | train | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/rna/cufflinks.py#L215-L231 |
openvax/topiary | topiary/rna/cufflinks.py | load_cufflinks_fpkm_dict | def load_cufflinks_fpkm_dict(*args, **kwargs):
"""
Returns dictionary mapping feature identifier (either transcript or gene ID)
to FPKM expression value.
"""
return {
row.id: row.fpkm
for (_, row)
in load_cufflinks_dataframe(*args, **kwargs).iterrows()
} | python | def load_cufflinks_fpkm_dict(*args, **kwargs):
"""
Returns dictionary mapping feature identifier (either transcript or gene ID)
to FPKM expression value.
"""
return {
row.id: row.fpkm
for (_, row)
in load_cufflinks_dataframe(*args, **kwargs).iterrows()
} | [
"def",
"load_cufflinks_fpkm_dict",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"{",
"row",
".",
"id",
":",
"row",
".",
"fpkm",
"for",
"(",
"_",
",",
"row",
")",
"in",
"load_cufflinks_dataframe",
"(",
"*",
"args",
",",
"*",
"*",
"... | Returns dictionary mapping feature identifier (either transcript or gene ID)
to FPKM expression value. | [
"Returns",
"dictionary",
"mapping",
"feature",
"identifier",
"(",
"either",
"transcript",
"or",
"gene",
"ID",
")",
"to",
"FPKM",
"expression",
"value",
"."
] | train | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/rna/cufflinks.py#L234-L243 |
gabrielelanaro/chemview | chemview/install.py | enable_notebook | def enable_notebook(verbose=0):
"""Enable IPython notebook widgets to be displayed.
This function should be called before using the chemview widgets.
"""
libs = ['objexporter.js',
'ArcballControls.js', 'filesaver.js',
'base64-arraybuffer.js', 'context.js',
'chemview.... | python | def enable_notebook(verbose=0):
"""Enable IPython notebook widgets to be displayed.
This function should be called before using the chemview widgets.
"""
libs = ['objexporter.js',
'ArcballControls.js', 'filesaver.js',
'base64-arraybuffer.js', 'context.js',
'chemview.... | [
"def",
"enable_notebook",
"(",
"verbose",
"=",
"0",
")",
":",
"libs",
"=",
"[",
"'objexporter.js'",
",",
"'ArcballControls.js'",
",",
"'filesaver.js'",
",",
"'base64-arraybuffer.js'",
",",
"'context.js'",
",",
"'chemview.js'",
",",
"'three.min.js'",
",",
"'jquery-ui... | Enable IPython notebook widgets to be displayed.
This function should be called before using the chemview widgets. | [
"Enable",
"IPython",
"notebook",
"widgets",
"to",
"be",
"displayed",
"."
] | train | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/install.py#L14-L29 |
trustar/trustar-python | trustar/examples/bulk_upload.py | extract_pdf | def extract_pdf(file_name):
"""
Extract text from a pdf file
:param file_name path to pdf to read
:return text from pdf
"""
rsrcmgr = pdfminer.pdfinterp.PDFResourceManager()
sio = StringIO()
laparams = LAParams()
device = TextConverter(rsrcmgr, sio, codec='utf-8', laparams=laparams)... | python | def extract_pdf(file_name):
"""
Extract text from a pdf file
:param file_name path to pdf to read
:return text from pdf
"""
rsrcmgr = pdfminer.pdfinterp.PDFResourceManager()
sio = StringIO()
laparams = LAParams()
device = TextConverter(rsrcmgr, sio, codec='utf-8', laparams=laparams)... | [
"def",
"extract_pdf",
"(",
"file_name",
")",
":",
"rsrcmgr",
"=",
"pdfminer",
".",
"pdfinterp",
".",
"PDFResourceManager",
"(",
")",
"sio",
"=",
"StringIO",
"(",
")",
"laparams",
"=",
"LAParams",
"(",
")",
"device",
"=",
"TextConverter",
"(",
"rsrcmgr",
",... | Extract text from a pdf file
:param file_name path to pdf to read
:return text from pdf | [
"Extract",
"text",
"from",
"a",
"pdf",
"file",
":",
"param",
"file_name",
"path",
"to",
"pdf",
"to",
"read",
":",
"return",
"text",
"from",
"pdf"
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/examples/bulk_upload.py#L30-L54 |
trustar/trustar-python | trustar/examples/bulk_upload.py | process_file | def process_file(source_file):
"""
Extract text from a file (pdf, txt, eml, csv, json)
:param source_file path to file to read
:return text from file
"""
if source_file.endswith(('.pdf', '.PDF')):
txt = extract_pdf(source_file)
elif source_file.endswith(('.txt', '.eml', '.csv', '.jso... | python | def process_file(source_file):
"""
Extract text from a file (pdf, txt, eml, csv, json)
:param source_file path to file to read
:return text from file
"""
if source_file.endswith(('.pdf', '.PDF')):
txt = extract_pdf(source_file)
elif source_file.endswith(('.txt', '.eml', '.csv', '.jso... | [
"def",
"process_file",
"(",
"source_file",
")",
":",
"if",
"source_file",
".",
"endswith",
"(",
"(",
"'.pdf'",
",",
"'.PDF'",
")",
")",
":",
"txt",
"=",
"extract_pdf",
"(",
"source_file",
")",
"elif",
"source_file",
".",
"endswith",
"(",
"(",
"'.txt'",
"... | Extract text from a file (pdf, txt, eml, csv, json)
:param source_file path to file to read
:return text from file | [
"Extract",
"text",
"from",
"a",
"file",
"(",
"pdf",
"txt",
"eml",
"csv",
"json",
")",
":",
"param",
"source_file",
"path",
"to",
"file",
"to",
"read",
":",
"return",
"text",
"from",
"file"
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/examples/bulk_upload.py#L57-L71 |
trustar/trustar-python | trustar/models/enum.py | Enum.from_string | def from_string(cls, string):
"""
Simply logs a warning if the desired enum value is not found.
:param string:
:return:
"""
# find enum value
for attr in dir(cls):
value = getattr(cls, attr)
if value == string:
return valu... | python | def from_string(cls, string):
"""
Simply logs a warning if the desired enum value is not found.
:param string:
:return:
"""
# find enum value
for attr in dir(cls):
value = getattr(cls, attr)
if value == string:
return valu... | [
"def",
"from_string",
"(",
"cls",
",",
"string",
")",
":",
"# find enum value",
"for",
"attr",
"in",
"dir",
"(",
"cls",
")",
":",
"value",
"=",
"getattr",
"(",
"cls",
",",
"attr",
")",
"if",
"value",
"==",
"string",
":",
"return",
"value",
"# if not fo... | Simply logs a warning if the desired enum value is not found.
:param string:
:return: | [
"Simply",
"logs",
"a",
"warning",
"if",
"the",
"desired",
"enum",
"value",
"is",
"not",
"found",
"."
] | train | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/enum.py#L16-L32 |
valohai/valohai-yaml | valohai_yaml/objs/parameter.py | Parameter.validate | def validate(self, value):
"""
Validate (and possibly typecast) the given parameter value value.
:param value: Parameter value
:return: Typecast parameter value
:raises ValidationErrors: if there were validation errors
"""
errors = []
value = self._valida... | python | def validate(self, value):
"""
Validate (and possibly typecast) the given parameter value value.
:param value: Parameter value
:return: Typecast parameter value
:raises ValidationErrors: if there were validation errors
"""
errors = []
value = self._valida... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"errors",
"=",
"[",
"]",
"value",
"=",
"self",
".",
"_validate_type",
"(",
"value",
",",
"errors",
")",
"self",
".",
"_validate_value",
"(",
"value",
",",
"errors",
")",
"if",
"errors",
":",
"ra... | Validate (and possibly typecast) the given parameter value value.
:param value: Parameter value
:return: Typecast parameter value
:raises ValidationErrors: if there were validation errors | [
"Validate",
"(",
"and",
"possibly",
"typecast",
")",
"the",
"given",
"parameter",
"value",
"value",
"."
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/objs/parameter.py#L62-L77 |
valohai/valohai-yaml | valohai_yaml/objs/parameter.py | Parameter.format_cli | def format_cli(self, value):
"""
Build a single parameter argument.
:return: list of CLI strings -- not escaped. If the parameter should not be expressed, returns None.
:rtype: list[str]|None
"""
if value is None or (self.type == 'flag' and not value):
return... | python | def format_cli(self, value):
"""
Build a single parameter argument.
:return: list of CLI strings -- not escaped. If the parameter should not be expressed, returns None.
:rtype: list[str]|None
"""
if value is None or (self.type == 'flag' and not value):
return... | [
"def",
"format_cli",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"(",
"self",
".",
"type",
"==",
"'flag'",
"and",
"not",
"value",
")",
":",
"return",
"None",
"pass_as_bits",
"=",
"text_type",
"(",
"self",
".",
"pass_as",
"... | Build a single parameter argument.
:return: list of CLI strings -- not escaped. If the parameter should not be expressed, returns None.
:rtype: list[str]|None | [
"Build",
"a",
"single",
"parameter",
"argument",
"."
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/objs/parameter.py#L85-L96 |
valohai/valohai-yaml | valohai_yaml/utils/__init__.py | listify | def listify(value):
"""
Wrap the given value into a list, with the below provisions:
* If the value is a list or a tuple, it's coerced into a new list.
* If the value is None, an empty list is returned.
* Otherwise, a single-element list is returned, containing the value.
:param value: A value... | python | def listify(value):
"""
Wrap the given value into a list, with the below provisions:
* If the value is a list or a tuple, it's coerced into a new list.
* If the value is None, an empty list is returned.
* Otherwise, a single-element list is returned, containing the value.
:param value: A value... | [
"def",
"listify",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"list",
"(",
"value",
")",
"return",
"[",
"value",
"]"
] | Wrap the given value into a list, with the below provisions:
* If the value is a list or a tuple, it's coerced into a new list.
* If the value is None, an empty list is returned.
* Otherwise, a single-element list is returned, containing the value.
:param value: A value.
:return: a list!
:rtyp... | [
"Wrap",
"the",
"given",
"value",
"into",
"a",
"list",
"with",
"the",
"below",
"provisions",
":"
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/utils/__init__.py#L12-L28 |
valohai/valohai-yaml | valohai_yaml/commands.py | build_command | def build_command(command, parameter_map):
"""
Build command line(s) using the given parameter map.
Even if the passed a single `command`, this function will return a list
of shell commands. It is the caller's responsibility to concatenate them,
likely using the semicolon or double ampersands.
... | python | def build_command(command, parameter_map):
"""
Build command line(s) using the given parameter map.
Even if the passed a single `command`, this function will return a list
of shell commands. It is the caller's responsibility to concatenate them,
likely using the semicolon or double ampersands.
... | [
"def",
"build_command",
"(",
"command",
",",
"parameter_map",
")",
":",
"if",
"isinstance",
"(",
"parameter_map",
",",
"list",
")",
":",
"# Partially emulate old (pre-0.7) API for this function.",
"parameter_map",
"=",
"LegacyParameterMap",
"(",
"parameter_map",
")",
"o... | Build command line(s) using the given parameter map.
Even if the passed a single `command`, this function will return a list
of shell commands. It is the caller's responsibility to concatenate them,
likely using the semicolon or double ampersands.
:param command: The command to interpolate params int... | [
"Build",
"command",
"line",
"(",
"s",
")",
"using",
"the",
"given",
"parameter",
"map",
"."
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/commands.py#L44-L83 |
valohai/valohai-yaml | valohai_yaml/validation.py | validate | def validate(yaml, raise_exc=True):
"""
Validate the given YAML document and return a list of errors.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param raise_exc: Whether to raise a meta-exception containing all discovered error... | python | def validate(yaml, raise_exc=True):
"""
Validate the given YAML document and return a list of errors.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param raise_exc: Whether to raise a meta-exception containing all discovered error... | [
"def",
"validate",
"(",
"yaml",
",",
"raise_exc",
"=",
"True",
")",
":",
"data",
"=",
"read_yaml",
"(",
"yaml",
")",
"validator",
"=",
"get_validator",
"(",
")",
"# Nb: this uses a list instead of being a generator function in order to be",
"# easier to call correctly. (W... | Validate the given YAML document and return a list of errors.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param raise_exc: Whether to raise a meta-exception containing all discovered errors after validation.
:type raise_exc: bool
... | [
"Validate",
"the",
"given",
"YAML",
"document",
"and",
"return",
"a",
"list",
"of",
"errors",
"."
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/validation.py#L66-L85 |
valohai/valohai-yaml | valohai_yaml/objs/parameter_map.py | ParameterMap.build_parameters | def build_parameters(self):
"""
Build the CLI command line from the parameter values.
:return: list of CLI strings -- not escaped!
:rtype: list[str]
"""
param_bits = []
for name in self.parameters:
param_bits.extend(self.build_parameter_by_name(name) ... | python | def build_parameters(self):
"""
Build the CLI command line from the parameter values.
:return: list of CLI strings -- not escaped!
:rtype: list[str]
"""
param_bits = []
for name in self.parameters:
param_bits.extend(self.build_parameter_by_name(name) ... | [
"def",
"build_parameters",
"(",
"self",
")",
":",
"param_bits",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".",
"parameters",
":",
"param_bits",
".",
"extend",
"(",
"self",
".",
"build_parameter_by_name",
"(",
"name",
")",
"or",
"[",
"]",
")",
"return",... | Build the CLI command line from the parameter values.
:return: list of CLI strings -- not escaped!
:rtype: list[str] | [
"Build",
"the",
"CLI",
"command",
"line",
"from",
"the",
"parameter",
"values",
"."
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/objs/parameter_map.py#L6-L16 |
valohai/valohai-yaml | valohai_yaml/objs/config.py | Config.parse | def parse(cls, data):
"""
Parse a Config structure out of a Python dict (that's likely deserialized from YAML).
:param data: Config-y dict
:type data: dict
:return: Config object
:rtype: valohai_yaml.objs.Config
"""
parsers = {
'step': ([], St... | python | def parse(cls, data):
"""
Parse a Config structure out of a Python dict (that's likely deserialized from YAML).
:param data: Config-y dict
:type data: dict
:return: Config object
:rtype: valohai_yaml.objs.Config
"""
parsers = {
'step': ([], St... | [
"def",
"parse",
"(",
"cls",
",",
"data",
")",
":",
"parsers",
"=",
"{",
"'step'",
":",
"(",
"[",
"]",
",",
"Step",
".",
"parse",
")",
",",
"'endpoint'",
":",
"(",
"[",
"]",
",",
"Endpoint",
".",
"parse",
")",
",",
"}",
"for",
"datum",
"in",
"... | Parse a Config structure out of a Python dict (that's likely deserialized from YAML).
:param data: Config-y dict
:type data: dict
:return: Config object
:rtype: valohai_yaml.objs.Config | [
"Parse",
"a",
"Config",
"structure",
"out",
"of",
"a",
"Python",
"dict",
"(",
"that",
"s",
"likely",
"deserialized",
"from",
"YAML",
")",
"."
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/objs/config.py#L24-L50 |
valohai/valohai-yaml | valohai_yaml/objs/config.py | Config.get_step_by | def get_step_by(self, **kwargs):
"""
Get the first step that matches all the passed named arguments.
Has special argument index not present in the real step.
Usage:
config.get_step_by(name='not found')
config.get_step_by(index=0)
config.get_step_by(n... | python | def get_step_by(self, **kwargs):
"""
Get the first step that matches all the passed named arguments.
Has special argument index not present in the real step.
Usage:
config.get_step_by(name='not found')
config.get_step_by(index=0)
config.get_step_by(n... | [
"def",
"get_step_by",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
":",
"return",
"None",
"for",
"index",
",",
"step",
"in",
"enumerate",
"(",
"self",
".",
"steps",
".",
"values",
"(",
")",
")",
":",
"extended_step",
"=",
... | Get the first step that matches all the passed named arguments.
Has special argument index not present in the real step.
Usage:
config.get_step_by(name='not found')
config.get_step_by(index=0)
config.get_step_by(name="greeting", command='echo HELLO MORDOR')
... | [
"Get",
"the",
"first",
"step",
"that",
"matches",
"all",
"the",
"passed",
"named",
"arguments",
"."
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/objs/config.py#L65-L87 |
valohai/valohai-yaml | valohai_yaml/parsing.py | parse | def parse(yaml, validate=True):
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param validate: Whether to validate the data before attempting to ... | python | def parse(yaml, validate=True):
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param validate: Whether to validate the data before attempting to ... | [
"def",
"parse",
"(",
"yaml",
",",
"validate",
"=",
"True",
")",
":",
"data",
"=",
"read_yaml",
"(",
"yaml",
")",
"if",
"validate",
":",
"# pragma: no branch",
"from",
".",
"validation",
"import",
"validate",
"validate",
"(",
"data",
",",
"raise_exc",
"=",
... | Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param validate: Whether to validate the data before attempting to parse it.
:type validate: bool
:retu... | [
"Parse",
"the",
"given",
"YAML",
"data",
"into",
"a",
"Config",
"object",
"optionally",
"validating",
"it",
"first",
"."
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/parsing.py#L6-L21 |
valohai/valohai-yaml | valohai_yaml/objs/step.py | Step.get_parameter_defaults | def get_parameter_defaults(self, include_flags=True):
"""
Get a dict mapping parameter names to their defaults (if set).
:rtype: dict[str, object]
"""
return {
name: parameter.default
for (name, parameter)
in self.parameters.items()
... | python | def get_parameter_defaults(self, include_flags=True):
"""
Get a dict mapping parameter names to their defaults (if set).
:rtype: dict[str, object]
"""
return {
name: parameter.default
for (name, parameter)
in self.parameters.items()
... | [
"def",
"get_parameter_defaults",
"(",
"self",
",",
"include_flags",
"=",
"True",
")",
":",
"return",
"{",
"name",
":",
"parameter",
".",
"default",
"for",
"(",
"name",
",",
"parameter",
")",
"in",
"self",
".",
"parameters",
".",
"items",
"(",
")",
"if",
... | Get a dict mapping parameter names to their defaults (if set).
:rtype: dict[str, object] | [
"Get",
"a",
"dict",
"mapping",
"parameter",
"names",
"to",
"their",
"defaults",
"(",
"if",
"set",
")",
".",
":",
"rtype",
":",
"dict",
"[",
"str",
"object",
"]"
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/objs/step.py#L76-L86 |
valohai/valohai-yaml | valohai_yaml/objs/step.py | Step.build_command | def build_command(self, parameter_values, command=None):
"""
Build the command for this step using the given parameter values.
Even if the original configuration only declared a single `command`,
this function will return a list of shell commands. It is the caller's
responsibil... | python | def build_command(self, parameter_values, command=None):
"""
Build the command for this step using the given parameter values.
Even if the original configuration only declared a single `command`,
this function will return a list of shell commands. It is the caller's
responsibil... | [
"def",
"build_command",
"(",
"self",
",",
"parameter_values",
",",
"command",
"=",
"None",
")",
":",
"command",
"=",
"(",
"command",
"or",
"self",
".",
"command",
")",
"# merge defaults with passed values",
"# ignore flag default values as they are special",
"# undefine... | Build the command for this step using the given parameter values.
Even if the original configuration only declared a single `command`,
this function will return a list of shell commands. It is the caller's
responsibility to concatenate them, likely using the semicolon or
double ampersa... | [
"Build",
"the",
"command",
"for",
"this",
"step",
"using",
"the",
"given",
"parameter",
"values",
"."
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/objs/step.py#L92-L118 |
valohai/valohai-yaml | valohai_yaml/lint.py | lint_file | def lint_file(file_path):
"""
Validate & lint `file_path` and return a LintResult.
:param file_path: YAML filename
:type file_path: str
:return: LintResult object
"""
with open(file_path, 'r') as yaml:
try:
return lint(yaml)
except Exception as e:
lr... | python | def lint_file(file_path):
"""
Validate & lint `file_path` and return a LintResult.
:param file_path: YAML filename
:type file_path: str
:return: LintResult object
"""
with open(file_path, 'r') as yaml:
try:
return lint(yaml)
except Exception as e:
lr... | [
"def",
"lint_file",
"(",
"file_path",
")",
":",
"with",
"open",
"(",
"file_path",
",",
"'r'",
")",
"as",
"yaml",
":",
"try",
":",
"return",
"lint",
"(",
"yaml",
")",
"except",
"Exception",
"as",
"e",
":",
"lr",
"=",
"LintResult",
"(",
")",
"lr",
".... | Validate & lint `file_path` and return a LintResult.
:param file_path: YAML filename
:type file_path: str
:return: LintResult object | [
"Validate",
"&",
"lint",
"file_path",
"and",
"return",
"a",
"LintResult",
"."
] | train | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/lint.py#L35-L50 |
metglobal/django-exchange | exchange/adapters/__init__.py | BaseAdapter.update | def update(self):
"""Actual update process goes here using auxialary ``get_currencies``
and ``get_exchangerates`` methods. This method creates or updates
corresponding ``Currency`` and ``ExchangeRate`` models
"""
currencies = self.get_currencies()
currency_objects = {}
... | python | def update(self):
"""Actual update process goes here using auxialary ``get_currencies``
and ``get_exchangerates`` methods. This method creates or updates
corresponding ``Currency`` and ``ExchangeRate`` models
"""
currencies = self.get_currencies()
currency_objects = {}
... | [
"def",
"update",
"(",
"self",
")",
":",
"currencies",
"=",
"self",
".",
"get_currencies",
"(",
")",
"currency_objects",
"=",
"{",
"}",
"for",
"code",
",",
"name",
"in",
"currencies",
":",
"currency_objects",
"[",
"code",
"]",
",",
"created",
"=",
"Curren... | Actual update process goes here using auxialary ``get_currencies``
and ``get_exchangerates`` methods. This method creates or updates
corresponding ``Currency`` and ``ExchangeRate`` models | [
"Actual",
"update",
"process",
"goes",
"here",
"using",
"auxialary",
"get_currencies",
"and",
"get_exchangerates",
"methods",
".",
"This",
"method",
"creates",
"or",
"updates",
"corresponding",
"Currency",
"and",
"ExchangeRate",
"models"
] | train | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/adapters/__init__.py#L17-L63 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | _re_flatten | def _re_flatten(p):
''' Turn all capturing groups in a regular expression pattern into
non-capturing groups. '''
if '(' not in p: return p
return re.sub(r'(\\*)(\(\?P<[^>]+>|\((?!\?))',
lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:', p) | python | def _re_flatten(p):
''' Turn all capturing groups in a regular expression pattern into
non-capturing groups. '''
if '(' not in p: return p
return re.sub(r'(\\*)(\(\?P<[^>]+>|\((?!\?))',
lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:', p) | [
"def",
"_re_flatten",
"(",
"p",
")",
":",
"if",
"'('",
"not",
"in",
"p",
":",
"return",
"p",
"return",
"re",
".",
"sub",
"(",
"r'(\\\\*)(\\(\\?P<[^>]+>|\\((?!\\?))'",
",",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"0",
")",
"if",
"len",
"(",
"m",
... | Turn all capturing groups in a regular expression pattern into
non-capturing groups. | [
"Turn",
"all",
"capturing",
"groups",
"in",
"a",
"regular",
"expression",
"pattern",
"into",
"non",
"-",
"capturing",
"groups",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L247-L252 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | redirect | def redirect(url, code=None):
""" Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. """
if not code:
code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
res = response.copy(cls=HTTPResponse)
res.status = code
res.body = ""
... | python | def redirect(url, code=None):
""" Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. """
if not code:
code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
res = response.copy(cls=HTTPResponse)
res.status = code
res.body = ""
... | [
"def",
"redirect",
"(",
"url",
",",
"code",
"=",
"None",
")",
":",
"if",
"not",
"code",
":",
"code",
"=",
"303",
"if",
"request",
".",
"get",
"(",
"'SERVER_PROTOCOL'",
")",
"==",
"\"HTTP/1.1\"",
"else",
"302",
"res",
"=",
"response",
".",
"copy",
"("... | Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. | [
"Aborts",
"execution",
"and",
"causes",
"a",
"303",
"or",
"302",
"redirect",
"depending",
"on",
"the",
"HTTP",
"protocol",
"version",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2413-L2422 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | _file_iter_range | def _file_iter_range(fp, offset, bytes, maxread=1024*1024):
''' Yield chunks from a range in a file. No chunk is bigger than maxread.'''
fp.seek(offset)
while bytes > 0:
part = fp.read(min(bytes, maxread))
if not part: break
bytes -= len(part)
yield part | python | def _file_iter_range(fp, offset, bytes, maxread=1024*1024):
''' Yield chunks from a range in a file. No chunk is bigger than maxread.'''
fp.seek(offset)
while bytes > 0:
part = fp.read(min(bytes, maxread))
if not part: break
bytes -= len(part)
yield part | [
"def",
"_file_iter_range",
"(",
"fp",
",",
"offset",
",",
"bytes",
",",
"maxread",
"=",
"1024",
"*",
"1024",
")",
":",
"fp",
".",
"seek",
"(",
"offset",
")",
"while",
"bytes",
">",
"0",
":",
"part",
"=",
"fp",
".",
"read",
"(",
"min",
"(",
"bytes... | Yield chunks from a range in a file. No chunk is bigger than maxread. | [
"Yield",
"chunks",
"from",
"a",
"range",
"in",
"a",
"file",
".",
"No",
"chunk",
"is",
"bigger",
"than",
"maxread",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2425-L2432 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | static_file | def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8'):
""" Open a file in a safe way and return :exc:`HTTPResponse` with status
code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``,
``Content-Length`` and ``Last-Modified`` headers are set if possible.
... | python | def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8'):
""" Open a file in a safe way and return :exc:`HTTPResponse` with status
code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``,
``Content-Length`` and ``Last-Modified`` headers are set if possible.
... | [
"def",
"static_file",
"(",
"filename",
",",
"root",
",",
"mimetype",
"=",
"'auto'",
",",
"download",
"=",
"False",
",",
"charset",
"=",
"'UTF-8'",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"root",
")",
"+",
"os",
".",
"sep",
"f... | Open a file in a safe way and return :exc:`HTTPResponse` with status
code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``,
``Content-Length`` and ``Last-Modified`` headers are set if possible.
Special support for ``If-Modified-Since``, ``Range`` and ``HEAD``
requests.
... | [
"Open",
"a",
"file",
"in",
"a",
"safe",
"way",
"and",
"return",
":",
"exc",
":",
"HTTPResponse",
"with",
"status",
"code",
"200",
"305",
"403",
"or",
"404",
".",
"The",
"Content",
"-",
"Type",
"Content",
"-",
"Encoding",
"Content",
"-",
"Length",
"and"... | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2435-L2504 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | debug | def debug(mode=True):
""" Change the debug level.
There is only one debug level supported at the moment."""
global DEBUG
if mode: warnings.simplefilter('default')
DEBUG = bool(mode) | python | def debug(mode=True):
""" Change the debug level.
There is only one debug level supported at the moment."""
global DEBUG
if mode: warnings.simplefilter('default')
DEBUG = bool(mode) | [
"def",
"debug",
"(",
"mode",
"=",
"True",
")",
":",
"global",
"DEBUG",
"if",
"mode",
":",
"warnings",
".",
"simplefilter",
"(",
"'default'",
")",
"DEBUG",
"=",
"bool",
"(",
"mode",
")"
] | Change the debug level.
There is only one debug level supported at the moment. | [
"Change",
"the",
"debug",
"level",
".",
"There",
"is",
"only",
"one",
"debug",
"level",
"supported",
"at",
"the",
"moment",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2516-L2521 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | parse_auth | def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
user, pwd = touni(base64.b64decode(tob(data))).split(':',1)
return user, pwd... | python | def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
user, pwd = touni(base64.b64decode(tob(data))).split(':',1)
return user, pwd... | [
"def",
"parse_auth",
"(",
"header",
")",
":",
"try",
":",
"method",
",",
"data",
"=",
"header",
".",
"split",
"(",
"None",
",",
"1",
")",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'basic'",
":",
"user",
",",
"pwd",
"=",
"touni",
"(",
"base64... | Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None | [
"Parse",
"rfc2617",
"HTTP",
"authentication",
"header",
"string",
"(",
"basic",
")",
"and",
"return",
"(",
"user",
"pass",
")",
"tuple",
"or",
"None"
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2540-L2548 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | parse_range_header | def parse_range_header(header, maxlen=0):
''' Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive.'''
if not header or header[:6] != 'bytes=': return
ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
for start, ... | python | def parse_range_header(header, maxlen=0):
''' Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive.'''
if not header or header[:6] != 'bytes=': return
ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
for start, ... | [
"def",
"parse_range_header",
"(",
"header",
",",
"maxlen",
"=",
"0",
")",
":",
"if",
"not",
"header",
"or",
"header",
"[",
":",
"6",
"]",
"!=",
"'bytes='",
":",
"return",
"ranges",
"=",
"[",
"r",
".",
"split",
"(",
"'-'",
",",
"1",
")",
"for",
"r... | Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive. | [
"Yield",
"(",
"start",
"end",
")",
"ranges",
"parsed",
"from",
"a",
"HTTP",
"Range",
"header",
".",
"Skip",
"unsatisfiable",
"ranges",
".",
"The",
"end",
"index",
"is",
"non",
"-",
"inclusive",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2550-L2566 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | auth_basic | def auth_basic(check, realm="private", text="Access denied"):
''' Callback decorator to require HTTP auth (basic).
TODO: Add route(check_auth=...) parameter. '''
def decorator(func):
def wrapper(*a, **ka):
user, password = request.auth or (None, None)
if user is None or n... | python | def auth_basic(check, realm="private", text="Access denied"):
''' Callback decorator to require HTTP auth (basic).
TODO: Add route(check_auth=...) parameter. '''
def decorator(func):
def wrapper(*a, **ka):
user, password = request.auth or (None, None)
if user is None or n... | [
"def",
"auth_basic",
"(",
"check",
",",
"realm",
"=",
"\"private\"",
",",
"text",
"=",
"\"Access denied\"",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"a",
",",
"*",
"*",
"ka",
")",
":",
"user",
",",
"password",
... | Callback decorator to require HTTP auth (basic).
TODO: Add route(check_auth=...) parameter. | [
"Callback",
"decorator",
"to",
"require",
"HTTP",
"auth",
"(",
"basic",
")",
".",
"TODO",
":",
"Add",
"route",
"(",
"check_auth",
"=",
"...",
")",
"parameter",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2670-L2682 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | view | def view(tpl_name, **defaults):
''' Decorator: renders a template for a handler.
The handler can control its behavior like that:
- return a dict of template vars to fill out the template
- return something other than a dict and the view decorator will not
process the templat... | python | def view(tpl_name, **defaults):
''' Decorator: renders a template for a handler.
The handler can control its behavior like that:
- return a dict of template vars to fill out the template
- return something other than a dict and the view decorator will not
process the templat... | [
"def",
"view",
"(",
"tpl_name",
",",
"*",
"*",
"defaults",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"="... | Decorator: renders a template for a handler.
The handler can control its behavior like that:
- return a dict of template vars to fill out the template
- return something other than a dict and the view decorator will not
process the template, but return the handler result as is.
... | [
"Decorator",
":",
"renders",
"a",
"template",
"for",
"a",
"handler",
".",
"The",
"handler",
"can",
"control",
"its",
"behavior",
"like",
"that",
":"
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L3602-L3624 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Router.add | def add(self, rule, method, target, name=None):
''' Add a new rule or replace the target for an existing rule. '''
anons = 0 # Number of anonymous wildcards found
keys = [] # Names of keys
pattern = '' # Regular expression pattern with named groups
filters = [... | python | def add(self, rule, method, target, name=None):
''' Add a new rule or replace the target for an existing rule. '''
anons = 0 # Number of anonymous wildcards found
keys = [] # Names of keys
pattern = '' # Regular expression pattern with named groups
filters = [... | [
"def",
"add",
"(",
"self",
",",
"rule",
",",
"method",
",",
"target",
",",
"name",
"=",
"None",
")",
":",
"anons",
"=",
"0",
"# Number of anonymous wildcards found",
"keys",
"=",
"[",
"]",
"# Names of keys",
"pattern",
"=",
"''",
"# Regular expression pattern ... | Add a new rule or replace the target for an existing rule. | [
"Add",
"a",
"new",
"rule",
"or",
"replace",
"the",
"target",
"for",
"an",
"existing",
"rule",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L318-L386 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Router.build | def build(self, _name, *anons, **query):
''' Build an URL by filling the wildcards in a rule. '''
builder = self.builder.get(_name)
if not builder: raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons): query['anon%d'%i] = value
... | python | def build(self, _name, *anons, **query):
''' Build an URL by filling the wildcards in a rule. '''
builder = self.builder.get(_name)
if not builder: raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons): query['anon%d'%i] = value
... | [
"def",
"build",
"(",
"self",
",",
"_name",
",",
"*",
"anons",
",",
"*",
"*",
"query",
")",
":",
"builder",
"=",
"self",
".",
"builder",
".",
"get",
"(",
"_name",
")",
"if",
"not",
"builder",
":",
"raise",
"RouteBuildError",
"(",
"\"No route with that n... | Build an URL by filling the wildcards in a rule. | [
"Build",
"an",
"URL",
"by",
"filling",
"the",
"wildcards",
"in",
"a",
"rule",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L400-L409 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Router.match | def match(self, environ):
''' Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). '''
verb = environ['REQUEST_METHOD'].upper()
path = environ['PATH_INFO'] or '/'
target = None
if verb == 'HEAD':
methods = ['PROXY', verb, 'GET', 'ANY']
else:
... | python | def match(self, environ):
''' Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). '''
verb = environ['REQUEST_METHOD'].upper()
path = environ['PATH_INFO'] or '/'
target = None
if verb == 'HEAD':
methods = ['PROXY', verb, 'GET', 'ANY']
else:
... | [
"def",
"match",
"(",
"self",
",",
"environ",
")",
":",
"verb",
"=",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
".",
"upper",
"(",
")",
"path",
"=",
"environ",
"[",
"'PATH_INFO'",
"]",
"or",
"'/'",
"target",
"=",
"None",
"if",
"verb",
"==",
"'HEAD'",
":... | Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). | [
"Return",
"a",
"(",
"target",
"url_agrs",
")",
"tuple",
"or",
"raise",
"HTTPError",
"(",
"400",
"/",
"404",
"/",
"405",
")",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L411-L448 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Route.get_undecorated_callback | def get_undecorated_callback(self):
''' Return the callback. If the callback is a decorated function, try to
recover the original function. '''
func = self.callback
func = getattr(func, '__func__' if py3k else 'im_func', func)
closure_attr = '__closure__' if py3k else 'func_c... | python | def get_undecorated_callback(self):
''' Return the callback. If the callback is a decorated function, try to
recover the original function. '''
func = self.callback
func = getattr(func, '__func__' if py3k else 'im_func', func)
closure_attr = '__closure__' if py3k else 'func_c... | [
"def",
"get_undecorated_callback",
"(",
"self",
")",
":",
"func",
"=",
"self",
".",
"callback",
"func",
"=",
"getattr",
"(",
"func",
",",
"'__func__'",
"if",
"py3k",
"else",
"'im_func'",
",",
"func",
")",
"closure_attr",
"=",
"'__closure__'",
"if",
"py3k",
... | Return the callback. If the callback is a decorated function, try to
recover the original function. | [
"Return",
"the",
"callback",
".",
"If",
"the",
"callback",
"is",
"a",
"decorated",
"function",
"try",
"to",
"recover",
"the",
"original",
"function",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L537-L545 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Route.get_config | def get_config(self, key, default=None):
''' Lookup a config field and return its value, first checking the
route.config, then route.app.config.'''
for conf in (self.config, self.app.conifg):
if key in conf: return conf[key]
return default | python | def get_config(self, key, default=None):
''' Lookup a config field and return its value, first checking the
route.config, then route.app.config.'''
for conf in (self.config, self.app.conifg):
if key in conf: return conf[key]
return default | [
"def",
"get_config",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"for",
"conf",
"in",
"(",
"self",
".",
"config",
",",
"self",
".",
"app",
".",
"conifg",
")",
":",
"if",
"key",
"in",
"conf",
":",
"return",
"conf",
"[",
"key",
... | Lookup a config field and return its value, first checking the
route.config, then route.app.config. | [
"Lookup",
"a",
"config",
"field",
"and",
"return",
"its",
"value",
"first",
"checking",
"the",
"route",
".",
"config",
"then",
"route",
".",
"app",
".",
"config",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L553-L558 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Bottle.add_hook | def add_hook(self, name, func):
''' Attach a callback to a hook. Three hooks are currently implemented:
before_request
Executed once before each request. The request context is
available, but no routing has happened yet.
after_request
Exec... | python | def add_hook(self, name, func):
''' Attach a callback to a hook. Three hooks are currently implemented:
before_request
Executed once before each request. The request context is
available, but no routing has happened yet.
after_request
Exec... | [
"def",
"add_hook",
"(",
"self",
",",
"name",
",",
"func",
")",
":",
"if",
"name",
"in",
"self",
".",
"__hook_reversed",
":",
"self",
".",
"_hooks",
"[",
"name",
"]",
".",
"insert",
"(",
"0",
",",
"func",
")",
"else",
":",
"self",
".",
"_hooks",
"... | Attach a callback to a hook. Three hooks are currently implemented:
before_request
Executed once before each request. The request context is
available, but no routing has happened yet.
after_request
Executed once after each request regardless of i... | [
"Attach",
"a",
"callback",
"to",
"a",
"hook",
".",
"Three",
"hooks",
"are",
"currently",
"implemented",
":"
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L616-L630 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Bottle.remove_hook | def remove_hook(self, name, func):
''' Remove a callback from a hook. '''
if name in self._hooks and func in self._hooks[name]:
self._hooks[name].remove(func)
return True | python | def remove_hook(self, name, func):
''' Remove a callback from a hook. '''
if name in self._hooks and func in self._hooks[name]:
self._hooks[name].remove(func)
return True | [
"def",
"remove_hook",
"(",
"self",
",",
"name",
",",
"func",
")",
":",
"if",
"name",
"in",
"self",
".",
"_hooks",
"and",
"func",
"in",
"self",
".",
"_hooks",
"[",
"name",
"]",
":",
"self",
".",
"_hooks",
"[",
"name",
"]",
".",
"remove",
"(",
"fun... | Remove a callback from a hook. | [
"Remove",
"a",
"callback",
"from",
"a",
"hook",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L632-L636 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Bottle.trigger_hook | def trigger_hook(self, __name, *args, **kwargs):
''' Trigger a hook and return a list of results. '''
return [hook(*args, **kwargs) for hook in self._hooks[__name][:]] | python | def trigger_hook(self, __name, *args, **kwargs):
''' Trigger a hook and return a list of results. '''
return [hook(*args, **kwargs) for hook in self._hooks[__name][:]] | [
"def",
"trigger_hook",
"(",
"self",
",",
"__name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"hook",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"hook",
"in",
"self",
".",
"_hooks",
"[",
"__name",
"]",
"[",
... | Trigger a hook and return a list of results. | [
"Trigger",
"a",
"hook",
"and",
"return",
"a",
"list",
"of",
"results",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L638-L640 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Bottle.hook | def hook(self, name):
""" Return a decorator that attaches a callback to a hook. See
:meth:`add_hook` for details."""
def decorator(func):
self.add_hook(name, func)
return func
return decorator | python | def hook(self, name):
""" Return a decorator that attaches a callback to a hook. See
:meth:`add_hook` for details."""
def decorator(func):
self.add_hook(name, func)
return func
return decorator | [
"def",
"hook",
"(",
"self",
",",
"name",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"self",
".",
"add_hook",
"(",
"name",
",",
"func",
")",
"return",
"func",
"return",
"decorator"
] | Return a decorator that attaches a callback to a hook. See
:meth:`add_hook` for details. | [
"Return",
"a",
"decorator",
"that",
"attaches",
"a",
"callback",
"to",
"a",
"hook",
".",
"See",
":",
"meth",
":",
"add_hook",
"for",
"details",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L642-L648 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Bottle.mount | def mount(self, prefix, app, **options):
''' Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it ends in a slash,
that slash is m... | python | def mount(self, prefix, app, **options):
''' Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it ends in a slash,
that slash is m... | [
"def",
"mount",
"(",
"self",
",",
"prefix",
",",
"app",
",",
"*",
"*",
"options",
")",
":",
"if",
"isinstance",
"(",
"app",
",",
"basestring",
")",
":",
"depr",
"(",
"'Parameter order of Bottle.mount() changed.'",
",",
"True",
")",
"# 0.10",
"segments",
"=... | Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it ends in a slash,
that slash is mandatory.
:param app: an instance of :cla... | [
"Mount",
"an",
"application",
"(",
":",
"class",
":",
"Bottle",
"or",
"plain",
"WSGI",
")",
"to",
"a",
"specific",
"URL",
"prefix",
".",
"Example",
"::"
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L650-L696 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Bottle.merge | def merge(self, routes):
''' Merge the routes of another :class:`Bottle` application or a list of
:class:`Route` objects into this application. The routes keep their
'owner', meaning that the :data:`Route.app` attribute is not
changed. '''
if isinstance(routes, Bottle... | python | def merge(self, routes):
''' Merge the routes of another :class:`Bottle` application or a list of
:class:`Route` objects into this application. The routes keep their
'owner', meaning that the :data:`Route.app` attribute is not
changed. '''
if isinstance(routes, Bottle... | [
"def",
"merge",
"(",
"self",
",",
"routes",
")",
":",
"if",
"isinstance",
"(",
"routes",
",",
"Bottle",
")",
":",
"routes",
"=",
"routes",
".",
"routes",
"for",
"route",
"in",
"routes",
":",
"self",
".",
"add_route",
"(",
"route",
")"
] | Merge the routes of another :class:`Bottle` application or a list of
:class:`Route` objects into this application. The routes keep their
'owner', meaning that the :data:`Route.app` attribute is not
changed. | [
"Merge",
"the",
"routes",
"of",
"another",
":",
"class",
":",
"Bottle",
"application",
"or",
"a",
"list",
"of",
":",
"class",
":",
"Route",
"objects",
"into",
"this",
"application",
".",
"The",
"routes",
"keep",
"their",
"owner",
"meaning",
"that",
"the",
... | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L698-L706 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Bottle.reset | def reset(self, route=None):
''' Reset all routes (force plugins to be re-applied) and clear all
caches. If an ID or route object is given, only that specific route
is affected. '''
if route is None: routes = self.routes
elif isinstance(route, Route): routes = [route]
... | python | def reset(self, route=None):
''' Reset all routes (force plugins to be re-applied) and clear all
caches. If an ID or route object is given, only that specific route
is affected. '''
if route is None: routes = self.routes
elif isinstance(route, Route): routes = [route]
... | [
"def",
"reset",
"(",
"self",
",",
"route",
"=",
"None",
")",
":",
"if",
"route",
"is",
"None",
":",
"routes",
"=",
"self",
".",
"routes",
"elif",
"isinstance",
"(",
"route",
",",
"Route",
")",
":",
"routes",
"=",
"[",
"route",
"]",
"else",
":",
"... | Reset all routes (force plugins to be re-applied) and clear all
caches. If an ID or route object is given, only that specific route
is affected. | [
"Reset",
"all",
"routes",
"(",
"force",
"plugins",
"to",
"be",
"re",
"-",
"applied",
")",
"and",
"clear",
"all",
"caches",
".",
"If",
"an",
"ID",
"or",
"route",
"object",
"is",
"given",
"only",
"that",
"specific",
"route",
"is",
"affected",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L735-L745 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Bottle.add_route | def add_route(self, route):
''' Add a route object, but do not change the :data:`Route.app`
attribute.'''
self.routes.append(route)
self.router.add(route.rule, route.method, route, name=route.name)
if DEBUG: route.prepare() | python | def add_route(self, route):
''' Add a route object, but do not change the :data:`Route.app`
attribute.'''
self.routes.append(route)
self.router.add(route.rule, route.method, route, name=route.name)
if DEBUG: route.prepare() | [
"def",
"add_route",
"(",
"self",
",",
"route",
")",
":",
"self",
".",
"routes",
".",
"append",
"(",
"route",
")",
"self",
".",
"router",
".",
"add",
"(",
"route",
".",
"rule",
",",
"route",
".",
"method",
",",
"route",
",",
"name",
"=",
"route",
... | Add a route object, but do not change the :data:`Route.app`
attribute. | [
"Add",
"a",
"route",
"object",
"but",
"do",
"not",
"change",
"the",
":",
"data",
":",
"Route",
".",
"app",
"attribute",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L769-L774 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Bottle._cast | def _cast(self, out, peek=None):
""" Try to convert the parameter into something WSGI compatible and set
correct HTTP headers when possible.
Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
iterable of strings and iterable of unicodes
"""
# Empty o... | python | def _cast(self, out, peek=None):
""" Try to convert the parameter into something WSGI compatible and set
correct HTTP headers when possible.
Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
iterable of strings and iterable of unicodes
"""
# Empty o... | [
"def",
"_cast",
"(",
"self",
",",
"out",
",",
"peek",
"=",
"None",
")",
":",
"# Empty output is done here",
"if",
"not",
"out",
":",
"if",
"'Content-Length'",
"not",
"in",
"response",
":",
"response",
"[",
"'Content-Length'",
"]",
"=",
"0",
"return",
"[",
... | Try to convert the parameter into something WSGI compatible and set
correct HTTP headers when possible.
Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
iterable of strings and iterable of unicodes | [
"Try",
"to",
"convert",
"the",
"parameter",
"into",
"something",
"WSGI",
"compatible",
"and",
"set",
"correct",
"HTTP",
"headers",
"when",
"possible",
".",
"Support",
":",
"False",
"str",
"unicode",
"dict",
"HTTPResponse",
"HTTPError",
"file",
"-",
"like",
"it... | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L879-L949 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Bottle.wsgi | def wsgi(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
out = self._cast(self._handle(environ))
# rfc2616 section 4.3
if response._status_code in (100, 101, 204, 304)\
or environ['REQUEST_METHOD'] == 'HEAD':
if hasa... | python | def wsgi(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
out = self._cast(self._handle(environ))
# rfc2616 section 4.3
if response._status_code in (100, 101, 204, 304)\
or environ['REQUEST_METHOD'] == 'HEAD':
if hasa... | [
"def",
"wsgi",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"try",
":",
"out",
"=",
"self",
".",
"_cast",
"(",
"self",
".",
"_handle",
"(",
"environ",
")",
")",
"# rfc2616 section 4.3",
"if",
"response",
".",
"_status_code",
"in",
"(",
... | The bottle WSGI-interface. | [
"The",
"bottle",
"WSGI",
"-",
"interface",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L951-L975 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | BaseRequest.forms | def forms(self):
""" Form values parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The result is returned as a
:class:`FormsDict`. All keys and values are strings. File uploads
are stored separately in :attr:`files`. """
forms = F... | python | def forms(self):
""" Form values parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The result is returned as a
:class:`FormsDict`. All keys and values are strings. File uploads
are stored separately in :attr:`files`. """
forms = F... | [
"def",
"forms",
"(",
"self",
")",
":",
"forms",
"=",
"FormsDict",
"(",
")",
"for",
"name",
",",
"item",
"in",
"self",
".",
"POST",
".",
"allitems",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"FileUpload",
")",
":",
"forms",
"[",
... | Form values parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The result is returned as a
:class:`FormsDict`. All keys and values are strings. File uploads
are stored separately in :attr:`files`. | [
"Form",
"values",
"parsed",
"from",
"an",
"url",
"-",
"encoded",
"or",
"multipart",
"/",
"form",
"-",
"data",
"encoded",
"POST",
"or",
"PUT",
"request",
"body",
".",
"The",
"result",
"is",
"returned",
"as",
"a",
":",
"class",
":",
"FormsDict",
".",
"Al... | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1078-L1087 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | BaseRequest.params | def params(self):
""" A :class:`FormsDict` with the combined values of :attr:`query` and
:attr:`forms`. File uploads are stored in :attr:`files`. """
params = FormsDict()
for key, value in self.query.allitems():
params[key] = value
for key, value in self.forms.all... | python | def params(self):
""" A :class:`FormsDict` with the combined values of :attr:`query` and
:attr:`forms`. File uploads are stored in :attr:`files`. """
params = FormsDict()
for key, value in self.query.allitems():
params[key] = value
for key, value in self.forms.all... | [
"def",
"params",
"(",
"self",
")",
":",
"params",
"=",
"FormsDict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"query",
".",
"allitems",
"(",
")",
":",
"params",
"[",
"key",
"]",
"=",
"value",
"for",
"key",
",",
"value",
"in",
"self... | A :class:`FormsDict` with the combined values of :attr:`query` and
:attr:`forms`. File uploads are stored in :attr:`files`. | [
"A",
":",
"class",
":",
"FormsDict",
"with",
"the",
"combined",
"values",
"of",
":",
"attr",
":",
"query",
"and",
":",
"attr",
":",
"forms",
".",
"File",
"uploads",
"are",
"stored",
"in",
":",
"attr",
":",
"files",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1090-L1098 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | BaseRequest.files | def files(self):
""" File uploads parsed from `multipart/form-data` encoded POST or PUT
request body. The values are instances of :class:`FileUpload`.
"""
files = FormsDict()
for name, item in self.POST.allitems():
if isinstance(item, FileUpload):
... | python | def files(self):
""" File uploads parsed from `multipart/form-data` encoded POST or PUT
request body. The values are instances of :class:`FileUpload`.
"""
files = FormsDict()
for name, item in self.POST.allitems():
if isinstance(item, FileUpload):
... | [
"def",
"files",
"(",
"self",
")",
":",
"files",
"=",
"FormsDict",
"(",
")",
"for",
"name",
",",
"item",
"in",
"self",
".",
"POST",
".",
"allitems",
"(",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"FileUpload",
")",
":",
"files",
"[",
"name",
... | File uploads parsed from `multipart/form-data` encoded POST or PUT
request body. The values are instances of :class:`FileUpload`. | [
"File",
"uploads",
"parsed",
"from",
"multipart",
"/",
"form",
"-",
"data",
"encoded",
"POST",
"or",
"PUT",
"request",
"body",
".",
"The",
"values",
"are",
"instances",
"of",
":",
"class",
":",
"FileUpload",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1101-L1110 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | BaseRequest.json | def json(self):
''' If the ``Content-Type`` header is ``application/json``, this
property holds the parsed content of the request body. Only requests
smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
exhaustion. '''
ctype = self.environ.get('CONTENT_TYPE'... | python | def json(self):
''' If the ``Content-Type`` header is ``application/json``, this
property holds the parsed content of the request body. Only requests
smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
exhaustion. '''
ctype = self.environ.get('CONTENT_TYPE'... | [
"def",
"json",
"(",
"self",
")",
":",
"ctype",
"=",
"self",
".",
"environ",
".",
"get",
"(",
"'CONTENT_TYPE'",
",",
"''",
")",
".",
"lower",
"(",
")",
".",
"split",
"(",
"';'",
")",
"[",
"0",
"]",
"if",
"ctype",
"==",
"'application/json'",
":",
"... | If the ``Content-Type`` header is ``application/json``, this
property holds the parsed content of the request body. Only requests
smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
exhaustion. | [
"If",
"the",
"Content",
"-",
"Type",
"header",
"is",
"application",
"/",
"json",
"this",
"property",
"holds",
"the",
"parsed",
"content",
"of",
"the",
"request",
"body",
".",
"Only",
"requests",
"smaller",
"than",
":",
"attr",
":",
"MEMFILE_MAX",
"are",
"p... | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1113-L1124 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | BaseRequest.POST | def POST(self):
""" The values of :attr:`forms` and :attr:`files` combined into a single
:class:`FormsDict`. Values are either strings (form values) or
instances of :class:`cgi.FieldStorage` (file uploads).
"""
post = FormsDict()
# We default to application/x-www-... | python | def POST(self):
""" The values of :attr:`forms` and :attr:`files` combined into a single
:class:`FormsDict`. Values are either strings (form values) or
instances of :class:`cgi.FieldStorage` (file uploads).
"""
post = FormsDict()
# We default to application/x-www-... | [
"def",
"POST",
"(",
"self",
")",
":",
"post",
"=",
"FormsDict",
"(",
")",
"# We default to application/x-www-form-urlencoded for everything that",
"# is not multipart and take the fast path (also: 3.1 workaround)",
"if",
"not",
"self",
".",
"content_type",
".",
"startswith",
... | The values of :attr:`forms` and :attr:`files` combined into a single
:class:`FormsDict`. Values are either strings (form values) or
instances of :class:`cgi.FieldStorage` (file uploads). | [
"The",
"values",
"of",
":",
"attr",
":",
"forms",
"and",
":",
"attr",
":",
"files",
"combined",
"into",
"a",
"single",
":",
"class",
":",
"FormsDict",
".",
"Values",
"are",
"either",
"strings",
"(",
"form",
"values",
")",
"or",
"instances",
"of",
":",
... | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1209-L1241 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | BaseRequest.urlparts | def urlparts(self):
''' The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
The tuple contains (scheme, host, path, query_string and fragment),
but the fragment is always empty because it is not visible to the
server. '''
env = self.environ
http ... | python | def urlparts(self):
''' The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
The tuple contains (scheme, host, path, query_string and fragment),
but the fragment is always empty because it is not visible to the
server. '''
env = self.environ
http ... | [
"def",
"urlparts",
"(",
"self",
")",
":",
"env",
"=",
"self",
".",
"environ",
"http",
"=",
"env",
".",
"get",
"(",
"'HTTP_X_FORWARDED_PROTO'",
")",
"or",
"env",
".",
"get",
"(",
"'wsgi.url_scheme'",
",",
"'http'",
")",
"host",
"=",
"env",
".",
"get",
... | The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
The tuple contains (scheme, host, path, query_string and fragment),
but the fragment is always empty because it is not visible to the
server. | [
"The",
":",
"attr",
":",
"url",
"string",
"as",
"an",
":",
"class",
":",
"urlparse",
".",
"SplitResult",
"tuple",
".",
"The",
"tuple",
"contains",
"(",
"scheme",
"host",
"path",
"query_string",
"and",
"fragment",
")",
"but",
"the",
"fragment",
"is",
"alw... | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1252-L1267 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | BaseResponse.copy | def copy(self, cls=None):
''' Returns a copy of self. '''
cls = cls or BaseResponse
assert issubclass(cls, BaseResponse)
copy = cls()
copy.status = self.status
copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
if self._cookies:
copy._... | python | def copy(self, cls=None):
''' Returns a copy of self. '''
cls = cls or BaseResponse
assert issubclass(cls, BaseResponse)
copy = cls()
copy.status = self.status
copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
if self._cookies:
copy._... | [
"def",
"copy",
"(",
"self",
",",
"cls",
"=",
"None",
")",
":",
"cls",
"=",
"cls",
"or",
"BaseResponse",
"assert",
"issubclass",
"(",
"cls",
",",
"BaseResponse",
")",
"copy",
"=",
"cls",
"(",
")",
"copy",
".",
"status",
"=",
"self",
".",
"status",
"... | Returns a copy of self. | [
"Returns",
"a",
"copy",
"of",
"self",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1466-L1476 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | BaseResponse.set_header | def set_header(self, name, value):
''' Create a new response header, replacing any previously defined
headers with the same name. '''
self._headers[_hkey(name)] = [str(value)] | python | def set_header(self, name, value):
''' Create a new response header, replacing any previously defined
headers with the same name. '''
self._headers[_hkey(name)] = [str(value)] | [
"def",
"set_header",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"_headers",
"[",
"_hkey",
"(",
"name",
")",
"]",
"=",
"[",
"str",
"(",
"value",
")",
"]"
] | Create a new response header, replacing any previously defined
headers with the same name. | [
"Create",
"a",
"new",
"response",
"header",
"replacing",
"any",
"previously",
"defined",
"headers",
"with",
"the",
"same",
"name",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1536-L1539 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | BaseResponse.headerlist | def headerlist(self):
''' WSGI conform list of (header, value) tuples. '''
out = []
headers = list(self._headers.items())
if 'Content-Type' not in self._headers:
headers.append(('Content-Type', [self.default_content_type]))
if self._status_code in self.bad_headers:
... | python | def headerlist(self):
''' WSGI conform list of (header, value) tuples. '''
out = []
headers = list(self._headers.items())
if 'Content-Type' not in self._headers:
headers.append(('Content-Type', [self.default_content_type]))
if self._status_code in self.bad_headers:
... | [
"def",
"headerlist",
"(",
"self",
")",
":",
"out",
"=",
"[",
"]",
"headers",
"=",
"list",
"(",
"self",
".",
"_headers",
".",
"items",
"(",
")",
")",
"if",
"'Content-Type'",
"not",
"in",
"self",
".",
"_headers",
":",
"headers",
".",
"append",
"(",
"... | WSGI conform list of (header, value) tuples. | [
"WSGI",
"conform",
"list",
"of",
"(",
"header",
"value",
")",
"tuples",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1551-L1564 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | BaseResponse.charset | def charset(self, default='UTF-8'):
""" Return the charset specified in the content-type header (default: utf8). """
if 'charset=' in self.content_type:
return self.content_type.split('charset=')[-1].split(';')[0].strip()
return default | python | def charset(self, default='UTF-8'):
""" Return the charset specified in the content-type header (default: utf8). """
if 'charset=' in self.content_type:
return self.content_type.split('charset=')[-1].split(';')[0].strip()
return default | [
"def",
"charset",
"(",
"self",
",",
"default",
"=",
"'UTF-8'",
")",
":",
"if",
"'charset='",
"in",
"self",
".",
"content_type",
":",
"return",
"self",
".",
"content_type",
".",
"split",
"(",
"'charset='",
")",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"... | Return the charset specified in the content-type header (default: utf8). | [
"Return",
"the",
"charset",
"specified",
"in",
"the",
"content",
"-",
"type",
"header",
"(",
"default",
":",
"utf8",
")",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1573-L1577 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | BaseResponse.set_cookie | def set_cookie(self, name, value, secret=None, **options):
''' Create a new cookie or replace an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param name: the name of the cookie.
:param value: the value of the cookie.
:pa... | python | def set_cookie(self, name, value, secret=None, **options):
''' Create a new cookie or replace an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param name: the name of the cookie.
:param value: the value of the cookie.
:pa... | [
"def",
"set_cookie",
"(",
"self",
",",
"name",
",",
"value",
",",
"secret",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"not",
"self",
".",
"_cookies",
":",
"self",
".",
"_cookies",
"=",
"SimpleCookie",
"(",
")",
"if",
"secret",
":",
"va... | Create a new cookie or replace an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param name: the name of the cookie.
:param value: the value of the cookie.
:param secret: a signature key required for signed cookies.
A... | [
"Create",
"a",
"new",
"cookie",
"or",
"replace",
"an",
"old",
"one",
".",
"If",
"the",
"secret",
"parameter",
"is",
"set",
"create",
"a",
"Signed",
"Cookie",
"(",
"described",
"below",
")",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1579-L1633 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | FormsDict.decode | def decode(self, encoding=None):
''' Returns a copy with all keys and values de- or recoded to match
:attr:`input_encoding`. Some libraries (e.g. WTForms) want a
unicode dictionary. '''
copy = FormsDict()
enc = copy.input_encoding = encoding or self.input_encoding
... | python | def decode(self, encoding=None):
''' Returns a copy with all keys and values de- or recoded to match
:attr:`input_encoding`. Some libraries (e.g. WTForms) want a
unicode dictionary. '''
copy = FormsDict()
enc = copy.input_encoding = encoding or self.input_encoding
... | [
"def",
"decode",
"(",
"self",
",",
"encoding",
"=",
"None",
")",
":",
"copy",
"=",
"FormsDict",
"(",
")",
"enc",
"=",
"copy",
".",
"input_encoding",
"=",
"encoding",
"or",
"self",
".",
"input_encoding",
"copy",
".",
"recode_unicode",
"=",
"False",
"for",... | Returns a copy with all keys and values de- or recoded to match
:attr:`input_encoding`. Some libraries (e.g. WTForms) want a
unicode dictionary. | [
"Returns",
"a",
"copy",
"with",
"all",
"keys",
"and",
"values",
"de",
"-",
"or",
"recoded",
"to",
"match",
":",
"attr",
":",
"input_encoding",
".",
"Some",
"libraries",
"(",
"e",
".",
"g",
".",
"WTForms",
")",
"want",
"a",
"unicode",
"dictionary",
"."
... | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1900-L1909 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | FormsDict.getunicode | def getunicode(self, name, default=None, encoding=None):
''' Return the value as a unicode string, or the default. '''
try:
return self._fix(self[name], encoding)
except (UnicodeError, KeyError):
return default | python | def getunicode(self, name, default=None, encoding=None):
''' Return the value as a unicode string, or the default. '''
try:
return self._fix(self[name], encoding)
except (UnicodeError, KeyError):
return default | [
"def",
"getunicode",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"encoding",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_fix",
"(",
"self",
"[",
"name",
"]",
",",
"encoding",
")",
"except",
"(",
"UnicodeError",
",",
... | Return the value as a unicode string, or the default. | [
"Return",
"the",
"value",
"as",
"a",
"unicode",
"string",
"or",
"the",
"default",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1911-L1916 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | ConfigDict.load_config | def load_config(self, filename):
''' Load values from an *.ini style config file.
If the config file contains sections, their names are used as
namespaces for the values within. The two special sections
``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix).
... | python | def load_config(self, filename):
''' Load values from an *.ini style config file.
If the config file contains sections, their names are used as
namespaces for the values within. The two special sections
``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix).
... | [
"def",
"load_config",
"(",
"self",
",",
"filename",
")",
":",
"conf",
"=",
"ConfigParser",
"(",
")",
"conf",
".",
"read",
"(",
"filename",
")",
"for",
"section",
"in",
"conf",
".",
"sections",
"(",
")",
":",
"for",
"key",
",",
"value",
"in",
"conf",
... | Load values from an *.ini style config file.
If the config file contains sections, their names are used as
namespaces for the values within. The two special sections
``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix). | [
"Load",
"values",
"from",
"an",
"*",
".",
"ini",
"style",
"config",
"file",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2081-L2095 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | ConfigDict.load_dict | def load_dict(self, source, namespace='', make_namespaces=False):
''' Import values from a dictionary structure. Nesting can be used to
represent namespaces.
>>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}})
{'name.space.key': 'value'}
'''
sta... | python | def load_dict(self, source, namespace='', make_namespaces=False):
''' Import values from a dictionary structure. Nesting can be used to
represent namespaces.
>>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}})
{'name.space.key': 'value'}
'''
sta... | [
"def",
"load_dict",
"(",
"self",
",",
"source",
",",
"namespace",
"=",
"''",
",",
"make_namespaces",
"=",
"False",
")",
":",
"stack",
"=",
"[",
"(",
"namespace",
",",
"source",
")",
"]",
"while",
"stack",
":",
"prefix",
",",
"source",
"=",
"stack",
"... | Import values from a dictionary structure. Nesting can be used to
represent namespaces.
>>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}})
{'name.space.key': 'value'} | [
"Import",
"values",
"from",
"a",
"dictionary",
"structure",
".",
"Nesting",
"can",
"be",
"used",
"to",
"represent",
"namespaces",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2097-L2119 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | ConfigDict.meta_get | def meta_get(self, key, metafield, default=None):
''' Return the value of a meta field for a key. '''
return self._meta.get(key, {}).get(metafield, default) | python | def meta_get(self, key, metafield, default=None):
''' Return the value of a meta field for a key. '''
return self._meta.get(key, {}).get(metafield, default) | [
"def",
"meta_get",
"(",
"self",
",",
"key",
",",
"metafield",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"_meta",
".",
"get",
"(",
"key",
",",
"{",
"}",
")",
".",
"get",
"(",
"metafield",
",",
"default",
")"
] | Return the value of a meta field for a key. | [
"Return",
"the",
"value",
"of",
"a",
"meta",
"field",
"for",
"a",
"key",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2154-L2156 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | ConfigDict.meta_set | def meta_set(self, key, metafield, value):
''' Set the meta field for a key to a new value. This triggers the
on-change handler for existing keys. '''
self._meta.setdefault(key, {})[metafield] = value
if key in self:
self[key] = self[key] | python | def meta_set(self, key, metafield, value):
''' Set the meta field for a key to a new value. This triggers the
on-change handler for existing keys. '''
self._meta.setdefault(key, {})[metafield] = value
if key in self:
self[key] = self[key] | [
"def",
"meta_set",
"(",
"self",
",",
"key",
",",
"metafield",
",",
"value",
")",
":",
"self",
".",
"_meta",
".",
"setdefault",
"(",
"key",
",",
"{",
"}",
")",
"[",
"metafield",
"]",
"=",
"value",
"if",
"key",
"in",
"self",
":",
"self",
"[",
"key"... | Set the meta field for a key to a new value. This triggers the
on-change handler for existing keys. | [
"Set",
"the",
"meta",
"field",
"for",
"a",
"key",
"to",
"a",
"new",
"value",
".",
"This",
"triggers",
"the",
"on",
"-",
"change",
"handler",
"for",
"existing",
"keys",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2158-L2163 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | ResourceManager.lookup | def lookup(self, name):
''' Search for a resource and return an absolute file path, or `None`.
The :attr:`path` list is searched in order. The first match is
returend. Symlinks are followed. The result is cached to speed up
future lookups. '''
if name not in self.cac... | python | def lookup(self, name):
''' Search for a resource and return an absolute file path, or `None`.
The :attr:`path` list is searched in order. The first match is
returend. Symlinks are followed. The result is cached to speed up
future lookups. '''
if name not in self.cac... | [
"def",
"lookup",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"cache",
"or",
"DEBUG",
":",
"for",
"path",
"in",
"self",
".",
"path",
":",
"fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")"... | Search for a resource and return an absolute file path, or `None`.
The :attr:`path` list is searched in order. The first match is
returend. Symlinks are followed. The result is cached to speed up
future lookups. | [
"Search",
"for",
"a",
"resource",
"and",
"return",
"an",
"absolute",
"file",
"path",
"or",
"None",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2312-L2327 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | ResourceManager.open | def open(self, name, mode='r', *args, **kwargs):
''' Find a resource and return a file object, or raise IOError. '''
fname = self.lookup(name)
if not fname: raise IOError("Resource %r not found." % name)
return self.opener(fname, mode=mode, *args, **kwargs) | python | def open(self, name, mode='r', *args, **kwargs):
''' Find a resource and return a file object, or raise IOError. '''
fname = self.lookup(name)
if not fname: raise IOError("Resource %r not found." % name)
return self.opener(fname, mode=mode, *args, **kwargs) | [
"def",
"open",
"(",
"self",
",",
"name",
",",
"mode",
"=",
"'r'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fname",
"=",
"self",
".",
"lookup",
"(",
"name",
")",
"if",
"not",
"fname",
":",
"raise",
"IOError",
"(",
"\"Resource %r not fou... | Find a resource and return a file object, or raise IOError. | [
"Find",
"a",
"resource",
"and",
"return",
"a",
"file",
"object",
"or",
"raise",
"IOError",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2329-L2333 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | FileUpload.save | def save(self, destination, overwrite=False, chunk_size=2**16):
''' Save file to disk or copy its content to an open file(-like) object.
If *destination* is a directory, :attr:`filename` is added to the
path. Existing files are not overwritten by default (IOError).
:param de... | python | def save(self, destination, overwrite=False, chunk_size=2**16):
''' Save file to disk or copy its content to an open file(-like) object.
If *destination* is a directory, :attr:`filename` is added to the
path. Existing files are not overwritten by default (IOError).
:param de... | [
"def",
"save",
"(",
"self",
",",
"destination",
",",
"overwrite",
"=",
"False",
",",
"chunk_size",
"=",
"2",
"**",
"16",
")",
":",
"if",
"isinstance",
"(",
"destination",
",",
"basestring",
")",
":",
"# Except file-likes here",
"if",
"os",
".",
"path",
"... | Save file to disk or copy its content to an open file(-like) object.
If *destination* is a directory, :attr:`filename` is added to the
path. Existing files are not overwritten by default (IOError).
:param destination: File path, directory or file(-like) object.
:param ov... | [
"Save",
"file",
"to",
"disk",
"or",
"copy",
"its",
"content",
"to",
"an",
"open",
"file",
"(",
"-",
"like",
")",
"object",
".",
"If",
"*",
"destination",
"*",
"is",
"a",
"directory",
":",
"attr",
":",
"filename",
"is",
"added",
"to",
"the",
"path",
... | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2379-L2396 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | SimpleTemplate.render | def render(self, *args, **kwargs):
""" Render the template using keyword arguments as local variables. """
env = {}; stdout = []
for dictarg in args: env.update(dictarg)
env.update(kwargs)
self.execute(stdout, env)
return ''.join(stdout) | python | def render(self, *args, **kwargs):
""" Render the template using keyword arguments as local variables. """
env = {}; stdout = []
for dictarg in args: env.update(dictarg)
env.update(kwargs)
self.execute(stdout, env)
return ''.join(stdout) | [
"def",
"render",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"env",
"=",
"{",
"}",
"stdout",
"=",
"[",
"]",
"for",
"dictarg",
"in",
"args",
":",
"env",
".",
"update",
"(",
"dictarg",
")",
"env",
".",
"update",
"(",
"kwargs... | Render the template using keyword arguments as local variables. | [
"Render",
"the",
"template",
"using",
"keyword",
"arguments",
"as",
"local",
"variables",
"."
] | train | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L3394-L3400 |
metglobal/django-exchange | exchange/conversion.py | convert_values | def convert_values(args_list):
"""convert_value in bulk.
:param args_list: list of value, source, target currency pairs
:return: map of converted values
"""
rate_map = get_rates(map(itemgetter(1, 2), args_list))
value_map = {}
for value, source, target in args_list:
args = (value, ... | python | def convert_values(args_list):
"""convert_value in bulk.
:param args_list: list of value, source, target currency pairs
:return: map of converted values
"""
rate_map = get_rates(map(itemgetter(1, 2), args_list))
value_map = {}
for value, source, target in args_list:
args = (value, ... | [
"def",
"convert_values",
"(",
"args_list",
")",
":",
"rate_map",
"=",
"get_rates",
"(",
"map",
"(",
"itemgetter",
"(",
"1",
",",
"2",
")",
",",
"args_list",
")",
")",
"value_map",
"=",
"{",
"}",
"for",
"value",
",",
"source",
",",
"target",
"in",
"ar... | convert_value in bulk.
:param args_list: list of value, source, target currency pairs
:return: map of converted values | [
"convert_value",
"in",
"bulk",
"."
] | train | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/conversion.py#L36-L52 |
metglobal/django-exchange | exchange/conversion.py | convert_value | def convert_value(value, source_currency, target_currency):
"""Converts the price of a currency to another one using exchange rates
:param price: the price value
:param type: decimal
:param source_currency: source ISO-4217 currency code
:param type: str
:param target_currency: target ISO-4217... | python | def convert_value(value, source_currency, target_currency):
"""Converts the price of a currency to another one using exchange rates
:param price: the price value
:param type: decimal
:param source_currency: source ISO-4217 currency code
:param type: str
:param target_currency: target ISO-4217... | [
"def",
"convert_value",
"(",
"value",
",",
"source_currency",
",",
"target_currency",
")",
":",
"# If price currency and target currency is same",
"# return given currency as is",
"if",
"source_currency",
"==",
"target_currency",
":",
"return",
"value",
"rate",
"=",
"get_ra... | Converts the price of a currency to another one using exchange rates
:param price: the price value
:param type: decimal
:param source_currency: source ISO-4217 currency code
:param type: str
:param target_currency: target ISO-4217 currency code
:param type: str
:returns: converted price ... | [
"Converts",
"the",
"price",
"of",
"a",
"currency",
"to",
"another",
"one",
"using",
"exchange",
"rates"
] | train | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/conversion.py#L100-L123 |
metglobal/django-exchange | exchange/conversion.py | convert | def convert(price, currency):
"""Shorthand function converts a price object instance of a source
currency to target currency
:param price: the price value
:param type: decimal
:param currency: target ISO-4217 currency code
:param type: str
:returns: converted price instance
:rtype: ``... | python | def convert(price, currency):
"""Shorthand function converts a price object instance of a source
currency to target currency
:param price: the price value
:param type: decimal
:param currency: target ISO-4217 currency code
:param type: str
:returns: converted price instance
:rtype: ``... | [
"def",
"convert",
"(",
"price",
",",
"currency",
")",
":",
"# If price currency and target currency is same",
"# return given currency as is",
"value",
"=",
"convert_value",
"(",
"price",
".",
"value",
",",
"price",
".",
"currency",
",",
"currency",
")",
"return",
"... | Shorthand function converts a price object instance of a source
currency to target currency
:param price: the price value
:param type: decimal
:param currency: target ISO-4217 currency code
:param type: str
:returns: converted price instance
:rtype: ``Price`` | [
"Shorthand",
"function",
"converts",
"a",
"price",
"object",
"instance",
"of",
"a",
"source",
"currency",
"to",
"target",
"currency"
] | train | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/conversion.py#L126-L143 |
metglobal/django-exchange | exchange/utils.py | import_class | def import_class(class_path):
"""imports and returns given class string.
:param class_path: Class path as string
:type class_path: str
:returns: Class that has given path
:rtype: class
:Example:
>>> import_class('collections.OrderedDict').__name__
'OrderedDict'
"""
try:
... | python | def import_class(class_path):
"""imports and returns given class string.
:param class_path: Class path as string
:type class_path: str
:returns: Class that has given path
:rtype: class
:Example:
>>> import_class('collections.OrderedDict').__name__
'OrderedDict'
"""
try:
... | [
"def",
"import_class",
"(",
"class_path",
")",
":",
"try",
":",
"from",
"django",
".",
"utils",
".",
"importlib",
"import",
"import_module",
"module_name",
"=",
"'.'",
".",
"join",
"(",
"class_path",
".",
"split",
"(",
"\".\"",
")",
"[",
":",
"-",
"1",
... | imports and returns given class string.
:param class_path: Class path as string
:type class_path: str
:returns: Class that has given path
:rtype: class
:Example:
>>> import_class('collections.OrderedDict').__name__
'OrderedDict' | [
"imports",
"and",
"returns",
"given",
"class",
"string",
"."
] | train | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/utils.py#L5-L25 |
metglobal/django-exchange | exchange/utils.py | insert_many | def insert_many(objects, using="default"):
"""Insert list of Django objects in one SQL query. Objects must be
of the same Django model. Note that save is not called and signals
on the model are not raised.
Mostly from: http://people.iola.dk/olau/python/bulkops.py
"""
if not objects:
ret... | python | def insert_many(objects, using="default"):
"""Insert list of Django objects in one SQL query. Objects must be
of the same Django model. Note that save is not called and signals
on the model are not raised.
Mostly from: http://people.iola.dk/olau/python/bulkops.py
"""
if not objects:
ret... | [
"def",
"insert_many",
"(",
"objects",
",",
"using",
"=",
"\"default\"",
")",
":",
"if",
"not",
"objects",
":",
"return",
"import",
"django",
".",
"db",
".",
"models",
"from",
"django",
".",
"db",
"import",
"connections",
"from",
"django",
".",
"db",
"imp... | Insert list of Django objects in one SQL query. Objects must be
of the same Django model. Note that save is not called and signals
on the model are not raised.
Mostly from: http://people.iola.dk/olau/python/bulkops.py | [
"Insert",
"list",
"of",
"Django",
"objects",
"in",
"one",
"SQL",
"query",
".",
"Objects",
"must",
"be",
"of",
"the",
"same",
"Django",
"model",
".",
"Note",
"that",
"save",
"is",
"not",
"called",
"and",
"signals",
"on",
"the",
"model",
"are",
"not",
"r... | train | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/utils.py#L28-L57 |
metglobal/django-exchange | exchange/utils.py | update_many | def update_many(objects, fields=[], using="default"):
"""Update list of Django objects in one SQL query, optionally only
overwrite the given fields (as names, e.g. fields=["foo"]).
Objects must be of the same Django model. Note that save is not
called and signals on the model are not raised.
Mostly... | python | def update_many(objects, fields=[], using="default"):
"""Update list of Django objects in one SQL query, optionally only
overwrite the given fields (as names, e.g. fields=["foo"]).
Objects must be of the same Django model. Note that save is not
called and signals on the model are not raised.
Mostly... | [
"def",
"update_many",
"(",
"objects",
",",
"fields",
"=",
"[",
"]",
",",
"using",
"=",
"\"default\"",
")",
":",
"if",
"not",
"objects",
":",
"return",
"import",
"django",
".",
"db",
".",
"models",
"from",
"django",
".",
"db",
"import",
"connections",
"... | Update list of Django objects in one SQL query, optionally only
overwrite the given fields (as names, e.g. fields=["foo"]).
Objects must be of the same Django model. Note that save is not
called and signals on the model are not raised.
Mostly from: http://people.iola.dk/olau/python/bulkops.py | [
"Update",
"list",
"of",
"Django",
"objects",
"in",
"one",
"SQL",
"query",
"optionally",
"only",
"overwrite",
"the",
"given",
"fields",
"(",
"as",
"names",
"e",
".",
"g",
".",
"fields",
"=",
"[",
"foo",
"]",
")",
".",
"Objects",
"must",
"be",
"of",
"t... | train | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/utils.py#L60-L98 |
metglobal/django-exchange | exchange/utils.py | memoize | def memoize(ttl=None):
""" Cache the result of the function call with given args for until
ttl (datetime.timedelta) expires.
"""
def decorator(obj):
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
now = datetime.now()
key =... | python | def memoize(ttl=None):
""" Cache the result of the function call with given args for until
ttl (datetime.timedelta) expires.
"""
def decorator(obj):
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
now = datetime.now()
key =... | [
"def",
"memoize",
"(",
"ttl",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"obj",
")",
":",
"cache",
"=",
"obj",
".",
"cache",
"=",
"{",
"}",
"@",
"functools",
".",
"wraps",
"(",
"obj",
")",
"def",
"memoizer",
"(",
"*",
"args",
",",
"*",
"*"... | Cache the result of the function call with given args for until
ttl (datetime.timedelta) expires. | [
"Cache",
"the",
"result",
"of",
"the",
"function",
"call",
"with",
"given",
"args",
"for",
"until",
"ttl",
"(",
"datetime",
".",
"timedelta",
")",
"expires",
"."
] | train | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/utils.py#L101-L119 |
liip/taxi | taxi/timesheet/timesheet.py | round_to_quarter | def round_to_quarter(start_time, end_time):
"""
Return the duration between `start_time` and `end_time` :class:`datetime.time` objects, rounded to 15 minutes.
"""
# We don't care about the date (only about the time) but Python
# can substract only datetime objects, not time ones
today = datetime... | python | def round_to_quarter(start_time, end_time):
"""
Return the duration between `start_time` and `end_time` :class:`datetime.time` objects, rounded to 15 minutes.
"""
# We don't care about the date (only about the time) but Python
# can substract only datetime objects, not time ones
today = datetime... | [
"def",
"round_to_quarter",
"(",
"start_time",
",",
"end_time",
")",
":",
"# We don't care about the date (only about the time) but Python",
"# can substract only datetime objects, not time ones",
"today",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"start_date",
"="... | Return the duration between `start_time` and `end_time` :class:`datetime.time` objects, rounded to 15 minutes. | [
"Return",
"the",
"duration",
"between",
"start_time",
"and",
"end_time",
":",
"class",
":",
"datetime",
".",
"time",
"objects",
"rounded",
"to",
"15",
"minutes",
"."
] | train | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/timesheet.py#L19-L36 |
liip/taxi | taxi/timesheet/timesheet.py | TimesheetCollection._timesheets_callback | def _timesheets_callback(self, callback):
"""
Call a method on all the timesheets, aggregate the return values in a
list and return it.
"""
def call(*args, **kwargs):
return_values = []
for timesheet in self:
attr = getattr(timesheet, call... | python | def _timesheets_callback(self, callback):
"""
Call a method on all the timesheets, aggregate the return values in a
list and return it.
"""
def call(*args, **kwargs):
return_values = []
for timesheet in self:
attr = getattr(timesheet, call... | [
"def",
"_timesheets_callback",
"(",
"self",
",",
"callback",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return_values",
"=",
"[",
"]",
"for",
"timesheet",
"in",
"self",
":",
"attr",
"=",
"getattr",
"(",
"timesheet",
... | Call a method on all the timesheets, aggregate the return values in a
list and return it. | [
"Call",
"a",
"method",
"on",
"all",
"the",
"timesheets",
"aggregate",
"the",
"return",
"values",
"in",
"a",
"list",
"and",
"return",
"it",
"."
] | train | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/timesheet.py#L202-L222 |
liip/taxi | taxi/timesheet/timesheet.py | TimesheetCollection.load | def load(cls, file_pattern, nb_previous_files=1, parser=None):
"""
Load a collection of timesheet from the given `file_pattern`. `file_pattern` is a path to a timesheet file that
will be expanded with :func:`datetime.date.strftime` and the current date. `nb_previous_files` is the number of
... | python | def load(cls, file_pattern, nb_previous_files=1, parser=None):
"""
Load a collection of timesheet from the given `file_pattern`. `file_pattern` is a path to a timesheet file that
will be expanded with :func:`datetime.date.strftime` and the current date. `nb_previous_files` is the number of
... | [
"def",
"load",
"(",
"cls",
",",
"file_pattern",
",",
"nb_previous_files",
"=",
"1",
",",
"parser",
"=",
"None",
")",
":",
"if",
"not",
"parser",
":",
"parser",
"=",
"TimesheetParser",
"(",
")",
"timesheet_files",
"=",
"cls",
".",
"get_files",
"(",
"file_... | Load a collection of timesheet from the given `file_pattern`. `file_pattern` is a path to a timesheet file that
will be expanded with :func:`datetime.date.strftime` and the current date. `nb_previous_files` is the number of
other timesheets to load, depending on `file_pattern` this will result in either... | [
"Load",
"a",
"collection",
"of",
"timesheet",
"from",
"the",
"given",
"file_pattern",
".",
"file_pattern",
"is",
"a",
"path",
"to",
"a",
"timesheet",
"file",
"that",
"will",
"be",
"expanded",
"with",
":",
"func",
":",
"datetime",
".",
"date",
".",
"strftim... | train | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/timesheet.py#L225-L264 |
liip/taxi | taxi/timesheet/timesheet.py | TimesheetCollection.get_files | def get_files(cls, file_pattern, nb_previous_files, from_date=None):
"""
Return an :class:`~taxi.utils.structures.OrderedSet` of file paths expanded from `filename`, with a maximum of
`nb_previous_files`. See :func:`taxi.utils.file.expand_date` for more information about filename expansion. If
... | python | def get_files(cls, file_pattern, nb_previous_files, from_date=None):
"""
Return an :class:`~taxi.utils.structures.OrderedSet` of file paths expanded from `filename`, with a maximum of
`nb_previous_files`. See :func:`taxi.utils.file.expand_date` for more information about filename expansion. If
... | [
"def",
"get_files",
"(",
"cls",
",",
"file_pattern",
",",
"nb_previous_files",
",",
"from_date",
"=",
"None",
")",
":",
"date_units",
"=",
"[",
"'m'",
",",
"'Y'",
"]",
"smallest_unit",
"=",
"None",
"if",
"not",
"from_date",
":",
"from_date",
"=",
"datetime... | Return an :class:`~taxi.utils.structures.OrderedSet` of file paths expanded from `filename`, with a maximum of
`nb_previous_files`. See :func:`taxi.utils.file.expand_date` for more information about filename expansion. If
`from_date` is set, it will be used as a starting date instead of the current date... | [
"Return",
"an",
":",
"class",
":",
"~taxi",
".",
"utils",
".",
"structures",
".",
"OrderedSet",
"of",
"file",
"paths",
"expanded",
"from",
"filename",
"with",
"a",
"maximum",
"of",
"nb_previous_files",
".",
"See",
":",
"func",
":",
"taxi",
".",
"utils",
... | train | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/timesheet.py#L267-L297 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.