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 |
|---|---|---|---|---|---|---|---|---|---|---|
retr0h/git-url-parse | giturlparse/parser.py | Parser.parse | def parse(self):
"""
Parses a GIT URL and returns an object. Raises an exception on invalid
URL.
:returns: Parsed object
:raise: :class:`.ParserError`
"""
d = {
'pathname': None,
'protocols': self._get_protocols(),
'protocol':... | python | def parse(self):
"""
Parses a GIT URL and returns an object. Raises an exception on invalid
URL.
:returns: Parsed object
:raise: :class:`.ParserError`
"""
d = {
'pathname': None,
'protocols': self._get_protocols(),
'protocol':... | [
"def",
"parse",
"(",
"self",
")",
":",
"d",
"=",
"{",
"'pathname'",
":",
"None",
",",
"'protocols'",
":",
"self",
".",
"_get_protocols",
"(",
")",
",",
"'protocol'",
":",
"'ssh'",
",",
"'href'",
":",
"self",
".",
"_url",
",",
"'resource'",
":",
"None... | Parses a GIT URL and returns an object. Raises an exception on invalid
URL.
:returns: Parsed object
:raise: :class:`.ParserError` | [
"Parses",
"a",
"GIT",
"URL",
"and",
"returns",
"an",
"object",
".",
"Raises",
"an",
"exception",
"on",
"invalid",
"URL",
"."
] | train | https://github.com/retr0h/git-url-parse/blob/98a5377aa8c8f3b8896f277c5c81558749feef58/giturlparse/parser.py#L78-L106 |
bachya/pypollencom | pypollencom/client.py | Client._request | async def _request(
self,
method: str,
url: str,
*,
headers: dict = None,
params: dict = None,
json: dict = None) -> dict:
"""Make a request against AirVisual."""
full_url = '{0}/{1}'.format(url, self.zip_code)
p... | python | async def _request(
self,
method: str,
url: str,
*,
headers: dict = None,
params: dict = None,
json: dict = None) -> dict:
"""Make a request against AirVisual."""
full_url = '{0}/{1}'.format(url, self.zip_code)
p... | [
"async",
"def",
"_request",
"(",
"self",
",",
"method",
":",
"str",
",",
"url",
":",
"str",
",",
"*",
",",
"headers",
":",
"dict",
"=",
"None",
",",
"params",
":",
"dict",
"=",
"None",
",",
"json",
":",
"dict",
"=",
"None",
")",
"->",
"dict",
"... | Make a request against AirVisual. | [
"Make",
"a",
"request",
"against",
"AirVisual",
"."
] | train | https://github.com/bachya/pypollencom/blob/d1616a8471b350953d4f99f5a1dddca035977366/pypollencom/client.py#L28-L56 |
LandRegistry/lr-utils | lrutils/errorhandler/errorhandler_utils.py | setup_errors | def setup_errors(app, error_template="error.html"):
"""Add a handler for each of the available HTTP error responses."""
def error_handler(error):
if isinstance(error, HTTPException):
description = error.get_description(request.environ)
code = error.code
name = error.n... | python | def setup_errors(app, error_template="error.html"):
"""Add a handler for each of the available HTTP error responses."""
def error_handler(error):
if isinstance(error, HTTPException):
description = error.get_description(request.environ)
code = error.code
name = error.n... | [
"def",
"setup_errors",
"(",
"app",
",",
"error_template",
"=",
"\"error.html\"",
")",
":",
"def",
"error_handler",
"(",
"error",
")",
":",
"if",
"isinstance",
"(",
"error",
",",
"HTTPException",
")",
":",
"description",
"=",
"error",
".",
"get_description",
... | Add a handler for each of the available HTTP error responses. | [
"Add",
"a",
"handler",
"for",
"each",
"of",
"the",
"available",
"HTTP",
"error",
"responses",
"."
] | train | https://github.com/LandRegistry/lr-utils/blob/811c9e5c11678a04ee203fa55a7c75080f4f9d89/lrutils/errorhandler/errorhandler_utils.py#L40-L58 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.domain_search | def domain_search(self, domain=None, company=None, limit=None, offset=None,
emails_type=None, raw=False):
"""
Return all the email addresses found for a given domain.
:param domain: The domain on which to search for emails. Must be
defined if company is not.
... | python | def domain_search(self, domain=None, company=None, limit=None, offset=None,
emails_type=None, raw=False):
"""
Return all the email addresses found for a given domain.
:param domain: The domain on which to search for emails. Must be
defined if company is not.
... | [
"def",
"domain_search",
"(",
"self",
",",
"domain",
"=",
"None",
",",
"company",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"emails_type",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"if",
"not",
"domain",
"and",
... | Return all the email addresses found for a given domain.
:param domain: The domain on which to search for emails. Must be
defined if company is not.
:param company: The name of the company on which to search for emails.
Must be defined if domain is not.
:param limit: The maxim... | [
"Return",
"all",
"the",
"email",
"addresses",
"found",
"for",
"a",
"given",
"domain",
"."
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L32-L76 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.email_finder | def email_finder(self, domain=None, company=None, first_name=None,
last_name=None, full_name=None, raw=False):
"""
Find the email address of a person given its name and company's domain.
:param domain: The domain of the company where the person works. Must
be define... | python | def email_finder(self, domain=None, company=None, first_name=None,
last_name=None, full_name=None, raw=False):
"""
Find the email address of a person given its name and company's domain.
:param domain: The domain of the company where the person works. Must
be define... | [
"def",
"email_finder",
"(",
"self",
",",
"domain",
"=",
"None",
",",
"company",
"=",
"None",
",",
"first_name",
"=",
"None",
",",
"last_name",
"=",
"None",
",",
"full_name",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"params",
"=",
"self",
".",... | Find the email address of a person given its name and company's domain.
:param domain: The domain of the company where the person works. Must
be defined if company is not.
:param company: The name of the company where the person works. Must
be defined if domain is not.
:param ... | [
"Find",
"the",
"email",
"address",
"of",
"a",
"person",
"given",
"its",
"name",
"and",
"company",
"s",
"domain",
"."
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L78-L134 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.email_verifier | def email_verifier(self, email, raw=False):
"""
Verify the deliverability of a given email adress.abs
:param email: The email adress to check.
:param raw: Gives back the entire response instead of just the 'data'.
:return: Full payload of the query as a dict.
"""
... | python | def email_verifier(self, email, raw=False):
"""
Verify the deliverability of a given email adress.abs
:param email: The email adress to check.
:param raw: Gives back the entire response instead of just the 'data'.
:return: Full payload of the query as a dict.
"""
... | [
"def",
"email_verifier",
"(",
"self",
",",
"email",
",",
"raw",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'email'",
":",
"email",
",",
"'api_key'",
":",
"self",
".",
"api_key",
"}",
"endpoint",
"=",
"self",
".",
"base_endpoint",
".",
"format",
"(",
... | Verify the deliverability of a given email adress.abs
:param email: The email adress to check.
:param raw: Gives back the entire response instead of just the 'data'.
:return: Full payload of the query as a dict. | [
"Verify",
"the",
"deliverability",
"of",
"a",
"given",
"email",
"adress",
".",
"abs"
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L136-L150 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.email_count | def email_count(self, domain=None, company=None, raw=False):
"""
Give back the number of email adresses Hunter has for this domain/company.
:param domain: The domain of the company where the person works. Must
be defined if company is not. If both 'domain' and 'company' are given,
... | python | def email_count(self, domain=None, company=None, raw=False):
"""
Give back the number of email adresses Hunter has for this domain/company.
:param domain: The domain of the company where the person works. Must
be defined if company is not. If both 'domain' and 'company' are given,
... | [
"def",
"email_count",
"(",
"self",
",",
"domain",
"=",
"None",
",",
"company",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"params",
"=",
"self",
".",
"base_params",
"if",
"not",
"domain",
"and",
"not",
"company",
":",
"raise",
"MissingCompanyError"... | Give back the number of email adresses Hunter has for this domain/company.
:param domain: The domain of the company where the person works. Must
be defined if company is not. If both 'domain' and 'company' are given,
the 'domain' will be used.
:param company: The name of the company wh... | [
"Give",
"back",
"the",
"number",
"of",
"email",
"adresses",
"Hunter",
"has",
"for",
"this",
"domain",
"/",
"company",
"."
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L152-L181 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.account_information | def account_information(self, raw=False):
"""
Gives the information about the account associated with the api_key.
:param raw: Gives back the entire response instead of just the 'data'.
:return: Full payload of the query as a dict.
"""
params = self.base_params
... | python | def account_information(self, raw=False):
"""
Gives the information about the account associated with the api_key.
:param raw: Gives back the entire response instead of just the 'data'.
:return: Full payload of the query as a dict.
"""
params = self.base_params
... | [
"def",
"account_information",
"(",
"self",
",",
"raw",
"=",
"False",
")",
":",
"params",
"=",
"self",
".",
"base_params",
"endpoint",
"=",
"self",
".",
"base_endpoint",
".",
"format",
"(",
"'account'",
")",
"res",
"=",
"self",
".",
"_query_hunter",
"(",
... | Gives the information about the account associated with the api_key.
:param raw: Gives back the entire response instead of just the 'data'.
:return: Full payload of the query as a dict. | [
"Gives",
"the",
"information",
"about",
"the",
"account",
"associated",
"with",
"the",
"api_key",
"."
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L183-L201 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.get_leads | def get_leads(self, offset=None, limit=None, lead_list_id=None,
first_name=None, last_name=None, email=None, company=None,
phone_number=None, twitter=None):
"""
Gives back all the leads saved in your account.
:param offset: Number of leads to skip.
:... | python | def get_leads(self, offset=None, limit=None, lead_list_id=None,
first_name=None, last_name=None, email=None, company=None,
phone_number=None, twitter=None):
"""
Gives back all the leads saved in your account.
:param offset: Number of leads to skip.
:... | [
"def",
"get_leads",
"(",
"self",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"lead_list_id",
"=",
"None",
",",
"first_name",
"=",
"None",
",",
"last_name",
"=",
"None",
",",
"email",
"=",
"None",
",",
"company",
"=",
"None",
",",
"pho... | Gives back all the leads saved in your account.
:param offset: Number of leads to skip.
:param limit: Maximum number of leads to return.
:param lead_list_id: Id of a lead list to query leads on.
:param first_name: First name to filter on.
:param last_name: Last name to filte... | [
"Gives",
"back",
"all",
"the",
"leads",
"saved",
"in",
"your",
"account",
"."
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L203-L239 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.get_lead | def get_lead(self, lead_id):
"""
Get a specific lead saved on your account.
:param lead_id: Id of the lead to search. Must be defined.
:return: Lead found as a dict.
"""
params = self.base_params
endpoint = self.base_endpoint.format('leads/' + str(lead_id))
... | python | def get_lead(self, lead_id):
"""
Get a specific lead saved on your account.
:param lead_id: Id of the lead to search. Must be defined.
:return: Lead found as a dict.
"""
params = self.base_params
endpoint = self.base_endpoint.format('leads/' + str(lead_id))
... | [
"def",
"get_lead",
"(",
"self",
",",
"lead_id",
")",
":",
"params",
"=",
"self",
".",
"base_params",
"endpoint",
"=",
"self",
".",
"base_endpoint",
".",
"format",
"(",
"'leads/'",
"+",
"str",
"(",
"lead_id",
")",
")",
"return",
"self",
".",
"_query_hunte... | Get a specific lead saved on your account.
:param lead_id: Id of the lead to search. Must be defined.
:return: Lead found as a dict. | [
"Get",
"a",
"specific",
"lead",
"saved",
"on",
"your",
"account",
"."
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L241-L253 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.create_lead | def create_lead(self, first_name, last_name, email=None, position=None,
company=None, company_industry=None, company_size=None,
confidence_score=None, website=None, country_code=None,
postal_code=None, source=None, linkedin_url=None,
phone_... | python | def create_lead(self, first_name, last_name, email=None, position=None,
company=None, company_industry=None, company_size=None,
confidence_score=None, website=None, country_code=None,
postal_code=None, source=None, linkedin_url=None,
phone_... | [
"def",
"create_lead",
"(",
"self",
",",
"first_name",
",",
"last_name",
",",
"email",
"=",
"None",
",",
"position",
"=",
"None",
",",
"company",
"=",
"None",
",",
"company_industry",
"=",
"None",
",",
"company_size",
"=",
"None",
",",
"confidence_score",
"... | Create a lead on your account.
:param first_name: The first name of the lead to create. Must be
defined.
:param last_name: The last name of the lead to create. Must be defined.
:param email: The email of the lead to create.
:param position: The professional position of the le... | [
"Create",
"a",
"lead",
"on",
"your",
"account",
"."
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L255-L309 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.get_leads_lists | def get_leads_lists(self, offset=None, limit=None):
"""
Gives back all the leads lists saved on your account.
:param offset: Number of lists to skip.
:param limit: Maximum number of lists to return.
:return: Leads lists found as a dict.
"""
params = self.base_p... | python | def get_leads_lists(self, offset=None, limit=None):
"""
Gives back all the leads lists saved on your account.
:param offset: Number of lists to skip.
:param limit: Maximum number of lists to return.
:return: Leads lists found as a dict.
"""
params = self.base_p... | [
"def",
"get_leads_lists",
"(",
"self",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"base_params",
"if",
"offset",
":",
"params",
"[",
"'offset'",
"]",
"=",
"offset",
"if",
"limit",
":",
"params",
"[",
... | Gives back all the leads lists saved on your account.
:param offset: Number of lists to skip.
:param limit: Maximum number of lists to return.
:return: Leads lists found as a dict. | [
"Gives",
"back",
"all",
"the",
"leads",
"lists",
"saved",
"on",
"your",
"account",
"."
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L385-L404 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.create_leads_list | def create_leads_list(self, name, team_id=None):
"""
Create a leads list.
:param name: Name of the list to create. Must be defined.
:param team_id: The id of the list to share this list with.
:return: The created leads list as a dict.
"""
params = self.base_par... | python | def create_leads_list(self, name, team_id=None):
"""
Create a leads list.
:param name: Name of the list to create. Must be defined.
:param team_id: The id of the list to share this list with.
:return: The created leads list as a dict.
"""
params = self.base_par... | [
"def",
"create_leads_list",
"(",
"self",
",",
"name",
",",
"team_id",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"base_params",
"payload",
"=",
"{",
"'name'",
":",
"name",
"}",
"if",
"team_id",
":",
"payload",
"[",
"'team_id'",
"]",
"=",
"team_... | Create a leads list.
:param name: Name of the list to create. Must be defined.
:param team_id: The id of the list to share this list with.
:return: The created leads list as a dict. | [
"Create",
"a",
"leads",
"list",
"."
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L423-L441 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.update_leads_list | def update_leads_list(self, leads_list_id, name, team_id=None):
"""
Update a leads list.
:param name: Name of the list to update. Must be defined.
:param team_id: The id of the list to share this list with.
:return: 204 Response.
"""
params = self.base_params
... | python | def update_leads_list(self, leads_list_id, name, team_id=None):
"""
Update a leads list.
:param name: Name of the list to update. Must be defined.
:param team_id: The id of the list to share this list with.
:return: 204 Response.
"""
params = self.base_params
... | [
"def",
"update_leads_list",
"(",
"self",
",",
"leads_list_id",
",",
"name",
",",
"team_id",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"base_params",
"payload",
"=",
"{",
"'name'",
":",
"name",
"}",
"if",
"team_id",
":",
"payload",
"[",
"'team_id... | Update a leads list.
:param name: Name of the list to update. Must be defined.
:param team_id: The id of the list to share this list with.
:return: 204 Response. | [
"Update",
"a",
"leads",
"list",
"."
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L443-L461 |
VonStruddle/PyHunter | pyhunter/pyhunter.py | PyHunter.delete_leads_list | def delete_leads_list(self, leads_list_id):
"""
Delete a leads list.
:param leads_list_id: The id of the list to delete.
:return: 204 Response.
"""
params = self.base_params
endpoint = self.base_endpoint.format(
'leads_lists/' +
str(lead... | python | def delete_leads_list(self, leads_list_id):
"""
Delete a leads list.
:param leads_list_id: The id of the list to delete.
:return: 204 Response.
"""
params = self.base_params
endpoint = self.base_endpoint.format(
'leads_lists/' +
str(lead... | [
"def",
"delete_leads_list",
"(",
"self",
",",
"leads_list_id",
")",
":",
"params",
"=",
"self",
".",
"base_params",
"endpoint",
"=",
"self",
".",
"base_endpoint",
".",
"format",
"(",
"'leads_lists/'",
"+",
"str",
"(",
"leads_list_id",
")",
")",
"return",
"se... | Delete a leads list.
:param leads_list_id: The id of the list to delete.
:return: 204 Response. | [
"Delete",
"a",
"leads",
"list",
"."
] | train | https://github.com/VonStruddle/PyHunter/blob/e14882d22527102515458cddeb8e0aa1c02da549/pyhunter/pyhunter.py#L463-L478 |
mfussenegger/cr8 | cr8/cli.py | to_int | def to_int(s):
""" converts a string to an integer
>>> to_int('1_000_000')
1000000
>>> to_int('1e6')
1000000
>>> to_int('1000')
1000
"""
try:
return int(s.replace('_', ''))
except ValueError:
return int(ast.literal_eval(s)) | python | def to_int(s):
""" converts a string to an integer
>>> to_int('1_000_000')
1000000
>>> to_int('1e6')
1000000
>>> to_int('1000')
1000
"""
try:
return int(s.replace('_', ''))
except ValueError:
return int(ast.literal_eval(s)) | [
"def",
"to_int",
"(",
"s",
")",
":",
"try",
":",
"return",
"int",
"(",
"s",
".",
"replace",
"(",
"'_'",
",",
"''",
")",
")",
"except",
"ValueError",
":",
"return",
"int",
"(",
"ast",
".",
"literal_eval",
"(",
"s",
")",
")"
] | converts a string to an integer
>>> to_int('1_000_000')
1000000
>>> to_int('1e6')
1000000
>>> to_int('1000')
1000 | [
"converts",
"a",
"string",
"to",
"an",
"integer"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/cli.py#L8-L23 |
mfussenegger/cr8 | cr8/cli.py | dicts_from_lines | def dicts_from_lines(lines):
""" returns a generator producing dicts from json lines
1 JSON object per line is supported:
{"name": "n1"}
{"name": "n2"}
Or 1 JSON object:
{
"name": "n1"
}
Or a list of JSON objects:
[
{"name": "n1"},
... | python | def dicts_from_lines(lines):
""" returns a generator producing dicts from json lines
1 JSON object per line is supported:
{"name": "n1"}
{"name": "n2"}
Or 1 JSON object:
{
"name": "n1"
}
Or a list of JSON objects:
[
{"name": "n1"},
... | [
"def",
"dicts_from_lines",
"(",
"lines",
")",
":",
"lines",
"=",
"iter",
"(",
"lines",
")",
"for",
"line",
"in",
"lines",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not",
"line",
":",
"continue",
"# skip empty lines",
"try",
":",
"yield",... | returns a generator producing dicts from json lines
1 JSON object per line is supported:
{"name": "n1"}
{"name": "n2"}
Or 1 JSON object:
{
"name": "n1"
}
Or a list of JSON objects:
[
{"name": "n1"},
{"name": "n2"},
] | [
"returns",
"a",
"generator",
"producing",
"dicts",
"from",
"json",
"lines"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/cli.py#L35-L69 |
jaraco/jaraco.functools | jaraco/functools.py | compose | def compose(*funcs):
"""
Compose any number of unary functions into a single unary function.
>>> import textwrap
>>> from six import text_type
>>> stripped = text_type.strip(textwrap.dedent(compose.__doc__))
>>> compose(text_type.strip, textwrap.dedent)(compose.__doc__) == stripped
True
Compose also allows th... | python | def compose(*funcs):
"""
Compose any number of unary functions into a single unary function.
>>> import textwrap
>>> from six import text_type
>>> stripped = text_type.strip(textwrap.dedent(compose.__doc__))
>>> compose(text_type.strip, textwrap.dedent)(compose.__doc__) == stripped
True
Compose also allows th... | [
"def",
"compose",
"(",
"*",
"funcs",
")",
":",
"def",
"compose_two",
"(",
"f1",
",",
"f2",
")",
":",
"return",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"f1",
"(",
"f2",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
... | Compose any number of unary functions into a single unary function.
>>> import textwrap
>>> from six import text_type
>>> stripped = text_type.strip(textwrap.dedent(compose.__doc__))
>>> compose(text_type.strip, textwrap.dedent)(compose.__doc__) == stripped
True
Compose also allows the innermost function to tak... | [
"Compose",
"any",
"number",
"of",
"unary",
"functions",
"into",
"a",
"single",
"unary",
"function",
"."
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L31-L51 |
jaraco/jaraco.functools | jaraco/functools.py | method_caller | def method_caller(method_name, *args, **kwargs):
"""
Return a function that will call a named method on the
target object with optional positional and keyword
arguments.
>>> lower = method_caller('lower')
>>> lower('MyString')
'mystring'
"""
def call_method(target):
func = getattr(target, method_name)
ret... | python | def method_caller(method_name, *args, **kwargs):
"""
Return a function that will call a named method on the
target object with optional positional and keyword
arguments.
>>> lower = method_caller('lower')
>>> lower('MyString')
'mystring'
"""
def call_method(target):
func = getattr(target, method_name)
ret... | [
"def",
"method_caller",
"(",
"method_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"call_method",
"(",
"target",
")",
":",
"func",
"=",
"getattr",
"(",
"target",
",",
"method_name",
")",
"return",
"func",
"(",
"*",
"args",
",",
"... | Return a function that will call a named method on the
target object with optional positional and keyword
arguments.
>>> lower = method_caller('lower')
>>> lower('MyString')
'mystring' | [
"Return",
"a",
"function",
"that",
"will",
"call",
"a",
"named",
"method",
"on",
"the",
"target",
"object",
"with",
"optional",
"positional",
"and",
"keyword",
"arguments",
"."
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L54-L67 |
jaraco/jaraco.functools | jaraco/functools.py | once | def once(func):
"""
Decorate func so it's only ever called the first time.
This decorator can ensure that an expensive or non-idempotent function
will not be expensive on subsequent calls and is idempotent.
>>> add_three = once(lambda a: a+3)
>>> add_three(3)
6
>>> add_three(9)
6
>>> add_three('12')
6
To... | python | def once(func):
"""
Decorate func so it's only ever called the first time.
This decorator can ensure that an expensive or non-idempotent function
will not be expensive on subsequent calls and is idempotent.
>>> add_three = once(lambda a: a+3)
>>> add_three(3)
6
>>> add_three(9)
6
>>> add_three('12')
6
To... | [
"def",
"once",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"wrapper",
",",
"'saved_result'",
")",
":",
"wrapper",
".",
... | Decorate func so it's only ever called the first time.
This decorator can ensure that an expensive or non-idempotent function
will not be expensive on subsequent calls and is idempotent.
>>> add_three = once(lambda a: a+3)
>>> add_three(3)
6
>>> add_three(9)
6
>>> add_three('12')
6
To reset the stored valu... | [
"Decorate",
"func",
"so",
"it",
"s",
"only",
"ever",
"called",
"the",
"first",
"time",
"."
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L70-L107 |
jaraco/jaraco.functools | jaraco/functools.py | method_cache | def method_cache(method, cache_wrapper=None):
"""
Wrap lru_cache to support storing the cache data in the object instances.
Abstracts the common paradigm where the method explicitly saves an
underscore-prefixed protected property on first call and returns that
subsequently.
>>> class MyClass:
... calls = 0... | python | def method_cache(method, cache_wrapper=None):
"""
Wrap lru_cache to support storing the cache data in the object instances.
Abstracts the common paradigm where the method explicitly saves an
underscore-prefixed protected property on first call and returns that
subsequently.
>>> class MyClass:
... calls = 0... | [
"def",
"method_cache",
"(",
"method",
",",
"cache_wrapper",
"=",
"None",
")",
":",
"cache_wrapper",
"=",
"cache_wrapper",
"or",
"lru_cache",
"(",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# it's the first cal... | Wrap lru_cache to support storing the cache data in the object instances.
Abstracts the common paradigm where the method explicitly saves an
underscore-prefixed protected property on first call and returns that
subsequently.
>>> class MyClass:
... calls = 0
...
... @method_cache
... def method(sel... | [
"Wrap",
"lru_cache",
"to",
"support",
"storing",
"the",
"cache",
"data",
"in",
"the",
"object",
"instances",
"."
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L110-L181 |
jaraco/jaraco.functools | jaraco/functools.py | _special_method_cache | def _special_method_cache(method, cache_wrapper):
"""
Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://github.com/jaraco/... | python | def _special_method_cache(method, cache_wrapper):
"""
Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://github.com/jaraco/... | [
"def",
"_special_method_cache",
"(",
"method",
",",
"cache_wrapper",
")",
":",
"name",
"=",
"method",
".",
"__name__",
"special_names",
"=",
"'__getattr__'",
",",
"'__getitem__'",
"if",
"name",
"not",
"in",
"special_names",
":",
"return",
"wrapper_name",
"=",
"'... | Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://github.com/jaraco/jaraco.functools/issues/5 | [
"Because",
"Python",
"treats",
"special",
"methods",
"differently",
"it",
"s",
"not",
"possible",
"to",
"use",
"instance",
"attributes",
"to",
"implement",
"the",
"cached",
"methods",
"."
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L184-L211 |
jaraco/jaraco.functools | jaraco/functools.py | result_invoke | def result_invoke(action):
r"""
Decorate a function with an action function that is
invoked on the results returned from the decorated
function (for its side-effect), then return the original
result.
>>> @result_invoke(print)
... def add_two(a, b):
... return a + b
>>> x = add_two(2, 3)
5
"""
def wrap(... | python | def result_invoke(action):
r"""
Decorate a function with an action function that is
invoked on the results returned from the decorated
function (for its side-effect), then return the original
result.
>>> @result_invoke(print)
... def add_two(a, b):
... return a + b
>>> x = add_two(2, 3)
5
"""
def wrap(... | [
"def",
"result_invoke",
"(",
"action",
")",
":",
"def",
"wrap",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"func",
"(",
"*",
"args... | r"""
Decorate a function with an action function that is
invoked on the results returned from the decorated
function (for its side-effect), then return the original
result.
>>> @result_invoke(print)
... def add_two(a, b):
... return a + b
>>> x = add_two(2, 3)
5 | [
"r",
"Decorate",
"a",
"function",
"with",
"an",
"action",
"function",
"that",
"is",
"invoked",
"on",
"the",
"results",
"returned",
"from",
"the",
"decorated",
"function",
"(",
"for",
"its",
"side",
"-",
"effect",
")",
"then",
"return",
"the",
"original",
"... | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L230-L250 |
jaraco/jaraco.functools | jaraco/functools.py | first_invoke | def first_invoke(func1, func2):
"""
Return a function that when invoked will invoke func1 without
any parameters (for its side-effect) and then invoke func2
with whatever parameters were passed, returning its result.
"""
def wrapper(*args, **kwargs):
func1()
return func2(*args, **kwargs)
return wrapper | python | def first_invoke(func1, func2):
"""
Return a function that when invoked will invoke func1 without
any parameters (for its side-effect) and then invoke func2
with whatever parameters were passed, returning its result.
"""
def wrapper(*args, **kwargs):
func1()
return func2(*args, **kwargs)
return wrapper | [
"def",
"first_invoke",
"(",
"func1",
",",
"func2",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func1",
"(",
")",
"return",
"func2",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | Return a function that when invoked will invoke func1 without
any parameters (for its side-effect) and then invoke func2
with whatever parameters were passed, returning its result. | [
"Return",
"a",
"function",
"that",
"when",
"invoked",
"will",
"invoke",
"func1",
"without",
"any",
"parameters",
"(",
"for",
"its",
"side",
"-",
"effect",
")",
"and",
"then",
"invoke",
"func2",
"with",
"whatever",
"parameters",
"were",
"passed",
"returning",
... | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L302-L311 |
jaraco/jaraco.functools | jaraco/functools.py | retry_call | def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
"""
Given a callable func, trap the indicated exceptions
for up to 'retries' times, invoking cleanup on the
exception. On the final attempt, allow any exceptions
to propagate.
"""
attempts = count() if retries == float('inf') else range(retries)
fo... | python | def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
"""
Given a callable func, trap the indicated exceptions
for up to 'retries' times, invoking cleanup on the
exception. On the final attempt, allow any exceptions
to propagate.
"""
attempts = count() if retries == float('inf') else range(retries)
fo... | [
"def",
"retry_call",
"(",
"func",
",",
"cleanup",
"=",
"lambda",
":",
"None",
",",
"retries",
"=",
"0",
",",
"trap",
"=",
"(",
")",
")",
":",
"attempts",
"=",
"count",
"(",
")",
"if",
"retries",
"==",
"float",
"(",
"'inf'",
")",
"else",
"range",
... | Given a callable func, trap the indicated exceptions
for up to 'retries' times, invoking cleanup on the
exception. On the final attempt, allow any exceptions
to propagate. | [
"Given",
"a",
"callable",
"func",
"trap",
"the",
"indicated",
"exceptions",
"for",
"up",
"to",
"retries",
"times",
"invoking",
"cleanup",
"on",
"the",
"exception",
".",
"On",
"the",
"final",
"attempt",
"allow",
"any",
"exceptions",
"to",
"propagate",
"."
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L314-L328 |
jaraco/jaraco.functools | jaraco/functools.py | retry | def retry(*r_args, **r_kwargs):
"""
Decorator wrapper for retry_call. Accepts arguments to retry_call
except func and then returns a decorator for the decorated function.
Ex:
>>> @retry(retries=3)
... def my_func(a, b):
... "this is my funk"
... print(a, b)
>>> my_func.__doc__
'this is my funk'
"""... | python | def retry(*r_args, **r_kwargs):
"""
Decorator wrapper for retry_call. Accepts arguments to retry_call
except func and then returns a decorator for the decorated function.
Ex:
>>> @retry(retries=3)
... def my_func(a, b):
... "this is my funk"
... print(a, b)
>>> my_func.__doc__
'this is my funk'
"""... | [
"def",
"retry",
"(",
"*",
"r_args",
",",
"*",
"*",
"r_kwargs",
")",
":",
"def",
"decorate",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"f_args",
",",
"*",
"*",
"f_kwargs",
")",
":",
"bound... | Decorator wrapper for retry_call. Accepts arguments to retry_call
except func and then returns a decorator for the decorated function.
Ex:
>>> @retry(retries=3)
... def my_func(a, b):
... "this is my funk"
... print(a, b)
>>> my_func.__doc__
'this is my funk' | [
"Decorator",
"wrapper",
"for",
"retry_call",
".",
"Accepts",
"arguments",
"to",
"retry_call",
"except",
"func",
"and",
"then",
"returns",
"a",
"decorator",
"for",
"the",
"decorated",
"function",
"."
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L331-L351 |
jaraco/jaraco.functools | jaraco/functools.py | print_yielded | def print_yielded(func):
"""
Convert a generator into a function that prints all yielded elements
>>> @print_yielded
... def x():
... yield 3; yield None
>>> x()
3
None
"""
print_all = functools.partial(map, print)
print_results = compose(more_itertools.recipes.consume, print_all, func)
return functool... | python | def print_yielded(func):
"""
Convert a generator into a function that prints all yielded elements
>>> @print_yielded
... def x():
... yield 3; yield None
>>> x()
3
None
"""
print_all = functools.partial(map, print)
print_results = compose(more_itertools.recipes.consume, print_all, func)
return functool... | [
"def",
"print_yielded",
"(",
"func",
")",
":",
"print_all",
"=",
"functools",
".",
"partial",
"(",
"map",
",",
"print",
")",
"print_results",
"=",
"compose",
"(",
"more_itertools",
".",
"recipes",
".",
"consume",
",",
"print_all",
",",
"func",
")",
"return... | Convert a generator into a function that prints all yielded elements
>>> @print_yielded
... def x():
... yield 3; yield None
>>> x()
3
None | [
"Convert",
"a",
"generator",
"into",
"a",
"function",
"that",
"prints",
"all",
"yielded",
"elements"
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L354-L367 |
jaraco/jaraco.functools | jaraco/functools.py | pass_none | def pass_none(func):
"""
Wrap func so it's not called if its first param is None
>>> print_text = pass_none(print)
>>> print_text('text')
text
>>> print_text(None)
"""
@functools.wraps(func)
def wrapper(param, *args, **kwargs):
if param is not None:
return func(param, *args, **kwargs)
return wrapper | python | def pass_none(func):
"""
Wrap func so it's not called if its first param is None
>>> print_text = pass_none(print)
>>> print_text('text')
text
>>> print_text(None)
"""
@functools.wraps(func)
def wrapper(param, *args, **kwargs):
if param is not None:
return func(param, *args, **kwargs)
return wrapper | [
"def",
"pass_none",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"param",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"param",
"is",
"not",
"None",
":",
"return",
"func",
"(",
"par... | Wrap func so it's not called if its first param is None
>>> print_text = pass_none(print)
>>> print_text('text')
text
>>> print_text(None) | [
"Wrap",
"func",
"so",
"it",
"s",
"not",
"called",
"if",
"its",
"first",
"param",
"is",
"None"
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L370-L383 |
jaraco/jaraco.functools | jaraco/functools.py | assign_params | def assign_params(func, namespace):
"""
Assign parameters from namespace where func solicits.
>>> def func(x, y=3):
... print(x, y)
>>> assigned = assign_params(func, dict(x=2, z=4))
>>> assigned()
2 3
The usual errors are raised if a function doesn't receive
its required parameters:
>>> assigned = ass... | python | def assign_params(func, namespace):
"""
Assign parameters from namespace where func solicits.
>>> def func(x, y=3):
... print(x, y)
>>> assigned = assign_params(func, dict(x=2, z=4))
>>> assigned()
2 3
The usual errors are raised if a function doesn't receive
its required parameters:
>>> assigned = ass... | [
"def",
"assign_params",
"(",
"func",
",",
"namespace",
")",
":",
"try",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"params",
"=",
"sig",
".",
"parameters",
".",
"keys",
"(",
")",
"except",
"AttributeError",
":",
"spec",
"=",
"inspe... | Assign parameters from namespace where func solicits.
>>> def func(x, y=3):
... print(x, y)
>>> assigned = assign_params(func, dict(x=2, z=4))
>>> assigned()
2 3
The usual errors are raised if a function doesn't receive
its required parameters:
>>> assigned = assign_params(func, dict(y=3, z=4))
>>> assi... | [
"Assign",
"parameters",
"from",
"namespace",
"where",
"func",
"solicits",
"."
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L386-L423 |
jaraco/jaraco.functools | jaraco/functools.py | save_method_args | def save_method_args(method):
"""
Wrap a method such that when it is called, the args and kwargs are
saved on the method.
>>> class MyClass:
... @save_method_args
... def method(self, a, b):
... print(a, b)
>>> my_ob = MyClass()
>>> my_ob.method(1, 2)
1 2
>>> my_ob._saved_method.args
(1, 2)... | python | def save_method_args(method):
"""
Wrap a method such that when it is called, the args and kwargs are
saved on the method.
>>> class MyClass:
... @save_method_args
... def method(self, a, b):
... print(a, b)
>>> my_ob = MyClass()
>>> my_ob.method(1, 2)
1 2
>>> my_ob._saved_method.args
(1, 2)... | [
"def",
"save_method_args",
"(",
"method",
")",
":",
"args_and_kwargs",
"=",
"collections",
".",
"namedtuple",
"(",
"'args_and_kwargs'",
",",
"'args kwargs'",
")",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"a... | Wrap a method such that when it is called, the args and kwargs are
saved on the method.
>>> class MyClass:
... @save_method_args
... def method(self, a, b):
... print(a, b)
>>> my_ob = MyClass()
>>> my_ob.method(1, 2)
1 2
>>> my_ob._saved_method.args
(1, 2)
>>> my_ob._saved_method.kwargs
{}... | [
"Wrap",
"a",
"method",
"such",
"that",
"when",
"it",
"is",
"called",
"the",
"args",
"and",
"kwargs",
"are",
"saved",
"on",
"the",
"method",
"."
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L426-L468 |
jaraco/jaraco.functools | jaraco/functools.py | Throttler._wait | def _wait(self):
"ensure at least 1/max_rate seconds from last call"
elapsed = time.time() - self.last_called
must_wait = 1 / self.max_rate - elapsed
time.sleep(max(0, must_wait))
self.last_called = time.time() | python | def _wait(self):
"ensure at least 1/max_rate seconds from last call"
elapsed = time.time() - self.last_called
must_wait = 1 / self.max_rate - elapsed
time.sleep(max(0, must_wait))
self.last_called = time.time() | [
"def",
"_wait",
"(",
"self",
")",
":",
"elapsed",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"last_called",
"must_wait",
"=",
"1",
"/",
"self",
".",
"max_rate",
"-",
"elapsed",
"time",
".",
"sleep",
"(",
"max",
"(",
"0",
",",
"must_wait"... | ensure at least 1/max_rate seconds from last call | [
"ensure",
"at",
"least",
"1",
"/",
"max_rate",
"seconds",
"from",
"last",
"call"
] | train | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L291-L296 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/utils.py | row_col_maker | def row_col_maker(app, fromdocname, all_needs, need_info, need_key, make_ref=False, ref_lookup=False, prefix=''):
"""
Creates and returns a column.
:param app: current sphinx app
:param fromdocname: current document
:param all_needs: Dictionary of all need objects
:param need_info: need_info ob... | python | def row_col_maker(app, fromdocname, all_needs, need_info, need_key, make_ref=False, ref_lookup=False, prefix=''):
"""
Creates and returns a column.
:param app: current sphinx app
:param fromdocname: current document
:param all_needs: Dictionary of all need objects
:param need_info: need_info ob... | [
"def",
"row_col_maker",
"(",
"app",
",",
"fromdocname",
",",
"all_needs",
",",
"need_info",
",",
"need_key",
",",
"make_ref",
"=",
"False",
",",
"ref_lookup",
"=",
"False",
",",
"prefix",
"=",
"''",
")",
":",
"row_col",
"=",
"nodes",
".",
"entry",
"(",
... | Creates and returns a column.
:param app: current sphinx app
:param fromdocname: current document
:param all_needs: Dictionary of all need objects
:param need_info: need_info object, which stores all related need data
:param need_key: The key to access the needed data from need_info
:param make... | [
"Creates",
"and",
"returns",
"a",
"column",
"."
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/utils.py#L18-L78 |
mfussenegger/cr8 | cr8/insert_blob.py | insert_blob | def insert_blob(filename, hosts=None, table=None):
"""Upload a file into a blob table """
conn = connect(hosts)
container = conn.get_blob_container(table)
with open(filename, 'rb') as f:
digest = container.put(f)
return '{server}/_blobs/{table}/{digest}'.format(
server=conn.client.ac... | python | def insert_blob(filename, hosts=None, table=None):
"""Upload a file into a blob table """
conn = connect(hosts)
container = conn.get_blob_container(table)
with open(filename, 'rb') as f:
digest = container.put(f)
return '{server}/_blobs/{table}/{digest}'.format(
server=conn.client.ac... | [
"def",
"insert_blob",
"(",
"filename",
",",
"hosts",
"=",
"None",
",",
"table",
"=",
"None",
")",
":",
"conn",
"=",
"connect",
"(",
"hosts",
")",
"container",
"=",
"conn",
".",
"get_blob_container",
"(",
"table",
")",
"with",
"open",
"(",
"filename",
"... | Upload a file into a blob table | [
"Upload",
"a",
"file",
"into",
"a",
"blob",
"table"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/insert_blob.py#L15-L25 |
nickmckay/LiPD-utilities | Python/lipd/fetch_doi.py | update_dois | def update_dois(csv_source, write_file=True):
"""
Get DOI publication info for a batch of DOIs. This is LiPD-independent and only requires a CSV file with all DOIs
listed in a single column. The output is LiPD-formatted publication data for each entry.
:param str csv_source: Local path to CSV file
... | python | def update_dois(csv_source, write_file=True):
"""
Get DOI publication info for a batch of DOIs. This is LiPD-independent and only requires a CSV file with all DOIs
listed in a single column. The output is LiPD-formatted publication data for each entry.
:param str csv_source: Local path to CSV file
... | [
"def",
"update_dois",
"(",
"csv_source",
",",
"write_file",
"=",
"True",
")",
":",
"_dois_arr",
"=",
"[",
"]",
"_dois_raw",
"=",
"[",
"]",
"# open the CSV file",
"with",
"open",
"(",
"csv_source",
",",
"\"r\"",
")",
"as",
"f",
":",
"reader",
"=",
"csv",
... | Get DOI publication info for a batch of DOIs. This is LiPD-independent and only requires a CSV file with all DOIs
listed in a single column. The output is LiPD-formatted publication data for each entry.
:param str csv_source: Local path to CSV file
:param bool write_file: Write output data to JSON file (Tr... | [
"Get",
"DOI",
"publication",
"info",
"for",
"a",
"batch",
"of",
"DOIs",
".",
"This",
"is",
"LiPD",
"-",
"independent",
"and",
"only",
"requires",
"a",
"CSV",
"file",
"with",
"all",
"DOIs",
"listed",
"in",
"a",
"single",
"column",
".",
"The",
"output",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/fetch_doi.py#L10-L42 |
nickmckay/LiPD-utilities | Python/lipd/fetch_doi.py | write_json_to_file | def write_json_to_file(json_data, filename="metadata"):
"""
Write all JSON in python dictionary to a new json file.
:param any json_data: JSON data
:param str filename: Target filename (defaults to 'metadata.jsonld')
:return None:
"""
# Use demjson to maintain unicode characters in output
... | python | def write_json_to_file(json_data, filename="metadata"):
"""
Write all JSON in python dictionary to a new json file.
:param any json_data: JSON data
:param str filename: Target filename (defaults to 'metadata.jsonld')
:return None:
"""
# Use demjson to maintain unicode characters in output
... | [
"def",
"write_json_to_file",
"(",
"json_data",
",",
"filename",
"=",
"\"metadata\"",
")",
":",
"# Use demjson to maintain unicode characters in output",
"json_bin",
"=",
"demjson",
".",
"encode",
"(",
"json_data",
",",
"encoding",
"=",
"'utf-8'",
",",
"compactly",
"="... | Write all JSON in python dictionary to a new json file.
:param any json_data: JSON data
:param str filename: Target filename (defaults to 'metadata.jsonld')
:return None: | [
"Write",
"all",
"JSON",
"in",
"python",
"dictionary",
"to",
"a",
"new",
"json",
"file",
".",
":",
"param",
"any",
"json_data",
":",
"JSON",
"data",
":",
"param",
"str",
"filename",
":",
"Target",
"filename",
"(",
"defaults",
"to",
"metadata",
".",
"jsonl... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/fetch_doi.py#L45-L59 |
nickmckay/LiPD-utilities | Python/lipd/fetch_doi.py | compile_authors | def compile_authors(authors):
"""
Compiles authors "Last, First" into a single list
:param list authors: Raw author data retrieved from doi.org
:return list: Author objects
"""
author_list = []
for person in authors:
author_list.append({'name': person['family'] + ", " + person['given... | python | def compile_authors(authors):
"""
Compiles authors "Last, First" into a single list
:param list authors: Raw author data retrieved from doi.org
:return list: Author objects
"""
author_list = []
for person in authors:
author_list.append({'name': person['family'] + ", " + person['given... | [
"def",
"compile_authors",
"(",
"authors",
")",
":",
"author_list",
"=",
"[",
"]",
"for",
"person",
"in",
"authors",
":",
"author_list",
".",
"append",
"(",
"{",
"'name'",
":",
"person",
"[",
"'family'",
"]",
"+",
"\", \"",
"+",
"person",
"[",
"'given'",
... | Compiles authors "Last, First" into a single list
:param list authors: Raw author data retrieved from doi.org
:return list: Author objects | [
"Compiles",
"authors",
"Last",
"First",
"into",
"a",
"single",
"list",
":",
"param",
"list",
"authors",
":",
"Raw",
"author",
"data",
"retrieved",
"from",
"doi",
".",
"org",
":",
"return",
"list",
":",
"Author",
"objects"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/fetch_doi.py#L86-L95 |
nickmckay/LiPD-utilities | Python/lipd/fetch_doi.py | compile_fetch | def compile_fetch(raw, doi_id):
"""
Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict:
"""
fetch_dict = OrderedDict()
order = {'author': 'author', 'type': 'type', 'identifier': '', 'title': 'title'... | python | def compile_fetch(raw, doi_id):
"""
Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict:
"""
fetch_dict = OrderedDict()
order = {'author': 'author', 'type': 'type', 'identifier': '', 'title': 'title'... | [
"def",
"compile_fetch",
"(",
"raw",
",",
"doi_id",
")",
":",
"fetch_dict",
"=",
"OrderedDict",
"(",
")",
"order",
"=",
"{",
"'author'",
":",
"'author'",
",",
"'type'",
":",
"'type'",
",",
"'identifier'",
":",
"''",
",",
"'title'",
":",
"'title'",
",",
... | Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict: | [
"Loop",
"over",
"Raw",
"and",
"add",
"selected",
"items",
"to",
"Fetch",
"with",
"proper",
"formatting",
":",
"param",
"dict",
"raw",
":",
"JSON",
"data",
"from",
"doi",
".",
"org",
":",
"param",
"str",
"doi_id",
":",
":",
"return",
"dict",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/fetch_doi.py#L98-L122 |
nickmckay/LiPD-utilities | Python/lipd/fetch_doi.py | get_data | def get_data(doi_id):
"""
Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary
"""
fetch_dict = {}
try:
# Send request to grab metadata at URL
print("Requesting : {}"... | python | def get_data(doi_id):
"""
Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary
"""
fetch_dict = {}
try:
# Send request to grab metadata at URL
print("Requesting : {}"... | [
"def",
"get_data",
"(",
"doi_id",
")",
":",
"fetch_dict",
"=",
"{",
"}",
"try",
":",
"# Send request to grab metadata at URL",
"print",
"(",
"\"Requesting : {}\"",
".",
"format",
"(",
"doi_id",
")",
")",
"url",
"=",
"\"http://dx.doi.org/\"",
"+",
"doi_id",
"head... | Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary | [
"Resolve",
"DOI",
"and",
"compile",
"all",
"attributes",
"into",
"one",
"dictionary",
":",
"param",
"str",
"doi_id",
":",
":",
"param",
"int",
"idx",
":",
"Publication",
"index",
":",
"return",
"dict",
":",
"Updated",
"publication",
"dictionary"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/fetch_doi.py#L124-L162 |
nickmckay/LiPD-utilities | Python/lipd/fetch_doi.py | clean_doi | def clean_doi(doi_string):
"""
Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids.
"""
regex = re.compile(r'\b(10[.][0-9]{3,}... | python | def clean_doi(doi_string):
"""
Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids.
"""
regex = re.compile(r'\b(10[.][0-9]{3,}... | [
"def",
"clean_doi",
"(",
"doi_string",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'\\b(10[.][0-9]{3,}(?:[.][0-9]+)*/(?:(?![\"&\\'<>,])\\S)+)\\b'",
")",
"try",
":",
"# Returns a list of matching strings",
"m",
"=",
"re",
".",
"findall",
"(",
"regex",
",",
"... | Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids. | [
"Use",
"regex",
"to",
"extract",
"all",
"DOI",
"ids",
"from",
"string",
"(",
"i",
".",
"e",
".",
"10",
".",
"1029",
"/",
"2005pa001215",
")"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/fetch_doi.py#L165-L180 |
nickmckay/LiPD-utilities | Python/lipd/loggers.py | log_benchmark | def log_benchmark(fn, start, end):
"""
Log a given function and how long the function takes in seconds
:param str fn: Function name
:param float start: Function start time
:param float end: Function end time
:return none:
"""
elapsed = round(end - start, 2)
line = ("Benchmark - Funct... | python | def log_benchmark(fn, start, end):
"""
Log a given function and how long the function takes in seconds
:param str fn: Function name
:param float start: Function start time
:param float end: Function end time
:return none:
"""
elapsed = round(end - start, 2)
line = ("Benchmark - Funct... | [
"def",
"log_benchmark",
"(",
"fn",
",",
"start",
",",
"end",
")",
":",
"elapsed",
"=",
"round",
"(",
"end",
"-",
"start",
",",
"2",
")",
"line",
"=",
"(",
"\"Benchmark - Function: {} , Time: {} seconds\"",
".",
"format",
"(",
"fn",
",",
"elapsed",
")",
"... | Log a given function and how long the function takes in seconds
:param str fn: Function name
:param float start: Function start time
:param float end: Function end time
:return none: | [
"Log",
"a",
"given",
"function",
"and",
"how",
"long",
"the",
"function",
"takes",
"in",
"seconds",
":",
"param",
"str",
"fn",
":",
"Function",
"name",
":",
"param",
"float",
"start",
":",
"Function",
"start",
"time",
":",
"param",
"float",
"end",
":",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/loggers.py#L7-L17 |
nickmckay/LiPD-utilities | Python/lipd/loggers.py | update_changelog | def update_changelog():
"""
Create or update the changelog txt file. Prompt for update description.
:return None:
"""
# description = input("Please enter a short description for this update:\n ")
description = 'Placeholder for description here.'
# open changelog file for appending. if doesn... | python | def update_changelog():
"""
Create or update the changelog txt file. Prompt for update description.
:return None:
"""
# description = input("Please enter a short description for this update:\n ")
description = 'Placeholder for description here.'
# open changelog file for appending. if doesn... | [
"def",
"update_changelog",
"(",
")",
":",
"# description = input(\"Please enter a short description for this update:\\n \")",
"description",
"=",
"'Placeholder for description here.'",
"# open changelog file for appending. if doesn't exist, creates file.",
"with",
"open",
"(",
"'changelog.... | Create or update the changelog txt file. Prompt for update description.
:return None: | [
"Create",
"or",
"update",
"the",
"changelog",
"txt",
"file",
".",
"Prompt",
"for",
"update",
"description",
".",
":",
"return",
"None",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/loggers.py#L20-L32 |
nickmckay/LiPD-utilities | Python/lipd/loggers.py | create_benchmark | def create_benchmark(name, log_file, level=logging.INFO):
"""
Creates a logger for function benchmark times
:param str name: Name of the logger
:param str log_file: Filename
:return obj: Logger
"""
handler = logging.FileHandler(log_file)
rtf_handler = RotatingFileHandler(log_file, maxByt... | python | def create_benchmark(name, log_file, level=logging.INFO):
"""
Creates a logger for function benchmark times
:param str name: Name of the logger
:param str log_file: Filename
:return obj: Logger
"""
handler = logging.FileHandler(log_file)
rtf_handler = RotatingFileHandler(log_file, maxByt... | [
"def",
"create_benchmark",
"(",
"name",
",",
"log_file",
",",
"level",
"=",
"logging",
".",
"INFO",
")",
":",
"handler",
"=",
"logging",
".",
"FileHandler",
"(",
"log_file",
")",
"rtf_handler",
"=",
"RotatingFileHandler",
"(",
"log_file",
",",
"maxBytes",
"=... | Creates a logger for function benchmark times
:param str name: Name of the logger
:param str log_file: Filename
:return obj: Logger | [
"Creates",
"a",
"logger",
"for",
"function",
"benchmark",
"times",
":",
"param",
"str",
"name",
":",
"Name",
"of",
"the",
"logger",
":",
"param",
"str",
"log_file",
":",
"Filename",
":",
"return",
"obj",
":",
"Logger"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/loggers.py#L35-L50 |
nickmckay/LiPD-utilities | Python/lipd/loggers.py | create_logger | def create_logger(name):
"""
Creates a logger with the below attributes.
:param str name: Name of the logger
:return obj: Logger
"""
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'forma... | python | def create_logger(name):
"""
Creates a logger with the below attributes.
:param str name: Name of the logger
:return obj: Logger
"""
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'forma... | [
"def",
"create_logger",
"(",
"name",
")",
":",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"{",
"'version'",
":",
"1",
",",
"'disable_existing_loggers'",
":",
"False",
",",
"'formatters'",
":",
"{",
"'simple'",
":",
"{",
"'format'",
":",
"'%(asctime)s ... | Creates a logger with the below attributes.
:param str name: Name of the logger
:return obj: Logger | [
"Creates",
"a",
"logger",
"with",
"the",
"below",
"attributes",
".",
":",
"param",
"str",
"name",
":",
"Name",
"of",
"the",
"logger",
":",
"return",
"obj",
":",
"Logger"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/loggers.py#L53-L100 |
mfussenegger/cr8 | cr8/timeit.py | timeit | def timeit(hosts=None,
stmt=None,
warmup=30,
repeat=None,
duration=None,
concurrency=1,
output_fmt=None,
fail_if=None,
sample_mode='reservoir'):
"""Run the given statement a number of times and return the runtime stats
Args... | python | def timeit(hosts=None,
stmt=None,
warmup=30,
repeat=None,
duration=None,
concurrency=1,
output_fmt=None,
fail_if=None,
sample_mode='reservoir'):
"""Run the given statement a number of times and return the runtime stats
Args... | [
"def",
"timeit",
"(",
"hosts",
"=",
"None",
",",
"stmt",
"=",
"None",
",",
"warmup",
"=",
"30",
",",
"repeat",
"=",
"None",
",",
"duration",
"=",
"None",
",",
"concurrency",
"=",
"1",
",",
"output_fmt",
"=",
"None",
",",
"fail_if",
"=",
"None",
","... | Run the given statement a number of times and return the runtime stats
Args:
fail-if: An expression that causes cr8 to exit with a failure if it
evaluates to true.
The expression can contain formatting expressions for:
- runtime_stats
- statement
... | [
"Run",
"the",
"given",
"statement",
"a",
"number",
"of",
"times",
"and",
"return",
"the",
"runtime",
"stats"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/timeit.py#L28-L70 |
nickmckay/LiPD-utilities | Python/lipd/retreive_dataset.py | get_download_path | def get_download_path():
"""
Determine the OS and the associated download folder.
:return str Download path:
"""
if os.name == 'nt':
import winreg
sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
downloads_guid = '{374DE290-123F-4565-9164-39C4925E... | python | def get_download_path():
"""
Determine the OS and the associated download folder.
:return str Download path:
"""
if os.name == 'nt':
import winreg
sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
downloads_guid = '{374DE290-123F-4565-9164-39C4925E... | [
"def",
"get_download_path",
"(",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"import",
"winreg",
"sub_key",
"=",
"r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'",
"downloads_guid",
"=",
"'{374DE290-123F-4565-9164-39C4925E467B}'",
"with",
... | Determine the OS and the associated download folder.
:return str Download path: | [
"Determine",
"the",
"OS",
"and",
"the",
"associated",
"download",
"folder",
".",
":",
"return",
"str",
"Download",
"path",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/retreive_dataset.py#L405-L418 |
nickmckay/LiPD-utilities | Python/lipd/retreive_dataset.py | download_file | def download_file(src_url, dst_path):
"""
Use the given URL and destination to download and save a file
:param str src_url: Direct URL to lipd file download
:param str dst_path: Local path to download file to, including filename and ext. ex. /path/to/filename.lpd
:return none:
"""
if "MD9821... | python | def download_file(src_url, dst_path):
"""
Use the given URL and destination to download and save a file
:param str src_url: Direct URL to lipd file download
:param str dst_path: Local path to download file to, including filename and ext. ex. /path/to/filename.lpd
:return none:
"""
if "MD9821... | [
"def",
"download_file",
"(",
"src_url",
",",
"dst_path",
")",
":",
"if",
"\"MD982181\"",
"not",
"in",
"src_url",
":",
"try",
":",
"print",
"(",
"\"downloading file from url...\"",
")",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"src_url",
",",
"dst_pat... | Use the given URL and destination to download and save a file
:param str src_url: Direct URL to lipd file download
:param str dst_path: Local path to download file to, including filename and ext. ex. /path/to/filename.lpd
:return none: | [
"Use",
"the",
"given",
"URL",
"and",
"destination",
"to",
"download",
"and",
"save",
"a",
"file",
":",
"param",
"str",
"src_url",
":",
"Direct",
"URL",
"to",
"lipd",
"file",
"download",
":",
"param",
"str",
"dst_path",
":",
"Local",
"path",
"to",
"downlo... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/retreive_dataset.py#L421-L434 |
mfussenegger/cr8 | cr8/run_crate.py | wait_until | def wait_until(predicate, timeout=30):
"""Wait until predicate returns a truthy value or the timeout is reached.
>>> wait_until(lambda: True, timeout=10)
"""
not_expired = Timeout(timeout)
while not_expired():
r = predicate()
if r:
break | python | def wait_until(predicate, timeout=30):
"""Wait until predicate returns a truthy value or the timeout is reached.
>>> wait_until(lambda: True, timeout=10)
"""
not_expired = Timeout(timeout)
while not_expired():
r = predicate()
if r:
break | [
"def",
"wait_until",
"(",
"predicate",
",",
"timeout",
"=",
"30",
")",
":",
"not_expired",
"=",
"Timeout",
"(",
"timeout",
")",
"while",
"not_expired",
"(",
")",
":",
"r",
"=",
"predicate",
"(",
")",
"if",
"r",
":",
"break"
] | Wait until predicate returns a truthy value or the timeout is reached.
>>> wait_until(lambda: True, timeout=10) | [
"Wait",
"until",
"predicate",
"returns",
"a",
"truthy",
"value",
"or",
"the",
"timeout",
"is",
"reached",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/run_crate.py#L116-L125 |
mfussenegger/cr8 | cr8/run_crate.py | _find_matching_version | def _find_matching_version(versions, version_pattern):
"""
Return the first matching version
>>> _find_matching_version(['1.1.4', '1.0.12', '1.0.5'], '1.0.x')
'1.0.12'
>>> _find_matching_version(['1.1.4', '1.0.6', '1.0.5'], '2.x.x')
"""
pattern = fnmatch.translate(version_pattern.replace('... | python | def _find_matching_version(versions, version_pattern):
"""
Return the first matching version
>>> _find_matching_version(['1.1.4', '1.0.12', '1.0.5'], '1.0.x')
'1.0.12'
>>> _find_matching_version(['1.1.4', '1.0.6', '1.0.5'], '2.x.x')
"""
pattern = fnmatch.translate(version_pattern.replace('... | [
"def",
"_find_matching_version",
"(",
"versions",
",",
"version_pattern",
")",
":",
"pattern",
"=",
"fnmatch",
".",
"translate",
"(",
"version_pattern",
".",
"replace",
"(",
"'x'",
",",
"'*'",
")",
")",
"return",
"next",
"(",
"(",
"v",
"for",
"v",
"in",
... | Return the first matching version
>>> _find_matching_version(['1.1.4', '1.0.12', '1.0.5'], '1.0.x')
'1.0.12'
>>> _find_matching_version(['1.1.4', '1.0.6', '1.0.5'], '2.x.x') | [
"Return",
"the",
"first",
"matching",
"version"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/run_crate.py#L474-L484 |
mfussenegger/cr8 | cr8/run_crate.py | _build_tarball | def _build_tarball(src_repo) -> str:
""" Build a tarball from src and return the path to it """
run = partial(subprocess.run, cwd=src_repo, check=True)
run(['git', 'clean', '-xdff'])
src_repo = Path(src_repo)
if os.path.exists(src_repo / 'es' / 'upstream'):
run(['git', 'submodule', 'update',... | python | def _build_tarball(src_repo) -> str:
""" Build a tarball from src and return the path to it """
run = partial(subprocess.run, cwd=src_repo, check=True)
run(['git', 'clean', '-xdff'])
src_repo = Path(src_repo)
if os.path.exists(src_repo / 'es' / 'upstream'):
run(['git', 'submodule', 'update',... | [
"def",
"_build_tarball",
"(",
"src_repo",
")",
"->",
"str",
":",
"run",
"=",
"partial",
"(",
"subprocess",
".",
"run",
",",
"cwd",
"=",
"src_repo",
",",
"check",
"=",
"True",
")",
"run",
"(",
"[",
"'git'",
",",
"'clean'",
",",
"'-xdff'",
"]",
")",
... | Build a tarball from src and return the path to it | [
"Build",
"a",
"tarball",
"from",
"src",
"and",
"return",
"the",
"path",
"to",
"it"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/run_crate.py#L517-L526 |
mfussenegger/cr8 | cr8/run_crate.py | _crates_cache | def _crates_cache() -> str:
""" Return the path to the crates cache folder """
return os.environ.get(
'XDG_CACHE_HOME',
os.path.join(os.path.expanduser('~'), '.cache', 'cr8', 'crates')) | python | def _crates_cache() -> str:
""" Return the path to the crates cache folder """
return os.environ.get(
'XDG_CACHE_HOME',
os.path.join(os.path.expanduser('~'), '.cache', 'cr8', 'crates')) | [
"def",
"_crates_cache",
"(",
")",
"->",
"str",
":",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"'XDG_CACHE_HOME'",
",",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'.cache'",
",",
"'cr8'",
... | Return the path to the crates cache folder | [
"Return",
"the",
"path",
"to",
"the",
"crates",
"cache",
"folder"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/run_crate.py#L573-L577 |
mfussenegger/cr8 | cr8/run_crate.py | get_crate | def get_crate(version, crate_root=None):
"""Retrieve a Crate tarball, extract it and return the path.
Args:
version: The Crate version to get.
Can be specified in different ways:
- A concrete version like '0.55.0'
- A version including a `x` as wildcards. Like: '1.1... | python | def get_crate(version, crate_root=None):
"""Retrieve a Crate tarball, extract it and return the path.
Args:
version: The Crate version to get.
Can be specified in different ways:
- A concrete version like '0.55.0'
- A version including a `x` as wildcards. Like: '1.1... | [
"def",
"get_crate",
"(",
"version",
",",
"crate_root",
"=",
"None",
")",
":",
"if",
"not",
"crate_root",
":",
"crate_root",
"=",
"_crates_cache",
"(",
")",
"_remove_old_crates",
"(",
"crate_root",
")",
"if",
"_is_project_repo",
"(",
"version",
")",
":",
"ret... | Retrieve a Crate tarball, extract it and return the path.
Args:
version: The Crate version to get.
Can be specified in different ways:
- A concrete version like '0.55.0'
- A version including a `x` as wildcards. Like: '1.1.x' or '1.x.x'.
This will use the ... | [
"Retrieve",
"a",
"Crate",
"tarball",
"extract",
"it",
"and",
"return",
"the",
"path",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/run_crate.py#L580-L607 |
mfussenegger/cr8 | cr8/run_crate.py | _parse_options | def _parse_options(options: List[str]) -> Dict[str, str]:
""" Parse repeatable CLI options
>>> opts = _parse_options(['cluster.name=foo', 'CRATE_JAVA_OPTS="-Dxy=foo"'])
>>> print(json.dumps(opts, sort_keys=True))
{"CRATE_JAVA_OPTS": "\\"-Dxy=foo\\"", "cluster.name": "foo"}
"""
try:
retu... | python | def _parse_options(options: List[str]) -> Dict[str, str]:
""" Parse repeatable CLI options
>>> opts = _parse_options(['cluster.name=foo', 'CRATE_JAVA_OPTS="-Dxy=foo"'])
>>> print(json.dumps(opts, sort_keys=True))
{"CRATE_JAVA_OPTS": "\\"-Dxy=foo\\"", "cluster.name": "foo"}
"""
try:
retu... | [
"def",
"_parse_options",
"(",
"options",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"try",
":",
"return",
"dict",
"(",
"i",
".",
"split",
"(",
"'='",
",",
"maxsplit",
"=",
"1",
")",
"for",
"i",
"in",
"opt... | Parse repeatable CLI options
>>> opts = _parse_options(['cluster.name=foo', 'CRATE_JAVA_OPTS="-Dxy=foo"'])
>>> print(json.dumps(opts, sort_keys=True))
{"CRATE_JAVA_OPTS": "\\"-Dxy=foo\\"", "cluster.name": "foo"} | [
"Parse",
"repeatable",
"CLI",
"options"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/run_crate.py#L610-L621 |
mfussenegger/cr8 | cr8/run_crate.py | run_crate | def run_crate(
version,
env=None,
setting=None,
crate_root=None,
keep_data=False,
disable_java_magic=False,
):
"""Launch a crate instance.
Supported version specifications:
- Concrete version like "0.55.0" or with wildcard: "1.1.x"
- An alias (one... | python | def run_crate(
version,
env=None,
setting=None,
crate_root=None,
keep_data=False,
disable_java_magic=False,
):
"""Launch a crate instance.
Supported version specifications:
- Concrete version like "0.55.0" or with wildcard: "1.1.x"
- An alias (one... | [
"def",
"run_crate",
"(",
"version",
",",
"env",
"=",
"None",
",",
"setting",
"=",
"None",
",",
"crate_root",
"=",
"None",
",",
"keep_data",
"=",
"False",
",",
"disable_java_magic",
"=",
"False",
",",
")",
":",
"with",
"create_node",
"(",
"version",
",",
... | Launch a crate instance.
Supported version specifications:
- Concrete version like "0.55.0" or with wildcard: "1.1.x"
- An alias (one of [latest-nightly, latest-stable, latest-testing])
- A URI pointing to a CrateDB tarball (in .tar.gz format)
- A URI pointing to a checked out Crate... | [
"Launch",
"a",
"crate",
"instance",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/run_crate.py#L660-L703 |
mfussenegger/cr8 | cr8/run_crate.py | CrateNode.start | def start(self):
"""Start the process.
This will block until the Crate cluster is ready to process requests.
"""
log.info('Starting Crate process')
self.process = proc = self.enter_context(subprocess.Popen(
self.cmd,
stdin=subprocess.DEVNULL,
... | python | def start(self):
"""Start the process.
This will block until the Crate cluster is ready to process requests.
"""
log.info('Starting Crate process')
self.process = proc = self.enter_context(subprocess.Popen(
self.cmd,
stdin=subprocess.DEVNULL,
... | [
"def",
"start",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Starting Crate process'",
")",
"self",
".",
"process",
"=",
"proc",
"=",
"self",
".",
"enter_context",
"(",
"subprocess",
".",
"Popen",
"(",
"self",
".",
"cmd",
",",
"stdin",
"=",
"subpr... | Start the process.
This will block until the Crate cluster is ready to process requests. | [
"Start",
"the",
"process",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/run_crate.py#L260-L327 |
mfussenegger/cr8 | cr8/run_crate.py | AddrConsumer._parse | def _parse(line):
""" Parse protocol and bound address from log message
>>> AddrConsumer._parse('NONE')
(None, None)
>>> AddrConsumer._parse('[INFO ][i.c.p.h.CrateNettyHttpServerTransport] [Widderstein] publish_address {127.0.0.1:4200}, bound_addresses {[fe80::1]:4200}, {[::1]:4200}, {... | python | def _parse(line):
""" Parse protocol and bound address from log message
>>> AddrConsumer._parse('NONE')
(None, None)
>>> AddrConsumer._parse('[INFO ][i.c.p.h.CrateNettyHttpServerTransport] [Widderstein] publish_address {127.0.0.1:4200}, bound_addresses {[fe80::1]:4200}, {[::1]:4200}, {... | [
"def",
"_parse",
"(",
"line",
")",
":",
"m",
"=",
"AddrConsumer",
".",
"ADDRESS_RE",
".",
"match",
"(",
"line",
")",
"if",
"not",
"m",
":",
"return",
"None",
",",
"None",
"protocol",
"=",
"m",
".",
"group",
"(",
"'protocol'",
")",
"protocol",
"=",
... | Parse protocol and bound address from log message
>>> AddrConsumer._parse('NONE')
(None, None)
>>> AddrConsumer._parse('[INFO ][i.c.p.h.CrateNettyHttpServerTransport] [Widderstein] publish_address {127.0.0.1:4200}, bound_addresses {[fe80::1]:4200}, {[::1]:4200}, {127.0.0.1:4200}')
('ht... | [
"Parse",
"protocol",
"and",
"bound",
"address",
"from",
"log",
"message"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/run_crate.py#L382-L402 |
dchaplinsky/unshred | unshred/threshold.py | _calc_block_mean_variance | def _calc_block_mean_variance(image, mask, blocksize):
"""Adaptively determines image background.
Args:
image: image converted 1-channel image.
mask: 1-channel mask, same size as image.
blocksize: adaptive algorithm parameter.
Returns:
image of same size as input with foreg... | python | def _calc_block_mean_variance(image, mask, blocksize):
"""Adaptively determines image background.
Args:
image: image converted 1-channel image.
mask: 1-channel mask, same size as image.
blocksize: adaptive algorithm parameter.
Returns:
image of same size as input with foreg... | [
"def",
"_calc_block_mean_variance",
"(",
"image",
",",
"mask",
",",
"blocksize",
")",
":",
"I",
"=",
"image",
".",
"copy",
"(",
")",
"I_f",
"=",
"I",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"/",
"255.",
"# Used for mean and std.",
"result",
"=",
... | Adaptively determines image background.
Args:
image: image converted 1-channel image.
mask: 1-channel mask, same size as image.
blocksize: adaptive algorithm parameter.
Returns:
image of same size as input with foreground inpainted with background. | [
"Adaptively",
"determines",
"image",
"background",
"."
] | train | https://github.com/dchaplinsky/unshred/blob/ca9cd6a1c6fb8c77d5424dd660ff5d2f3720c0f8/unshred/threshold.py#L30-L74 |
dchaplinsky/unshred | unshred/threshold.py | threshold | def threshold(image, block_size=DEFAULT_BLOCKSIZE, mask=None):
"""Applies adaptive thresholding to the given image.
Args:
image: BGRA image.
block_size: optional int block_size to use for adaptive thresholding.
mask: optional mask.
Returns:
Thresholded image.
"""
if ... | python | def threshold(image, block_size=DEFAULT_BLOCKSIZE, mask=None):
"""Applies adaptive thresholding to the given image.
Args:
image: BGRA image.
block_size: optional int block_size to use for adaptive thresholding.
mask: optional mask.
Returns:
Thresholded image.
"""
if ... | [
"def",
"threshold",
"(",
"image",
",",
"block_size",
"=",
"DEFAULT_BLOCKSIZE",
",",
"mask",
"=",
"None",
")",
":",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"np",
".",
"zeros",
"(",
"image",
".",
"shape",
"[",
":",
"2",
"]",
",",
"dtype",
"=",
... | Applies adaptive thresholding to the given image.
Args:
image: BGRA image.
block_size: optional int block_size to use for adaptive thresholding.
mask: optional mask.
Returns:
Thresholded image. | [
"Applies",
"adaptive",
"thresholding",
"to",
"the",
"given",
"image",
"."
] | train | https://github.com/dchaplinsky/unshred/blob/ca9cd6a1c6fb8c77d5424dd660ff5d2f3720c0f8/unshred/threshold.py#L77-L96 |
habnabit/vcversioner | vcversioner.py | find_version | def find_version(include_dev_version=True, root='%(pwd)s',
version_file='%(root)s/version.txt', version_module_paths=(),
git_args=None, vcs_args=None, decrement_dev_version=None,
strip_prefix='v',
Popen=subprocess.Popen, open=open):
"""Find an appr... | python | def find_version(include_dev_version=True, root='%(pwd)s',
version_file='%(root)s/version.txt', version_module_paths=(),
git_args=None, vcs_args=None, decrement_dev_version=None,
strip_prefix='v',
Popen=subprocess.Popen, open=open):
"""Find an appr... | [
"def",
"find_version",
"(",
"include_dev_version",
"=",
"True",
",",
"root",
"=",
"'%(pwd)s'",
",",
"version_file",
"=",
"'%(root)s/version.txt'",
",",
"version_module_paths",
"=",
"(",
")",
",",
"git_args",
"=",
"None",
",",
"vcs_args",
"=",
"None",
",",
"dec... | Find an appropriate version number from version control.
It's much more convenient to be able to use your version control system's
tagging mechanism to derive a version number than to have to duplicate that
information all over the place.
The default behavior is to write out a ``version.txt`` file whi... | [
"Find",
"an",
"appropriate",
"version",
"number",
"from",
"version",
"control",
"."
] | train | https://github.com/habnabit/vcversioner/blob/72f8f0a7e0121cf5989a2cb00d5e1395e02a0445/vcversioner.py#L52-L244 |
habnabit/vcversioner | vcversioner.py | setup | def setup(dist, attr, value):
"""A hook for simplifying ``vcversioner`` use from distutils.
This hook, when installed properly, allows vcversioner to automatically run
when specifying a ``vcversioner`` argument to ``setup``. For example::
from setuptools import setup
setup(
setup_re... | python | def setup(dist, attr, value):
"""A hook for simplifying ``vcversioner`` use from distutils.
This hook, when installed properly, allows vcversioner to automatically run
when specifying a ``vcversioner`` argument to ``setup``. For example::
from setuptools import setup
setup(
setup_re... | [
"def",
"setup",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"dist",
".",
"metadata",
".",
"version",
"=",
"find_version",
"(",
"*",
"*",
"value",
")",
".",
"version"
] | A hook for simplifying ``vcversioner`` use from distutils.
This hook, when installed properly, allows vcversioner to automatically run
when specifying a ``vcversioner`` argument to ``setup``. For example::
from setuptools import setup
setup(
setup_requires=['vcversioner'],
vcv... | [
"A",
"hook",
"for",
"simplifying",
"vcversioner",
"use",
"from",
"distutils",
"."
] | train | https://github.com/habnabit/vcversioner/blob/72f8f0a7e0121cf5989a2cb00d5e1395e02a0445/vcversioner.py#L247-L265 |
mfussenegger/cr8 | cr8/insert_json.py | to_insert | def to_insert(table, d):
"""Generate an insert statement using the given table and dictionary.
Args:
table (str): table name
d (dict): dictionary with column names as keys and values as values.
Returns:
tuple of statement and arguments
>>> to_insert('doc.foobar', {'name': 'Marv... | python | def to_insert(table, d):
"""Generate an insert statement using the given table and dictionary.
Args:
table (str): table name
d (dict): dictionary with column names as keys and values as values.
Returns:
tuple of statement and arguments
>>> to_insert('doc.foobar', {'name': 'Marv... | [
"def",
"to_insert",
"(",
"table",
",",
"d",
")",
":",
"columns",
"=",
"[",
"]",
"args",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"d",
".",
"items",
"(",
")",
":",
"columns",
".",
"append",
"(",
"'\"{}\"'",
".",
"format",
"(",
"key",
")",
... | Generate an insert statement using the given table and dictionary.
Args:
table (str): table name
d (dict): dictionary with column names as keys and values as values.
Returns:
tuple of statement and arguments
>>> to_insert('doc.foobar', {'name': 'Marvin'})
('insert into doc.foob... | [
"Generate",
"an",
"insert",
"statement",
"using",
"the",
"given",
"table",
"and",
"dictionary",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/insert_json.py#L15-L37 |
mfussenegger/cr8 | cr8/insert_json.py | insert_json | def insert_json(table=None,
bulk_size=1000,
concurrency=25,
hosts=None,
output_fmt=None):
"""Insert JSON lines fed into stdin into a Crate cluster.
If no hosts are specified the statements will be printed.
Args:
table: Target table na... | python | def insert_json(table=None,
bulk_size=1000,
concurrency=25,
hosts=None,
output_fmt=None):
"""Insert JSON lines fed into stdin into a Crate cluster.
If no hosts are specified the statements will be printed.
Args:
table: Target table na... | [
"def",
"insert_json",
"(",
"table",
"=",
"None",
",",
"bulk_size",
"=",
"1000",
",",
"concurrency",
"=",
"25",
",",
"hosts",
"=",
"None",
",",
"output_fmt",
"=",
"None",
")",
":",
"if",
"not",
"hosts",
":",
"return",
"print_only",
"(",
"table",
")",
... | Insert JSON lines fed into stdin into a Crate cluster.
If no hosts are specified the statements will be printed.
Args:
table: Target table name.
bulk_size: Bulk size of the insert statements.
concurrency: Number of operations to run concurrently.
hosts: hostname:port pairs of t... | [
"Insert",
"JSON",
"lines",
"fed",
"into",
"stdin",
"into",
"a",
"Crate",
"cluster",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/insert_json.py#L54-L89 |
dchaplinsky/unshred | unshred/features/lines.py | _get_dominant_angle | def _get_dominant_angle(lines, domination_type=MEDIAN):
"""Picks dominant angle of a set of lines.
Args:
lines: iterable of (x1, y1, x2, y2) tuples that define lines.
domination_type: either MEDIAN or MEAN.
Returns:
Dominant angle value in radians.
Raises:
ValueError: ... | python | def _get_dominant_angle(lines, domination_type=MEDIAN):
"""Picks dominant angle of a set of lines.
Args:
lines: iterable of (x1, y1, x2, y2) tuples that define lines.
domination_type: either MEDIAN or MEAN.
Returns:
Dominant angle value in radians.
Raises:
ValueError: ... | [
"def",
"_get_dominant_angle",
"(",
"lines",
",",
"domination_type",
"=",
"MEDIAN",
")",
":",
"if",
"domination_type",
"==",
"MEDIAN",
":",
"return",
"_get_median_angle",
"(",
"lines",
")",
"elif",
"domination_type",
"==",
"MEAN",
":",
"return",
"_get_mean_angle",
... | Picks dominant angle of a set of lines.
Args:
lines: iterable of (x1, y1, x2, y2) tuples that define lines.
domination_type: either MEDIAN or MEAN.
Returns:
Dominant angle value in radians.
Raises:
ValueError: on unknown domination_type. | [
"Picks",
"dominant",
"angle",
"of",
"a",
"set",
"of",
"lines",
"."
] | train | https://github.com/dchaplinsky/unshred/blob/ca9cd6a1c6fb8c77d5424dd660ff5d2f3720c0f8/unshred/features/lines.py#L16-L35 |
dchaplinsky/unshred | unshred/features/lines.py | _normalize_angle | def _normalize_angle(angle, range, step):
"""Finds an angle that matches the given one modulo step.
Increments and decrements the given value with a given step.
Args:
range: a 2-tuple of min and max target values.
step: tuning step.
Returns:
Normalized value within a given ran... | python | def _normalize_angle(angle, range, step):
"""Finds an angle that matches the given one modulo step.
Increments and decrements the given value with a given step.
Args:
range: a 2-tuple of min and max target values.
step: tuning step.
Returns:
Normalized value within a given ran... | [
"def",
"_normalize_angle",
"(",
"angle",
",",
"range",
",",
"step",
")",
":",
"while",
"angle",
"<=",
"range",
"[",
"0",
"]",
":",
"angle",
"+=",
"step",
"while",
"angle",
">=",
"range",
"[",
"1",
"]",
":",
"angle",
"-=",
"step",
"return",
"angle"
] | Finds an angle that matches the given one modulo step.
Increments and decrements the given value with a given step.
Args:
range: a 2-tuple of min and max target values.
step: tuning step.
Returns:
Normalized value within a given range. | [
"Finds",
"an",
"angle",
"that",
"matches",
"the",
"given",
"one",
"modulo",
"step",
"."
] | train | https://github.com/dchaplinsky/unshred/blob/ca9cd6a1c6fb8c77d5424dd660ff5d2f3720c0f8/unshred/features/lines.py#L38-L54 |
sijis/sumologic-python | src/sumologic/collectors.py | Collectors.get_collectors | def get_collectors(self, limit=1000, offset=0):
"""Returns a dict of collectors.
Args:
limit (int): number of collectors to return
offset (int): the offset of where the list of collectors should begin from
"""
options = {
'limit': limit,
'... | python | def get_collectors(self, limit=1000, offset=0):
"""Returns a dict of collectors.
Args:
limit (int): number of collectors to return
offset (int): the offset of where the list of collectors should begin from
"""
options = {
'limit': limit,
'... | [
"def",
"get_collectors",
"(",
"self",
",",
"limit",
"=",
"1000",
",",
"offset",
"=",
"0",
")",
":",
"options",
"=",
"{",
"'limit'",
":",
"limit",
",",
"'offset'",
":",
"offset",
",",
"}",
"request",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"u... | Returns a dict of collectors.
Args:
limit (int): number of collectors to return
offset (int): the offset of where the list of collectors should begin from | [
"Returns",
"a",
"dict",
"of",
"collectors",
"."
] | train | https://github.com/sijis/sumologic-python/blob/b50200907837f0d452d14ead5e647b8e24e2e9e5/src/sumologic/collectors.py#L29-L49 |
sijis/sumologic-python | src/sumologic/collectors.py | Collectors.find | def find(self, name):
"""Returns a dict of collector's details if found.
Args:
name (str): name of collector searching for
"""
collectors = self.get_collectors()
for collector in collectors:
if name.lower() == collector['name'].lower():
s... | python | def find(self, name):
"""Returns a dict of collector's details if found.
Args:
name (str): name of collector searching for
"""
collectors = self.get_collectors()
for collector in collectors:
if name.lower() == collector['name'].lower():
s... | [
"def",
"find",
"(",
"self",
",",
"name",
")",
":",
"collectors",
"=",
"self",
".",
"get_collectors",
"(",
")",
"for",
"collector",
"in",
"collectors",
":",
"if",
"name",
".",
"lower",
"(",
")",
"==",
"collector",
"[",
"'name'",
"]",
".",
"lower",
"("... | Returns a dict of collector's details if found.
Args:
name (str): name of collector searching for | [
"Returns",
"a",
"dict",
"of",
"collector",
"s",
"details",
"if",
"found",
"."
] | train | https://github.com/sijis/sumologic-python/blob/b50200907837f0d452d14ead5e647b8e24e2e9e5/src/sumologic/collectors.py#L51-L64 |
sijis/sumologic-python | src/sumologic/collectors.py | Collectors.delete | def delete(self, collector_id=None):
"""Delete a collector from inventory.
Args:
collector_id (int): id of collector (optional)
"""
cid = self.collector_id
if collector_id:
cid = collector_id
# param to delete id
url = '{0}/{1}'.format(s... | python | def delete(self, collector_id=None):
"""Delete a collector from inventory.
Args:
collector_id (int): id of collector (optional)
"""
cid = self.collector_id
if collector_id:
cid = collector_id
# param to delete id
url = '{0}/{1}'.format(s... | [
"def",
"delete",
"(",
"self",
",",
"collector_id",
"=",
"None",
")",
":",
"cid",
"=",
"self",
".",
"collector_id",
"if",
"collector_id",
":",
"cid",
"=",
"collector_id",
"# param to delete id",
"url",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"self",
".",
"url... | Delete a collector from inventory.
Args:
collector_id (int): id of collector (optional) | [
"Delete",
"a",
"collector",
"from",
"inventory",
"."
] | train | https://github.com/sijis/sumologic-python/blob/b50200907837f0d452d14ead5e647b8e24e2e9e5/src/sumologic/collectors.py#L66-L91 |
sijis/sumologic-python | src/sumologic/collectors.py | Collectors.info | def info(self, collector_id):
"""Return a dict of collector.
Args:
collector_id (int): id of collector (optional)
"""
cid = self.collector_id
if collector_id:
cid = collector_id
url = '{0}/{1}'.format(self.url, cid)
request = requests.get... | python | def info(self, collector_id):
"""Return a dict of collector.
Args:
collector_id (int): id of collector (optional)
"""
cid = self.collector_id
if collector_id:
cid = collector_id
url = '{0}/{1}'.format(self.url, cid)
request = requests.get... | [
"def",
"info",
"(",
"self",
",",
"collector_id",
")",
":",
"cid",
"=",
"self",
".",
"collector_id",
"if",
"collector_id",
":",
"cid",
"=",
"collector_id",
"url",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"self",
".",
"url",
",",
"cid",
")",
"request",
"=",... | Return a dict of collector.
Args:
collector_id (int): id of collector (optional) | [
"Return",
"a",
"dict",
"of",
"collector",
"."
] | train | https://github.com/sijis/sumologic-python/blob/b50200907837f0d452d14ead5e647b8e24e2e9e5/src/sumologic/collectors.py#L93-L105 |
nickmckay/LiPD-utilities | Python/lipd/dataframes.py | _dotnotation_for_nested_dictionary | def _dotnotation_for_nested_dictionary(d, key, dots):
"""
Flattens nested data structures using dot notation.
:param dict d: Original or nested dictionary
:param str key:
:param dict dots: Dotted dictionary so far
:return dict: Dotted dictionary so far
"""
if key == 'chronData':
... | python | def _dotnotation_for_nested_dictionary(d, key, dots):
"""
Flattens nested data structures using dot notation.
:param dict d: Original or nested dictionary
:param str key:
:param dict dots: Dotted dictionary so far
:return dict: Dotted dictionary so far
"""
if key == 'chronData':
... | [
"def",
"_dotnotation_for_nested_dictionary",
"(",
"d",
",",
"key",
",",
"dots",
")",
":",
"if",
"key",
"==",
"'chronData'",
":",
"# Not interested in expanding chronData in dot notation. Keep it as a chunk.",
"dots",
"[",
"key",
"]",
"=",
"d",
"elif",
"isinstance",
"(... | Flattens nested data structures using dot notation.
:param dict d: Original or nested dictionary
:param str key:
:param dict dots: Dotted dictionary so far
:return dict: Dotted dictionary so far | [
"Flattens",
"nested",
"data",
"structures",
"using",
"dot",
"notation",
".",
":",
"param",
"dict",
"d",
":",
"Original",
"or",
"nested",
"dictionary",
":",
"param",
"str",
"key",
":",
":",
"param",
"dict",
"dots",
":",
"Dotted",
"dictionary",
"so",
"far",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/dataframes.py#L13-L33 |
nickmckay/LiPD-utilities | Python/lipd/dataframes.py | create_dataframe | def create_dataframe(ensemble):
"""
Create a data frame from given nested lists of ensemble data
:param list ensemble: Ensemble data
:return obj: Dataframe
"""
logger_dataframes.info("enter ens_to_df")
# "Flatten" the nested lists. Bring all nested lists up to top-level. Output looks like [ ... | python | def create_dataframe(ensemble):
"""
Create a data frame from given nested lists of ensemble data
:param list ensemble: Ensemble data
:return obj: Dataframe
"""
logger_dataframes.info("enter ens_to_df")
# "Flatten" the nested lists. Bring all nested lists up to top-level. Output looks like [ ... | [
"def",
"create_dataframe",
"(",
"ensemble",
")",
":",
"logger_dataframes",
".",
"info",
"(",
"\"enter ens_to_df\"",
")",
"# \"Flatten\" the nested lists. Bring all nested lists up to top-level. Output looks like [ [1,2], [1,2], ... ]",
"ll",
"=",
"unwrap_arrays",
"(",
"ensemble",
... | Create a data frame from given nested lists of ensemble data
:param list ensemble: Ensemble data
:return obj: Dataframe | [
"Create",
"a",
"data",
"frame",
"from",
"given",
"nested",
"lists",
"of",
"ensemble",
"data",
":",
"param",
"list",
"ensemble",
":",
"Ensemble",
"data",
":",
"return",
"obj",
":",
"Dataframe"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/dataframes.py#L36-L55 |
nickmckay/LiPD-utilities | Python/lipd/dataframes.py | lipd_to_df | def lipd_to_df(metadata, csvs):
"""
Create an organized collection of data frames from LiPD data
:param dict metadata: LiPD data
:param dict csvs: Csv data
:return dict: One data frame per table, organized in a dictionary by name
"""
dfs = {}
logger_dataframes.info("enter lipd_to_df")
... | python | def lipd_to_df(metadata, csvs):
"""
Create an organized collection of data frames from LiPD data
:param dict metadata: LiPD data
:param dict csvs: Csv data
:return dict: One data frame per table, organized in a dictionary by name
"""
dfs = {}
logger_dataframes.info("enter lipd_to_df")
... | [
"def",
"lipd_to_df",
"(",
"metadata",
",",
"csvs",
")",
":",
"dfs",
"=",
"{",
"}",
"logger_dataframes",
".",
"info",
"(",
"\"enter lipd_to_df\"",
")",
"# Flatten the dictionary, but ignore the chron data items",
"dict_in_dotted",
"=",
"{",
"}",
"logger_dataframes",
".... | Create an organized collection of data frames from LiPD data
:param dict metadata: LiPD data
:param dict csvs: Csv data
:return dict: One data frame per table, organized in a dictionary by name | [
"Create",
"an",
"organized",
"collection",
"of",
"data",
"frames",
"from",
"LiPD",
"data",
":",
"param",
"dict",
"metadata",
":",
"LiPD",
"data",
":",
"param",
"dict",
"csvs",
":",
"Csv",
"data",
":",
"return",
"dict",
":",
"One",
"data",
"frame",
"per",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/dataframes.py#L58-L80 |
nickmckay/LiPD-utilities | Python/lipd/dataframes.py | ts_to_df | def ts_to_df(metadata):
"""
Create a data frame from one TimeSeries object
:param dict metadata: Time Series dictionary
:return dict: One data frame per table, organized in a dictionary by name
"""
logger_dataframes.info("enter ts_to_df")
dfs = {}
# Plot the variable + values vs year, a... | python | def ts_to_df(metadata):
"""
Create a data frame from one TimeSeries object
:param dict metadata: Time Series dictionary
:return dict: One data frame per table, organized in a dictionary by name
"""
logger_dataframes.info("enter ts_to_df")
dfs = {}
# Plot the variable + values vs year, a... | [
"def",
"ts_to_df",
"(",
"metadata",
")",
":",
"logger_dataframes",
".",
"info",
"(",
"\"enter ts_to_df\"",
")",
"dfs",
"=",
"{",
"}",
"# Plot the variable + values vs year, age, depth (whichever are available)",
"dfs",
"[",
"\"paleoData\"",
"]",
"=",
"pd",
".",
"DataF... | Create a data frame from one TimeSeries object
:param dict metadata: Time Series dictionary
:return dict: One data frame per table, organized in a dictionary by name | [
"Create",
"a",
"data",
"frame",
"from",
"one",
"TimeSeries",
"object",
":",
"param",
"dict",
"metadata",
":",
"Time",
"Series",
"dictionary",
":",
"return",
"dict",
":",
"One",
"data",
"frame",
"per",
"table",
"organized",
"in",
"a",
"dictionary",
"by",
"n... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/dataframes.py#L83-L108 |
nickmckay/LiPD-utilities | Python/lipd/dataframes.py | _plot_ts_cols | def _plot_ts_cols(ts):
"""
Get variable + values vs year, age, depth (whichever are available)
:param dict ts: TimeSeries dictionary
:return dict: Key: variableName, Value: Panda Series object
"""
logger_dataframes.info("enter get_ts_cols()")
d = {}
# Not entirely necessary, but this wi... | python | def _plot_ts_cols(ts):
"""
Get variable + values vs year, age, depth (whichever are available)
:param dict ts: TimeSeries dictionary
:return dict: Key: variableName, Value: Panda Series object
"""
logger_dataframes.info("enter get_ts_cols()")
d = {}
# Not entirely necessary, but this wi... | [
"def",
"_plot_ts_cols",
"(",
"ts",
")",
":",
"logger_dataframes",
".",
"info",
"(",
"\"enter get_ts_cols()\"",
")",
"d",
"=",
"{",
"}",
"# Not entirely necessary, but this will make the column headers look nicer for the data frame",
"# The column header will be in format \"variable... | Get variable + values vs year, age, depth (whichever are available)
:param dict ts: TimeSeries dictionary
:return dict: Key: variableName, Value: Panda Series object | [
"Get",
"variable",
"+",
"values",
"vs",
"year",
"age",
"depth",
"(",
"whichever",
"are",
"available",
")",
":",
"param",
"dict",
"ts",
":",
"TimeSeries",
"dictionary",
":",
"return",
"dict",
":",
"Key",
":",
"variableName",
"Value",
":",
"Panda",
"Series",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/dataframes.py#L111-L141 |
nickmckay/LiPD-utilities | Python/lipd/dataframes.py | _get_dfs | def _get_dfs(csvs):
"""
LiPD Version 1.2
Create a data frame for each table for the given key
:param dict csvs: LiPD metadata dictionary
:return dict: paleo data data frames
"""
logger_dataframes.info("enter get_lipd_cols")
# placeholders for the incoming data frames
dfs = {"chronDat... | python | def _get_dfs(csvs):
"""
LiPD Version 1.2
Create a data frame for each table for the given key
:param dict csvs: LiPD metadata dictionary
:return dict: paleo data data frames
"""
logger_dataframes.info("enter get_lipd_cols")
# placeholders for the incoming data frames
dfs = {"chronDat... | [
"def",
"_get_dfs",
"(",
"csvs",
")",
":",
"logger_dataframes",
".",
"info",
"(",
"\"enter get_lipd_cols\"",
")",
"# placeholders for the incoming data frames",
"dfs",
"=",
"{",
"\"chronData\"",
":",
"{",
"}",
",",
"\"paleoData\"",
":",
"{",
"}",
"}",
"try",
":",... | LiPD Version 1.2
Create a data frame for each table for the given key
:param dict csvs: LiPD metadata dictionary
:return dict: paleo data data frames | [
"LiPD",
"Version",
"1",
".",
"2",
"Create",
"a",
"data",
"frame",
"for",
"each",
"table",
"for",
"the",
"given",
"key",
":",
"param",
"dict",
"csvs",
":",
"LiPD",
"metadata",
"dictionary",
":",
"return",
"dict",
":",
"paleo",
"data",
"data",
"frames"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/dataframes.py#L144-L167 |
nickmckay/LiPD-utilities | Python/lipd/dataframes.py | _get_key_data | def _get_key_data(d, key):
"""
Generic function to grab dictionary data by key with error handling
:return:
"""
d2 = ""
try:
d2 = d[key]
except KeyError:
logger_dataframes.info("get_key_data: KeyError: {}".format(key))
return d2 | python | def _get_key_data(d, key):
"""
Generic function to grab dictionary data by key with error handling
:return:
"""
d2 = ""
try:
d2 = d[key]
except KeyError:
logger_dataframes.info("get_key_data: KeyError: {}".format(key))
return d2 | [
"def",
"_get_key_data",
"(",
"d",
",",
"key",
")",
":",
"d2",
"=",
"\"\"",
"try",
":",
"d2",
"=",
"d",
"[",
"key",
"]",
"except",
"KeyError",
":",
"logger_dataframes",
".",
"info",
"(",
"\"get_key_data: KeyError: {}\"",
".",
"format",
"(",
"key",
")",
... | Generic function to grab dictionary data by key with error handling
:return: | [
"Generic",
"function",
"to",
"grab",
"dictionary",
"data",
"by",
"key",
"with",
"error",
"handling",
":",
"return",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/dataframes.py#L170-L180 |
nickmckay/LiPD-utilities | Python/lipd/dataframes.py | get_filtered_dfs | def get_filtered_dfs(lib, expr):
"""
Main: Get all data frames that match the given expression
:return dict: Filenames and data frames (filtered)
"""
logger_dataframes.info("enter get_filtered_dfs")
dfs = {}
tt = None
# Process all lipds files or one lipds file?
specific_files = _c... | python | def get_filtered_dfs(lib, expr):
"""
Main: Get all data frames that match the given expression
:return dict: Filenames and data frames (filtered)
"""
logger_dataframes.info("enter get_filtered_dfs")
dfs = {}
tt = None
# Process all lipds files or one lipds file?
specific_files = _c... | [
"def",
"get_filtered_dfs",
"(",
"lib",
",",
"expr",
")",
":",
"logger_dataframes",
".",
"info",
"(",
"\"enter get_filtered_dfs\"",
")",
"dfs",
"=",
"{",
"}",
"tt",
"=",
"None",
"# Process all lipds files or one lipds file?",
"specific_files",
"=",
"_check_expr_filenam... | Main: Get all data frames that match the given expression
:return dict: Filenames and data frames (filtered) | [
"Main",
":",
"Get",
"all",
"data",
"frames",
"that",
"match",
"the",
"given",
"expression",
":",
"return",
"dict",
":",
"Filenames",
"and",
"data",
"frames",
"(",
"filtered",
")"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/dataframes.py#L183-L237 |
nickmckay/LiPD-utilities | Python/lipd/dataframes.py | _match_dfs_expr | def _match_dfs_expr(lo_meta, expr, tt):
"""
Use the given expression to get all data frames that match the criteria (i.e. "paleo measurement tables")
:param dict lo_meta: Lipd object metadata
:param str expr: Search expression
:param str tt: Table type (chron or paleo)
:return list: All filename... | python | def _match_dfs_expr(lo_meta, expr, tt):
"""
Use the given expression to get all data frames that match the criteria (i.e. "paleo measurement tables")
:param dict lo_meta: Lipd object metadata
:param str expr: Search expression
:param str tt: Table type (chron or paleo)
:return list: All filename... | [
"def",
"_match_dfs_expr",
"(",
"lo_meta",
",",
"expr",
",",
"tt",
")",
":",
"logger_dataframes",
".",
"info",
"(",
"\"enter match_dfs_expr\"",
")",
"filenames",
"=",
"[",
"]",
"s",
"=",
"\"{}Data\"",
".",
"format",
"(",
"tt",
")",
"# Top table level. Going thr... | Use the given expression to get all data frames that match the criteria (i.e. "paleo measurement tables")
:param dict lo_meta: Lipd object metadata
:param str expr: Search expression
:param str tt: Table type (chron or paleo)
:return list: All filenames that match the expression | [
"Use",
"the",
"given",
"expression",
"to",
"get",
"all",
"data",
"frames",
"that",
"match",
"the",
"criteria",
"(",
"i",
".",
"e",
".",
"paleo",
"measurement",
"tables",
")",
":",
"param",
"dict",
"lo_meta",
":",
"Lipd",
"object",
"metadata",
":",
"param... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/dataframes.py#L240-L299 |
nickmckay/LiPD-utilities | Python/lipd/dataframes.py | _match_filenames_w_dfs | def _match_filenames_w_dfs(filenames, lo_dfs):
"""
Match a list of filenames to their data frame counterparts. Return data frames
:param list filenames: Filenames of data frames to retrieve
:param dict lo_dfs: All data frames
:return dict: Filenames and data frames (filtered)
"""
logger_data... | python | def _match_filenames_w_dfs(filenames, lo_dfs):
"""
Match a list of filenames to their data frame counterparts. Return data frames
:param list filenames: Filenames of data frames to retrieve
:param dict lo_dfs: All data frames
:return dict: Filenames and data frames (filtered)
"""
logger_data... | [
"def",
"_match_filenames_w_dfs",
"(",
"filenames",
",",
"lo_dfs",
")",
":",
"logger_dataframes",
".",
"info",
"(",
"\"enter match_filenames_w_dfs\"",
")",
"dfs",
"=",
"{",
"}",
"for",
"filename",
"in",
"filenames",
":",
"try",
":",
"if",
"filename",
"in",
"lo_... | Match a list of filenames to their data frame counterparts. Return data frames
:param list filenames: Filenames of data frames to retrieve
:param dict lo_dfs: All data frames
:return dict: Filenames and data frames (filtered) | [
"Match",
"a",
"list",
"of",
"filenames",
"to",
"their",
"data",
"frame",
"counterparts",
".",
"Return",
"data",
"frames",
":",
"param",
"list",
"filenames",
":",
"Filenames",
"of",
"data",
"frames",
"to",
"retrieve",
":",
"param",
"dict",
"lo_dfs",
":",
"A... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/dataframes.py#L302-L322 |
nickmckay/LiPD-utilities | Python/lipd/dataframes.py | _check_expr_filename | def _check_expr_filename(expr):
"""
Split the expression and look to see if there's a specific filename that the user wants to process.
:param str expr: Search expression
:return str: Filename or None
"""
expr_lst = expr.split()
f = [x for x in expr_lst if x not in DATA_FRAMES and x.endswith... | python | def _check_expr_filename(expr):
"""
Split the expression and look to see if there's a specific filename that the user wants to process.
:param str expr: Search expression
:return str: Filename or None
"""
expr_lst = expr.split()
f = [x for x in expr_lst if x not in DATA_FRAMES and x.endswith... | [
"def",
"_check_expr_filename",
"(",
"expr",
")",
":",
"expr_lst",
"=",
"expr",
".",
"split",
"(",
")",
"f",
"=",
"[",
"x",
"for",
"x",
"in",
"expr_lst",
"if",
"x",
"not",
"in",
"DATA_FRAMES",
"and",
"x",
".",
"endswith",
"(",
"\".lpd\"",
")",
"]",
... | Split the expression and look to see if there's a specific filename that the user wants to process.
:param str expr: Search expression
:return str: Filename or None | [
"Split",
"the",
"expression",
"and",
"look",
"to",
"see",
"if",
"there",
"s",
"a",
"specific",
"filename",
"that",
"the",
"user",
"wants",
"to",
"process",
".",
":",
"param",
"str",
"expr",
":",
"Search",
"expression",
":",
"return",
"str",
":",
"Filenam... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/dataframes.py#L325-L333 |
nickmckay/LiPD-utilities | Python/lipd/lipd_io.py | lipd_read | def lipd_read(path):
"""
Loads a LiPD file from local path. Unzip, read, and process data
Steps: create tmp, unzip lipd, read files into memory, manipulate data, move to original dir, delete tmp.
:param str path: Source path
:return none:
"""
_j = {}
dir_original = os.getcwd()
# Im... | python | def lipd_read(path):
"""
Loads a LiPD file from local path. Unzip, read, and process data
Steps: create tmp, unzip lipd, read files into memory, manipulate data, move to original dir, delete tmp.
:param str path: Source path
:return none:
"""
_j = {}
dir_original = os.getcwd()
# Im... | [
"def",
"lipd_read",
"(",
"path",
")",
":",
"_j",
"=",
"{",
"}",
"dir_original",
"=",
"os",
".",
"getcwd",
"(",
")",
"# Import metadata into object",
"try",
":",
"print",
"(",
"\"reading: {}\"",
".",
"format",
"(",
"print_filename",
"(",
"path",
")",
")",
... | Loads a LiPD file from local path. Unzip, read, and process data
Steps: create tmp, unzip lipd, read files into memory, manipulate data, move to original dir, delete tmp.
:param str path: Source path
:return none: | [
"Loads",
"a",
"LiPD",
"file",
"from",
"local",
"path",
".",
"Unzip",
"read",
"and",
"process",
"data",
"Steps",
":",
"create",
"tmp",
"unzip",
"lipd",
"read",
"files",
"into",
"memory",
"manipulate",
"data",
"move",
"to",
"original",
"dir",
"delete",
"tmp"... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lipd_io.py#L21-L65 |
nickmckay/LiPD-utilities | Python/lipd/lipd_io.py | lipd_write | def lipd_write(_json, path):
"""
Saves current state of LiPD object data. Outputs to a LiPD file.
Steps: create tmp, create bag dir, get dsn, splice csv from json, write csv, clean json, write json, create bagit,
zip up bag folder, place lipd in target dst, move to original dir, delete tmp
:par... | python | def lipd_write(_json, path):
"""
Saves current state of LiPD object data. Outputs to a LiPD file.
Steps: create tmp, create bag dir, get dsn, splice csv from json, write csv, clean json, write json, create bagit,
zip up bag folder, place lipd in target dst, move to original dir, delete tmp
:par... | [
"def",
"lipd_write",
"(",
"_json",
",",
"path",
")",
":",
"# Json is pass by reference. Make a copy so we don't mess up the original data.",
"_json_tmp",
"=",
"copy",
".",
"deepcopy",
"(",
"_json",
")",
"dir_original",
"=",
"os",
".",
"getcwd",
"(",
")",
"try",
":",... | Saves current state of LiPD object data. Outputs to a LiPD file.
Steps: create tmp, create bag dir, get dsn, splice csv from json, write csv, clean json, write json, create bagit,
zip up bag folder, place lipd in target dst, move to original dir, delete tmp
:param dict _json: Metadata
:param str pa... | [
"Saves",
"current",
"state",
"of",
"LiPD",
"object",
"data",
".",
"Outputs",
"to",
"a",
"LiPD",
"file",
".",
"Steps",
":",
"create",
"tmp",
"create",
"bag",
"dir",
"get",
"dsn",
"splice",
"csv",
"from",
"json",
"write",
"csv",
"clean",
"json",
"write",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lipd_io.py#L71-L105 |
mfussenegger/cr8 | cr8/insert_fake_data.py | _bulk_size_generator | def _bulk_size_generator(num_records, bulk_size, active):
""" Generate bulk_size until num_records is reached or active becomes false
>>> gen = _bulk_size_generator(155, 50, [True])
>>> list(gen)
[50, 50, 50, 5]
"""
while active and num_records > 0:
req_size = min(num_records, bulk_size... | python | def _bulk_size_generator(num_records, bulk_size, active):
""" Generate bulk_size until num_records is reached or active becomes false
>>> gen = _bulk_size_generator(155, 50, [True])
>>> list(gen)
[50, 50, 50, 5]
"""
while active and num_records > 0:
req_size = min(num_records, bulk_size... | [
"def",
"_bulk_size_generator",
"(",
"num_records",
",",
"bulk_size",
",",
"active",
")",
":",
"while",
"active",
"and",
"num_records",
">",
"0",
":",
"req_size",
"=",
"min",
"(",
"num_records",
",",
"bulk_size",
")",
"num_records",
"-=",
"req_size",
"yield",
... | Generate bulk_size until num_records is reached or active becomes false
>>> gen = _bulk_size_generator(155, 50, [True])
>>> list(gen)
[50, 50, 50, 5] | [
"Generate",
"bulk_size",
"until",
"num_records",
"is",
"reached",
"or",
"active",
"becomes",
"false"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/insert_fake_data.py#L171-L181 |
mfussenegger/cr8 | cr8/insert_fake_data.py | insert_fake_data | def insert_fake_data(hosts=None,
table=None,
num_records=1e5,
bulk_size=1000,
concurrency=25,
mapping_file=None):
"""Generate random data and insert it into a table.
This will read the table schema and then... | python | def insert_fake_data(hosts=None,
table=None,
num_records=1e5,
bulk_size=1000,
concurrency=25,
mapping_file=None):
"""Generate random data and insert it into a table.
This will read the table schema and then... | [
"def",
"insert_fake_data",
"(",
"hosts",
"=",
"None",
",",
"table",
"=",
"None",
",",
"num_records",
"=",
"1e5",
",",
"bulk_size",
"=",
"1000",
",",
"concurrency",
"=",
"25",
",",
"mapping_file",
"=",
"None",
")",
":",
"with",
"clients",
".",
"client",
... | Generate random data and insert it into a table.
This will read the table schema and then find suitable random data providers.
Which provider is choosen depends on the column name and data type.
Example:
A column named `name` will map to the `name` provider.
A column named `x` of type int... | [
"Generate",
"random",
"data",
"and",
"insert",
"it",
"into",
"a",
"table",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/insert_fake_data.py#L204-L289 |
nickmckay/LiPD-utilities | Python/lipd/doi_resolver.py | DOIResolver.main | def main(self):
"""
Main function that gets file(s), creates outputs, and runs all operations.
:return dict: Updated or original data for jsonld file
"""
logger_doi_resolver.info("enter doi_resolver")
for idx, pub in enumerate(self.root_dict['pub']):
# Retriev... | python | def main(self):
"""
Main function that gets file(s), creates outputs, and runs all operations.
:return dict: Updated or original data for jsonld file
"""
logger_doi_resolver.info("enter doi_resolver")
for idx, pub in enumerate(self.root_dict['pub']):
# Retriev... | [
"def",
"main",
"(",
"self",
")",
":",
"logger_doi_resolver",
".",
"info",
"(",
"\"enter doi_resolver\"",
")",
"for",
"idx",
",",
"pub",
"in",
"enumerate",
"(",
"self",
".",
"root_dict",
"[",
"'pub'",
"]",
")",
":",
"# Retrieve DOI id key-value from the root_dict... | Main function that gets file(s), creates outputs, and runs all operations.
:return dict: Updated or original data for jsonld file | [
"Main",
"function",
"that",
"gets",
"file",
"(",
"s",
")",
"creates",
"outputs",
"and",
"runs",
"all",
"operations",
".",
":",
"return",
"dict",
":",
"Updated",
"or",
"original",
"data",
"for",
"jsonld",
"file"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/doi_resolver.py#L34-L57 |
nickmckay/LiPD-utilities | Python/lipd/doi_resolver.py | DOIResolver.compare_replace | def compare_replace(pub_dict, fetch_dict):
"""
Take in our Original Pub, and Fetched Pub. For each Fetched entry that has data, overwrite the Original entry
:param pub_dict: (dict) Original pub dictionary
:param fetch_dict: (dict) Fetched pub dictionary from doi.org
:return: (dic... | python | def compare_replace(pub_dict, fetch_dict):
"""
Take in our Original Pub, and Fetched Pub. For each Fetched entry that has data, overwrite the Original entry
:param pub_dict: (dict) Original pub dictionary
:param fetch_dict: (dict) Fetched pub dictionary from doi.org
:return: (dic... | [
"def",
"compare_replace",
"(",
"pub_dict",
",",
"fetch_dict",
")",
":",
"blank",
"=",
"[",
"\" \"",
",",
"\"\"",
",",
"None",
"]",
"for",
"k",
",",
"v",
"in",
"fetch_dict",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"fetch_dict",
"[",
"k",
"]",... | Take in our Original Pub, and Fetched Pub. For each Fetched entry that has data, overwrite the Original entry
:param pub_dict: (dict) Original pub dictionary
:param fetch_dict: (dict) Fetched pub dictionary from doi.org
:return: (dict) Updated pub dictionary, with fetched data taking precedence | [
"Take",
"in",
"our",
"Original",
"Pub",
"and",
"Fetched",
"Pub",
".",
"For",
"each",
"Fetched",
"entry",
"that",
"has",
"data",
"overwrite",
"the",
"Original",
"entry",
":",
"param",
"pub_dict",
":",
"(",
"dict",
")",
"Original",
"pub",
"dictionary",
":",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/doi_resolver.py#L83-L97 |
nickmckay/LiPD-utilities | Python/lipd/doi_resolver.py | DOIResolver.noaa_citation | def noaa_citation(self, doi_string):
"""
Special instructions for moving noaa data to the correct fields
:param doi_string: (str) NOAA url
:return: None
"""
# Append location 1
if 'link' in self.root_dict['pub'][0]:
self.root_dict['pub'][0]['link'].app... | python | def noaa_citation(self, doi_string):
"""
Special instructions for moving noaa data to the correct fields
:param doi_string: (str) NOAA url
:return: None
"""
# Append location 1
if 'link' in self.root_dict['pub'][0]:
self.root_dict['pub'][0]['link'].app... | [
"def",
"noaa_citation",
"(",
"self",
",",
"doi_string",
")",
":",
"# Append location 1",
"if",
"'link'",
"in",
"self",
".",
"root_dict",
"[",
"'pub'",
"]",
"[",
"0",
"]",
":",
"self",
".",
"root_dict",
"[",
"'pub'",
"]",
"[",
"0",
"]",
"[",
"'link'",
... | Special instructions for moving noaa data to the correct fields
:param doi_string: (str) NOAA url
:return: None | [
"Special",
"instructions",
"for",
"moving",
"noaa",
"data",
"to",
"the",
"correct",
"fields",
":",
"param",
"doi_string",
":",
"(",
"str",
")",
"NOAA",
"url",
":",
"return",
":",
"None"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/doi_resolver.py#L108-L123 |
nickmckay/LiPD-utilities | Python/lipd/doi_resolver.py | DOIResolver.illegal_doi | def illegal_doi(self, doi_string):
"""
DOI string did not match the regex. Determine what the data is.
:param doi_string: (str) Malformed DOI string
:return: None
"""
logger_doi_resolver.info("enter illegal_doi")
# Ignores empty or irrelevant strings (blank, space... | python | def illegal_doi(self, doi_string):
"""
DOI string did not match the regex. Determine what the data is.
:param doi_string: (str) Malformed DOI string
:return: None
"""
logger_doi_resolver.info("enter illegal_doi")
# Ignores empty or irrelevant strings (blank, space... | [
"def",
"illegal_doi",
"(",
"self",
",",
"doi_string",
")",
":",
"logger_doi_resolver",
".",
"info",
"(",
"\"enter illegal_doi\"",
")",
"# Ignores empty or irrelevant strings (blank, spaces, na, nan, ', others)",
"if",
"len",
"(",
"doi_string",
")",
">",
"5",
":",
"# NOA... | DOI string did not match the regex. Determine what the data is.
:param doi_string: (str) Malformed DOI string
:return: None | [
"DOI",
"string",
"did",
"not",
"match",
"the",
"regex",
".",
"Determine",
"what",
"the",
"data",
"is",
".",
":",
"param",
"doi_string",
":",
"(",
"str",
")",
"Malformed",
"DOI",
"string",
":",
"return",
":",
"None"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/doi_resolver.py#L125-L147 |
nickmckay/LiPD-utilities | Python/lipd/doi_resolver.py | DOIResolver.compile_fetch | def compile_fetch(self, raw, doi_id):
"""
Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict:
"""
fetch_dict = OrderedDict()
order = {'author': 'author', 'type': 'typ... | python | def compile_fetch(self, raw, doi_id):
"""
Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict:
"""
fetch_dict = OrderedDict()
order = {'author': 'author', 'type': 'typ... | [
"def",
"compile_fetch",
"(",
"self",
",",
"raw",
",",
"doi_id",
")",
":",
"fetch_dict",
"=",
"OrderedDict",
"(",
")",
"order",
"=",
"{",
"'author'",
":",
"'author'",
",",
"'type'",
":",
"'type'",
",",
"'identifier'",
":",
"''",
",",
"'title'",
":",
"'t... | Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict: | [
"Loop",
"over",
"Raw",
"and",
"add",
"selected",
"items",
"to",
"Fetch",
"with",
"proper",
"formatting",
":",
"param",
"dict",
"raw",
":",
"JSON",
"data",
"from",
"doi",
".",
"org",
":",
"param",
"str",
"doi_id",
":",
":",
"return",
"dict",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/doi_resolver.py#L149-L173 |
nickmckay/LiPD-utilities | Python/lipd/doi_resolver.py | DOIResolver.get_data | def get_data(self, doi_id, idx):
"""
Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary
"""
tmp_dict = self.root_dict['pub'][0].copy()
try:
... | python | def get_data(self, doi_id, idx):
"""
Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary
"""
tmp_dict = self.root_dict['pub'][0].copy()
try:
... | [
"def",
"get_data",
"(",
"self",
",",
"doi_id",
",",
"idx",
")",
":",
"tmp_dict",
"=",
"self",
".",
"root_dict",
"[",
"'pub'",
"]",
"[",
"0",
"]",
".",
"copy",
"(",
")",
"try",
":",
"# Send request to grab metadata at URL",
"url",
"=",
"\"http://dx.doi.org/... | Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary | [
"Resolve",
"DOI",
"and",
"compile",
"all",
"attributes",
"into",
"one",
"dictionary",
":",
"param",
"str",
"doi_id",
":",
":",
"param",
"int",
"idx",
":",
"Publication",
"index",
":",
"return",
"dict",
":",
"Updated",
"publication",
"dictionary"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/doi_resolver.py#L175-L212 |
nickmckay/LiPD-utilities | Python/lipd/doi_resolver.py | DOIResolver.find_doi | def find_doi(self, curr_dict):
"""
Recursively search the file for the DOI id. More taxing, but more flexible when dictionary structuring isn't absolute
:param dict curr_dict: Current dictionary being searched
:return dict bool: Recursive - Current dictionary, False flag that DOI was not... | python | def find_doi(self, curr_dict):
"""
Recursively search the file for the DOI id. More taxing, but more flexible when dictionary structuring isn't absolute
:param dict curr_dict: Current dictionary being searched
:return dict bool: Recursive - Current dictionary, False flag that DOI was not... | [
"def",
"find_doi",
"(",
"self",
",",
"curr_dict",
")",
":",
"try",
":",
"if",
"'id'",
"in",
"curr_dict",
":",
"return",
"curr_dict",
"[",
"'id'",
"]",
",",
"True",
"elif",
"isinstance",
"(",
"curr_dict",
",",
"list",
")",
":",
"for",
"i",
"in",
"curr... | Recursively search the file for the DOI id. More taxing, but more flexible when dictionary structuring isn't absolute
:param dict curr_dict: Current dictionary being searched
:return dict bool: Recursive - Current dictionary, False flag that DOI was not found
:return str bool: Final - DOI id, Tr... | [
"Recursively",
"search",
"the",
"file",
"for",
"the",
"DOI",
"id",
".",
"More",
"taxing",
"but",
"more",
"flexible",
"when",
"dictionary",
"structuring",
"isn",
"t",
"absolute",
":",
"param",
"dict",
"curr_dict",
":",
"Current",
"dictionary",
"being",
"searche... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/doi_resolver.py#L214-L236 |
nickmckay/LiPD-utilities | Python/lipd/misc.py | cast_values_csvs | def cast_values_csvs(d, idx, x):
"""
Attempt to cast string to float. If error, keep as a string.
:param dict d: Data
:param int idx: Index number
:param str x: Data
:return any:
"""
try:
d[idx].append(float(x))
except ValueError:
d[idx].append(x)
# logger_mi... | python | def cast_values_csvs(d, idx, x):
"""
Attempt to cast string to float. If error, keep as a string.
:param dict d: Data
:param int idx: Index number
:param str x: Data
:return any:
"""
try:
d[idx].append(float(x))
except ValueError:
d[idx].append(x)
# logger_mi... | [
"def",
"cast_values_csvs",
"(",
"d",
",",
"idx",
",",
"x",
")",
":",
"try",
":",
"d",
"[",
"idx",
"]",
".",
"append",
"(",
"float",
"(",
"x",
")",
")",
"except",
"ValueError",
":",
"d",
"[",
"idx",
"]",
".",
"append",
"(",
"x",
")",
"# logger_m... | Attempt to cast string to float. If error, keep as a string.
:param dict d: Data
:param int idx: Index number
:param str x: Data
:return any: | [
"Attempt",
"to",
"cast",
"string",
"to",
"float",
".",
"If",
"error",
"keep",
"as",
"a",
"string",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L22-L40 |
nickmckay/LiPD-utilities | Python/lipd/misc.py | cast_float | def cast_float(x):
"""
Attempt to cleanup string or convert to number value.
:param any x:
:return float:
"""
try:
x = float(x)
except ValueError:
try:
x = x.strip()
except AttributeError as e:
logger_misc.warn("parse_str: AttributeError: Stri... | python | def cast_float(x):
"""
Attempt to cleanup string or convert to number value.
:param any x:
:return float:
"""
try:
x = float(x)
except ValueError:
try:
x = x.strip()
except AttributeError as e:
logger_misc.warn("parse_str: AttributeError: Stri... | [
"def",
"cast_float",
"(",
"x",
")",
":",
"try",
":",
"x",
"=",
"float",
"(",
"x",
")",
"except",
"ValueError",
":",
"try",
":",
"x",
"=",
"x",
".",
"strip",
"(",
")",
"except",
"AttributeError",
"as",
"e",
":",
"logger_misc",
".",
"warn",
"(",
"\... | Attempt to cleanup string or convert to number value.
:param any x:
:return float: | [
"Attempt",
"to",
"cleanup",
"string",
"or",
"convert",
"to",
"number",
"value",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L43-L57 |
nickmckay/LiPD-utilities | Python/lipd/misc.py | cast_int | def cast_int(x):
"""
Cast unknown type into integer
:param any x:
:return int:
"""
try:
x = int(x)
except ValueError:
try:
x = x.strip()
except AttributeError as e:
logger_misc.warn("parse_str: AttributeError: String not number or word, {}, {}... | python | def cast_int(x):
"""
Cast unknown type into integer
:param any x:
:return int:
"""
try:
x = int(x)
except ValueError:
try:
x = x.strip()
except AttributeError as e:
logger_misc.warn("parse_str: AttributeError: String not number or word, {}, {}... | [
"def",
"cast_int",
"(",
"x",
")",
":",
"try",
":",
"x",
"=",
"int",
"(",
"x",
")",
"except",
"ValueError",
":",
"try",
":",
"x",
"=",
"x",
".",
"strip",
"(",
")",
"except",
"AttributeError",
"as",
"e",
":",
"logger_misc",
".",
"warn",
"(",
"\"par... | Cast unknown type into integer
:param any x:
:return int: | [
"Cast",
"unknown",
"type",
"into",
"integer"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L60-L74 |
nickmckay/LiPD-utilities | Python/lipd/misc.py | clean_doi | def clean_doi(doi_string):
"""
Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids.
"""
regex = re.compile(r'\b(10[.][0-9]{3,}... | python | def clean_doi(doi_string):
"""
Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids.
"""
regex = re.compile(r'\b(10[.][0-9]{3,}... | [
"def",
"clean_doi",
"(",
"doi_string",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'\\b(10[.][0-9]{3,}(?:[.][0-9]+)*/(?:(?![\"&\\'<>,])\\S)+)\\b'",
")",
"try",
":",
"# Returns a list of matching strings",
"m",
"=",
"re",
".",
"findall",
"(",
"regex",
",",
"... | Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids. | [
"Use",
"regex",
"to",
"extract",
"all",
"DOI",
"ids",
"from",
"string",
"(",
"i",
".",
"e",
".",
"10",
".",
"1029",
"/",
"2005pa001215",
")"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L89-L104 |
nickmckay/LiPD-utilities | Python/lipd/misc.py | decimal_precision | def decimal_precision(row):
"""
Change the "precision" of values before writing to CSV. Each value is rounded to 3 numbers.
ex: 300 -> 300
ex: 300.123456 -> 300.123
ex: 3.123456e-25 - > 3.123e-25
:param tuple row: Row of numbers to process
:return list row: Processed row
"""
# _row... | python | def decimal_precision(row):
"""
Change the "precision" of values before writing to CSV. Each value is rounded to 3 numbers.
ex: 300 -> 300
ex: 300.123456 -> 300.123
ex: 3.123456e-25 - > 3.123e-25
:param tuple row: Row of numbers to process
:return list row: Processed row
"""
# _row... | [
"def",
"decimal_precision",
"(",
"row",
")",
":",
"# _row = []",
"try",
":",
"# Convert tuple to list for processing",
"row",
"=",
"list",
"(",
"row",
")",
"for",
"idx",
",",
"x",
"in",
"enumerate",
"(",
"row",
")",
":",
"x",
"=",
"str",
"(",
"x",
")",
... | Change the "precision" of values before writing to CSV. Each value is rounded to 3 numbers.
ex: 300 -> 300
ex: 300.123456 -> 300.123
ex: 3.123456e-25 - > 3.123e-25
:param tuple row: Row of numbers to process
:return list row: Processed row | [
"Change",
"the",
"precision",
"of",
"values",
"before",
"writing",
"to",
"CSV",
".",
"Each",
"value",
"is",
"rounded",
"to",
"3",
"numbers",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L106-L140 |
nickmckay/LiPD-utilities | Python/lipd/misc.py | fix_coordinate_decimal | def fix_coordinate_decimal(d):
"""
Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal.
Round them down to 5 decimals
:param dict d: Metadata
:return dict d: Metadata
"""
try:
for idx, n in enumerate(d["geo"]["geometry"]["coordinates"]... | python | def fix_coordinate_decimal(d):
"""
Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal.
Round them down to 5 decimals
:param dict d: Metadata
:return dict d: Metadata
"""
try:
for idx, n in enumerate(d["geo"]["geometry"]["coordinates"]... | [
"def",
"fix_coordinate_decimal",
"(",
"d",
")",
":",
"try",
":",
"for",
"idx",
",",
"n",
"in",
"enumerate",
"(",
"d",
"[",
"\"geo\"",
"]",
"[",
"\"geometry\"",
"]",
"[",
"\"coordinates\"",
"]",
")",
":",
"d",
"[",
"\"geo\"",
"]",
"[",
"\"geometry\"",
... | Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal.
Round them down to 5 decimals
:param dict d: Metadata
:return dict d: Metadata | [
"Coordinate",
"decimal",
"degrees",
"calculated",
"by",
"an",
"excel",
"formula",
"are",
"often",
"too",
"long",
"as",
"a",
"repeating",
"decimal",
".",
"Round",
"them",
"down",
"to",
"5",
"decimals"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L143-L156 |
nickmckay/LiPD-utilities | Python/lipd/misc.py | generate_timestamp | def generate_timestamp(fmt=None):
"""
Generate a timestamp to mark when this file was last modified.
:param str fmt: Special format instructions
:return str: YYYY-MM-DD format, or specified format
"""
if fmt:
time = dt.datetime.now().strftime(fmt)
else:
time = dt.date.today(... | python | def generate_timestamp(fmt=None):
"""
Generate a timestamp to mark when this file was last modified.
:param str fmt: Special format instructions
:return str: YYYY-MM-DD format, or specified format
"""
if fmt:
time = dt.datetime.now().strftime(fmt)
else:
time = dt.date.today(... | [
"def",
"generate_timestamp",
"(",
"fmt",
"=",
"None",
")",
":",
"if",
"fmt",
":",
"time",
"=",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"fmt",
")",
"else",
":",
"time",
"=",
"dt",
".",
"date",
".",
"today",
"(",
")",
"... | Generate a timestamp to mark when this file was last modified.
:param str fmt: Special format instructions
:return str: YYYY-MM-DD format, or specified format | [
"Generate",
"a",
"timestamp",
"to",
"mark",
"when",
"this",
"file",
"was",
"last",
"modified",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L159-L170 |
nickmckay/LiPD-utilities | Python/lipd/misc.py | generate_tsid | def generate_tsid(size=8):
"""
Generate a TSid string. Use the "PYT" prefix for traceability, and 8 trailing generated characters
ex: PYT9AG234GS
:return str: TSid
"""
chars = string.ascii_uppercase + string.digits
_gen = "".join(random.choice(chars) for _ in range(size))
return "PYT" +... | python | def generate_tsid(size=8):
"""
Generate a TSid string. Use the "PYT" prefix for traceability, and 8 trailing generated characters
ex: PYT9AG234GS
:return str: TSid
"""
chars = string.ascii_uppercase + string.digits
_gen = "".join(random.choice(chars) for _ in range(size))
return "PYT" +... | [
"def",
"generate_tsid",
"(",
"size",
"=",
"8",
")",
":",
"chars",
"=",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"digits",
"_gen",
"=",
"\"\"",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"chars",
")",
"for",
"_",
"in",
"range",
"(",
... | Generate a TSid string. Use the "PYT" prefix for traceability, and 8 trailing generated characters
ex: PYT9AG234GS
:return str: TSid | [
"Generate",
"a",
"TSid",
"string",
".",
"Use",
"the",
"PYT",
"prefix",
"for",
"traceability",
"and",
"8",
"trailing",
"generated",
"characters",
"ex",
":",
"PYT9AG234GS"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L173-L182 |
nickmckay/LiPD-utilities | Python/lipd/misc.py | get_appended_name | def get_appended_name(name, columns):
"""
Append numbers to a name until it no longer conflicts with the other names in a column.
Necessary to avoid overwriting columns and losing data. Loop a preset amount of times to avoid an infinite loop.
There shouldn't ever be more than two or three identical vari... | python | def get_appended_name(name, columns):
"""
Append numbers to a name until it no longer conflicts with the other names in a column.
Necessary to avoid overwriting columns and losing data. Loop a preset amount of times to avoid an infinite loop.
There shouldn't ever be more than two or three identical vari... | [
"def",
"get_appended_name",
"(",
"name",
",",
"columns",
")",
":",
"loop",
"=",
"0",
"while",
"name",
"in",
"columns",
":",
"loop",
"+=",
"1",
"if",
"loop",
">",
"10",
":",
"logger_misc",
".",
"warn",
"(",
"\"get_appended_name: Too many loops: Tried to get app... | Append numbers to a name until it no longer conflicts with the other names in a column.
Necessary to avoid overwriting columns and losing data. Loop a preset amount of times to avoid an infinite loop.
There shouldn't ever be more than two or three identical variable names in a table.
:param str name: Varia... | [
"Append",
"numbers",
"to",
"a",
"name",
"until",
"it",
"no",
"longer",
"conflicts",
"with",
"the",
"other",
"names",
"in",
"a",
"column",
".",
"Necessary",
"to",
"avoid",
"overwriting",
"columns",
"and",
"losing",
"data",
".",
"Loop",
"a",
"preset",
"amoun... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L185-L204 |
nickmckay/LiPD-utilities | Python/lipd/misc.py | get_authors_as_str | def get_authors_as_str(x):
"""
Take author or investigator data, and convert it to a concatenated string of names.
Author data structure has a few variations, so account for all.
:param any x: Author data
:return str: Author string
"""
_authors = ""
# if it's a string already, we're don... | python | def get_authors_as_str(x):
"""
Take author or investigator data, and convert it to a concatenated string of names.
Author data structure has a few variations, so account for all.
:param any x: Author data
:return str: Author string
"""
_authors = ""
# if it's a string already, we're don... | [
"def",
"get_authors_as_str",
"(",
"x",
")",
":",
"_authors",
"=",
"\"\"",
"# if it's a string already, we're done",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"return",
"x",
"# elif it's a list, keep going",
"elif",
"isinstance",
"(",
"x",
",",
"list",
... | Take author or investigator data, and convert it to a concatenated string of names.
Author data structure has a few variations, so account for all.
:param any x: Author data
:return str: Author string | [
"Take",
"author",
"or",
"investigator",
"data",
"and",
"convert",
"it",
"to",
"a",
"concatenated",
"string",
"of",
"names",
".",
"Author",
"data",
"structure",
"has",
"a",
"few",
"variations",
"so",
"account",
"for",
"all",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L207-L247 |
nickmckay/LiPD-utilities | Python/lipd/misc.py | get_dsn | def get_dsn(d):
"""
Get the dataset name from a record
:param dict d: Metadata
:return str: Dataset name
"""
try:
return d["dataSetName"]
except Exception as e:
logger_misc.warn("get_dsn: Exception: No datasetname found, unable to continue: {}".format(e))
exit(1) | python | def get_dsn(d):
"""
Get the dataset name from a record
:param dict d: Metadata
:return str: Dataset name
"""
try:
return d["dataSetName"]
except Exception as e:
logger_misc.warn("get_dsn: Exception: No datasetname found, unable to continue: {}".format(e))
exit(1) | [
"def",
"get_dsn",
"(",
"d",
")",
":",
"try",
":",
"return",
"d",
"[",
"\"dataSetName\"",
"]",
"except",
"Exception",
"as",
"e",
":",
"logger_misc",
".",
"warn",
"(",
"\"get_dsn: Exception: No datasetname found, unable to continue: {}\"",
".",
"format",
"(",
"e",
... | Get the dataset name from a record
:param dict d: Metadata
:return str: Dataset name | [
"Get",
"the",
"dataset",
"name",
"from",
"a",
"record"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L250-L262 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.