repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
happyleavesaoc/python-motorparts | motorparts/__init__.py | get_vehicle_health_report | def get_vehicle_health_report(session, vehicle_index):
"""Get complete vehicle health report."""
profile = get_profile(session)
_validate_vehicle(vehicle_index, profile)
return session.get(VHR_URL, params={
'uuid': profile['vehicles'][vehicle_index]['uuid']
}).json() | python | def get_vehicle_health_report(session, vehicle_index):
"""Get complete vehicle health report."""
profile = get_profile(session)
_validate_vehicle(vehicle_index, profile)
return session.get(VHR_URL, params={
'uuid': profile['vehicles'][vehicle_index]['uuid']
}).json() | [
"def",
"get_vehicle_health_report",
"(",
"session",
",",
"vehicle_index",
")",
":",
"profile",
"=",
"get_profile",
"(",
"session",
")",
"_validate_vehicle",
"(",
"vehicle_index",
",",
"profile",
")",
"return",
"session",
".",
"get",
"(",
"VHR_URL",
",",
"params"... | Get complete vehicle health report. | [
"Get",
"complete",
"vehicle",
"health",
"report",
"."
] | train | https://github.com/happyleavesaoc/python-motorparts/blob/4a6b4dc72dd45524dd64a7a079478bd98c55215c/motorparts/__init__.py#L131-L137 |
happyleavesaoc/python-motorparts | motorparts/__init__.py | _traverse_report | def _traverse_report(data):
"""Recursively traverse vehicle health report."""
if 'items' not in data:
return {}
out = {}
for item in data['items']:
skip = (item['severity'] == 'NonDisplay' or
item['itemKey'] == 'categoryDesc' or
item['value'] in [None, 'Nu... | python | def _traverse_report(data):
"""Recursively traverse vehicle health report."""
if 'items' not in data:
return {}
out = {}
for item in data['items']:
skip = (item['severity'] == 'NonDisplay' or
item['itemKey'] == 'categoryDesc' or
item['value'] in [None, 'Nu... | [
"def",
"_traverse_report",
"(",
"data",
")",
":",
"if",
"'items'",
"not",
"in",
"data",
":",
"return",
"{",
"}",
"out",
"=",
"{",
"}",
"for",
"item",
"in",
"data",
"[",
"'items'",
"]",
":",
"skip",
"=",
"(",
"item",
"[",
"'severity'",
"]",
"==",
... | Recursively traverse vehicle health report. | [
"Recursively",
"traverse",
"vehicle",
"health",
"report",
"."
] | train | https://github.com/happyleavesaoc/python-motorparts/blob/4a6b4dc72dd45524dd64a7a079478bd98c55215c/motorparts/__init__.py#L140-L154 |
happyleavesaoc/python-motorparts | motorparts/__init__.py | get_tow_guide | def get_tow_guide(session, vehicle_index):
"""Get tow guide information."""
profile = get_profile(session)
_validate_vehicle(vehicle_index, profile)
return session.post(TOW_URL, {
'vin': profile['vehicles'][vehicle_index]['vin']
}).json() | python | def get_tow_guide(session, vehicle_index):
"""Get tow guide information."""
profile = get_profile(session)
_validate_vehicle(vehicle_index, profile)
return session.post(TOW_URL, {
'vin': profile['vehicles'][vehicle_index]['vin']
}).json() | [
"def",
"get_tow_guide",
"(",
"session",
",",
"vehicle_index",
")",
":",
"profile",
"=",
"get_profile",
"(",
"session",
")",
"_validate_vehicle",
"(",
"vehicle_index",
",",
"profile",
")",
"return",
"session",
".",
"post",
"(",
"TOW_URL",
",",
"{",
"'vin'",
"... | Get tow guide information. | [
"Get",
"tow",
"guide",
"information",
"."
] | train | https://github.com/happyleavesaoc/python-motorparts/blob/4a6b4dc72dd45524dd64a7a079478bd98c55215c/motorparts/__init__.py#L159-L165 |
happyleavesaoc/python-motorparts | motorparts/__init__.py | _get_model | def _get_model(vehicle):
"""Clean the model field. Best guess."""
model = vehicle['model']
model = model.replace(vehicle['year'], '')
model = model.replace(vehicle['make'], '')
return model.strip().split(' ')[0] | python | def _get_model(vehicle):
"""Clean the model field. Best guess."""
model = vehicle['model']
model = model.replace(vehicle['year'], '')
model = model.replace(vehicle['make'], '')
return model.strip().split(' ')[0] | [
"def",
"_get_model",
"(",
"vehicle",
")",
":",
"model",
"=",
"vehicle",
"[",
"'model'",
"]",
"model",
"=",
"model",
".",
"replace",
"(",
"vehicle",
"[",
"'year'",
"]",
",",
"''",
")",
"model",
"=",
"model",
".",
"replace",
"(",
"vehicle",
"[",
"'make... | Clean the model field. Best guess. | [
"Clean",
"the",
"model",
"field",
".",
"Best",
"guess",
"."
] | train | https://github.com/happyleavesaoc/python-motorparts/blob/4a6b4dc72dd45524dd64a7a079478bd98c55215c/motorparts/__init__.py#L168-L173 |
happyleavesaoc/python-motorparts | motorparts/__init__.py | get_summary | def get_summary(session):
"""Get vehicle summary."""
profile = get_profile(session)
return {
'user': {
'email': profile['userProfile']['eMail'],
'name': '{} {}'.format(profile['userProfile']['firstName'],
profile['userProfile']['lastName'])
... | python | def get_summary(session):
"""Get vehicle summary."""
profile = get_profile(session)
return {
'user': {
'email': profile['userProfile']['eMail'],
'name': '{} {}'.format(profile['userProfile']['firstName'],
profile['userProfile']['lastName'])
... | [
"def",
"get_summary",
"(",
"session",
")",
":",
"profile",
"=",
"get_profile",
"(",
"session",
")",
"return",
"{",
"'user'",
":",
"{",
"'email'",
":",
"profile",
"[",
"'userProfile'",
"]",
"[",
"'eMail'",
"]",
",",
"'name'",
":",
"'{} {}'",
".",
"format"... | Get vehicle summary. | [
"Get",
"vehicle",
"summary",
"."
] | train | https://github.com/happyleavesaoc/python-motorparts/blob/4a6b4dc72dd45524dd64a7a079478bd98c55215c/motorparts/__init__.py#L176-L194 |
happyleavesaoc/python-motorparts | motorparts/__init__.py | _remote_status | def _remote_status(session, service_id, uuid, url, interval=3):
"""Poll for remote command status."""
_LOGGER.info('polling for status')
resp = session.get(url, params={
'remoteServiceRequestID':service_id,
'uuid':uuid
}).json()
if resp['status'] == 'SUCCESS':
return 'complet... | python | def _remote_status(session, service_id, uuid, url, interval=3):
"""Poll for remote command status."""
_LOGGER.info('polling for status')
resp = session.get(url, params={
'remoteServiceRequestID':service_id,
'uuid':uuid
}).json()
if resp['status'] == 'SUCCESS':
return 'complet... | [
"def",
"_remote_status",
"(",
"session",
",",
"service_id",
",",
"uuid",
",",
"url",
",",
"interval",
"=",
"3",
")",
":",
"_LOGGER",
".",
"info",
"(",
"'polling for status'",
")",
"resp",
"=",
"session",
".",
"get",
"(",
"url",
",",
"params",
"=",
"{",... | Poll for remote command status. | [
"Poll",
"for",
"remote",
"command",
"status",
"."
] | train | https://github.com/happyleavesaoc/python-motorparts/blob/4a6b4dc72dd45524dd64a7a079478bd98c55215c/motorparts/__init__.py#L197-L207 |
happyleavesaoc/python-motorparts | motorparts/__init__.py | remote_command | def remote_command(session, command, vehicle_index, poll=True):
"""Send a remote command."""
if command not in SUPPORTED_COMMANDS:
raise MoparError("unsupported command: " + command)
profile = get_profile(session)
_validate_vehicle(vehicle_index, profile)
if command in [COMMAND_LOCK, COMMAND... | python | def remote_command(session, command, vehicle_index, poll=True):
"""Send a remote command."""
if command not in SUPPORTED_COMMANDS:
raise MoparError("unsupported command: " + command)
profile = get_profile(session)
_validate_vehicle(vehicle_index, profile)
if command in [COMMAND_LOCK, COMMAND... | [
"def",
"remote_command",
"(",
"session",
",",
"command",
",",
"vehicle_index",
",",
"poll",
"=",
"True",
")",
":",
"if",
"command",
"not",
"in",
"SUPPORTED_COMMANDS",
":",
"raise",
"MoparError",
"(",
"\"unsupported command: \"",
"+",
"command",
")",
"profile",
... | Send a remote command. | [
"Send",
"a",
"remote",
"command",
"."
] | train | https://github.com/happyleavesaoc/python-motorparts/blob/4a6b4dc72dd45524dd64a7a079478bd98c55215c/motorparts/__init__.py#L211-L232 |
happyleavesaoc/python-motorparts | motorparts/__init__.py | get_session | def get_session(username, password, pin, cookie_path=COOKIE_PATH):
"""Get a new session."""
class MoparAuth(AuthBase): # pylint: disable=too-few-public-methods
"""Authentication wrapper."""
def __init__(self, username, password, pin, cookie_path):
"""Init."""
self.usern... | python | def get_session(username, password, pin, cookie_path=COOKIE_PATH):
"""Get a new session."""
class MoparAuth(AuthBase): # pylint: disable=too-few-public-methods
"""Authentication wrapper."""
def __init__(self, username, password, pin, cookie_path):
"""Init."""
self.usern... | [
"def",
"get_session",
"(",
"username",
",",
"password",
",",
"pin",
",",
"cookie_path",
"=",
"COOKIE_PATH",
")",
":",
"class",
"MoparAuth",
"(",
"AuthBase",
")",
":",
"# pylint: disable=too-few-public-methods",
"\"\"\"Authentication wrapper.\"\"\"",
"def",
"__init__",
... | Get a new session. | [
"Get",
"a",
"new",
"session",
"."
] | train | https://github.com/happyleavesaoc/python-motorparts/blob/4a6b4dc72dd45524dd64a7a079478bd98c55215c/motorparts/__init__.py#L260-L284 |
erikdejonge/arguments | arguments/__init__.py | Arguments.get_usage_from_mdoc | def get_usage_from_mdoc(self):
"""
get_usage_from_mdoc
"""
usage = self.m_doc.strip().split("Usage:")
if len(usage) > 1:
usage = "\033[34mUsage:\033[34m" + usage[1]
return "\n".join(usage.strip().split("\n")[:2]) + "\033[0m" | python | def get_usage_from_mdoc(self):
"""
get_usage_from_mdoc
"""
usage = self.m_doc.strip().split("Usage:")
if len(usage) > 1:
usage = "\033[34mUsage:\033[34m" + usage[1]
return "\n".join(usage.strip().split("\n")[:2]) + "\033[0m" | [
"def",
"get_usage_from_mdoc",
"(",
"self",
")",
":",
"usage",
"=",
"self",
".",
"m_doc",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"Usage:\"",
")",
"if",
"len",
"(",
"usage",
")",
">",
"1",
":",
"usage",
"=",
"\"\\033[34mUsage:\\033[34m\"",
"+",
"us... | get_usage_from_mdoc | [
"get_usage_from_mdoc"
] | train | https://github.com/erikdejonge/arguments/blob/fc222d3989d459343a81944cabb56854014335ed/arguments/__init__.py#L421-L430 |
erikdejonge/arguments | arguments/__init__.py | Arguments.print_commandless_help | def print_commandless_help(self):
"""
print_commandless_help
"""
doc_help = self.m_doc.strip().split("\n")
if len(doc_help) > 0:
print("\033[33m--\033[0m")
print("\033[34m" + doc_help[0] + "\033[0m")
asp = "author :"
doc_help_rest... | python | def print_commandless_help(self):
"""
print_commandless_help
"""
doc_help = self.m_doc.strip().split("\n")
if len(doc_help) > 0:
print("\033[33m--\033[0m")
print("\033[34m" + doc_help[0] + "\033[0m")
asp = "author :"
doc_help_rest... | [
"def",
"print_commandless_help",
"(",
"self",
")",
":",
"doc_help",
"=",
"self",
".",
"m_doc",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"len",
"(",
"doc_help",
")",
">",
"0",
":",
"print",
"(",
"\"\\033[33m--\\033[0m\"",
")",
"p... | print_commandless_help | [
"print_commandless_help"
] | train | https://github.com/erikdejonge/arguments/blob/fc222d3989d459343a81944cabb56854014335ed/arguments/__init__.py#L602-L628 |
erikdejonge/arguments | arguments/__init__.py | Arguments.get_command_path | def get_command_path(self):
"""
get_command_path
"""
name = ""
if self.m_parents is not None:
for parent in self.m_parents:
name += parent.snake_case_class_name()
name += " "
name += self.snake_case_class_name()
return... | python | def get_command_path(self):
"""
get_command_path
"""
name = ""
if self.m_parents is not None:
for parent in self.m_parents:
name += parent.snake_case_class_name()
name += " "
name += self.snake_case_class_name()
return... | [
"def",
"get_command_path",
"(",
"self",
")",
":",
"name",
"=",
"\"\"",
"if",
"self",
".",
"m_parents",
"is",
"not",
"None",
":",
"for",
"parent",
"in",
"self",
".",
"m_parents",
":",
"name",
"+=",
"parent",
".",
"snake_case_class_name",
"(",
")",
"name",... | get_command_path | [
"get_command_path"
] | train | https://github.com/erikdejonge/arguments/blob/fc222d3989d459343a81944cabb56854014335ed/arguments/__init__.py#L723-L735 |
erikdejonge/arguments | arguments/__init__.py | Arguments.for_print | def for_print(self):
"""
for_print
"""
s = "\033[34m" + self.get_object_info() + "\033[0m"
s += "\n"
s += self.as_string()
return s | python | def for_print(self):
"""
for_print
"""
s = "\033[34m" + self.get_object_info() + "\033[0m"
s += "\n"
s += self.as_string()
return s | [
"def",
"for_print",
"(",
"self",
")",
":",
"s",
"=",
"\"\\033[34m\"",
"+",
"self",
".",
"get_object_info",
"(",
")",
"+",
"\"\\033[0m\"",
"s",
"+=",
"\"\\n\"",
"s",
"+=",
"self",
".",
"as_string",
"(",
")",
"return",
"s"
] | for_print | [
"for_print"
] | train | https://github.com/erikdejonge/arguments/blob/fc222d3989d459343a81944cabb56854014335ed/arguments/__init__.py#L743-L750 |
erikdejonge/arguments | arguments/__init__.py | Arguments.get_subclass | def get_subclass(self):
"""
get_subclass
"""
strbldr = """
class IArguments(Arguments):
\"\"\"
IArguments
\"\"\"
def __init__(self, doc=None, validateschema=None, argvalue=None, yamlstr=None, yamlfile=None, parse... | python | def get_subclass(self):
"""
get_subclass
"""
strbldr = """
class IArguments(Arguments):
\"\"\"
IArguments
\"\"\"
def __init__(self, doc=None, validateschema=None, argvalue=None, yamlstr=None, yamlfile=None, parse... | [
"def",
"get_subclass",
"(",
"self",
")",
":",
"strbldr",
"=",
"\"\"\"\n class IArguments(Arguments):\n \\\"\\\"\\\"\n IArguments\n \\\"\\\"\\\"\n def __init__(self, doc=None, validateschema=None, argvalue=None, yamlstr=None, yaml... | get_subclass | [
"get_subclass"
] | train | https://github.com/erikdejonge/arguments/blob/fc222d3989d459343a81944cabb56854014335ed/arguments/__init__.py#L752-L791 |
erikdejonge/arguments | arguments/__init__.py | Arguments.write_members | def write_members(self):
"""
write_members
"""
s = ""
objattributes = list(self.m_reprdict["positional"].keys())
objattributes.extend(list(self.m_reprdict["options"].keys()))
objattributes.sort()
for objattr in objattributes:
s += 8 * " " + "s... | python | def write_members(self):
"""
write_members
"""
s = ""
objattributes = list(self.m_reprdict["positional"].keys())
objattributes.extend(list(self.m_reprdict["options"].keys()))
objattributes.sort()
for objattr in objattributes:
s += 8 * " " + "s... | [
"def",
"write_members",
"(",
"self",
")",
":",
"s",
"=",
"\"\"",
"objattributes",
"=",
"list",
"(",
"self",
".",
"m_reprdict",
"[",
"\"positional\"",
"]",
".",
"keys",
"(",
")",
")",
"objattributes",
".",
"extend",
"(",
"list",
"(",
"self",
".",
"m_rep... | write_members | [
"write_members"
] | train | https://github.com/erikdejonge/arguments/blob/fc222d3989d459343a81944cabb56854014335ed/arguments/__init__.py#L794-L822 |
erikdejonge/arguments | arguments/__init__.py | Arguments.get_object_info | def get_object_info(self):
"""
Returns object info in following form <module.class object at address>
"""
objectinfo = str(self.__class__).replace(">", "")
objectinfo = objectinfo.replace("class ", "")
objectinfo = objectinfo.replace("'", "")
objectinfo += " objec... | python | def get_object_info(self):
"""
Returns object info in following form <module.class object at address>
"""
objectinfo = str(self.__class__).replace(">", "")
objectinfo = objectinfo.replace("class ", "")
objectinfo = objectinfo.replace("'", "")
objectinfo += " objec... | [
"def",
"get_object_info",
"(",
"self",
")",
":",
"objectinfo",
"=",
"str",
"(",
"self",
".",
"__class__",
")",
".",
"replace",
"(",
"\">\"",
",",
"\"\"",
")",
"objectinfo",
"=",
"objectinfo",
".",
"replace",
"(",
"\"class \"",
",",
"\"\"",
")",
"objectin... | Returns object info in following form <module.class object at address> | [
"Returns",
"object",
"info",
"in",
"following",
"form",
"<module",
".",
"class",
"object",
"at",
"address",
">"
] | train | https://github.com/erikdejonge/arguments/blob/fc222d3989d459343a81944cabb56854014335ed/arguments/__init__.py#L851-L859 |
erikdejonge/arguments | arguments/__init__.py | Arguments._set_fields | def _set_fields(self, positional, options):
"""
_parse_arguments
"""
dictionary = {}
if positional is not None and options is not None:
self.positional = positional.copy()
self.options = options.copy()
dictionary = positional.copy()
... | python | def _set_fields(self, positional, options):
"""
_parse_arguments
"""
dictionary = {}
if positional is not None and options is not None:
self.positional = positional.copy()
self.options = options.copy()
dictionary = positional.copy()
... | [
"def",
"_set_fields",
"(",
"self",
",",
"positional",
",",
"options",
")",
":",
"dictionary",
"=",
"{",
"}",
"if",
"positional",
"is",
"not",
"None",
"and",
"options",
"is",
"not",
"None",
":",
"self",
".",
"positional",
"=",
"positional",
".",
"copy",
... | _parse_arguments | [
"_parse_arguments"
] | train | https://github.com/erikdejonge/arguments/blob/fc222d3989d459343a81944cabb56854014335ed/arguments/__init__.py#L861-L880 |
erikdejonge/arguments | arguments/__init__.py | Arguments.set_reprdict_from_attributes | def set_reprdict_from_attributes(self):
"""
set_reprdict_from_attributes
"""
reprcopy = self.m_reprdict.copy()
for kd, d in reprcopy.items():
for k in d.keys():
if hasattr(self, k):
self.m_reprdict[kd][k] = getattr(self, k) | python | def set_reprdict_from_attributes(self):
"""
set_reprdict_from_attributes
"""
reprcopy = self.m_reprdict.copy()
for kd, d in reprcopy.items():
for k in d.keys():
if hasattr(self, k):
self.m_reprdict[kd][k] = getattr(self, k) | [
"def",
"set_reprdict_from_attributes",
"(",
"self",
")",
":",
"reprcopy",
"=",
"self",
".",
"m_reprdict",
".",
"copy",
"(",
")",
"for",
"kd",
",",
"d",
"in",
"reprcopy",
".",
"items",
"(",
")",
":",
"for",
"k",
"in",
"d",
".",
"keys",
"(",
")",
":"... | set_reprdict_from_attributes | [
"set_reprdict_from_attributes"
] | train | https://github.com/erikdejonge/arguments/blob/fc222d3989d459343a81944cabb56854014335ed/arguments/__init__.py#L920-L929 |
erikdejonge/arguments | arguments/__init__.py | Arguments.as_yaml | def as_yaml(self):
"""
as_yaml
"""
self.set_reprdict_from_attributes()
return "---\n" + yaml.dump(self.m_reprdict, default_flow_style=False) | python | def as_yaml(self):
"""
as_yaml
"""
self.set_reprdict_from_attributes()
return "---\n" + yaml.dump(self.m_reprdict, default_flow_style=False) | [
"def",
"as_yaml",
"(",
"self",
")",
":",
"self",
".",
"set_reprdict_from_attributes",
"(",
")",
"return",
"\"---\\n\"",
"+",
"yaml",
".",
"dump",
"(",
"self",
".",
"m_reprdict",
",",
"default_flow_style",
"=",
"False",
")"
] | as_yaml | [
"as_yaml"
] | train | https://github.com/erikdejonge/arguments/blob/fc222d3989d459343a81944cabb56854014335ed/arguments/__init__.py#L931-L936 |
erikdejonge/arguments | arguments/__init__.py | SchemaError.code | def code(self):
"""
code
"""
def uniq(seq):
"""
@type seq: str
@return: None
"""
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and not seen_add(x)]
# noinspection PyTy... | python | def code(self):
"""
code
"""
def uniq(seq):
"""
@type seq: str
@return: None
"""
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and not seen_add(x)]
# noinspection PyTy... | [
"def",
"code",
"(",
"self",
")",
":",
"def",
"uniq",
"(",
"seq",
")",
":",
"\"\"\"\n @type seq: str\n @return: None\n \"\"\"",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"return",
"[",
"x",
"for",
"x",
"... | code | [
"code"
] | train | https://github.com/erikdejonge/arguments/blob/fc222d3989d459343a81944cabb56854014335ed/arguments/__init__.py#L1081-L1103 |
ionelmc/python-cogen | examples/cogen-chat/ChatApp/chatapp/config/routing.py | make_map | def make_map():
"""Create, configure and return the routes Mapper"""
map = Mapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
# The ErrorController route (handles 404/500 error pages); it should
# likely stay at the top, ensuring it can always be... | python | def make_map():
"""Create, configure and return the routes Mapper"""
map = Mapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
# The ErrorController route (handles 404/500 error pages); it should
# likely stay at the top, ensuring it can always be... | [
"def",
"make_map",
"(",
")",
":",
"map",
"=",
"Mapper",
"(",
"directory",
"=",
"config",
"[",
"'pylons.paths'",
"]",
"[",
"'controllers'",
"]",
",",
"always_scan",
"=",
"config",
"[",
"'debug'",
"]",
")",
"# The ErrorController route (handles 404/500 error pages);... | Create, configure and return the routes Mapper | [
"Create",
"configure",
"and",
"return",
"the",
"routes",
"Mapper"
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/cogen-chat/ChatApp/chatapp/config/routing.py#L10-L23 |
henzk/django-productline | django_productline/features/djpladmin/context_processors.py | django_admin | def django_admin(request):
'''
Adds additional information to the context:
``django_admin`` - boolean variable indicating whether the current
page is part of the django admin or not.
``ADMIN_URL`` - normalized version of settings.ADMIN_URL; starts with a slash, ends without a slash
NOTE: do no... | python | def django_admin(request):
'''
Adds additional information to the context:
``django_admin`` - boolean variable indicating whether the current
page is part of the django admin or not.
``ADMIN_URL`` - normalized version of settings.ADMIN_URL; starts with a slash, ends without a slash
NOTE: do no... | [
"def",
"django_admin",
"(",
"request",
")",
":",
"# ensure that adminurl always starts with a '/' but never ends with a '/'",
"if",
"settings",
".",
"ADMIN_URL",
".",
"endswith",
"(",
"'/'",
")",
":",
"admin_url",
"=",
"settings",
".",
"ADMIN_URL",
"[",
":",
"-",
"1... | Adds additional information to the context:
``django_admin`` - boolean variable indicating whether the current
page is part of the django admin or not.
``ADMIN_URL`` - normalized version of settings.ADMIN_URL; starts with a slash, ends without a slash
NOTE: do not set ADMIN_URL='/' in case your applic... | [
"Adds",
"additional",
"information",
"to",
"the",
"context",
":"
] | train | https://github.com/henzk/django-productline/blob/24ff156924c1a8c07b99cbb8a1de0a42b8d81f60/django_productline/features/djpladmin/context_processors.py#L6-L33 |
ionelmc/python-cogen | examples/cogen-chat/ChatApp/chatapp/controllers/error.py | ErrorController.document | def document(self):
"""Render the error document"""
resp = request.environ.get('pylons.original_response')
page = error_document_template % \
dict(prefix=request.environ.get('SCRIPT_NAME', ''),
code=request.params.get('code', resp.status_int),
... | python | def document(self):
"""Render the error document"""
resp = request.environ.get('pylons.original_response')
page = error_document_template % \
dict(prefix=request.environ.get('SCRIPT_NAME', ''),
code=request.params.get('code', resp.status_int),
... | [
"def",
"document",
"(",
"self",
")",
":",
"resp",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"'pylons.original_response'",
")",
"page",
"=",
"error_document_template",
"%",
"dict",
"(",
"prefix",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"'SCR... | Render the error document | [
"Render",
"the",
"error",
"document"
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/cogen-chat/ChatApp/chatapp/controllers/error.py#L19-L26 |
ionelmc/python-cogen | examples/cogen-chat/ChatApp/chatapp/controllers/error.py | ErrorController.img | def img(self, id):
"""Serve Pylons' stock images"""
return self._serve_file(os.path.join(media_path, 'img', id)) | python | def img(self, id):
"""Serve Pylons' stock images"""
return self._serve_file(os.path.join(media_path, 'img', id)) | [
"def",
"img",
"(",
"self",
",",
"id",
")",
":",
"return",
"self",
".",
"_serve_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"media_path",
",",
"'img'",
",",
"id",
")",
")"
] | Serve Pylons' stock images | [
"Serve",
"Pylons",
"stock",
"images"
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/cogen-chat/ChatApp/chatapp/controllers/error.py#L28-L30 |
ionelmc/python-cogen | examples/cogen-chat/ChatApp/chatapp/controllers/error.py | ErrorController.style | def style(self, id):
"""Serve Pylons' stock stylesheets"""
return self._serve_file(os.path.join(media_path, 'style', id)) | python | def style(self, id):
"""Serve Pylons' stock stylesheets"""
return self._serve_file(os.path.join(media_path, 'style', id)) | [
"def",
"style",
"(",
"self",
",",
"id",
")",
":",
"return",
"self",
".",
"_serve_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"media_path",
",",
"'style'",
",",
"id",
")",
")"
] | Serve Pylons' stock stylesheets | [
"Serve",
"Pylons",
"stock",
"stylesheets"
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/cogen-chat/ChatApp/chatapp/controllers/error.py#L32-L34 |
ionelmc/python-cogen | examples/cogen-chat/ChatApp/chatapp/controllers/error.py | ErrorController._serve_file | def _serve_file(self, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
fapp = paste.fileapp.FileApp(path)
return fapp(request.environ, self.start_response) | python | def _serve_file(self, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
fapp = paste.fileapp.FileApp(path)
return fapp(request.environ, self.start_response) | [
"def",
"_serve_file",
"(",
"self",
",",
"path",
")",
":",
"fapp",
"=",
"paste",
".",
"fileapp",
".",
"FileApp",
"(",
"path",
")",
"return",
"fapp",
"(",
"request",
".",
"environ",
",",
"self",
".",
"start_response",
")"
] | Call Paste's FileApp (a WSGI application) to serve the file
at the specified path | [
"Call",
"Paste",
"s",
"FileApp",
"(",
"a",
"WSGI",
"application",
")",
"to",
"serve",
"the",
"file",
"at",
"the",
"specified",
"path"
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/cogen-chat/ChatApp/chatapp/controllers/error.py#L36-L41 |
aequitas/rcfile | rcfile.py | rcfile | def rcfile(appname, args={}, strip_dashes=True, module_name=None):
"""
Read environment variables and config files and return them merged with predefined list of arguments.
Arguments:
appname - application name, used for config files and environemnt variable names.
args - ar... | python | def rcfile(appname, args={}, strip_dashes=True, module_name=None):
"""
Read environment variables and config files and return them merged with predefined list of arguments.
Arguments:
appname - application name, used for config files and environemnt variable names.
args - ar... | [
"def",
"rcfile",
"(",
"appname",
",",
"args",
"=",
"{",
"}",
",",
"strip_dashes",
"=",
"True",
",",
"module_name",
"=",
"None",
")",
":",
"if",
"strip_dashes",
":",
"for",
"k",
"in",
"args",
".",
"keys",
"(",
")",
":",
"args",
"[",
"k",
".",
"lst... | Read environment variables and config files and return them merged with predefined list of arguments.
Arguments:
appname - application name, used for config files and environemnt variable names.
args - arguments from command line (optparse, docopt, etc).
strip_dashes - strip... | [
"Read",
"environment",
"variables",
"and",
"config",
"files",
"and",
"return",
"them",
"merged",
"with",
"predefined",
"list",
"of",
"arguments",
"."
] | train | https://github.com/aequitas/rcfile/blob/9036cefae7d9472c077149c42069bac249ead3c1/rcfile.py#L62-L101 |
jgilchrist/pybib | pybib/formatters.py | color_parts | def color_parts(parts):
"""Adds colors to each part of the citation"""
return parts._replace(
title=Fore.GREEN + parts.title + Style.RESET_ALL,
doi=Fore.CYAN + parts.doi + Style.RESET_ALL
) | python | def color_parts(parts):
"""Adds colors to each part of the citation"""
return parts._replace(
title=Fore.GREEN + parts.title + Style.RESET_ALL,
doi=Fore.CYAN + parts.doi + Style.RESET_ALL
) | [
"def",
"color_parts",
"(",
"parts",
")",
":",
"return",
"parts",
".",
"_replace",
"(",
"title",
"=",
"Fore",
".",
"GREEN",
"+",
"parts",
".",
"title",
"+",
"Style",
".",
"RESET_ALL",
",",
"doi",
"=",
"Fore",
".",
"CYAN",
"+",
"parts",
".",
"doi",
"... | Adds colors to each part of the citation | [
"Adds",
"colors",
"to",
"each",
"part",
"of",
"the",
"citation"
] | train | https://github.com/jgilchrist/pybib/blob/da2130d281bb02e930728ed7c1d0c1dffa747ee0/pybib/formatters.py#L22-L27 |
jgilchrist/pybib | pybib/formatters.py | get_common_parts | def get_common_parts(r):
"""Gets citation parts which are common to all types of citation"""
title = format_title(r.get('title'))
author_list = format_author_list(r.get('author'))
container = format_container(r.get('container-title'))
date = format_date(r.get('issued'))
doi = r.get('DOI')
... | python | def get_common_parts(r):
"""Gets citation parts which are common to all types of citation"""
title = format_title(r.get('title'))
author_list = format_author_list(r.get('author'))
container = format_container(r.get('container-title'))
date = format_date(r.get('issued'))
doi = r.get('DOI')
... | [
"def",
"get_common_parts",
"(",
"r",
")",
":",
"title",
"=",
"format_title",
"(",
"r",
".",
"get",
"(",
"'title'",
")",
")",
"author_list",
"=",
"format_author_list",
"(",
"r",
".",
"get",
"(",
"'author'",
")",
")",
"container",
"=",
"format_container",
... | Gets citation parts which are common to all types of citation | [
"Gets",
"citation",
"parts",
"which",
"are",
"common",
"to",
"all",
"types",
"of",
"citation"
] | train | https://github.com/jgilchrist/pybib/blob/da2130d281bb02e930728ed7c1d0c1dffa747ee0/pybib/formatters.py#L65-L74 |
DomBennett/TaxonNamesResolver | taxon_names_resolver/gnr_tools.py | safeReadJSON | def safeReadJSON(url, logger, max_check=6, waittime=30):
'''Return JSON object from URL'''
counter = 0
# try, try and try again ....
while counter < max_check:
try:
with contextlib.closing(urllib.request.urlopen(url)) as f:
res = json.loads(f.read().decode('utf8'))
... | python | def safeReadJSON(url, logger, max_check=6, waittime=30):
'''Return JSON object from URL'''
counter = 0
# try, try and try again ....
while counter < max_check:
try:
with contextlib.closing(urllib.request.urlopen(url)) as f:
res = json.loads(f.read().decode('utf8'))
... | [
"def",
"safeReadJSON",
"(",
"url",
",",
"logger",
",",
"max_check",
"=",
"6",
",",
"waittime",
"=",
"30",
")",
":",
"counter",
"=",
"0",
"# try, try and try again ....",
"while",
"counter",
"<",
"max_check",
":",
"try",
":",
"with",
"contextlib",
".",
"clo... | Return JSON object from URL | [
"Return",
"JSON",
"object",
"from",
"URL"
] | train | https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/gnr_tools.py#L18-L32 |
DomBennett/TaxonNamesResolver | taxon_names_resolver/gnr_tools.py | GnrResolver.search | def search(self, terms, prelim=True):
"""Search terms against GNR. If prelim = False, search other datasources \
for alternative names (i.e. synonyms) with which to search main datasource.\
Return JSON object."""
# TODO: There are now lots of additional data sources, make additional
# searching ... | python | def search(self, terms, prelim=True):
"""Search terms against GNR. If prelim = False, search other datasources \
for alternative names (i.e. synonyms) with which to search main datasource.\
Return JSON object."""
# TODO: There are now lots of additional data sources, make additional
# searching ... | [
"def",
"search",
"(",
"self",
",",
"terms",
",",
"prelim",
"=",
"True",
")",
":",
"# TODO: There are now lots of additional data sources, make additional",
"# searching optional (11/01/2017)",
"if",
"prelim",
":",
"# preliminary search",
"res",
"=",
"self",
".",
"_resolve... | Search terms against GNR. If prelim = False, search other datasources \
for alternative names (i.e. synonyms) with which to search main datasource.\
Return JSON object. | [
"Search",
"terms",
"against",
"GNR",
".",
"If",
"prelim",
"=",
"False",
"search",
"other",
"datasources",
"\\",
"for",
"alternative",
"names",
"(",
"i",
".",
"e",
".",
"synonyms",
")",
"with",
"which",
"to",
"search",
"main",
"datasource",
".",
"\\",
"Re... | train | https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/gnr_tools.py#L67-L97 |
celliern/triflow | triflow/core/compilers.py | theano_compiler | def theano_compiler(model):
"""Take a triflow model and return optimized theano routines.
Parameters
----------
model: triflow.Model:
Model to compile
Returns
-------
(theano function, theano_function):
Optimized routine that compute the evolution equations and their
... | python | def theano_compiler(model):
"""Take a triflow model and return optimized theano routines.
Parameters
----------
model: triflow.Model:
Model to compile
Returns
-------
(theano function, theano_function):
Optimized routine that compute the evolution equations and their
... | [
"def",
"theano_compiler",
"(",
"model",
")",
":",
"from",
"theano",
"import",
"tensor",
"as",
"T",
"from",
"theano",
".",
"ifelse",
"import",
"ifelse",
"import",
"theano",
".",
"sparse",
"as",
"ths",
"from",
"theano",
"import",
"function",
"def",
"th_Min",
... | Take a triflow model and return optimized theano routines.
Parameters
----------
model: triflow.Model:
Model to compile
Returns
-------
(theano function, theano_function):
Optimized routine that compute the evolution equations and their
jacobian matrix. | [
"Take",
"a",
"triflow",
"model",
"and",
"return",
"optimized",
"theano",
"routines",
"."
] | train | https://github.com/celliern/triflow/blob/9522de077c43c8af7d4bf08fbd4ce4b7b480dccb/triflow/core/compilers.py#L11-L178 |
celliern/triflow | triflow/core/compilers.py | numpy_compiler | def numpy_compiler(model):
"""Take a triflow model and return optimized numpy routines.
Parameters
----------
model: triflow.Model:
Model to compile
Returns
-------
(numpy function, numpy function):
Optimized routine that compute the evolution equations and their
ja... | python | def numpy_compiler(model):
"""Take a triflow model and return optimized numpy routines.
Parameters
----------
model: triflow.Model:
Model to compile
Returns
-------
(numpy function, numpy function):
Optimized routine that compute the evolution equations and their
ja... | [
"def",
"numpy_compiler",
"(",
"model",
")",
":",
"def",
"np_Min",
"(",
"args",
")",
":",
"a",
",",
"b",
"=",
"args",
"return",
"np",
".",
"where",
"(",
"a",
"<",
"b",
",",
"a",
",",
"b",
")",
"def",
"np_Max",
"(",
"args",
")",
":",
"a",
",",
... | Take a triflow model and return optimized numpy routines.
Parameters
----------
model: triflow.Model:
Model to compile
Returns
-------
(numpy function, numpy function):
Optimized routine that compute the evolution equations and their
jacobian matrix. | [
"Take",
"a",
"triflow",
"model",
"and",
"return",
"optimized",
"numpy",
"routines",
"."
] | train | https://github.com/celliern/triflow/blob/9522de077c43c8af7d4bf08fbd4ce4b7b480dccb/triflow/core/compilers.py#L181-L224 |
sjwood/pydvdid | pydvdid/crc64calculator.py | _Crc64Calculator.update | def update(self, content):
"""Enumerates the bytes of the supplied bytearray and updates the CRC-64.
No return value.
"""
for byte in content:
self._crc64 = (self._crc64 >> 8) ^ self._lookup_table[(self._crc64 & 0xff) ^ byte] | python | def update(self, content):
"""Enumerates the bytes of the supplied bytearray and updates the CRC-64.
No return value.
"""
for byte in content:
self._crc64 = (self._crc64 >> 8) ^ self._lookup_table[(self._crc64 & 0xff) ^ byte] | [
"def",
"update",
"(",
"self",
",",
"content",
")",
":",
"for",
"byte",
"in",
"content",
":",
"self",
".",
"_crc64",
"=",
"(",
"self",
".",
"_crc64",
">>",
"8",
")",
"^",
"self",
".",
"_lookup_table",
"[",
"(",
"self",
".",
"_crc64",
"&",
"0xff",
... | Enumerates the bytes of the supplied bytearray and updates the CRC-64.
No return value. | [
"Enumerates",
"the",
"bytes",
"of",
"the",
"supplied",
"bytearray",
"and",
"updates",
"the",
"CRC",
"-",
"64",
".",
"No",
"return",
"value",
"."
] | train | https://github.com/sjwood/pydvdid/blob/03914fb7e24283c445e5af724f9d919b23caaf95/pydvdid/crc64calculator.py#L29-L35 |
sjwood/pydvdid | pydvdid/crc64calculator.py | _Crc64Calculator._construct_lookup_table | def _construct_lookup_table(self, polynomial):
"""Precomputes a CRC-64 lookup table seeded from the supplied polynomial.
No return value.
"""
self._lookup_table = []
for i in range(0, 256):
lookup_value = i
for _ in range(0, 8):
if lo... | python | def _construct_lookup_table(self, polynomial):
"""Precomputes a CRC-64 lookup table seeded from the supplied polynomial.
No return value.
"""
self._lookup_table = []
for i in range(0, 256):
lookup_value = i
for _ in range(0, 8):
if lo... | [
"def",
"_construct_lookup_table",
"(",
"self",
",",
"polynomial",
")",
":",
"self",
".",
"_lookup_table",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"256",
")",
":",
"lookup_value",
"=",
"i",
"for",
"_",
"in",
"range",
"(",
"0",
",",
... | Precomputes a CRC-64 lookup table seeded from the supplied polynomial.
No return value. | [
"Precomputes",
"a",
"CRC",
"-",
"64",
"lookup",
"table",
"seeded",
"from",
"the",
"supplied",
"polynomial",
".",
"No",
"return",
"value",
"."
] | train | https://github.com/sjwood/pydvdid/blob/03914fb7e24283c445e5af724f9d919b23caaf95/pydvdid/crc64calculator.py#L38-L55 |
ionelmc/python-cogen | cogen/magic/socketlets.py | Socket.makefile | def makefile(self, mode='r', bufsize=-1):
"""
Returns a special fileobject that has corutines instead of the usual
read/readline/write methods. Will work in the same manner though.
"""
return _fileobject(Socket(
_sock=self._fd._sock,
_timeout=self.... | python | def makefile(self, mode='r', bufsize=-1):
"""
Returns a special fileobject that has corutines instead of the usual
read/readline/write methods. Will work in the same manner though.
"""
return _fileobject(Socket(
_sock=self._fd._sock,
_timeout=self.... | [
"def",
"makefile",
"(",
"self",
",",
"mode",
"=",
"'r'",
",",
"bufsize",
"=",
"-",
"1",
")",
":",
"return",
"_fileobject",
"(",
"Socket",
"(",
"_sock",
"=",
"self",
".",
"_fd",
".",
"_sock",
",",
"_timeout",
"=",
"self",
".",
"_timeout",
",",
"_pro... | Returns a special fileobject that has corutines instead of the usual
read/readline/write methods. Will work in the same manner though. | [
"Returns",
"a",
"special",
"fileobject",
"that",
"has",
"corutines",
"instead",
"of",
"the",
"usual",
"read",
"/",
"readline",
"/",
"write",
"methods",
".",
"Will",
"work",
"in",
"the",
"same",
"manner",
"though",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/magic/socketlets.py#L46-L55 |
ionelmc/python-cogen | cogen/magic/socketlets.py | Socket.send | def send(self, data, **kws):
"""Send data to the socket. The socket must be connected to a remote
socket. Ammount sent may be less than the data provided."""
return yield_(Send(self, data, timeout=self._timeout, **kws)) | python | def send(self, data, **kws):
"""Send data to the socket. The socket must be connected to a remote
socket. Ammount sent may be less than the data provided."""
return yield_(Send(self, data, timeout=self._timeout, **kws)) | [
"def",
"send",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kws",
")",
":",
"return",
"yield_",
"(",
"Send",
"(",
"self",
",",
"data",
",",
"timeout",
"=",
"self",
".",
"_timeout",
",",
"*",
"*",
"kws",
")",
")"
] | Send data to the socket. The socket must be connected to a remote
socket. Ammount sent may be less than the data provided. | [
"Send",
"data",
"to",
"the",
"socket",
".",
"The",
"socket",
"must",
"be",
"connected",
"to",
"a",
"remote",
"socket",
".",
"Ammount",
"sent",
"may",
"be",
"less",
"than",
"the",
"data",
"provided",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/magic/socketlets.py#L57-L60 |
ionelmc/python-cogen | cogen/magic/socketlets.py | Socket.accept | def accept(self, **kws):
"""Accept a connection. The socket must be bound to an address and
listening for connections. The return value is a pair (conn, address)
where conn is a new socket object usable to send and receive data on the
connection, and address is the address bound to t... | python | def accept(self, **kws):
"""Accept a connection. The socket must be bound to an address and
listening for connections. The return value is a pair (conn, address)
where conn is a new socket object usable to send and receive data on the
connection, and address is the address bound to t... | [
"def",
"accept",
"(",
"self",
",",
"*",
"*",
"kws",
")",
":",
"return",
"yield_",
"(",
"Accept",
"(",
"self",
",",
"timeout",
"=",
"self",
".",
"_timeout",
",",
"*",
"*",
"kws",
")",
")"
] | Accept a connection. The socket must be bound to an address and
listening for connections. The return value is a pair (conn, address)
where conn is a new socket object usable to send and receive data on the
connection, and address is the address bound to the socket on the other
end o... | [
"Accept",
"a",
"connection",
".",
"The",
"socket",
"must",
"be",
"bound",
"to",
"an",
"address",
"and",
"listening",
"for",
"connections",
".",
"The",
"return",
"value",
"is",
"a",
"pair",
"(",
"conn",
"address",
")",
"where",
"conn",
"is",
"a",
"new",
... | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/magic/socketlets.py#L67-L79 |
ionelmc/python-cogen | cogen/magic/socketlets.py | Socket.connect | def connect(self, address, **kws):
"""Connect to a remote socket at _address_. """
return yield_(Connect(self, address, timeout=self._timeout, **kws)) | python | def connect(self, address, **kws):
"""Connect to a remote socket at _address_. """
return yield_(Connect(self, address, timeout=self._timeout, **kws)) | [
"def",
"connect",
"(",
"self",
",",
"address",
",",
"*",
"*",
"kws",
")",
":",
"return",
"yield_",
"(",
"Connect",
"(",
"self",
",",
"address",
",",
"timeout",
"=",
"self",
".",
"_timeout",
",",
"*",
"*",
"kws",
")",
")"
] | Connect to a remote socket at _address_. | [
"Connect",
"to",
"a",
"remote",
"socket",
"at",
"_address_",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/magic/socketlets.py#L81-L83 |
klen/django-netauth | netauth/auth.py | NetBackend.authenticate | def authenticate(identity=None, provider=None):
" Authenticate user by net identity. "
if not identity:
return None
try:
netid = NetID.objects.get(identity=identity, provider=provider)
return netid.user
except NetID.DoesNotExist:
return No... | python | def authenticate(identity=None, provider=None):
" Authenticate user by net identity. "
if not identity:
return None
try:
netid = NetID.objects.get(identity=identity, provider=provider)
return netid.user
except NetID.DoesNotExist:
return No... | [
"def",
"authenticate",
"(",
"identity",
"=",
"None",
",",
"provider",
"=",
"None",
")",
":",
"if",
"not",
"identity",
":",
"return",
"None",
"try",
":",
"netid",
"=",
"NetID",
".",
"objects",
".",
"get",
"(",
"identity",
"=",
"identity",
",",
"provider... | Authenticate user by net identity. | [
"Authenticate",
"user",
"by",
"net",
"identity",
"."
] | train | https://github.com/klen/django-netauth/blob/228e4297fda98d5f9df35f86a01f87c6fb05ab1d/netauth/auth.py#L22-L31 |
kennknowles/python-rightarrow | rightarrow/enforce.py | check | def check(ty, val):
"Checks that `val` adheres to type `ty`"
if isinstance(ty, basestring):
ty = Parser().parse(ty)
return ty.enforce(val) | python | def check(ty, val):
"Checks that `val` adheres to type `ty`"
if isinstance(ty, basestring):
ty = Parser().parse(ty)
return ty.enforce(val) | [
"def",
"check",
"(",
"ty",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"ty",
",",
"basestring",
")",
":",
"ty",
"=",
"Parser",
"(",
")",
".",
"parse",
"(",
"ty",
")",
"return",
"ty",
".",
"enforce",
"(",
"val",
")"
] | Checks that `val` adheres to type `ty` | [
"Checks",
"that",
"val",
"adheres",
"to",
"type",
"ty"
] | train | https://github.com/kennknowles/python-rightarrow/blob/86c83bde9d2fba6d54744eac9abedd1c248b7e73/rightarrow/enforce.py#L4-L10 |
SetBased/py-etlt | etlt/dimension/RegularDimension.py | RegularDimension.get_id | def get_id(self, natural_key, enhancement=None):
"""
Returns the technical ID for a natural key or None if the given natural key is not valid.
:param T natural_key: The natural key.
:param T enhancement: Enhancement data of the dimension row.
:rtype: int|None
"""
... | python | def get_id(self, natural_key, enhancement=None):
"""
Returns the technical ID for a natural key or None if the given natural key is not valid.
:param T natural_key: The natural key.
:param T enhancement: Enhancement data of the dimension row.
:rtype: int|None
"""
... | [
"def",
"get_id",
"(",
"self",
",",
"natural_key",
",",
"enhancement",
"=",
"None",
")",
":",
"# If the natural key is known return the technical ID immediately.",
"if",
"natural_key",
"in",
"self",
".",
"_map",
":",
"return",
"self",
".",
"_map",
"[",
"natural_key",... | Returns the technical ID for a natural key or None if the given natural key is not valid.
:param T natural_key: The natural key.
:param T enhancement: Enhancement data of the dimension row.
:rtype: int|None | [
"Returns",
"the",
"technical",
"ID",
"for",
"a",
"natural",
"key",
"or",
"None",
"if",
"the",
"given",
"natural",
"key",
"is",
"not",
"valid",
"."
] | train | https://github.com/SetBased/py-etlt/blob/1c5b8ea60293c14f54d7845a9fe5c595021f66f2/etlt/dimension/RegularDimension.py#L33-L59 |
seibert-media/Highton | highton/models/tag.py | Tag.get | def get(cls, object_id):
"""
Get all parties (people and companies) associated with a given tag.
:param object_id: the primary id of the model
:type object_id: integer
:return: the parties
:rtype: list
"""
from highton.models.party import Party
ret... | python | def get(cls, object_id):
"""
Get all parties (people and companies) associated with a given tag.
:param object_id: the primary id of the model
:type object_id: integer
:return: the parties
:rtype: list
"""
from highton.models.party import Party
ret... | [
"def",
"get",
"(",
"cls",
",",
"object_id",
")",
":",
"from",
"highton",
".",
"models",
".",
"party",
"import",
"Party",
"return",
"fields",
".",
"ListField",
"(",
"name",
"=",
"Party",
".",
"ENDPOINT",
",",
"init_class",
"=",
"Party",
")",
".",
"decod... | Get all parties (people and companies) associated with a given tag.
:param object_id: the primary id of the model
:type object_id: integer
:return: the parties
:rtype: list | [
"Get",
"all",
"parties",
"(",
"people",
"and",
"companies",
")",
"associated",
"with",
"a",
"given",
"tag",
".",
":",
"param",
"object_id",
":",
"the",
"primary",
"id",
"of",
"the",
"model",
":",
"type",
"object_id",
":",
"integer",
":",
"return",
":",
... | train | https://github.com/seibert-media/Highton/blob/1519e4fb105f62882c2e7bc81065d994649558d8/highton/models/tag.py#L26-L39 |
sjwood/pydvdid | pydvdid/functions.py | compute | def compute(dvd_path):
"""Computes a Windows API IDvdInfo2::GetDiscID-compatible 64-bit Cyclic Redundancy Check
checksum from the DVD .vob, .ifo and .bup files found in the supplied DVD path.
"""
_check_dvd_path_exists(dvd_path)
_check_video_ts_path_exists(dvd_path)
# the polynomial used f... | python | def compute(dvd_path):
"""Computes a Windows API IDvdInfo2::GetDiscID-compatible 64-bit Cyclic Redundancy Check
checksum from the DVD .vob, .ifo and .bup files found in the supplied DVD path.
"""
_check_dvd_path_exists(dvd_path)
_check_video_ts_path_exists(dvd_path)
# the polynomial used f... | [
"def",
"compute",
"(",
"dvd_path",
")",
":",
"_check_dvd_path_exists",
"(",
"dvd_path",
")",
"_check_video_ts_path_exists",
"(",
"dvd_path",
")",
"# the polynomial used for this CRC-64 checksum is:",
"# x^63 + x^60 + x^57 + x^55 + x^54 + x^50 + x^49 + x^46 + x^41 + x^38 + x^37 + x^34 +... | Computes a Windows API IDvdInfo2::GetDiscID-compatible 64-bit Cyclic Redundancy Check
checksum from the DVD .vob, .ifo and .bup files found in the supplied DVD path. | [
"Computes",
"a",
"Windows",
"API",
"IDvdInfo2",
"::",
"GetDiscID",
"-",
"compatible",
"64",
"-",
"bit",
"Cyclic",
"Redundancy",
"Check",
"checksum",
"from",
"the",
"DVD",
".",
"vob",
".",
"ifo",
"and",
".",
"bup",
"files",
"found",
"in",
"the",
"supplied",... | train | https://github.com/sjwood/pydvdid/blob/03914fb7e24283c445e5af724f9d919b23caaf95/pydvdid/functions.py#L19-L41 |
sjwood/pydvdid | pydvdid/functions.py | _get_video_ts_file_paths | def _get_video_ts_file_paths(dvd_path):
"""Returns a sorted list of paths for files contained in th VIDEO_TS folder of the specified
DVD path.
"""
video_ts_folder_path = join(dvd_path, "VIDEO_TS")
video_ts_file_paths = []
for video_ts_folder_content_name in listdir(video_ts_folder_path):
... | python | def _get_video_ts_file_paths(dvd_path):
"""Returns a sorted list of paths for files contained in th VIDEO_TS folder of the specified
DVD path.
"""
video_ts_folder_path = join(dvd_path, "VIDEO_TS")
video_ts_file_paths = []
for video_ts_folder_content_name in listdir(video_ts_folder_path):
... | [
"def",
"_get_video_ts_file_paths",
"(",
"dvd_path",
")",
":",
"video_ts_folder_path",
"=",
"join",
"(",
"dvd_path",
",",
"\"VIDEO_TS\"",
")",
"video_ts_file_paths",
"=",
"[",
"]",
"for",
"video_ts_folder_content_name",
"in",
"listdir",
"(",
"video_ts_folder_path",
")"... | Returns a sorted list of paths for files contained in th VIDEO_TS folder of the specified
DVD path. | [
"Returns",
"a",
"sorted",
"list",
"of",
"paths",
"for",
"files",
"contained",
"in",
"th",
"VIDEO_TS",
"folder",
"of",
"the",
"specified",
"DVD",
"path",
"."
] | train | https://github.com/sjwood/pydvdid/blob/03914fb7e24283c445e5af724f9d919b23caaf95/pydvdid/functions.py#L62-L77 |
sjwood/pydvdid | pydvdid/functions.py | _get_file_creation_time | def _get_file_creation_time(file_path):
"""Returns the creation time of the file at the specified file path in Microsoft FILETIME
structure format (https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx),
formatted as a 8-byte unsigned integer bytearray.
"""
ctime = getctime(f... | python | def _get_file_creation_time(file_path):
"""Returns the creation time of the file at the specified file path in Microsoft FILETIME
structure format (https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx),
formatted as a 8-byte unsigned integer bytearray.
"""
ctime = getctime(f... | [
"def",
"_get_file_creation_time",
"(",
"file_path",
")",
":",
"ctime",
"=",
"getctime",
"(",
"file_path",
")",
"if",
"ctime",
"<",
"-",
"11644473600",
"or",
"ctime",
">=",
"253402300800",
":",
"raise",
"FileTimeOutOfRangeException",
"(",
"ctime",
")",
"creation_... | Returns the creation time of the file at the specified file path in Microsoft FILETIME
structure format (https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx),
formatted as a 8-byte unsigned integer bytearray. | [
"Returns",
"the",
"creation",
"time",
"of",
"the",
"file",
"at",
"the",
"specified",
"file",
"path",
"in",
"Microsoft",
"FILETIME",
"structure",
"format",
"(",
"https",
":",
"//",
"msdn",
".",
"microsoft",
".",
"com",
"/",
"en",
"-",
"us",
"/",
"library"... | train | https://github.com/sjwood/pydvdid/blob/03914fb7e24283c445e5af724f9d919b23caaf95/pydvdid/functions.py#L80-L102 |
sjwood/pydvdid | pydvdid/functions.py | _convert_timedelta_to_seconds | def _convert_timedelta_to_seconds(timedelta):
"""Returns the total seconds calculated from the supplied timedelta.
(Function provided to enable running on Python 2.6 which lacks timedelta.total_seconds()).
"""
days_in_seconds = timedelta.days * 24 * 3600
return int((timedelta.microseconds + (ti... | python | def _convert_timedelta_to_seconds(timedelta):
"""Returns the total seconds calculated from the supplied timedelta.
(Function provided to enable running on Python 2.6 which lacks timedelta.total_seconds()).
"""
days_in_seconds = timedelta.days * 24 * 3600
return int((timedelta.microseconds + (ti... | [
"def",
"_convert_timedelta_to_seconds",
"(",
"timedelta",
")",
":",
"days_in_seconds",
"=",
"timedelta",
".",
"days",
"*",
"24",
"*",
"3600",
"return",
"int",
"(",
"(",
"timedelta",
".",
"microseconds",
"+",
"(",
"timedelta",
".",
"seconds",
"+",
"days_in_seco... | Returns the total seconds calculated from the supplied timedelta.
(Function provided to enable running on Python 2.6 which lacks timedelta.total_seconds()). | [
"Returns",
"the",
"total",
"seconds",
"calculated",
"from",
"the",
"supplied",
"timedelta",
"."
] | train | https://github.com/sjwood/pydvdid/blob/03914fb7e24283c445e5af724f9d919b23caaf95/pydvdid/functions.py#L105-L112 |
sjwood/pydvdid | pydvdid/functions.py | _get_file_size | def _get_file_size(file_path):
"""Returns the size of the file at the specified file path, formatted as a 4-byte unsigned
integer bytearray.
"""
size = getsize(file_path)
file_size = bytearray(4)
pack_into(b"I", file_size, 0, size)
return file_size | python | def _get_file_size(file_path):
"""Returns the size of the file at the specified file path, formatted as a 4-byte unsigned
integer bytearray.
"""
size = getsize(file_path)
file_size = bytearray(4)
pack_into(b"I", file_size, 0, size)
return file_size | [
"def",
"_get_file_size",
"(",
"file_path",
")",
":",
"size",
"=",
"getsize",
"(",
"file_path",
")",
"file_size",
"=",
"bytearray",
"(",
"4",
")",
"pack_into",
"(",
"b\"I\"",
",",
"file_size",
",",
"0",
",",
"size",
")",
"return",
"file_size"
] | Returns the size of the file at the specified file path, formatted as a 4-byte unsigned
integer bytearray. | [
"Returns",
"the",
"size",
"of",
"the",
"file",
"at",
"the",
"specified",
"file",
"path",
"formatted",
"as",
"a",
"4",
"-",
"byte",
"unsigned",
"integer",
"bytearray",
"."
] | train | https://github.com/sjwood/pydvdid/blob/03914fb7e24283c445e5af724f9d919b23caaf95/pydvdid/functions.py#L115-L125 |
sjwood/pydvdid | pydvdid/functions.py | _get_file_name | def _get_file_name(file_path):
"""Returns the name of the file at the specified file path, formatted as a UTF-8 bytearray
terminated with a null character.
"""
file_name = basename(file_path)
utf8_file_name = bytearray(file_name, "utf8")
utf8_file_name.append(0)
return utf8_file_name | python | def _get_file_name(file_path):
"""Returns the name of the file at the specified file path, formatted as a UTF-8 bytearray
terminated with a null character.
"""
file_name = basename(file_path)
utf8_file_name = bytearray(file_name, "utf8")
utf8_file_name.append(0)
return utf8_file_name | [
"def",
"_get_file_name",
"(",
"file_path",
")",
":",
"file_name",
"=",
"basename",
"(",
"file_path",
")",
"utf8_file_name",
"=",
"bytearray",
"(",
"file_name",
",",
"\"utf8\"",
")",
"utf8_file_name",
".",
"append",
"(",
"0",
")",
"return",
"utf8_file_name"
] | Returns the name of the file at the specified file path, formatted as a UTF-8 bytearray
terminated with a null character. | [
"Returns",
"the",
"name",
"of",
"the",
"file",
"at",
"the",
"specified",
"file",
"path",
"formatted",
"as",
"a",
"UTF",
"-",
"8",
"bytearray",
"terminated",
"with",
"a",
"null",
"character",
"."
] | train | https://github.com/sjwood/pydvdid/blob/03914fb7e24283c445e5af724f9d919b23caaf95/pydvdid/functions.py#L128-L138 |
sjwood/pydvdid | pydvdid/functions.py | _get_first_64k_content | def _get_first_64k_content(file_path):
"""Returns the first 65536 (or the file size, whichever is smaller) bytes of the file at the
specified file path, as a bytearray.
"""
if not isfile(file_path):
raise PathDoesNotExistException(file_path)
file_size = getsize(file_path)
content_s... | python | def _get_first_64k_content(file_path):
"""Returns the first 65536 (or the file size, whichever is smaller) bytes of the file at the
specified file path, as a bytearray.
"""
if not isfile(file_path):
raise PathDoesNotExistException(file_path)
file_size = getsize(file_path)
content_s... | [
"def",
"_get_first_64k_content",
"(",
"file_path",
")",
":",
"if",
"not",
"isfile",
"(",
"file_path",
")",
":",
"raise",
"PathDoesNotExistException",
"(",
"file_path",
")",
"file_size",
"=",
"getsize",
"(",
"file_path",
")",
"content_size",
"=",
"min",
"(",
"f... | Returns the first 65536 (or the file size, whichever is smaller) bytes of the file at the
specified file path, as a bytearray. | [
"Returns",
"the",
"first",
"65536",
"(",
"or",
"the",
"file",
"size",
"whichever",
"is",
"smaller",
")",
"bytes",
"of",
"the",
"file",
"at",
"the",
"specified",
"file",
"path",
"as",
"a",
"bytearray",
"."
] | train | https://github.com/sjwood/pydvdid/blob/03914fb7e24283c445e5af724f9d919b23caaf95/pydvdid/functions.py#L161-L180 |
DomBennett/TaxonNamesResolver | TaxonNamesResolver.py | parseArgs | def parseArgs():
"""Read arguments"""
parser = argparse.ArgumentParser()
parser.add_argument("-names", "-n", help=".txt file of taxonomic names")
parser.add_argument("-datasource", "-d", help="taxonomic datasource by \
which names will be resolved (default NCBI)")
parser.add_argument("-taxonid", "-t... | python | def parseArgs():
"""Read arguments"""
parser = argparse.ArgumentParser()
parser.add_argument("-names", "-n", help=".txt file of taxonomic names")
parser.add_argument("-datasource", "-d", help="taxonomic datasource by \
which names will be resolved (default NCBI)")
parser.add_argument("-taxonid", "-t... | [
"def",
"parseArgs",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"-names\"",
",",
"\"-n\"",
",",
"help",
"=",
"\".txt file of taxonomic names\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-d... | Read arguments | [
"Read",
"arguments"
] | train | https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/TaxonNamesResolver.py#L30-L41 |
DomBennett/TaxonNamesResolver | TaxonNamesResolver.py | logSysInfo | def logSysInfo():
"""Write system info to log file"""
logger.info('#' * 70)
logger.info(datetime.today().strftime("%A, %d %B %Y %I:%M%p"))
logger.info('Running on [{0}] [{1}]'.format(platform.node(),
platform.platform()))
logger.info('Python [{0}]'.for... | python | def logSysInfo():
"""Write system info to log file"""
logger.info('#' * 70)
logger.info(datetime.today().strftime("%A, %d %B %Y %I:%M%p"))
logger.info('Running on [{0}] [{1}]'.format(platform.node(),
platform.platform()))
logger.info('Python [{0}]'.for... | [
"def",
"logSysInfo",
"(",
")",
":",
"logger",
".",
"info",
"(",
"'#'",
"*",
"70",
")",
"logger",
".",
"info",
"(",
"datetime",
".",
"today",
"(",
")",
".",
"strftime",
"(",
"\"%A, %d %B %Y %I:%M%p\"",
")",
")",
"logger",
".",
"info",
"(",
"'Running on ... | Write system info to log file | [
"Write",
"system",
"info",
"to",
"log",
"file"
] | train | https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/TaxonNamesResolver.py#L44-L51 |
DomBennett/TaxonNamesResolver | TaxonNamesResolver.py | logEndTime | def logEndTime():
"""Write end info to log"""
logger.info('\n' + '#' * 70)
logger.info('Complete')
logger.info(datetime.today().strftime("%A, %d %B %Y %I:%M%p"))
logger.info('#' * 70 + '\n') | python | def logEndTime():
"""Write end info to log"""
logger.info('\n' + '#' * 70)
logger.info('Complete')
logger.info(datetime.today().strftime("%A, %d %B %Y %I:%M%p"))
logger.info('#' * 70 + '\n') | [
"def",
"logEndTime",
"(",
")",
":",
"logger",
".",
"info",
"(",
"'\\n'",
"+",
"'#'",
"*",
"70",
")",
"logger",
".",
"info",
"(",
"'Complete'",
")",
"logger",
".",
"info",
"(",
"datetime",
".",
"today",
"(",
")",
".",
"strftime",
"(",
"\"%A, %d %B %Y ... | Write end info to log | [
"Write",
"end",
"info",
"to",
"log"
] | train | https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/TaxonNamesResolver.py#L54-L59 |
crodjer/paster | paster/config.py | get_config | def get_config(section, option, allow_empty_option=True, default=""):
'''
Get data from configs
'''
try:
value = config.get(section, option)
if value is None or len(value) == 0:
if allow_empty_option:
return ""
else:
return default
... | python | def get_config(section, option, allow_empty_option=True, default=""):
'''
Get data from configs
'''
try:
value = config.get(section, option)
if value is None or len(value) == 0:
if allow_empty_option:
return ""
else:
return default
... | [
"def",
"get_config",
"(",
"section",
",",
"option",
",",
"allow_empty_option",
"=",
"True",
",",
"default",
"=",
"\"\"",
")",
":",
"try",
":",
"value",
"=",
"config",
".",
"get",
"(",
"section",
",",
"option",
")",
"if",
"value",
"is",
"None",
"or",
... | Get data from configs | [
"Get",
"data",
"from",
"configs"
] | train | https://github.com/crodjer/paster/blob/0cd7230074850ba74e80c740a8bc2502645dd743/paster/config.py#L41-L55 |
crodjer/paster | paster/config.py | getboolean_config | def getboolean_config(section, option, default=False):
'''
Get data from configs which store boolean records
'''
try:
return config.getboolean(section, option) or default
except ConfigParser.NoSectionError:
return default | python | def getboolean_config(section, option, default=False):
'''
Get data from configs which store boolean records
'''
try:
return config.getboolean(section, option) or default
except ConfigParser.NoSectionError:
return default | [
"def",
"getboolean_config",
"(",
"section",
",",
"option",
",",
"default",
"=",
"False",
")",
":",
"try",
":",
"return",
"config",
".",
"getboolean",
"(",
"section",
",",
"option",
")",
"or",
"default",
"except",
"ConfigParser",
".",
"NoSectionError",
":",
... | Get data from configs which store boolean records | [
"Get",
"data",
"from",
"configs",
"which",
"store",
"boolean",
"records"
] | train | https://github.com/crodjer/paster/blob/0cd7230074850ba74e80c740a8bc2502645dd743/paster/config.py#L57-L64 |
SetBased/py-etlt | etlt/condition/InListCondition.py | InListCondition.populate_values | def populate_values(self, rows, field):
"""
Populates the filter values of this filter using list of rows.
:param list[dict[str,T]] rows: The row set.
:param str field: The field name.
"""
self._values.clear()
for row in rows:
condition = SimpleCondit... | python | def populate_values(self, rows, field):
"""
Populates the filter values of this filter using list of rows.
:param list[dict[str,T]] rows: The row set.
:param str field: The field name.
"""
self._values.clear()
for row in rows:
condition = SimpleCondit... | [
"def",
"populate_values",
"(",
"self",
",",
"rows",
",",
"field",
")",
":",
"self",
".",
"_values",
".",
"clear",
"(",
")",
"for",
"row",
"in",
"rows",
":",
"condition",
"=",
"SimpleConditionFactory",
".",
"create_condition",
"(",
"self",
".",
"_field",
... | Populates the filter values of this filter using list of rows.
:param list[dict[str,T]] rows: The row set.
:param str field: The field name. | [
"Populates",
"the",
"filter",
"values",
"of",
"this",
"filter",
"using",
"list",
"of",
"rows",
"."
] | train | https://github.com/SetBased/py-etlt/blob/1c5b8ea60293c14f54d7845a9fe5c595021f66f2/etlt/condition/InListCondition.py#L57-L70 |
SetBased/py-etlt | etlt/condition/InListCondition.py | InListCondition.match | def match(self, row):
"""
Returns True if the field is in the list of conditions. Returns False otherwise.
:param dict row: The row.
:rtype: bool
"""
if row[self._field] in self._values:
return True
for condition in self._conditions:
if ... | python | def match(self, row):
"""
Returns True if the field is in the list of conditions. Returns False otherwise.
:param dict row: The row.
:rtype: bool
"""
if row[self._field] in self._values:
return True
for condition in self._conditions:
if ... | [
"def",
"match",
"(",
"self",
",",
"row",
")",
":",
"if",
"row",
"[",
"self",
".",
"_field",
"]",
"in",
"self",
".",
"_values",
":",
"return",
"True",
"for",
"condition",
"in",
"self",
".",
"_conditions",
":",
"if",
"condition",
".",
"match",
"(",
"... | Returns True if the field is in the list of conditions. Returns False otherwise.
:param dict row: The row.
:rtype: bool | [
"Returns",
"True",
"if",
"the",
"field",
"is",
"in",
"the",
"list",
"of",
"conditions",
".",
"Returns",
"False",
"otherwise",
"."
] | train | https://github.com/SetBased/py-etlt/blob/1c5b8ea60293c14f54d7845a9fe5c595021f66f2/etlt/condition/InListCondition.py#L73-L88 |
crypto101/merlyn | merlyn/exercise.py | solveAndNotify | def solveAndNotify(proto, exercise):
"""The user at the given AMP protocol has solved the given exercise.
This will log the solution and notify the user.
"""
exercise.solvedBy(proto.user)
proto.callRemote(ce.NotifySolved,
identifier=exercise.identifier,
tit... | python | def solveAndNotify(proto, exercise):
"""The user at the given AMP protocol has solved the given exercise.
This will log the solution and notify the user.
"""
exercise.solvedBy(proto.user)
proto.callRemote(ce.NotifySolved,
identifier=exercise.identifier,
tit... | [
"def",
"solveAndNotify",
"(",
"proto",
",",
"exercise",
")",
":",
"exercise",
".",
"solvedBy",
"(",
"proto",
".",
"user",
")",
"proto",
".",
"callRemote",
"(",
"ce",
".",
"NotifySolved",
",",
"identifier",
"=",
"exercise",
".",
"identifier",
",",
"title",
... | The user at the given AMP protocol has solved the given exercise.
This will log the solution and notify the user. | [
"The",
"user",
"at",
"the",
"given",
"AMP",
"protocol",
"has",
"solved",
"the",
"given",
"exercise",
"."
] | train | https://github.com/crypto101/merlyn/blob/0f313210b9ea5385cc2e5b725dc766df9dc3284d/merlyn/exercise.py#L50-L58 |
crypto101/merlyn | merlyn/exercise.py | Exercise.solvedBy | def solvedBy(self, user):
"""Stores that this user has just solved this exercise.
You probably want to notify the user when this happens. For
that, see ``solveAndNotify``.
"""
_Solution(store=self.store, who=user, what=self) | python | def solvedBy(self, user):
"""Stores that this user has just solved this exercise.
You probably want to notify the user when this happens. For
that, see ``solveAndNotify``.
"""
_Solution(store=self.store, who=user, what=self) | [
"def",
"solvedBy",
"(",
"self",
",",
"user",
")",
":",
"_Solution",
"(",
"store",
"=",
"self",
".",
"store",
",",
"who",
"=",
"user",
",",
"what",
"=",
"self",
")"
] | Stores that this user has just solved this exercise.
You probably want to notify the user when this happens. For
that, see ``solveAndNotify``. | [
"Stores",
"that",
"this",
"user",
"has",
"just",
"solved",
"this",
"exercise",
"."
] | train | https://github.com/crypto101/merlyn/blob/0f313210b9ea5385cc2e5b725dc766df9dc3284d/merlyn/exercise.py#L20-L27 |
crypto101/merlyn | merlyn/exercise.py | Exercise.wasSolvedBy | def wasSolvedBy(self, user):
"""Checks if this exercise has previously been solved by the user.
"""
thisExercise = _Solution.what == self
byThisUser = _Solution.who == user
condition = q.AND(thisExercise, byThisUser)
return self.store.query(_Solution, condition, limit=1)... | python | def wasSolvedBy(self, user):
"""Checks if this exercise has previously been solved by the user.
"""
thisExercise = _Solution.what == self
byThisUser = _Solution.who == user
condition = q.AND(thisExercise, byThisUser)
return self.store.query(_Solution, condition, limit=1)... | [
"def",
"wasSolvedBy",
"(",
"self",
",",
"user",
")",
":",
"thisExercise",
"=",
"_Solution",
".",
"what",
"==",
"self",
"byThisUser",
"=",
"_Solution",
".",
"who",
"==",
"user",
"condition",
"=",
"q",
".",
"AND",
"(",
"thisExercise",
",",
"byThisUser",
")... | Checks if this exercise has previously been solved by the user. | [
"Checks",
"if",
"this",
"exercise",
"has",
"previously",
"been",
"solved",
"by",
"the",
"user",
"."
] | train | https://github.com/crypto101/merlyn/blob/0f313210b9ea5385cc2e5b725dc766df9dc3284d/merlyn/exercise.py#L30-L37 |
crypto101/merlyn | merlyn/exercise.py | Locator.getExerciseDetails | def getExerciseDetails(self, identifier):
"""Gets the details for a particular exercise.
"""
exercise = self._getExercise(identifier)
response = {
b"identifier": exercise.identifier,
b"title": exercise.title,
b"description": exercise.description,
... | python | def getExerciseDetails(self, identifier):
"""Gets the details for a particular exercise.
"""
exercise = self._getExercise(identifier)
response = {
b"identifier": exercise.identifier,
b"title": exercise.title,
b"description": exercise.description,
... | [
"def",
"getExerciseDetails",
"(",
"self",
",",
"identifier",
")",
":",
"exercise",
"=",
"self",
".",
"_getExercise",
"(",
"identifier",
")",
"response",
"=",
"{",
"b\"identifier\"",
":",
"exercise",
".",
"identifier",
",",
"b\"title\"",
":",
"exercise",
".",
... | Gets the details for a particular exercise. | [
"Gets",
"the",
"details",
"for",
"a",
"particular",
"exercise",
"."
] | train | https://github.com/crypto101/merlyn/blob/0f313210b9ea5385cc2e5b725dc766df9dc3284d/merlyn/exercise.py#L81-L92 |
crypto101/merlyn | merlyn/exercise.py | SolvableResourceMixin.solveAndNotify | def solveAndNotify(self, request):
"""Notifies the owner of the current request (so, the user doing the
exercise) that they've solved the exercise, and mark it as
solved in the database.
"""
remote = request.transport.remote
withThisIdentifier = Exercise.identifier == se... | python | def solveAndNotify(self, request):
"""Notifies the owner of the current request (so, the user doing the
exercise) that they've solved the exercise, and mark it as
solved in the database.
"""
remote = request.transport.remote
withThisIdentifier = Exercise.identifier == se... | [
"def",
"solveAndNotify",
"(",
"self",
",",
"request",
")",
":",
"remote",
"=",
"request",
".",
"transport",
".",
"remote",
"withThisIdentifier",
"=",
"Exercise",
".",
"identifier",
"==",
"self",
".",
"exerciseIdentifier",
"exercise",
"=",
"self",
".",
"store",... | Notifies the owner of the current request (so, the user doing the
exercise) that they've solved the exercise, and mark it as
solved in the database. | [
"Notifies",
"the",
"owner",
"of",
"the",
"current",
"request",
"(",
"so",
"the",
"user",
"doing",
"the",
"exercise",
")",
"that",
"they",
"ve",
"solved",
"the",
"exercise",
"and",
"mark",
"it",
"as",
"solved",
"in",
"the",
"database",
"."
] | train | https://github.com/crypto101/merlyn/blob/0f313210b9ea5385cc2e5b725dc766df9dc3284d/merlyn/exercise.py#L115-L124 |
justquick/django-native-tags | native_tags/nodes.py | split | def split(s):
"""
Split a string into a list, respecting any quoted strings inside
Uses ``shelx.split`` which has a bad habbit of inserting null bytes where they are not wanted
"""
return map(lambda w: filter(lambda c: c != '\x00', w), lexsplit(s)) | python | def split(s):
"""
Split a string into a list, respecting any quoted strings inside
Uses ``shelx.split`` which has a bad habbit of inserting null bytes where they are not wanted
"""
return map(lambda w: filter(lambda c: c != '\x00', w), lexsplit(s)) | [
"def",
"split",
"(",
"s",
")",
":",
"return",
"map",
"(",
"lambda",
"w",
":",
"filter",
"(",
"lambda",
"c",
":",
"c",
"!=",
"'\\x00'",
",",
"w",
")",
",",
"lexsplit",
"(",
"s",
")",
")"
] | Split a string into a list, respecting any quoted strings inside
Uses ``shelx.split`` which has a bad habbit of inserting null bytes where they are not wanted | [
"Split",
"a",
"string",
"into",
"a",
"list",
"respecting",
"any",
"quoted",
"strings",
"inside",
"Uses",
"shelx",
".",
"split",
"which",
"has",
"a",
"bad",
"habbit",
"of",
"inserting",
"null",
"bytes",
"where",
"they",
"are",
"not",
"wanted"
] | train | https://github.com/justquick/django-native-tags/blob/d40b976ee1cb13faeb04f0dedf02933d4274abf2/native_tags/nodes.py#L23-L28 |
justquick/django-native-tags | native_tags/nodes.py | lookup | def lookup(parser, var, context, resolve=True, apply_filters=True):
"""
Try to resolve the varialbe in a context
If ``resolve`` is ``False``, only string variables are returned
"""
if resolve:
try:
return Variable(var).resolve(context)
except VariableDoesNotExist:
... | python | def lookup(parser, var, context, resolve=True, apply_filters=True):
"""
Try to resolve the varialbe in a context
If ``resolve`` is ``False``, only string variables are returned
"""
if resolve:
try:
return Variable(var).resolve(context)
except VariableDoesNotExist:
... | [
"def",
"lookup",
"(",
"parser",
",",
"var",
",",
"context",
",",
"resolve",
"=",
"True",
",",
"apply_filters",
"=",
"True",
")",
":",
"if",
"resolve",
":",
"try",
":",
"return",
"Variable",
"(",
"var",
")",
".",
"resolve",
"(",
"context",
")",
"excep... | Try to resolve the varialbe in a context
If ``resolve`` is ``False``, only string variables are returned | [
"Try",
"to",
"resolve",
"the",
"varialbe",
"in",
"a",
"context",
"If",
"resolve",
"is",
"False",
"only",
"string",
"variables",
"are",
"returned"
] | train | https://github.com/justquick/django-native-tags/blob/d40b976ee1cb13faeb04f0dedf02933d4274abf2/native_tags/nodes.py#L30-L45 |
justquick/django-native-tags | native_tags/nodes.py | get_cache_key | def get_cache_key(bucket, name, args, kwargs):
"""
Gets a unique SHA1 cache key for any call to a native tag.
Use args and kwargs in hash so that the same arguments use the same key
"""
u = ''.join(map(str, (bucket, name, args, kwargs)))
return 'native_tags.%s' % sha_constructor(u).hexdigest() | python | def get_cache_key(bucket, name, args, kwargs):
"""
Gets a unique SHA1 cache key for any call to a native tag.
Use args and kwargs in hash so that the same arguments use the same key
"""
u = ''.join(map(str, (bucket, name, args, kwargs)))
return 'native_tags.%s' % sha_constructor(u).hexdigest() | [
"def",
"get_cache_key",
"(",
"bucket",
",",
"name",
",",
"args",
",",
"kwargs",
")",
":",
"u",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"str",
",",
"(",
"bucket",
",",
"name",
",",
"args",
",",
"kwargs",
")",
")",
")",
"return",
"'native_tags.%s'",... | Gets a unique SHA1 cache key for any call to a native tag.
Use args and kwargs in hash so that the same arguments use the same key | [
"Gets",
"a",
"unique",
"SHA1",
"cache",
"key",
"for",
"any",
"call",
"to",
"a",
"native",
"tag",
".",
"Use",
"args",
"and",
"kwargs",
"in",
"hash",
"so",
"that",
"the",
"same",
"arguments",
"use",
"the",
"same",
"key"
] | train | https://github.com/justquick/django-native-tags/blob/d40b976ee1cb13faeb04f0dedf02933d4274abf2/native_tags/nodes.py#L47-L53 |
justquick/django-native-tags | native_tags/nodes.py | get_signature | def get_signature(token, contextable=False, comparison=False):
"""
Gets the signature tuple for any native tag
contextable searchs for ``as`` variable to update context
comparison if true uses ``negate`` (p) to ``not`` the result (~p)
returns (``tag_name``, ``args``, ``kwargs``)
"""
bits = s... | python | def get_signature(token, contextable=False, comparison=False):
"""
Gets the signature tuple for any native tag
contextable searchs for ``as`` variable to update context
comparison if true uses ``negate`` (p) to ``not`` the result (~p)
returns (``tag_name``, ``args``, ``kwargs``)
"""
bits = s... | [
"def",
"get_signature",
"(",
"token",
",",
"contextable",
"=",
"False",
",",
"comparison",
"=",
"False",
")",
":",
"bits",
"=",
"split",
"(",
"token",
".",
"contents",
")",
"args",
",",
"kwargs",
"=",
"(",
")",
",",
"{",
"}",
"if",
"comparison",
"and... | Gets the signature tuple for any native tag
contextable searchs for ``as`` variable to update context
comparison if true uses ``negate`` (p) to ``not`` the result (~p)
returns (``tag_name``, ``args``, ``kwargs``) | [
"Gets",
"the",
"signature",
"tuple",
"for",
"any",
"native",
"tag",
"contextable",
"searchs",
"for",
"as",
"variable",
"to",
"update",
"context",
"comparison",
"if",
"true",
"uses",
"negate",
"(",
"p",
")",
"to",
"not",
"the",
"result",
"(",
"~p",
")",
"... | train | https://github.com/justquick/django-native-tags/blob/d40b976ee1cb13faeb04f0dedf02933d4274abf2/native_tags/nodes.py#L55-L77 |
justquick/django-native-tags | native_tags/nodes.py | do_comparison | def do_comparison(parser, token):
"""
Compares passed arguments.
Attached functions should return boolean ``True`` or ``False``.
If the attached function returns ``True``, the first node list is rendered.
If the attached function returns ``False``, the second optional node list is rendered (part af... | python | def do_comparison(parser, token):
"""
Compares passed arguments.
Attached functions should return boolean ``True`` or ``False``.
If the attached function returns ``True``, the first node list is rendered.
If the attached function returns ``False``, the second optional node list is rendered (part af... | [
"def",
"do_comparison",
"(",
"parser",
",",
"token",
")",
":",
"name",
",",
"args",
",",
"kwargs",
"=",
"get_signature",
"(",
"token",
",",
"comparison",
"=",
"True",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"'if_if'",
",",
"'if'",
")",
"end_tag"... | Compares passed arguments.
Attached functions should return boolean ``True`` or ``False``.
If the attached function returns ``True``, the first node list is rendered.
If the attached function returns ``False``, the second optional node list is rendered (part after the ``{% else %}`` statement).
If the... | [
"Compares",
"passed",
"arguments",
".",
"Attached",
"functions",
"should",
"return",
"boolean",
"True",
"or",
"False",
".",
"If",
"the",
"attached",
"function",
"returns",
"True",
"the",
"first",
"node",
"list",
"is",
"rendered",
".",
"If",
"the",
"attached",
... | train | https://github.com/justquick/django-native-tags/blob/d40b976ee1cb13faeb04f0dedf02933d4274abf2/native_tags/nodes.py#L170-L214 |
justquick/django-native-tags | native_tags/nodes.py | do_function | def do_function(parser, token):
"""
Performs a defined function on the passed arguments.
Normally this returns the output of the function into the template.
If the second to last argument is ``as``, the result of the function is stored in the context and is named whatever the last argument is.
Synt... | python | def do_function(parser, token):
"""
Performs a defined function on the passed arguments.
Normally this returns the output of the function into the template.
If the second to last argument is ``as``, the result of the function is stored in the context and is named whatever the last argument is.
Synt... | [
"def",
"do_function",
"(",
"parser",
",",
"token",
")",
":",
"name",
",",
"args",
",",
"kwargs",
"=",
"get_signature",
"(",
"token",
",",
"True",
",",
"True",
")",
"return",
"FunctionNode",
"(",
"parser",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",... | Performs a defined function on the passed arguments.
Normally this returns the output of the function into the template.
If the second to last argument is ``as``, the result of the function is stored in the context and is named whatever the last argument is.
Syntax::
{% [function] [var args...] [n... | [
"Performs",
"a",
"defined",
"function",
"on",
"the",
"passed",
"arguments",
".",
"Normally",
"this",
"returns",
"the",
"output",
"of",
"the",
"function",
"into",
"the",
"template",
".",
"If",
"the",
"second",
"to",
"last",
"argument",
"is",
"as",
"the",
"r... | train | https://github.com/justquick/django-native-tags/blob/d40b976ee1cb13faeb04f0dedf02933d4274abf2/native_tags/nodes.py#L227-L245 |
justquick/django-native-tags | native_tags/nodes.py | do_block | def do_block(parser, token):
"""
Process several nodes inside a single block
Block functions take ``context``, ``nodelist`` as first arguments
If the second to last argument is ``as``, the rendered result is stored in the context and is named whatever the last argument is.
Syntax::
{% [blo... | python | def do_block(parser, token):
"""
Process several nodes inside a single block
Block functions take ``context``, ``nodelist`` as first arguments
If the second to last argument is ``as``, the rendered result is stored in the context and is named whatever the last argument is.
Syntax::
{% [blo... | [
"def",
"do_block",
"(",
"parser",
",",
"token",
")",
":",
"name",
",",
"args",
",",
"kwargs",
"=",
"get_signature",
"(",
"token",
",",
"contextable",
"=",
"True",
")",
"kwargs",
"[",
"'nodelist'",
"]",
"=",
"parser",
".",
"parse",
"(",
"(",
"'end%s'",
... | Process several nodes inside a single block
Block functions take ``context``, ``nodelist`` as first arguments
If the second to last argument is ``as``, the rendered result is stored in the context and is named whatever the last argument is.
Syntax::
{% [block] [var args...] [name=value kwargs...] ... | [
"Process",
"several",
"nodes",
"inside",
"a",
"single",
"block",
"Block",
"functions",
"take",
"context",
"nodelist",
"as",
"first",
"arguments",
"If",
"the",
"second",
"to",
"last",
"argument",
"is",
"as",
"the",
"rendered",
"result",
"is",
"stored",
"in",
... | train | https://github.com/justquick/django-native-tags/blob/d40b976ee1cb13faeb04f0dedf02933d4274abf2/native_tags/nodes.py#L253-L279 |
zetaops/pyoko | pyoko/modelmeta.py | ModelMeta.process_attributes_of_node | def process_attributes_of_node(attrs, node_name, class_type):
"""
prepare the model fields, nodes and relations
Args:
node_name (str): name of the node we are currently processing
attrs (dict): attribute dict
class_type (str): Type of class.
C... | python | def process_attributes_of_node(attrs, node_name, class_type):
"""
prepare the model fields, nodes and relations
Args:
node_name (str): name of the node we are currently processing
attrs (dict): attribute dict
class_type (str): Type of class.
C... | [
"def",
"process_attributes_of_node",
"(",
"attrs",
",",
"node_name",
",",
"class_type",
")",
":",
"# print(\"Node: %s\" % node_name)",
"attrs",
"[",
"'_nodes'",
"]",
"=",
"{",
"}",
"attrs",
"[",
"'_linked_models'",
"]",
"=",
"defaultdict",
"(",
"list",
")",
"att... | prepare the model fields, nodes and relations
Args:
node_name (str): name of the node we are currently processing
attrs (dict): attribute dict
class_type (str): Type of class.
Can be one of these: 'ListNode', 'Model', 'Node' | [
"prepare",
"the",
"model",
"fields",
"nodes",
"and",
"relations"
] | train | https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/modelmeta.py#L47-L111 |
zetaops/pyoko | pyoko/modelmeta.py | ModelMeta.process_models | def process_models(attrs, base_model_class):
"""
Attach default fields and meta options to models
"""
attrs.update(base_model_class._DEFAULT_BASE_FIELDS)
attrs['_instance_registry'] = set()
attrs['_is_unpermitted_fields_set'] = False
attrs['save_meta_data'] = None... | python | def process_models(attrs, base_model_class):
"""
Attach default fields and meta options to models
"""
attrs.update(base_model_class._DEFAULT_BASE_FIELDS)
attrs['_instance_registry'] = set()
attrs['_is_unpermitted_fields_set'] = False
attrs['save_meta_data'] = None... | [
"def",
"process_models",
"(",
"attrs",
",",
"base_model_class",
")",
":",
"attrs",
".",
"update",
"(",
"base_model_class",
".",
"_DEFAULT_BASE_FIELDS",
")",
"attrs",
"[",
"'_instance_registry'",
"]",
"=",
"set",
"(",
")",
"attrs",
"[",
"'_is_unpermitted_fields_set... | Attach default fields and meta options to models | [
"Attach",
"default",
"fields",
"and",
"meta",
"options",
"to",
"models"
] | train | https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/modelmeta.py#L114-L137 |
zetaops/pyoko | pyoko/modelmeta.py | ModelMeta.process_objects | def process_objects(kls):
"""
Applies default Meta properties.
"""
# first add a Meta object if not exists
if 'Meta' not in kls.__dict__:
kls.Meta = type('Meta', (object,), {})
if 'unique_together' not in kls.Meta.__dict__:
kls.Meta.unique_together... | python | def process_objects(kls):
"""
Applies default Meta properties.
"""
# first add a Meta object if not exists
if 'Meta' not in kls.__dict__:
kls.Meta = type('Meta', (object,), {})
if 'unique_together' not in kls.Meta.__dict__:
kls.Meta.unique_together... | [
"def",
"process_objects",
"(",
"kls",
")",
":",
"# first add a Meta object if not exists",
"if",
"'Meta'",
"not",
"in",
"kls",
".",
"__dict__",
":",
"kls",
".",
"Meta",
"=",
"type",
"(",
"'Meta'",
",",
"(",
"object",
",",
")",
",",
"{",
"}",
")",
"if",
... | Applies default Meta properties. | [
"Applies",
"default",
"Meta",
"properties",
"."
] | train | https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/modelmeta.py#L144-L157 |
fp12/achallonge | challonge/user.py | get_user | async def get_user(username: str, api_key: str, **kwargs) -> User:
""" Creates a new user, validate its credentials and returns it
|funccoro|
Args:
username: username as specified on the challonge website
api_key: key as found on the challonge
`settings <https://challonge.com/s... | python | async def get_user(username: str, api_key: str, **kwargs) -> User:
""" Creates a new user, validate its credentials and returns it
|funccoro|
Args:
username: username as specified on the challonge website
api_key: key as found on the challonge
`settings <https://challonge.com/s... | [
"async",
"def",
"get_user",
"(",
"username",
":",
"str",
",",
"api_key",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"User",
":",
"new_user",
"=",
"User",
"(",
"username",
",",
"api_key",
",",
"*",
"*",
"kwargs",
")",
"await",
"new_user",
".",
... | Creates a new user, validate its credentials and returns it
|funccoro|
Args:
username: username as specified on the challonge website
api_key: key as found on the challonge
`settings <https://challonge.com/settings/developer>`_
Returns:
User: a logged in user if no exc... | [
"Creates",
"a",
"new",
"user",
"validate",
"its",
"credentials",
"and",
"returns",
"it"
] | train | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/user.py#L184-L203 |
fp12/achallonge | challonge/user.py | User.get_tournament | async def get_tournament(self, t_id: int = None, url: str = None, subdomain: str = None, force_update=False) -> Tournament:
""" gets a tournament with its id or url or url+subdomain
Note: from the API, it can't be known if the retrieved tournament was made from this user.
Thus, any tournament i... | python | async def get_tournament(self, t_id: int = None, url: str = None, subdomain: str = None, force_update=False) -> Tournament:
""" gets a tournament with its id or url or url+subdomain
Note: from the API, it can't be known if the retrieved tournament was made from this user.
Thus, any tournament i... | [
"async",
"def",
"get_tournament",
"(",
"self",
",",
"t_id",
":",
"int",
"=",
"None",
",",
"url",
":",
"str",
"=",
"None",
",",
"subdomain",
":",
"str",
"=",
"None",
",",
"force_update",
"=",
"False",
")",
"->",
"Tournament",
":",
"assert_or_raise",
"("... | gets a tournament with its id or url or url+subdomain
Note: from the API, it can't be known if the retrieved tournament was made from this user.
Thus, any tournament is added to the local list of tournaments, but some functions (updates/destroy...) cannot be used for tournaments not owned by this user.... | [
"gets",
"a",
"tournament",
"with",
"its",
"id",
"or",
"url",
"or",
"url",
"+",
"subdomain",
"Note",
":",
"from",
"the",
"API",
"it",
"can",
"t",
"be",
"known",
"if",
"the",
"retrieved",
"tournament",
"was",
"made",
"from",
"this",
"user",
".",
"Thus",
... | train | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/user.py#L58-L95 |
fp12/achallonge | challonge/user.py | User.get_tournaments | async def get_tournaments(self, subdomain: str = None, force_update: bool = False) -> list:
""" gets all user's tournaments
|methcoro|
Args:
subdomain: *optional* subdomain needs to be given explicitely to get tournaments in a subdomain
force_update: *optional* set to T... | python | async def get_tournaments(self, subdomain: str = None, force_update: bool = False) -> list:
""" gets all user's tournaments
|methcoro|
Args:
subdomain: *optional* subdomain needs to be given explicitely to get tournaments in a subdomain
force_update: *optional* set to T... | [
"async",
"def",
"get_tournaments",
"(",
"self",
",",
"subdomain",
":",
"str",
"=",
"None",
",",
"force_update",
":",
"bool",
"=",
"False",
")",
"->",
"list",
":",
"if",
"self",
".",
"tournaments",
"is",
"None",
":",
"force_update",
"=",
"True",
"self",
... | gets all user's tournaments
|methcoro|
Args:
subdomain: *optional* subdomain needs to be given explicitely to get tournaments in a subdomain
force_update: *optional* set to True to force the data update from Challonge
Returns:
list[Tournament]: list of all ... | [
"gets",
"all",
"user",
"s",
"tournaments"
] | train | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/user.py#L97-L138 |
fp12/achallonge | challonge/user.py | User.create_tournament | async def create_tournament(self, name: str, url: str, tournament_type: TournamentType = TournamentType.single_elimination, **params) -> Tournament:
""" creates a simple tournament with basic options
|methcoro|
Args:
name: name of the new tournament
url: url of the new ... | python | async def create_tournament(self, name: str, url: str, tournament_type: TournamentType = TournamentType.single_elimination, **params) -> Tournament:
""" creates a simple tournament with basic options
|methcoro|
Args:
name: name of the new tournament
url: url of the new ... | [
"async",
"def",
"create_tournament",
"(",
"self",
",",
"name",
":",
"str",
",",
"url",
":",
"str",
",",
"tournament_type",
":",
"TournamentType",
"=",
"TournamentType",
".",
"single_elimination",
",",
"*",
"*",
"params",
")",
"->",
"Tournament",
":",
"params... | creates a simple tournament with basic options
|methcoro|
Args:
name: name of the new tournament
url: url of the new tournament (http://challonge.com/url)
tournament_type: Defaults to TournamentType.single_elimination
params: optional params (see http://... | [
"creates",
"a",
"simple",
"tournament",
"with",
"basic",
"options"
] | train | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/user.py#L140-L165 |
fp12/achallonge | challonge/user.py | User.destroy_tournament | async def destroy_tournament(self, t: Tournament):
""" completely removes a tournament from Challonge
|methcoro|
Note:
|from_api| Deletes a tournament along with all its associated records. There is no undo, so use with care!
Raises:
APIException
"""
... | python | async def destroy_tournament(self, t: Tournament):
""" completely removes a tournament from Challonge
|methcoro|
Note:
|from_api| Deletes a tournament along with all its associated records. There is no undo, so use with care!
Raises:
APIException
"""
... | [
"async",
"def",
"destroy_tournament",
"(",
"self",
",",
"t",
":",
"Tournament",
")",
":",
"await",
"self",
".",
"connection",
"(",
"'DELETE'",
",",
"'tournaments/{}'",
".",
"format",
"(",
"t",
".",
"id",
")",
")",
"if",
"t",
"in",
"self",
".",
"tournam... | completely removes a tournament from Challonge
|methcoro|
Note:
|from_api| Deletes a tournament along with all its associated records. There is no undo, so use with care!
Raises:
APIException | [
"completely",
"removes",
"a",
"tournament",
"from",
"Challonge"
] | train | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/user.py#L167-L181 |
zetaops/pyoko | pyoko/lib/utils.py | ub_to_str | def ub_to_str(string):
"""
converts py2 unicode / py3 bytestring into str
Args:
string (unicode, byte_string): string to be converted
Returns:
(str)
"""
if not isinstance(string, str):
if six.PY2:
return str(string)
else:
return st... | python | def ub_to_str(string):
"""
converts py2 unicode / py3 bytestring into str
Args:
string (unicode, byte_string): string to be converted
Returns:
(str)
"""
if not isinstance(string, str):
if six.PY2:
return str(string)
else:
return st... | [
"def",
"ub_to_str",
"(",
"string",
")",
":",
"if",
"not",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"if",
"six",
".",
"PY2",
":",
"return",
"str",
"(",
"string",
")",
"else",
":",
"return",
"string",
".",
"decode",
"(",
")",
"return",
"str... | converts py2 unicode / py3 bytestring into str
Args:
string (unicode, byte_string): string to be converted
Returns:
(str) | [
"converts",
"py2",
"unicode",
"/",
"py3",
"bytestring",
"into",
"str",
"Args",
":",
"string",
"(",
"unicode",
"byte_string",
")",
":",
"string",
"to",
"be",
"converted",
"Returns",
":",
"(",
"str",
")"
] | train | https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/lib/utils.py#L22-L36 |
zetaops/pyoko | pyoko/lib/utils.py | to_camel | def to_camel(s):
"""
:param string s: under_scored string to be CamelCased
:return: CamelCase version of input
:rtype: str
"""
# r'(?!^)_([a-zA-Z]) original regex wasn't process first groups
return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s) | python | def to_camel(s):
"""
:param string s: under_scored string to be CamelCased
:return: CamelCase version of input
:rtype: str
"""
# r'(?!^)_([a-zA-Z]) original regex wasn't process first groups
return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s) | [
"def",
"to_camel",
"(",
"s",
")",
":",
"# r'(?!^)_([a-zA-Z]) original regex wasn't process first groups",
"return",
"re",
".",
"sub",
"(",
"r'_([a-zA-Z])'",
",",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"1",
")",
".",
"upper",
"(",
")",
",",
"'_'",
"+",
... | :param string s: under_scored string to be CamelCased
:return: CamelCase version of input
:rtype: str | [
":",
"param",
"string",
"s",
":",
"under_scored",
"string",
"to",
"be",
"CamelCased",
":",
"return",
":",
"CamelCase",
"version",
"of",
"input",
":",
"rtype",
":",
"str"
] | train | https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/lib/utils.py#L94-L101 |
zetaops/pyoko | pyoko/lib/utils.py | get_object_from_path | def get_object_from_path(path):
"""
Import's object from given Python path.
"""
try:
return sys.IMPORT_CACHE[path]
except KeyError:
_path = path.split('.')
module_path = '.'.join(_path[:-1])
class_name = _path[-1]
module = importlib.import_module(module_path)
... | python | def get_object_from_path(path):
"""
Import's object from given Python path.
"""
try:
return sys.IMPORT_CACHE[path]
except KeyError:
_path = path.split('.')
module_path = '.'.join(_path[:-1])
class_name = _path[-1]
module = importlib.import_module(module_path)
... | [
"def",
"get_object_from_path",
"(",
"path",
")",
":",
"try",
":",
"return",
"sys",
".",
"IMPORT_CACHE",
"[",
"path",
"]",
"except",
"KeyError",
":",
"_path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"module_path",
"=",
"'.'",
".",
"join",
"(",
"_pat... | Import's object from given Python path. | [
"Import",
"s",
"object",
"from",
"given",
"Python",
"path",
"."
] | train | https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/lib/utils.py#L128-L140 |
zetaops/pyoko | pyoko/lib/utils.py | pprnt | def pprnt(input, return_data=False):
"""
Prettier print for nested data
Args:
input: Input data
return_data (bool): Default False. Print outs if False, returns if True.
Returns:
None | Pretty formatted text representation of input data.
"""
HEADER = '\033[95m'
OKBLUE... | python | def pprnt(input, return_data=False):
"""
Prettier print for nested data
Args:
input: Input data
return_data (bool): Default False. Print outs if False, returns if True.
Returns:
None | Pretty formatted text representation of input data.
"""
HEADER = '\033[95m'
OKBLUE... | [
"def",
"pprnt",
"(",
"input",
",",
"return_data",
"=",
"False",
")",
":",
"HEADER",
"=",
"'\\033[95m'",
"OKBLUE",
"=",
"'\\033[94m'",
"OKGREEN",
"=",
"'\\033[32m'",
"WARNING",
"=",
"'\\033[93m'",
"FAIL",
"=",
"'\\033[91m'",
"ENDC",
"=",
"'\\033[0m'",
"BOLD",
... | Prettier print for nested data
Args:
input: Input data
return_data (bool): Default False. Print outs if False, returns if True.
Returns:
None | Pretty formatted text representation of input data. | [
"Prettier",
"print",
"for",
"nested",
"data"
] | train | https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/lib/utils.py#L143-L169 |
ionelmc/python-cogen | cogen/core/proactors/base.py | wrapped_sendfile | def wrapped_sendfile(act, offset, length):
"""
Calls the sendfile system call or simulate with file read and socket send if
unavailable.
"""
if sendfile:
offset, sent = sendfile.sendfile(
act.sock.fileno(),
act.file_handle.fileno(),
offset, length... | python | def wrapped_sendfile(act, offset, length):
"""
Calls the sendfile system call or simulate with file read and socket send if
unavailable.
"""
if sendfile:
offset, sent = sendfile.sendfile(
act.sock.fileno(),
act.file_handle.fileno(),
offset, length... | [
"def",
"wrapped_sendfile",
"(",
"act",
",",
"offset",
",",
"length",
")",
":",
"if",
"sendfile",
":",
"offset",
",",
"sent",
"=",
"sendfile",
".",
"sendfile",
"(",
"act",
".",
"sock",
".",
"fileno",
"(",
")",
",",
"act",
".",
"file_handle",
".",
"fil... | Calls the sendfile system call or simulate with file read and socket send if
unavailable. | [
"Calls",
"the",
"sendfile",
"system",
"call",
"or",
"simulate",
"with",
"file",
"read",
"and",
"socket",
"send",
"if",
"unavailable",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/base.py#L54-L68 |
ionelmc/python-cogen | cogen/core/proactors/base.py | ProactorBase.set_options | def set_options(self, multiplex_first=True, **bogus_options):
"Takes implementation specific options. To be overriden in a subclass."
self.multiplex_first = multiplex_first
self._warn_bogus_options(**bogus_options) | python | def set_options(self, multiplex_first=True, **bogus_options):
"Takes implementation specific options. To be overriden in a subclass."
self.multiplex_first = multiplex_first
self._warn_bogus_options(**bogus_options) | [
"def",
"set_options",
"(",
"self",
",",
"multiplex_first",
"=",
"True",
",",
"*",
"*",
"bogus_options",
")",
":",
"self",
".",
"multiplex_first",
"=",
"multiplex_first",
"self",
".",
"_warn_bogus_options",
"(",
"*",
"*",
"bogus_options",
")"
] | Takes implementation specific options. To be overriden in a subclass. | [
"Takes",
"implementation",
"specific",
"options",
".",
"To",
"be",
"overriden",
"in",
"a",
"subclass",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/base.py#L115-L118 |
ionelmc/python-cogen | cogen/core/proactors/base.py | ProactorBase._warn_bogus_options | def _warn_bogus_options(self, **opts):
"""
Shows a warning for unsupported options for the current implementation.
Called form set_options with remainig unsupported options.
"""
if opts:
import warnings
for i in opts:
warnings.warn(... | python | def _warn_bogus_options(self, **opts):
"""
Shows a warning for unsupported options for the current implementation.
Called form set_options with remainig unsupported options.
"""
if opts:
import warnings
for i in opts:
warnings.warn(... | [
"def",
"_warn_bogus_options",
"(",
"self",
",",
"*",
"*",
"opts",
")",
":",
"if",
"opts",
":",
"import",
"warnings",
"for",
"i",
"in",
"opts",
":",
"warnings",
".",
"warn",
"(",
"\"Unsupported option %s for %s\"",
"%",
"(",
"i",
",",
"self",
")",
",",
... | Shows a warning for unsupported options for the current implementation.
Called form set_options with remainig unsupported options. | [
"Shows",
"a",
"warning",
"for",
"unsupported",
"options",
"for",
"the",
"current",
"implementation",
".",
"Called",
"form",
"set_options",
"with",
"remainig",
"unsupported",
"options",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/base.py#L120-L128 |
ionelmc/python-cogen | cogen/core/proactors/base.py | ProactorBase.request_connect | def request_connect(self, act, coro):
"Requests a connect for `coro` corutine with parameters and completion \
passed via `act`"
result = self.try_run_act(act, perform_connect)
if result:
return result, coro
else:
self.add_token(act, coro, perform_c... | python | def request_connect(self, act, coro):
"Requests a connect for `coro` corutine with parameters and completion \
passed via `act`"
result = self.try_run_act(act, perform_connect)
if result:
return result, coro
else:
self.add_token(act, coro, perform_c... | [
"def",
"request_connect",
"(",
"self",
",",
"act",
",",
"coro",
")",
":",
"result",
"=",
"self",
".",
"try_run_act",
"(",
"act",
",",
"perform_connect",
")",
"if",
"result",
":",
"return",
"result",
",",
"coro",
"else",
":",
"self",
".",
"add_token",
"... | Requests a connect for `coro` corutine with parameters and completion \
passed via `act` | [
"Requests",
"a",
"connect",
"for",
"coro",
"corutine",
"with",
"parameters",
"and",
"completion",
"\\",
"passed",
"via",
"act"
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/base.py#L153-L160 |
ionelmc/python-cogen | cogen/core/proactors/base.py | ProactorBase.request_generic | def request_generic(self, act, coro, perform):
"""
Requests an socket operation (in the form of a callable `perform` that
does the actual socket system call) for `coro` corutine with parameters
and completion passed via `act`.
The socket operation request parameters are pa... | python | def request_generic(self, act, coro, perform):
"""
Requests an socket operation (in the form of a callable `perform` that
does the actual socket system call) for `coro` corutine with parameters
and completion passed via `act`.
The socket operation request parameters are pa... | [
"def",
"request_generic",
"(",
"self",
",",
"act",
",",
"coro",
",",
"perform",
")",
":",
"result",
"=",
"self",
".",
"multiplex_first",
"and",
"self",
".",
"try_run_act",
"(",
"act",
",",
"perform",
")",
"if",
"result",
":",
"return",
"result",
",",
"... | Requests an socket operation (in the form of a callable `perform` that
does the actual socket system call) for `coro` corutine with parameters
and completion passed via `act`.
The socket operation request parameters are passed in `act`.
When request is completed the results will be... | [
"Requests",
"an",
"socket",
"operation",
"(",
"in",
"the",
"form",
"of",
"a",
"callable",
"perform",
"that",
"does",
"the",
"actual",
"socket",
"system",
"call",
")",
"for",
"coro",
"corutine",
"with",
"parameters",
"and",
"completion",
"passed",
"via",
"act... | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/base.py#L167-L183 |
ionelmc/python-cogen | cogen/core/proactors/base.py | ProactorBase.add_token | def add_token(self, act, coro, performer):
"""
Adds a completion token `act` in the proactor with associated `coro`
corutine and perform callable.
"""
assert act not in self.tokens
act.coro = coro
self.tokens[act] = performer
self.register_fd(act, ... | python | def add_token(self, act, coro, performer):
"""
Adds a completion token `act` in the proactor with associated `coro`
corutine and perform callable.
"""
assert act not in self.tokens
act.coro = coro
self.tokens[act] = performer
self.register_fd(act, ... | [
"def",
"add_token",
"(",
"self",
",",
"act",
",",
"coro",
",",
"performer",
")",
":",
"assert",
"act",
"not",
"in",
"self",
".",
"tokens",
"act",
".",
"coro",
"=",
"coro",
"self",
".",
"tokens",
"[",
"act",
"]",
"=",
"performer",
"self",
".",
"regi... | Adds a completion token `act` in the proactor with associated `coro`
corutine and perform callable. | [
"Adds",
"a",
"completion",
"token",
"act",
"in",
"the",
"proactor",
"with",
"associated",
"coro",
"corutine",
"and",
"perform",
"callable",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/base.py#L186-L194 |
ionelmc/python-cogen | cogen/core/proactors/base.py | ProactorBase.remove_token | def remove_token(self, act):
"""
Remove a token from the proactor.
If removal succeeds (the token is in the proactor) return True.
"""
if act in self.tokens:
self.unregister_fd(act)
del self.tokens[act]
return True
else:
... | python | def remove_token(self, act):
"""
Remove a token from the proactor.
If removal succeeds (the token is in the proactor) return True.
"""
if act in self.tokens:
self.unregister_fd(act)
del self.tokens[act]
return True
else:
... | [
"def",
"remove_token",
"(",
"self",
",",
"act",
")",
":",
"if",
"act",
"in",
"self",
".",
"tokens",
":",
"self",
".",
"unregister_fd",
"(",
"act",
")",
"del",
"self",
".",
"tokens",
"[",
"act",
"]",
"return",
"True",
"else",
":",
"import",
"warnings"... | Remove a token from the proactor.
If removal succeeds (the token is in the proactor) return True. | [
"Remove",
"a",
"token",
"from",
"the",
"proactor",
".",
"If",
"removal",
"succeeds",
"(",
"the",
"token",
"is",
"in",
"the",
"proactor",
")",
"return",
"True",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/base.py#L196-L207 |
ionelmc/python-cogen | cogen/core/proactors/base.py | ProactorBase.handle_event | def handle_event(self, act):
"""
Handle completion for a request.
Calls the scheduler to run or schedule the associated coroutine.
"""
scheduler = self.scheduler
if act in self.tokens:
coro = act.coro
op = self.try_run_act(act, self.token... | python | def handle_event(self, act):
"""
Handle completion for a request.
Calls the scheduler to run or schedule the associated coroutine.
"""
scheduler = self.scheduler
if act in self.tokens:
coro = act.coro
op = self.try_run_act(act, self.token... | [
"def",
"handle_event",
"(",
"self",
",",
"act",
")",
":",
"scheduler",
"=",
"self",
".",
"scheduler",
"if",
"act",
"in",
"self",
".",
"tokens",
":",
"coro",
"=",
"act",
".",
"coro",
"op",
"=",
"self",
".",
"try_run_act",
"(",
"act",
",",
"self",
".... | Handle completion for a request.
Calls the scheduler to run or schedule the associated coroutine. | [
"Handle",
"completion",
"for",
"a",
"request",
".",
"Calls",
"the",
"scheduler",
"to",
"run",
"or",
"schedule",
"the",
"associated",
"coroutine",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/base.py#L253-L283 |
ionelmc/python-cogen | cogen/core/proactors/base.py | ProactorBase.yield_event | def yield_event(self, act):
"""
Hande completion for a request and return an (op, coro) to be
passed to the scheduler on the last completion loop of a proactor.
"""
if act in self.tokens:
coro = act.coro
op = self.try_run_act(act, self.tokens[act])
... | python | def yield_event(self, act):
"""
Hande completion for a request and return an (op, coro) to be
passed to the scheduler on the last completion loop of a proactor.
"""
if act in self.tokens:
coro = act.coro
op = self.try_run_act(act, self.tokens[act])
... | [
"def",
"yield_event",
"(",
"self",
",",
"act",
")",
":",
"if",
"act",
"in",
"self",
".",
"tokens",
":",
"coro",
"=",
"act",
".",
"coro",
"op",
"=",
"self",
".",
"try_run_act",
"(",
"act",
",",
"self",
".",
"tokens",
"[",
"act",
"]",
")",
"if",
... | Hande completion for a request and return an (op, coro) to be
passed to the scheduler on the last completion loop of a proactor. | [
"Hande",
"completion",
"for",
"a",
"request",
"and",
"return",
"an",
"(",
"op",
"coro",
")",
"to",
"be",
"passed",
"to",
"the",
"scheduler",
"on",
"the",
"last",
"completion",
"loop",
"of",
"a",
"proactor",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/base.py#L285-L295 |
ionelmc/python-cogen | cogen/core/proactors/base.py | ProactorBase.handle_error_event | def handle_error_event(self, act, detail, exc=SocketError):
"""
Handle an errored event. Calls the scheduler to schedule the associated
coroutine.
"""
del self.tokens[act]
self.scheduler.active.append((
CoroutineException(exc, exc(detail)),
... | python | def handle_error_event(self, act, detail, exc=SocketError):
"""
Handle an errored event. Calls the scheduler to schedule the associated
coroutine.
"""
del self.tokens[act]
self.scheduler.active.append((
CoroutineException(exc, exc(detail)),
... | [
"def",
"handle_error_event",
"(",
"self",
",",
"act",
",",
"detail",
",",
"exc",
"=",
"SocketError",
")",
":",
"del",
"self",
".",
"tokens",
"[",
"act",
"]",
"self",
".",
"scheduler",
".",
"active",
".",
"append",
"(",
"(",
"CoroutineException",
"(",
"... | Handle an errored event. Calls the scheduler to schedule the associated
coroutine. | [
"Handle",
"an",
"errored",
"event",
".",
"Calls",
"the",
"scheduler",
"to",
"schedule",
"the",
"associated",
"coroutine",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/base.py#L297-L306 |
yatiml/yatiml | yatiml/dumper.py | add_to_dumper | def add_to_dumper(dumper: Type, classes: List[Type]) -> None:
"""Register user-defined classes with the Dumper.
This enables the Dumper to write objects of your classes to a \
YAML file. Note that all the arguments are types, not instances!
Args:
dumper: Your dumper class(!), derived from yati... | python | def add_to_dumper(dumper: Type, classes: List[Type]) -> None:
"""Register user-defined classes with the Dumper.
This enables the Dumper to write objects of your classes to a \
YAML file. Note that all the arguments are types, not instances!
Args:
dumper: Your dumper class(!), derived from yati... | [
"def",
"add_to_dumper",
"(",
"dumper",
":",
"Type",
",",
"classes",
":",
"List",
"[",
"Type",
"]",
")",
"->",
"None",
":",
"if",
"not",
"isinstance",
"(",
"classes",
",",
"list",
")",
":",
"classes",
"=",
"[",
"classes",
"]",
"# type: ignore",
"for",
... | Register user-defined classes with the Dumper.
This enables the Dumper to write objects of your classes to a \
YAML file. Note that all the arguments are types, not instances!
Args:
dumper: Your dumper class(!), derived from yatiml.Dumper
classes: One or more classes to add. | [
"Register",
"user",
"-",
"defined",
"classes",
"with",
"the",
"Dumper",
"."
] | train | https://github.com/yatiml/yatiml/blob/4f55c058b72388350f0af3076ac3ea9bc1c142b0/yatiml/dumper.py#L26-L44 |
cthoyt/onto2nx | src/onto2nx/ontospy/core/ontospy.py | Ontospy.sparql | def sparql(self, stringa):
""" wrapper around a sparql query """
qres = self.rdfgraph.query(stringa)
return list(qres) | python | def sparql(self, stringa):
""" wrapper around a sparql query """
qres = self.rdfgraph.query(stringa)
return list(qres) | [
"def",
"sparql",
"(",
"self",
",",
"stringa",
")",
":",
"qres",
"=",
"self",
".",
"rdfgraph",
".",
"query",
"(",
"stringa",
")",
"return",
"list",
"(",
"qres",
")"
] | wrapper around a sparql query | [
"wrapper",
"around",
"a",
"sparql",
"query"
] | train | https://github.com/cthoyt/onto2nx/blob/94c86e5e187cca67534afe0260097177b66e02c8/src/onto2nx/ontospy/core/ontospy.py#L86-L89 |
cthoyt/onto2nx | src/onto2nx/ontospy/core/ontospy.py | Ontospy._scan | def _scan(self, verbose=False, hide_base_schemas=True):
"""
scan a source of RDF triples
build all the objects to deal with the ontology/ies pythonically
"""
if verbose:
printDebug("Scanning entities...", "green")
printDebug("----------", "comment")
... | python | def _scan(self, verbose=False, hide_base_schemas=True):
"""
scan a source of RDF triples
build all the objects to deal with the ontology/ies pythonically
"""
if verbose:
printDebug("Scanning entities...", "green")
printDebug("----------", "comment")
... | [
"def",
"_scan",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"hide_base_schemas",
"=",
"True",
")",
":",
"if",
"verbose",
":",
"printDebug",
"(",
"\"Scanning entities...\"",
",",
"\"green\"",
")",
"printDebug",
"(",
"\"----------\"",
",",
"\"comment\"",
")"... | scan a source of RDF triples
build all the objects to deal with the ontology/ies pythonically | [
"scan",
"a",
"source",
"of",
"RDF",
"triples",
"build",
"all",
"the",
"objects",
"to",
"deal",
"with",
"the",
"ontology",
"/",
"ies",
"pythonically"
] | train | https://github.com/cthoyt/onto2nx/blob/94c86e5e187cca67534afe0260097177b66e02c8/src/onto2nx/ontospy/core/ontospy.py#L104-L133 |
cthoyt/onto2nx | src/onto2nx/ontospy/core/ontospy.py | Ontospy.stats | def stats(self):
""" shotcut to pull out useful info for a graph
2016-08-18 the try/except is a dirty solution to a problem
emerging with counting graph lenght on cached Graph objects..
TODO: investigate what's going on..
"""
out = []
try:
out += [("... | python | def stats(self):
""" shotcut to pull out useful info for a graph
2016-08-18 the try/except is a dirty solution to a problem
emerging with counting graph lenght on cached Graph objects..
TODO: investigate what's going on..
"""
out = []
try:
out += [("... | [
"def",
"stats",
"(",
"self",
")",
":",
"out",
"=",
"[",
"]",
"try",
":",
"out",
"+=",
"[",
"(",
"\"Triples\"",
",",
"len",
"(",
"self",
".",
"rdfgraph",
")",
")",
"]",
"except",
":",
"pass",
"out",
"+=",
"[",
"(",
"\"Classes\"",
",",
"len",
"("... | shotcut to pull out useful info for a graph
2016-08-18 the try/except is a dirty solution to a problem
emerging with counting graph lenght on cached Graph objects..
TODO: investigate what's going on.. | [
"shotcut",
"to",
"pull",
"out",
"useful",
"info",
"for",
"a",
"graph"
] | train | https://github.com/cthoyt/onto2nx/blob/94c86e5e187cca67534afe0260097177b66e02c8/src/onto2nx/ontospy/core/ontospy.py#L136-L155 |
cthoyt/onto2nx | src/onto2nx/ontospy/core/ontospy.py | Ontospy.__extractOntologies | def __extractOntologies(self, exclude_BNodes = False, return_string=False):
"""
returns Ontology class instances
[ a owl:Ontology ;
vann:preferredNamespacePrefix "bsym" ;
vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ],
"""
out = []
... | python | def __extractOntologies(self, exclude_BNodes = False, return_string=False):
"""
returns Ontology class instances
[ a owl:Ontology ;
vann:preferredNamespacePrefix "bsym" ;
vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ],
"""
out = []
... | [
"def",
"__extractOntologies",
"(",
"self",
",",
"exclude_BNodes",
"=",
"False",
",",
"return_string",
"=",
"False",
")",
":",
"out",
"=",
"[",
"]",
"qres",
"=",
"self",
".",
"queryHelper",
".",
"getOntology",
"(",
")",
"if",
"qres",
":",
"# NOTE: SPARQL re... | returns Ontology class instances
[ a owl:Ontology ;
vann:preferredNamespacePrefix "bsym" ;
vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ], | [
"returns",
"Ontology",
"class",
"instances"
] | train | https://github.com/cthoyt/onto2nx/blob/94c86e5e187cca67534afe0260097177b66e02c8/src/onto2nx/ontospy/core/ontospy.py#L159-L207 |
cthoyt/onto2nx | src/onto2nx/ontospy/core/ontospy.py | Ontospy.__extractClasses | def __extractClasses(self, hide_base_schemas=True):
"""
2015-06-04: removed sparql 1.1 queries
2015-05-25: optimized via sparql queries in order to remove BNodes
2015-05-09: new attempt
Note: queryHelper.getAllClasses() returns a list of tuples,
(class, classRDFtype)
... | python | def __extractClasses(self, hide_base_schemas=True):
"""
2015-06-04: removed sparql 1.1 queries
2015-05-25: optimized via sparql queries in order to remove BNodes
2015-05-09: new attempt
Note: queryHelper.getAllClasses() returns a list of tuples,
(class, classRDFtype)
... | [
"def",
"__extractClasses",
"(",
"self",
",",
"hide_base_schemas",
"=",
"True",
")",
":",
"self",
".",
"classes",
"=",
"[",
"]",
"# @todo: keep adding?",
"qres",
"=",
"self",
".",
"queryHelper",
".",
"getAllClasses",
"(",
"hide_base_schemas",
"=",
"hide_base_sche... | 2015-06-04: removed sparql 1.1 queries
2015-05-25: optimized via sparql queries in order to remove BNodes
2015-05-09: new attempt
Note: queryHelper.getAllClasses() returns a list of tuples,
(class, classRDFtype)
so in some cases there are duplicates if a class is both RDFS.CLass... | [
"2015",
"-",
"06",
"-",
"04",
":",
"removed",
"sparql",
"1",
".",
"1",
"queries",
"2015",
"-",
"05",
"-",
"25",
":",
"optimized",
"via",
"sparql",
"queries",
"in",
"order",
"to",
"remove",
"BNodes",
"2015",
"-",
"05",
"-",
"09",
":",
"new",
"attemp... | train | https://github.com/cthoyt/onto2nx/blob/94c86e5e187cca67534afe0260097177b66e02c8/src/onto2nx/ontospy/core/ontospy.py#L220-L281 |
cthoyt/onto2nx | src/onto2nx/ontospy/core/ontospy.py | Ontospy.__extractProperties | def __extractProperties(self):
"""
2015-06-04: removed sparql 1.1 queries
2015-06-03: analogous to get classes
# instantiate properties making sure duplicates are pruned
# but the most specific rdftype is kept
# eg OWL:ObjectProperty over RDF:property
"""
... | python | def __extractProperties(self):
"""
2015-06-04: removed sparql 1.1 queries
2015-06-03: analogous to get classes
# instantiate properties making sure duplicates are pruned
# but the most specific rdftype is kept
# eg OWL:ObjectProperty over RDF:property
"""
... | [
"def",
"__extractProperties",
"(",
"self",
")",
":",
"self",
".",
"properties",
"=",
"[",
"]",
"# @todo: keep adding?",
"self",
".",
"annotationProperties",
"=",
"[",
"]",
"self",
".",
"objectProperties",
"=",
"[",
"]",
"self",
".",
"datatypeProperties",
"=",
... | 2015-06-04: removed sparql 1.1 queries
2015-06-03: analogous to get classes
# instantiate properties making sure duplicates are pruned
# but the most specific rdftype is kept
# eg OWL:ObjectProperty over RDF:property | [
"2015",
"-",
"06",
"-",
"04",
":",
"removed",
"sparql",
"1",
".",
"1",
"queries",
"2015",
"-",
"06",
"-",
"03",
":",
"analogous",
"to",
"get",
"classes"
] | train | https://github.com/cthoyt/onto2nx/blob/94c86e5e187cca67534afe0260097177b66e02c8/src/onto2nx/ontospy/core/ontospy.py#L285-L350 |
cthoyt/onto2nx | src/onto2nx/ontospy/core/ontospy.py | Ontospy.__buildDomainRanges | def __buildDomainRanges(self, aProp):
"""
extract domain/range details and add to Python objects
"""
domains = aProp.rdfgraph.objects(None, rdflib.RDFS.domain)
ranges = aProp.rdfgraph.objects(None, rdflib.RDFS.range)
for x in domains:
if not isBlankNode(x):
... | python | def __buildDomainRanges(self, aProp):
"""
extract domain/range details and add to Python objects
"""
domains = aProp.rdfgraph.objects(None, rdflib.RDFS.domain)
ranges = aProp.rdfgraph.objects(None, rdflib.RDFS.range)
for x in domains:
if not isBlankNode(x):
... | [
"def",
"__buildDomainRanges",
"(",
"self",
",",
"aProp",
")",
":",
"domains",
"=",
"aProp",
".",
"rdfgraph",
".",
"objects",
"(",
"None",
",",
"rdflib",
".",
"RDFS",
".",
"domain",
")",
"ranges",
"=",
"aProp",
".",
"rdfgraph",
".",
"objects",
"(",
"Non... | extract domain/range details and add to Python objects | [
"extract",
"domain",
"/",
"range",
"details",
"and",
"add",
"to",
"Python",
"objects"
] | train | https://github.com/cthoyt/onto2nx/blob/94c86e5e187cca67534afe0260097177b66e02c8/src/onto2nx/ontospy/core/ontospy.py#L354-L377 |
cthoyt/onto2nx | src/onto2nx/ontospy/core/ontospy.py | Ontospy.__extractSkosConcepts | def __extractSkosConcepts(self):
"""
2015-08-19: first draft
"""
self.skosConcepts = [] # @todo: keep adding?
qres = self.queryHelper.getSKOSInstances()
for candidate in qres:
test_existing_cl = self.getSkosConcept(uri=candidate[0])
if not test_... | python | def __extractSkosConcepts(self):
"""
2015-08-19: first draft
"""
self.skosConcepts = [] # @todo: keep adding?
qres = self.queryHelper.getSKOSInstances()
for candidate in qres:
test_existing_cl = self.getSkosConcept(uri=candidate[0])
if not test_... | [
"def",
"__extractSkosConcepts",
"(",
"self",
")",
":",
"self",
".",
"skosConcepts",
"=",
"[",
"]",
"# @todo: keep adding?",
"qres",
"=",
"self",
".",
"queryHelper",
".",
"getSKOSInstances",
"(",
")",
"for",
"candidate",
"in",
"qres",
":",
"test_existing_cl",
"... | 2015-08-19: first draft | [
"2015",
"-",
"08",
"-",
"19",
":",
"first",
"draft"
] | train | https://github.com/cthoyt/onto2nx/blob/94c86e5e187cca67534afe0260097177b66e02c8/src/onto2nx/ontospy/core/ontospy.py#L383-L428 |
cthoyt/onto2nx | src/onto2nx/ontospy/core/ontospy.py | Ontospy.getInferredPropertiesForClass | def getInferredPropertiesForClass(self, aClass, rel="domain_of"):
"""
returns all properties valid for a class (as they have it in their domain)
recursively ie traveling up the descendants tree
Note: results in a list of dicts including itself
Note [2]: all properties with no dom... | python | def getInferredPropertiesForClass(self, aClass, rel="domain_of"):
"""
returns all properties valid for a class (as they have it in their domain)
recursively ie traveling up the descendants tree
Note: results in a list of dicts including itself
Note [2]: all properties with no dom... | [
"def",
"getInferredPropertiesForClass",
"(",
"self",
",",
"aClass",
",",
"rel",
"=",
"\"domain_of\"",
")",
":",
"_list",
"=",
"[",
"]",
"if",
"rel",
"==",
"\"domain_of\"",
":",
"_list",
".",
"append",
"(",
"{",
"aClass",
":",
"aClass",
".",
"domain_of",
... | returns all properties valid for a class (as they have it in their domain)
recursively ie traveling up the descendants tree
Note: results in a list of dicts including itself
Note [2]: all properties with no domain info are added at the top as [None, props]
:return:
[{<Class *htt... | [
"returns",
"all",
"properties",
"valid",
"for",
"a",
"class",
"(",
"as",
"they",
"have",
"it",
"in",
"their",
"domain",
")",
"recursively",
"ie",
"traveling",
"up",
"the",
"descendants",
"tree",
"Note",
":",
"results",
"in",
"a",
"list",
"of",
"dicts",
"... | train | https://github.com/cthoyt/onto2nx/blob/94c86e5e187cca67534afe0260097177b66e02c8/src/onto2nx/ontospy/core/ontospy.py#L465-L506 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.