repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
xenadevel/PyXenaManager | xenamanager/xena_statistics_view.py | XenaStreamsStats.read_stats | def read_stats(self):
""" Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}}
"""
self.tx_statistics = TgnObjectsDict()
for port in self.session.ports.values():
for stream in p... | python | def read_stats(self):
""" Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}}
"""
self.tx_statistics = TgnObjectsDict()
for port in self.session.ports.values():
for stream in p... | [
"def",
"read_stats",
"(",
"self",
")",
":",
"self",
".",
"tx_statistics",
"=",
"TgnObjectsDict",
"(",
")",
"for",
"port",
"in",
"self",
".",
"session",
".",
"ports",
".",
"values",
"(",
")",
":",
"for",
"stream",
"in",
"port",
".",
"streams",
".",
"v... | Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}} | [
"Read",
"current",
"statistics",
"from",
"chassis",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_statistics_view.py#L90-L112 |
xenadevel/PyXenaManager | xenamanager/xena_statistics_view.py | XenaTpldsStats.read_stats | def read_stats(self):
""" Read current statistics from chassis.
:return: dictionary {tpld full index {group name {stat name: stat value}}}
"""
self.statistics = TgnObjectsDict()
for port in self.session.ports.values():
for tpld in port.tplds.values():
... | python | def read_stats(self):
""" Read current statistics from chassis.
:return: dictionary {tpld full index {group name {stat name: stat value}}}
"""
self.statistics = TgnObjectsDict()
for port in self.session.ports.values():
for tpld in port.tplds.values():
... | [
"def",
"read_stats",
"(",
"self",
")",
":",
"self",
".",
"statistics",
"=",
"TgnObjectsDict",
"(",
")",
"for",
"port",
"in",
"self",
".",
"session",
".",
"ports",
".",
"values",
"(",
")",
":",
"for",
"tpld",
"in",
"port",
".",
"tplds",
".",
"values",... | Read current statistics from chassis.
:return: dictionary {tpld full index {group name {stat name: stat value}}} | [
"Read",
"current",
"statistics",
"from",
"chassis",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_statistics_view.py#L134-L144 |
quizl/quizler | quizler/utils.py | get_user_sets | def get_user_sets(client_id, user_id):
"""Find all user sets."""
data = api_call('get', 'users/{}/sets'.format(user_id), client_id=client_id)
return [WordSet.from_dict(wordset) for wordset in data] | python | def get_user_sets(client_id, user_id):
"""Find all user sets."""
data = api_call('get', 'users/{}/sets'.format(user_id), client_id=client_id)
return [WordSet.from_dict(wordset) for wordset in data] | [
"def",
"get_user_sets",
"(",
"client_id",
",",
"user_id",
")",
":",
"data",
"=",
"api_call",
"(",
"'get'",
",",
"'users/{}/sets'",
".",
"format",
"(",
"user_id",
")",
",",
"client_id",
"=",
"client_id",
")",
"return",
"[",
"WordSet",
".",
"from_dict",
"(",... | Find all user sets. | [
"Find",
"all",
"user",
"sets",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/utils.py#L10-L13 |
quizl/quizler | quizler/utils.py | print_user_sets | def print_user_sets(wordsets, print_terms):
"""Print all user sets by title. If 'print_terms', also prints all terms of all user sets.
:param wordsets: List of WordSet.
:param print_terms: If True, also prints all terms of all user sets.
"""
if not wordsets:
print('No sets found')
else:
... | python | def print_user_sets(wordsets, print_terms):
"""Print all user sets by title. If 'print_terms', also prints all terms of all user sets.
:param wordsets: List of WordSet.
:param print_terms: If True, also prints all terms of all user sets.
"""
if not wordsets:
print('No sets found')
else:
... | [
"def",
"print_user_sets",
"(",
"wordsets",
",",
"print_terms",
")",
":",
"if",
"not",
"wordsets",
":",
"print",
"(",
"'No sets found'",
")",
"else",
":",
"print",
"(",
"'Found sets: {}'",
".",
"format",
"(",
"len",
"(",
"wordsets",
")",
")",
")",
"for",
... | Print all user sets by title. If 'print_terms', also prints all terms of all user sets.
:param wordsets: List of WordSet.
:param print_terms: If True, also prints all terms of all user sets. | [
"Print",
"all",
"user",
"sets",
"by",
"title",
".",
"If",
"print_terms",
"also",
"prints",
"all",
"terms",
"of",
"all",
"user",
"sets",
".",
":",
"param",
"wordsets",
":",
"List",
"of",
"WordSet",
".",
":",
"param",
"print_terms",
":",
"If",
"True",
"a... | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/utils.py#L16-L29 |
quizl/quizler | quizler/utils.py | get_common_terms | def get_common_terms(*api_envs):
"""Get all term duplicates across all user word sets as a list of
(title of first word set, title of second word set, set of terms) tuples."""
common_terms = []
# pylint: disable=no-value-for-parameter
wordsets = get_user_sets(*api_envs)
# pylint: enable=no-value... | python | def get_common_terms(*api_envs):
"""Get all term duplicates across all user word sets as a list of
(title of first word set, title of second word set, set of terms) tuples."""
common_terms = []
# pylint: disable=no-value-for-parameter
wordsets = get_user_sets(*api_envs)
# pylint: enable=no-value... | [
"def",
"get_common_terms",
"(",
"*",
"api_envs",
")",
":",
"common_terms",
"=",
"[",
"]",
"# pylint: disable=no-value-for-parameter",
"wordsets",
"=",
"get_user_sets",
"(",
"*",
"api_envs",
")",
"# pylint: enable=no-value-for-parameter",
"for",
"wordset1",
",",
"wordset... | Get all term duplicates across all user word sets as a list of
(title of first word set, title of second word set, set of terms) tuples. | [
"Get",
"all",
"term",
"duplicates",
"across",
"all",
"user",
"word",
"sets",
"as",
"a",
"list",
"of",
"(",
"title",
"of",
"first",
"word",
"set",
"title",
"of",
"second",
"word",
"set",
"set",
"of",
"terms",
")",
"tuples",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/utils.py#L32-L44 |
quizl/quizler | quizler/utils.py | print_common_terms | def print_common_terms(common_terms):
"""Print common terms for each pair of word sets.
:param common_terms: Output of get_common_terms().
"""
if not common_terms:
print('No duplicates')
else:
for set_pair in common_terms:
set1, set2, terms = set_pair
print('{... | python | def print_common_terms(common_terms):
"""Print common terms for each pair of word sets.
:param common_terms: Output of get_common_terms().
"""
if not common_terms:
print('No duplicates')
else:
for set_pair in common_terms:
set1, set2, terms = set_pair
print('{... | [
"def",
"print_common_terms",
"(",
"common_terms",
")",
":",
"if",
"not",
"common_terms",
":",
"print",
"(",
"'No duplicates'",
")",
"else",
":",
"for",
"set_pair",
"in",
"common_terms",
":",
"set1",
",",
"set2",
",",
"terms",
"=",
"set_pair",
"print",
"(",
... | Print common terms for each pair of word sets.
:param common_terms: Output of get_common_terms(). | [
"Print",
"common",
"terms",
"for",
"each",
"pair",
"of",
"word",
"sets",
".",
":",
"param",
"common_terms",
":",
"Output",
"of",
"get_common_terms",
"()",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/utils.py#L47-L58 |
quizl/quizler | quizler/utils.py | delete_term | def delete_term(set_id, term_id, access_token):
"""Delete the given term."""
api_call('delete', 'sets/{}/terms/{}'.format(set_id, term_id), access_token=access_token) | python | def delete_term(set_id, term_id, access_token):
"""Delete the given term."""
api_call('delete', 'sets/{}/terms/{}'.format(set_id, term_id), access_token=access_token) | [
"def",
"delete_term",
"(",
"set_id",
",",
"term_id",
",",
"access_token",
")",
":",
"api_call",
"(",
"'delete'",
",",
"'sets/{}/terms/{}'",
".",
"format",
"(",
"set_id",
",",
"term_id",
")",
",",
"access_token",
"=",
"access_token",
")"
] | Delete the given term. | [
"Delete",
"the",
"given",
"term",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/utils.py#L61-L63 |
quizl/quizler | quizler/utils.py | add_term | def add_term(set_id, term, access_token):
"""Add the given term to the given set.
:param term: Instance of Term.
"""
api_call('post', 'sets/{}/terms'.format(set_id), term.to_dict(), access_token=access_token) | python | def add_term(set_id, term, access_token):
"""Add the given term to the given set.
:param term: Instance of Term.
"""
api_call('post', 'sets/{}/terms'.format(set_id), term.to_dict(), access_token=access_token) | [
"def",
"add_term",
"(",
"set_id",
",",
"term",
",",
"access_token",
")",
":",
"api_call",
"(",
"'post'",
",",
"'sets/{}/terms'",
".",
"format",
"(",
"set_id",
")",
",",
"term",
".",
"to_dict",
"(",
")",
",",
"access_token",
"=",
"access_token",
")"
] | Add the given term to the given set.
:param term: Instance of Term. | [
"Add",
"the",
"given",
"term",
"to",
"the",
"given",
"set",
".",
":",
"param",
"term",
":",
"Instance",
"of",
"Term",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/utils.py#L66-L70 |
quizl/quizler | quizler/utils.py | reset_term_stats | def reset_term_stats(set_id, term_id, client_id, user_id, access_token):
"""Reset the stats of a term by deleting and re-creating it."""
found_sets = [user_set for user_set in get_user_sets(client_id, user_id)
if user_set.set_id == set_id]
if len(found_sets) != 1:
raise ValueError(... | python | def reset_term_stats(set_id, term_id, client_id, user_id, access_token):
"""Reset the stats of a term by deleting and re-creating it."""
found_sets = [user_set for user_set in get_user_sets(client_id, user_id)
if user_set.set_id == set_id]
if len(found_sets) != 1:
raise ValueError(... | [
"def",
"reset_term_stats",
"(",
"set_id",
",",
"term_id",
",",
"client_id",
",",
"user_id",
",",
"access_token",
")",
":",
"found_sets",
"=",
"[",
"user_set",
"for",
"user_set",
"in",
"get_user_sets",
"(",
"client_id",
",",
"user_id",
")",
"if",
"user_set",
... | Reset the stats of a term by deleting and re-creating it. | [
"Reset",
"the",
"stats",
"of",
"a",
"term",
"by",
"deleting",
"and",
"re",
"-",
"creating",
"it",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/utils.py#L73-L94 |
davidblaisonneau-orange/foreman | foreman/hosts.py | Hosts.createController | def createController(self, key, attributes, ipmi, printer=False):
""" Function createController
Create a controller node
@param key: The host name or ID
@param attributes:The payload of the host creation
@param printer: - False for no creation progression message
... | python | def createController(self, key, attributes, ipmi, printer=False):
""" Function createController
Create a controller node
@param key: The host name or ID
@param attributes:The payload of the host creation
@param printer: - False for no creation progression message
... | [
"def",
"createController",
"(",
"self",
",",
"key",
",",
"attributes",
",",
"ipmi",
",",
"printer",
"=",
"False",
")",
":",
"if",
"key",
"not",
"in",
"self",
":",
"self",
".",
"printer",
"=",
"printer",
"self",
".",
"async",
"=",
"False",
"# Create the... | Function createController
Create a controller node
@param key: The host name or ID
@param attributes:The payload of the host creation
@param printer: - False for no creation progression message
- True to get creation progression printed on STDOUT
... | [
"Function",
"createController",
"Create",
"a",
"controller",
"node"
] | train | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/hosts.py#L50-L77 |
davidblaisonneau-orange/foreman | foreman/hosts.py | Hosts.waitPuppetCatalogToBeApplied | def waitPuppetCatalogToBeApplied(self, key, sleepTime=5):
""" Function waitPuppetCatalogToBeApplied
Wait for puppet catalog to be applied
@param key: The host name or ID
@return RETURN: None
"""
# Wait for puppet catalog to be applied
loop_stop = False
wh... | python | def waitPuppetCatalogToBeApplied(self, key, sleepTime=5):
""" Function waitPuppetCatalogToBeApplied
Wait for puppet catalog to be applied
@param key: The host name or ID
@return RETURN: None
"""
# Wait for puppet catalog to be applied
loop_stop = False
wh... | [
"def",
"waitPuppetCatalogToBeApplied",
"(",
"self",
",",
"key",
",",
"sleepTime",
"=",
"5",
")",
":",
"# Wait for puppet catalog to be applied",
"loop_stop",
"=",
"False",
"while",
"not",
"loop_stop",
":",
"status",
"=",
"self",
"[",
"key",
"]",
".",
"getStatus"... | Function waitPuppetCatalogToBeApplied
Wait for puppet catalog to be applied
@param key: The host name or ID
@return RETURN: None | [
"Function",
"waitPuppetCatalogToBeApplied",
"Wait",
"for",
"puppet",
"catalog",
"to",
"be",
"applied"
] | train | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/hosts.py#L79-L105 |
davidblaisonneau-orange/foreman | foreman/hosts.py | Hosts.createVM | def createVM(self, key, attributes, printer=False):
""" Function createVM
Create a Virtual Machine
The creation of a VM with libVirt is a bit complexe.
We first create the element in foreman, the ask to start before
the result of the creation.
To do so, we make async cal... | python | def createVM(self, key, attributes, printer=False):
""" Function createVM
Create a Virtual Machine
The creation of a VM with libVirt is a bit complexe.
We first create the element in foreman, the ask to start before
the result of the creation.
To do so, we make async cal... | [
"def",
"createVM",
"(",
"self",
",",
"key",
",",
"attributes",
",",
"printer",
"=",
"False",
")",
":",
"self",
".",
"printer",
"=",
"printer",
"self",
".",
"async",
"=",
"False",
"# Create the VM in foreman",
"# NOTA: with 1.8 it will return 422 'Failed to login via... | Function createVM
Create a Virtual Machine
The creation of a VM with libVirt is a bit complexe.
We first create the element in foreman, the ask to start before
the result of the creation.
To do so, we make async calls to the API and check the results
@param key: The hos... | [
"Function",
"createVM",
"Create",
"a",
"Virtual",
"Machine"
] | train | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/hosts.py#L107-L174 |
qubell/contrib-python-qubell-client | qubell/api/private/user.py | User.get | def get(router, organization, email):
"""
:rtype: User
"""
log.info("Getting user: %s" % email)
resp = router.get_users(org_id=organization.id).json()
ids = [x['id'] for x in resp if x['email'] == email]
if len(ids):
user = User(organization, ids[0]).i... | python | def get(router, organization, email):
"""
:rtype: User
"""
log.info("Getting user: %s" % email)
resp = router.get_users(org_id=organization.id).json()
ids = [x['id'] for x in resp if x['email'] == email]
if len(ids):
user = User(organization, ids[0]).i... | [
"def",
"get",
"(",
"router",
",",
"organization",
",",
"email",
")",
":",
"log",
".",
"info",
"(",
"\"Getting user: %s\"",
"%",
"email",
")",
"resp",
"=",
"router",
".",
"get_users",
"(",
"org_id",
"=",
"organization",
".",
"id",
")",
".",
"json",
"(",... | :rtype: User | [
":",
"rtype",
":",
"User"
] | train | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/user.py#L37-L48 |
MatterMiners/cobald | cobald/daemon/config/mapping.py | Translator.construct | def construct(self, mapping: dict, **kwargs):
"""
Construct an object from a mapping
:param mapping: the constructor definition, with ``__type__`` name and keyword arguments
:param kwargs: additional keyword arguments to pass to the constructor
"""
assert '__type__' not ... | python | def construct(self, mapping: dict, **kwargs):
"""
Construct an object from a mapping
:param mapping: the constructor definition, with ``__type__`` name and keyword arguments
:param kwargs: additional keyword arguments to pass to the constructor
"""
assert '__type__' not ... | [
"def",
"construct",
"(",
"self",
",",
"mapping",
":",
"dict",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"'__type__'",
"not",
"in",
"kwargs",
"and",
"'__args__'",
"not",
"in",
"kwargs",
"mapping",
"=",
"{",
"*",
"*",
"mapping",
",",
"*",
"*",
"kwar... | Construct an object from a mapping
:param mapping: the constructor definition, with ``__type__`` name and keyword arguments
:param kwargs: additional keyword arguments to pass to the constructor | [
"Construct",
"an",
"object",
"from",
"a",
"mapping"
] | train | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/config/mapping.py#L55-L67 |
MatterMiners/cobald | cobald/daemon/config/mapping.py | Translator.load_name | def load_name(absolute_name: str):
"""Load an object based on an absolute, dotted name"""
path = absolute_name.split('.')
try:
__import__(absolute_name)
except ImportError:
try:
obj = sys.modules[path[0]]
except KeyError:
... | python | def load_name(absolute_name: str):
"""Load an object based on an absolute, dotted name"""
path = absolute_name.split('.')
try:
__import__(absolute_name)
except ImportError:
try:
obj = sys.modules[path[0]]
except KeyError:
... | [
"def",
"load_name",
"(",
"absolute_name",
":",
"str",
")",
":",
"path",
"=",
"absolute_name",
".",
"split",
"(",
"'.'",
")",
"try",
":",
"__import__",
"(",
"absolute_name",
")",
"except",
"ImportError",
":",
"try",
":",
"obj",
"=",
"sys",
".",
"modules",... | Load an object based on an absolute, dotted name | [
"Load",
"an",
"object",
"based",
"on",
"an",
"absolute",
"dotted",
"name"
] | train | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/config/mapping.py#L70-L88 |
qubell/contrib-python-qubell-client | qubell/api/private/manifest.py | Manifest.patch | def patch(self, path, value=None):
""" Set specified value to yaml path.
Example:
patch('application/components/child/configuration/__locator.application-id','777')
Will change child app ID to 777
"""
# noinspection PyShadowingNames
def pathGet(dictionary, path):
... | python | def patch(self, path, value=None):
""" Set specified value to yaml path.
Example:
patch('application/components/child/configuration/__locator.application-id','777')
Will change child app ID to 777
"""
# noinspection PyShadowingNames
def pathGet(dictionary, path):
... | [
"def",
"patch",
"(",
"self",
",",
"path",
",",
"value",
"=",
"None",
")",
":",
"# noinspection PyShadowingNames",
"def",
"pathGet",
"(",
"dictionary",
",",
"path",
")",
":",
"for",
"item",
"in",
"path",
".",
"split",
"(",
"\"/\"",
")",
":",
"dictionary",... | Set specified value to yaml path.
Example:
patch('application/components/child/configuration/__locator.application-id','777')
Will change child app ID to 777 | [
"Set",
"specified",
"value",
"to",
"yaml",
"path",
".",
"Example",
":",
"patch",
"(",
"application",
"/",
"components",
"/",
"child",
"/",
"configuration",
"/",
"__locator",
".",
"application",
"-",
"id",
"777",
")",
"Will",
"change",
"child",
"app",
"ID",... | train | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/manifest.py#L63-L95 |
MatterMiners/cobald | cobald/daemon/runners/trio_runner.py | TrioRunner._await_all | async def _await_all(self):
"""Async component of _run"""
delay = 0.0
# we run a top-level nursery that automatically reaps/cancels for us
async with trio.open_nursery() as nursery:
while self.running.is_set():
await self._start_payloads(nursery=nursery)
... | python | async def _await_all(self):
"""Async component of _run"""
delay = 0.0
# we run a top-level nursery that automatically reaps/cancels for us
async with trio.open_nursery() as nursery:
while self.running.is_set():
await self._start_payloads(nursery=nursery)
... | [
"async",
"def",
"_await_all",
"(",
"self",
")",
":",
"delay",
"=",
"0.0",
"# we run a top-level nursery that automatically reaps/cancels for us",
"async",
"with",
"trio",
".",
"open_nursery",
"(",
")",
"as",
"nursery",
":",
"while",
"self",
".",
"running",
".",
"i... | Async component of _run | [
"Async",
"component",
"of",
"_run"
] | train | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/trio_runner.py#L28-L38 |
MatterMiners/cobald | cobald/daemon/runners/trio_runner.py | TrioRunner._start_payloads | async def _start_payloads(self, nursery):
"""Start all queued payloads"""
with self._lock:
for coroutine in self._payloads:
nursery.start_soon(coroutine)
self._payloads.clear()
await trio.sleep(0) | python | async def _start_payloads(self, nursery):
"""Start all queued payloads"""
with self._lock:
for coroutine in self._payloads:
nursery.start_soon(coroutine)
self._payloads.clear()
await trio.sleep(0) | [
"async",
"def",
"_start_payloads",
"(",
"self",
",",
"nursery",
")",
":",
"with",
"self",
".",
"_lock",
":",
"for",
"coroutine",
"in",
"self",
".",
"_payloads",
":",
"nursery",
".",
"start_soon",
"(",
"coroutine",
")",
"self",
".",
"_payloads",
".",
"cle... | Start all queued payloads | [
"Start",
"all",
"queued",
"payloads"
] | train | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/trio_runner.py#L40-L46 |
frostming/atoml | atoml/decoder.py | contains_list | def contains_list(longer, shorter):
"""Check if longer list starts with shorter list"""
if len(longer) <= len(shorter):
return False
for a, b in zip(shorter, longer):
if a != b:
return False
return True | python | def contains_list(longer, shorter):
"""Check if longer list starts with shorter list"""
if len(longer) <= len(shorter):
return False
for a, b in zip(shorter, longer):
if a != b:
return False
return True | [
"def",
"contains_list",
"(",
"longer",
",",
"shorter",
")",
":",
"if",
"len",
"(",
"longer",
")",
"<=",
"len",
"(",
"shorter",
")",
":",
"return",
"False",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"shorter",
",",
"longer",
")",
":",
"if",
"a",
"!=... | Check if longer list starts with shorter list | [
"Check",
"if",
"longer",
"list",
"starts",
"with",
"shorter",
"list"
] | train | https://github.com/frostming/atoml/blob/85414ef77777366887a819a05b496d5279296cd2/atoml/decoder.py#L28-L35 |
frostming/atoml | atoml/decoder.py | load | def load(f, dict_=dict):
"""Load and parse toml from a file object
An additional argument `dict_` is used to specify the output type
"""
if not f.read:
raise ValueError('The first parameter needs to be a file object, ',
'%r is passed' % type(f))
return loads(f.read()... | python | def load(f, dict_=dict):
"""Load and parse toml from a file object
An additional argument `dict_` is used to specify the output type
"""
if not f.read:
raise ValueError('The first parameter needs to be a file object, ',
'%r is passed' % type(f))
return loads(f.read()... | [
"def",
"load",
"(",
"f",
",",
"dict_",
"=",
"dict",
")",
":",
"if",
"not",
"f",
".",
"read",
":",
"raise",
"ValueError",
"(",
"'The first parameter needs to be a file object, '",
",",
"'%r is passed'",
"%",
"type",
"(",
"f",
")",
")",
"return",
"loads",
"(... | Load and parse toml from a file object
An additional argument `dict_` is used to specify the output type | [
"Load",
"and",
"parse",
"toml",
"from",
"a",
"file",
"object",
"An",
"additional",
"argument",
"dict_",
"is",
"used",
"to",
"specify",
"the",
"output",
"type"
] | train | https://github.com/frostming/atoml/blob/85414ef77777366887a819a05b496d5279296cd2/atoml/decoder.py#L466-L473 |
frostming/atoml | atoml/decoder.py | loads | def loads(content, dict_=dict):
"""Parse a toml string
An additional argument `dict_` is used to specify the output type
"""
if not isinstance(content, basestring):
raise ValueError('The first parameter needs to be a string object, ',
'%r is passed' % type(content))
... | python | def loads(content, dict_=dict):
"""Parse a toml string
An additional argument `dict_` is used to specify the output type
"""
if not isinstance(content, basestring):
raise ValueError('The first parameter needs to be a string object, ',
'%r is passed' % type(content))
... | [
"def",
"loads",
"(",
"content",
",",
"dict_",
"=",
"dict",
")",
":",
"if",
"not",
"isinstance",
"(",
"content",
",",
"basestring",
")",
":",
"raise",
"ValueError",
"(",
"'The first parameter needs to be a string object, '",
",",
"'%r is passed'",
"%",
"type",
"(... | Parse a toml string
An additional argument `dict_` is used to specify the output type | [
"Parse",
"a",
"toml",
"string",
"An",
"additional",
"argument",
"dict_",
"is",
"used",
"to",
"specify",
"the",
"output",
"type"
] | train | https://github.com/frostming/atoml/blob/85414ef77777366887a819a05b496d5279296cd2/atoml/decoder.py#L476-L485 |
frostming/atoml | atoml/decoder.py | Converter.convert | def convert(self, line=None, is_end=True):
"""Read the line content and return the converted value
:param line: the line to feed to converter
:param is_end: if set to True, will raise an error if
the line has something remaining.
"""
if line is not None:
self... | python | def convert(self, line=None, is_end=True):
"""Read the line content and return the converted value
:param line: the line to feed to converter
:param is_end: if set to True, will raise an error if
the line has something remaining.
"""
if line is not None:
self... | [
"def",
"convert",
"(",
"self",
",",
"line",
"=",
"None",
",",
"is_end",
"=",
"True",
")",
":",
"if",
"line",
"is",
"not",
"None",
":",
"self",
".",
"line",
"=",
"line",
"if",
"not",
"self",
".",
"line",
":",
"raise",
"TomlDecodeError",
"(",
"self",... | Read the line content and return the converted value
:param line: the line to feed to converter
:param is_end: if set to True, will raise an error if
the line has something remaining. | [
"Read",
"the",
"line",
"content",
"and",
"return",
"the",
"converted",
"value"
] | train | https://github.com/frostming/atoml/blob/85414ef77777366887a819a05b496d5279296cd2/atoml/decoder.py#L130-L157 |
frostming/atoml | atoml/decoder.py | Decoder.parse | def parse(self, data=None, table_name=None):
"""Parse the lines from index i
:param data: optional, store the parsed result to it when specified
:param table_name: when inside a table array, it is the table name
"""
temp = self.dict_()
sub_table = None
is_array =... | python | def parse(self, data=None, table_name=None):
"""Parse the lines from index i
:param data: optional, store the parsed result to it when specified
:param table_name: when inside a table array, it is the table name
"""
temp = self.dict_()
sub_table = None
is_array =... | [
"def",
"parse",
"(",
"self",
",",
"data",
"=",
"None",
",",
"table_name",
"=",
"None",
")",
":",
"temp",
"=",
"self",
".",
"dict_",
"(",
")",
"sub_table",
"=",
"None",
"is_array",
"=",
"False",
"line",
"=",
"''",
"while",
"True",
":",
"line",
"=",
... | Parse the lines from index i
:param data: optional, store the parsed result to it when specified
:param table_name: when inside a table array, it is the table name | [
"Parse",
"the",
"lines",
"from",
"index",
"i"
] | train | https://github.com/frostming/atoml/blob/85414ef77777366887a819a05b496d5279296cd2/atoml/decoder.py#L323-L386 |
frostming/atoml | atoml/decoder.py | Decoder.split_string | def split_string(self, string, splitter='.', allow_empty=True):
"""Split the string with respect of quotes"""
i = 0
rv = []
need_split = False
while i < len(string):
m = re.compile(_KEY_NAME).match(string, i)
if not need_split and m:
i = m.... | python | def split_string(self, string, splitter='.', allow_empty=True):
"""Split the string with respect of quotes"""
i = 0
rv = []
need_split = False
while i < len(string):
m = re.compile(_KEY_NAME).match(string, i)
if not need_split and m:
i = m.... | [
"def",
"split_string",
"(",
"self",
",",
"string",
",",
"splitter",
"=",
"'.'",
",",
"allow_empty",
"=",
"True",
")",
":",
"i",
"=",
"0",
"rv",
"=",
"[",
"]",
"need_split",
"=",
"False",
"while",
"i",
"<",
"len",
"(",
"string",
")",
":",
"m",
"="... | Split the string with respect of quotes | [
"Split",
"the",
"string",
"with",
"respect",
"of",
"quotes"
] | train | https://github.com/frostming/atoml/blob/85414ef77777366887a819a05b496d5279296cd2/atoml/decoder.py#L428-L463 |
aroberge/experimental | experimental/transformers/where_clause.py | transform_source | def transform_source(text):
'''removes a "where" clause which is identified by the use of "where"
as an identifier and ends at the first DEDENT (i.e. decrease in indentation)'''
toks = tokenize.generate_tokens(StringIO(text).readline)
result = []
where_clause = False
for toktype, tokvalue, _, _,... | python | def transform_source(text):
'''removes a "where" clause which is identified by the use of "where"
as an identifier and ends at the first DEDENT (i.e. decrease in indentation)'''
toks = tokenize.generate_tokens(StringIO(text).readline)
result = []
where_clause = False
for toktype, tokvalue, _, _,... | [
"def",
"transform_source",
"(",
"text",
")",
":",
"toks",
"=",
"tokenize",
".",
"generate_tokens",
"(",
"StringIO",
"(",
"text",
")",
".",
"readline",
")",
"result",
"=",
"[",
"]",
"where_clause",
"=",
"False",
"for",
"toktype",
",",
"tokvalue",
",",
"_"... | removes a "where" clause which is identified by the use of "where"
as an identifier and ends at the first DEDENT (i.e. decrease in indentation) | [
"removes",
"a",
"where",
"clause",
"which",
"is",
"identified",
"by",
"the",
"use",
"of",
"where",
"as",
"an",
"identifier",
"and",
"ends",
"at",
"the",
"first",
"DEDENT",
"(",
"i",
".",
"e",
".",
"decrease",
"in",
"indentation",
")"
] | train | https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/transformers/where_clause.py#L31-L46 |
developersociety/django-glitter | glitter/pages/models.py | Page.is_visible | def is_visible(self):
"""
Return a boolean if the page is visible in navigation.
Pages must have show in navigation set. Regular pages must be published (published and
have a current version - checked with `is_published`), pages with a glitter app associated
don't need any page ... | python | def is_visible(self):
"""
Return a boolean if the page is visible in navigation.
Pages must have show in navigation set. Regular pages must be published (published and
have a current version - checked with `is_published`), pages with a glitter app associated
don't need any page ... | [
"def",
"is_visible",
"(",
"self",
")",
":",
"if",
"self",
".",
"glitter_app_name",
":",
"visible",
"=",
"self",
".",
"show_in_navigation",
"else",
":",
"visible",
"=",
"self",
".",
"show_in_navigation",
"and",
"self",
".",
"is_published",
"return",
"visible"
] | Return a boolean if the page is visible in navigation.
Pages must have show in navigation set. Regular pages must be published (published and
have a current version - checked with `is_published`), pages with a glitter app associated
don't need any page versions. | [
"Return",
"a",
"boolean",
"if",
"the",
"page",
"is",
"visible",
"in",
"navigation",
"."
] | train | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/pages/models.py#L66-L79 |
DataMedSci/mcpartools | mcpartools/generatemc.py | main | def main(args=sys.argv[1:]):
"""
Main function, called from CLI script
:return:
"""
import mcpartools
parser = argparse.ArgumentParser()
parser.add_argument('-V', '--version',
action='version',
version=mcpartools.__version__)
parser.add_arg... | python | def main(args=sys.argv[1:]):
"""
Main function, called from CLI script
:return:
"""
import mcpartools
parser = argparse.ArgumentParser()
parser.add_argument('-V', '--version',
action='version',
version=mcpartools.__version__)
parser.add_arg... | [
"def",
"main",
"(",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"import",
"mcpartools",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-V'",
",",
"'--version'",
",",
"action",
"=",
... | Main function, called from CLI script
:return: | [
"Main",
"function",
"called",
"from",
"CLI",
"script",
":",
"return",
":"
] | train | https://github.com/DataMedSci/mcpartools/blob/84f869094d05bf70f09e8aaeca671ddaa1c56ec4/mcpartools/generatemc.py#L10-L92 |
josiah-wolf-oberholtzer/uqbar | uqbar/apis/APIBuilder.py | APIBuilder.build_node_tree | def build_node_tree(self, source_paths):
"""
Build a node tree.
"""
import uqbar.apis
root = PackageNode()
# Build node tree, top-down
for source_path in sorted(
source_paths, key=lambda x: uqbar.apis.source_path_to_package_path(x)
):
... | python | def build_node_tree(self, source_paths):
"""
Build a node tree.
"""
import uqbar.apis
root = PackageNode()
# Build node tree, top-down
for source_path in sorted(
source_paths, key=lambda x: uqbar.apis.source_path_to_package_path(x)
):
... | [
"def",
"build_node_tree",
"(",
"self",
",",
"source_paths",
")",
":",
"import",
"uqbar",
".",
"apis",
"root",
"=",
"PackageNode",
"(",
")",
"# Build node tree, top-down",
"for",
"source_path",
"in",
"sorted",
"(",
"source_paths",
",",
"key",
"=",
"lambda",
"x"... | Build a node tree. | [
"Build",
"a",
"node",
"tree",
"."
] | train | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/apis/APIBuilder.py#L134-L215 |
developersociety/django-glitter | glitter/reminders/forms.py | ReminderInlineAdminForm.validate_unique | def validate_unique(self):
"""
Add this method because django doesn't validate correctly because required fields are
excluded.
"""
unique_checks, date_checks = self.instance._get_unique_checks(exclude=[])
errors = self.instance._perform_unique_checks(unique_checks)
... | python | def validate_unique(self):
"""
Add this method because django doesn't validate correctly because required fields are
excluded.
"""
unique_checks, date_checks = self.instance._get_unique_checks(exclude=[])
errors = self.instance._perform_unique_checks(unique_checks)
... | [
"def",
"validate_unique",
"(",
"self",
")",
":",
"unique_checks",
",",
"date_checks",
"=",
"self",
".",
"instance",
".",
"_get_unique_checks",
"(",
"exclude",
"=",
"[",
"]",
")",
"errors",
"=",
"self",
".",
"instance",
".",
"_perform_unique_checks",
"(",
"un... | Add this method because django doesn't validate correctly because required fields are
excluded. | [
"Add",
"this",
"method",
"because",
"django",
"doesn",
"t",
"validate",
"correctly",
"because",
"required",
"fields",
"are",
"excluded",
"."
] | train | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/reminders/forms.py#L20-L28 |
qubell/contrib-python-qubell-client | qubell/monitor/monitor.py | prepare_monitor | def prepare_monitor(tenant=tenant, user=user, password=password, organization=organization, zone_name=zone_name):
"""
:param tenant: tenant url
:param user: user's email
:param password: user's password
:param zone_name: (optional) zone_name
:return:
"""
router = PrivatePath(tenant, veri... | python | def prepare_monitor(tenant=tenant, user=user, password=password, organization=organization, zone_name=zone_name):
"""
:param tenant: tenant url
:param user: user's email
:param password: user's password
:param zone_name: (optional) zone_name
:return:
"""
router = PrivatePath(tenant, veri... | [
"def",
"prepare_monitor",
"(",
"tenant",
"=",
"tenant",
",",
"user",
"=",
"user",
",",
"password",
"=",
"password",
",",
"organization",
"=",
"organization",
",",
"zone_name",
"=",
"zone_name",
")",
":",
"router",
"=",
"PrivatePath",
"(",
"tenant",
",",
"v... | :param tenant: tenant url
:param user: user's email
:param password: user's password
:param zone_name: (optional) zone_name
:return: | [
":",
"param",
"tenant",
":",
"tenant",
"url",
":",
"param",
"user",
":",
"user",
"s",
"email",
":",
"param",
"password",
":",
"user",
"s",
"password",
":",
"param",
"zone_name",
":",
"(",
"optional",
")",
"zone_name",
":",
"return",
":"
] | train | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/monitor/monitor.py#L67-L113 |
qubell/contrib-python-qubell-client | qubell/monitor/monitor.py | Monitor.launch | def launch(self, timeout=2):
"""
Hierapp instance, with environment dependencies:
- can be launched within short timeout
- auto-destroys shortly
"""
self.start_time = time.time()
self.end_time = time.time()
instance = self.app.launch(environment=self.env)
... | python | def launch(self, timeout=2):
"""
Hierapp instance, with environment dependencies:
- can be launched within short timeout
- auto-destroys shortly
"""
self.start_time = time.time()
self.end_time = time.time()
instance = self.app.launch(environment=self.env)
... | [
"def",
"launch",
"(",
"self",
",",
"timeout",
"=",
"2",
")",
":",
"self",
".",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"instance",
"=",
"self",
".",
"app",
".",
"launch",
"(",... | Hierapp instance, with environment dependencies:
- can be launched within short timeout
- auto-destroys shortly | [
"Hierapp",
"instance",
"with",
"environment",
"dependencies",
":",
"-",
"can",
"be",
"launched",
"within",
"short",
"timeout",
"-",
"auto",
"-",
"destroys",
"shortly"
] | train | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/monitor/monitor.py#L138-L156 |
qubell/contrib-python-qubell-client | qubell/monitor/monitor.py | Monitor.clone | def clone(self):
"""
Do not initialize again since everything is ready to launch app.
:return: Initialized monitor instance
"""
return Monitor(org=self.org, app=self.app, env=self.env) | python | def clone(self):
"""
Do not initialize again since everything is ready to launch app.
:return: Initialized monitor instance
"""
return Monitor(org=self.org, app=self.app, env=self.env) | [
"def",
"clone",
"(",
"self",
")",
":",
"return",
"Monitor",
"(",
"org",
"=",
"self",
".",
"org",
",",
"app",
"=",
"self",
".",
"app",
",",
"env",
"=",
"self",
".",
"env",
")"
] | Do not initialize again since everything is ready to launch app.
:return: Initialized monitor instance | [
"Do",
"not",
"initialize",
"again",
"since",
"everything",
"is",
"ready",
"to",
"launch",
"app",
".",
":",
"return",
":",
"Initialized",
"monitor",
"instance"
] | train | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/monitor/monitor.py#L168-L173 |
quizl/quizler | quizler/models.py | Image.from_dict | def from_dict(raw_data):
"""Create Image from raw dictionary data."""
url = None
width = None
height = None
try:
url = raw_data['url']
width = raw_data['width']
height = raw_data['height']
except KeyError:
raise ValueError('... | python | def from_dict(raw_data):
"""Create Image from raw dictionary data."""
url = None
width = None
height = None
try:
url = raw_data['url']
width = raw_data['width']
height = raw_data['height']
except KeyError:
raise ValueError('... | [
"def",
"from_dict",
"(",
"raw_data",
")",
":",
"url",
"=",
"None",
"width",
"=",
"None",
"height",
"=",
"None",
"try",
":",
"url",
"=",
"raw_data",
"[",
"'url'",
"]",
"width",
"=",
"raw_data",
"[",
"'width'",
"]",
"height",
"=",
"raw_data",
"[",
"'he... | Create Image from raw dictionary data. | [
"Create",
"Image",
"from",
"raw",
"dictionary",
"data",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/models.py#L13-L27 |
quizl/quizler | quizler/models.py | Image.to_dict | def to_dict(self):
"""Convert Image into raw dictionary data."""
if not self.url:
return None
return {
'url': self.url,
'width': self.width,
'height': self.height
} | python | def to_dict(self):
"""Convert Image into raw dictionary data."""
if not self.url:
return None
return {
'url': self.url,
'width': self.width,
'height': self.height
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"url",
":",
"return",
"None",
"return",
"{",
"'url'",
":",
"self",
".",
"url",
",",
"'width'",
":",
"self",
".",
"width",
",",
"'height'",
":",
"self",
".",
"height",
"}"
] | Convert Image into raw dictionary data. | [
"Convert",
"Image",
"into",
"raw",
"dictionary",
"data",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/models.py#L29-L37 |
quizl/quizler | quizler/models.py | Term.from_dict | def from_dict(raw_data):
"""Create Term from raw dictionary data."""
try:
definition = raw_data['definition']
term_id = raw_data['id']
image = Image.from_dict(raw_data['image'])
rank = raw_data['rank']
term = raw_data['term']
return... | python | def from_dict(raw_data):
"""Create Term from raw dictionary data."""
try:
definition = raw_data['definition']
term_id = raw_data['id']
image = Image.from_dict(raw_data['image'])
rank = raw_data['rank']
term = raw_data['term']
return... | [
"def",
"from_dict",
"(",
"raw_data",
")",
":",
"try",
":",
"definition",
"=",
"raw_data",
"[",
"'definition'",
"]",
"term_id",
"=",
"raw_data",
"[",
"'id'",
"]",
"image",
"=",
"Image",
".",
"from_dict",
"(",
"raw_data",
"[",
"'image'",
"]",
")",
"rank",
... | Create Term from raw dictionary data. | [
"Create",
"Term",
"from",
"raw",
"dictionary",
"data",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/models.py#L60-L70 |
quizl/quizler | quizler/models.py | Term.to_dict | def to_dict(self):
"""Convert Term into raw dictionary data."""
return {
'definition': self.definition,
'id': self.term_id,
'image': self.image.to_dict(),
'rank': self.rank,
'term': self.term
} | python | def to_dict(self):
"""Convert Term into raw dictionary data."""
return {
'definition': self.definition,
'id': self.term_id,
'image': self.image.to_dict(),
'rank': self.rank,
'term': self.term
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'definition'",
":",
"self",
".",
"definition",
",",
"'id'",
":",
"self",
".",
"term_id",
",",
"'image'",
":",
"self",
".",
"image",
".",
"to_dict",
"(",
")",
",",
"'rank'",
":",
"self",
".",
... | Convert Term into raw dictionary data. | [
"Convert",
"Term",
"into",
"raw",
"dictionary",
"data",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/models.py#L72-L80 |
quizl/quizler | quizler/models.py | WordSet.has_common | def has_common(self, other):
"""Return set of common words between two word sets."""
if not isinstance(other, WordSet):
raise ValueError('Can compare only WordSets')
return self.term_set & other.term_set | python | def has_common(self, other):
"""Return set of common words between two word sets."""
if not isinstance(other, WordSet):
raise ValueError('Can compare only WordSets')
return self.term_set & other.term_set | [
"def",
"has_common",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"WordSet",
")",
":",
"raise",
"ValueError",
"(",
"'Can compare only WordSets'",
")",
"return",
"self",
".",
"term_set",
"&",
"other",
".",
"term_set"
] | Return set of common words between two word sets. | [
"Return",
"set",
"of",
"common",
"words",
"between",
"two",
"word",
"sets",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/models.py#L105-L109 |
quizl/quizler | quizler/models.py | WordSet.from_dict | def from_dict(raw_data):
"""Create WordSet from raw dictionary data."""
try:
set_id = raw_data['id']
title = raw_data['title']
terms = [Term.from_dict(term) for term in raw_data['terms']]
return WordSet(set_id, title, terms)
except KeyError:
... | python | def from_dict(raw_data):
"""Create WordSet from raw dictionary data."""
try:
set_id = raw_data['id']
title = raw_data['title']
terms = [Term.from_dict(term) for term in raw_data['terms']]
return WordSet(set_id, title, terms)
except KeyError:
... | [
"def",
"from_dict",
"(",
"raw_data",
")",
":",
"try",
":",
"set_id",
"=",
"raw_data",
"[",
"'id'",
"]",
"title",
"=",
"raw_data",
"[",
"'title'",
"]",
"terms",
"=",
"[",
"Term",
".",
"from_dict",
"(",
"term",
")",
"for",
"term",
"in",
"raw_data",
"["... | Create WordSet from raw dictionary data. | [
"Create",
"WordSet",
"from",
"raw",
"dictionary",
"data",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/models.py#L117-L125 |
quizl/quizler | quizler/models.py | WordSet.to_dict | def to_dict(self):
"""Convert WordSet into raw dictionary data."""
return {
'id': self.set_id,
'title': self.title,
'terms': [term.to_dict() for term in self.terms]
} | python | def to_dict(self):
"""Convert WordSet into raw dictionary data."""
return {
'id': self.set_id,
'title': self.title,
'terms': [term.to_dict() for term in self.terms]
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'id'",
":",
"self",
".",
"set_id",
",",
"'title'",
":",
"self",
".",
"title",
",",
"'terms'",
":",
"[",
"term",
".",
"to_dict",
"(",
")",
"for",
"term",
"in",
"self",
".",
"terms",
"]",
"}"... | Convert WordSet into raw dictionary data. | [
"Convert",
"WordSet",
"into",
"raw",
"dictionary",
"data",
"."
] | train | https://github.com/quizl/quizler/blob/44b3fd91f7074e7013ffde8147455f45ebdccc46/quizler/models.py#L127-L133 |
quantmind/agile-toolkit | agiletoolkit/github/release.py | release | def release(ctx, yes, latest):
"""Create a new release in github
"""
m = RepoManager(ctx.obj['agile'])
api = m.github_repo()
if latest:
latest = api.releases.latest()
if latest:
click.echo(latest['tag_name'])
elif m.can_release('sandbox'):
branch = m.info['bra... | python | def release(ctx, yes, latest):
"""Create a new release in github
"""
m = RepoManager(ctx.obj['agile'])
api = m.github_repo()
if latest:
latest = api.releases.latest()
if latest:
click.echo(latest['tag_name'])
elif m.can_release('sandbox'):
branch = m.info['bra... | [
"def",
"release",
"(",
"ctx",
",",
"yes",
",",
"latest",
")",
":",
"m",
"=",
"RepoManager",
"(",
"ctx",
".",
"obj",
"[",
"'agile'",
"]",
")",
"api",
"=",
"m",
".",
"github_repo",
"(",
")",
"if",
"latest",
":",
"latest",
"=",
"api",
".",
"releases... | Create a new release in github | [
"Create",
"a",
"new",
"release",
"in",
"github"
] | train | https://github.com/quantmind/agile-toolkit/blob/96028e36a842c57b171907c20583a60d1045fec1/agiletoolkit/github/release.py#L15-L42 |
josiah-wolf-oberholtzer/uqbar | uqbar/sphinx/book.py | on_builder_inited | def on_builder_inited(app):
"""
Hooks into Sphinx's ``builder-inited`` event.
"""
app.cache_db_path = ":memory:"
if app.config["uqbar_book_use_cache"]:
logger.info(bold("[uqbar-book]"), nonl=True)
logger.info(" initializing cache db")
app.connection = uqbar.book.sphinx.create... | python | def on_builder_inited(app):
"""
Hooks into Sphinx's ``builder-inited`` event.
"""
app.cache_db_path = ":memory:"
if app.config["uqbar_book_use_cache"]:
logger.info(bold("[uqbar-book]"), nonl=True)
logger.info(" initializing cache db")
app.connection = uqbar.book.sphinx.create... | [
"def",
"on_builder_inited",
"(",
"app",
")",
":",
"app",
".",
"cache_db_path",
"=",
"\":memory:\"",
"if",
"app",
".",
"config",
"[",
"\"uqbar_book_use_cache\"",
"]",
":",
"logger",
".",
"info",
"(",
"bold",
"(",
"\"[uqbar-book]\"",
")",
",",
"nonl",
"=",
"... | Hooks into Sphinx's ``builder-inited`` event. | [
"Hooks",
"into",
"Sphinx",
"s",
"builder",
"-",
"inited",
"event",
"."
] | train | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/book.py#L55-L63 |
josiah-wolf-oberholtzer/uqbar | uqbar/sphinx/book.py | on_config_inited | def on_config_inited(app, config):
"""
Hooks into Sphinx's ``config-inited`` event.
"""
extension_paths = config["uqbar_book_extensions"] or [
"uqbar.book.extensions.GraphExtension"
]
app.uqbar_book_extensions = []
for extension_path in extension_paths:
module_name, _, class_... | python | def on_config_inited(app, config):
"""
Hooks into Sphinx's ``config-inited`` event.
"""
extension_paths = config["uqbar_book_extensions"] or [
"uqbar.book.extensions.GraphExtension"
]
app.uqbar_book_extensions = []
for extension_path in extension_paths:
module_name, _, class_... | [
"def",
"on_config_inited",
"(",
"app",
",",
"config",
")",
":",
"extension_paths",
"=",
"config",
"[",
"\"uqbar_book_extensions\"",
"]",
"or",
"[",
"\"uqbar.book.extensions.GraphExtension\"",
"]",
"app",
".",
"uqbar_book_extensions",
"=",
"[",
"]",
"for",
"extension... | Hooks into Sphinx's ``config-inited`` event. | [
"Hooks",
"into",
"Sphinx",
"s",
"config",
"-",
"inited",
"event",
"."
] | train | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/book.py#L66-L79 |
josiah-wolf-oberholtzer/uqbar | uqbar/sphinx/book.py | on_doctree_read | def on_doctree_read(app, document):
"""
Hooks into Sphinx's ``doctree-read`` event.
"""
literal_blocks = uqbar.book.sphinx.collect_literal_blocks(document)
cache_mapping = uqbar.book.sphinx.group_literal_blocks_by_cache_path(literal_blocks)
node_mapping = {}
use_cache = bool(app.config["uqba... | python | def on_doctree_read(app, document):
"""
Hooks into Sphinx's ``doctree-read`` event.
"""
literal_blocks = uqbar.book.sphinx.collect_literal_blocks(document)
cache_mapping = uqbar.book.sphinx.group_literal_blocks_by_cache_path(literal_blocks)
node_mapping = {}
use_cache = bool(app.config["uqba... | [
"def",
"on_doctree_read",
"(",
"app",
",",
"document",
")",
":",
"literal_blocks",
"=",
"uqbar",
".",
"book",
".",
"sphinx",
".",
"collect_literal_blocks",
"(",
"document",
")",
"cache_mapping",
"=",
"uqbar",
".",
"book",
".",
"sphinx",
".",
"group_literal_blo... | Hooks into Sphinx's ``doctree-read`` event. | [
"Hooks",
"into",
"Sphinx",
"s",
"doctree",
"-",
"read",
"event",
"."
] | train | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/book.py#L82-L113 |
josiah-wolf-oberholtzer/uqbar | uqbar/sphinx/book.py | on_build_finished | def on_build_finished(app, exception):
"""
Hooks into Sphinx's ``build-finished`` event.
"""
if not app.config["uqbar_book_use_cache"]:
return
logger.info("")
for row in app.connection.execute("SELECT path, hits FROM cache ORDER BY path"):
path, hits = row
if not hits:
... | python | def on_build_finished(app, exception):
"""
Hooks into Sphinx's ``build-finished`` event.
"""
if not app.config["uqbar_book_use_cache"]:
return
logger.info("")
for row in app.connection.execute("SELECT path, hits FROM cache ORDER BY path"):
path, hits = row
if not hits:
... | [
"def",
"on_build_finished",
"(",
"app",
",",
"exception",
")",
":",
"if",
"not",
"app",
".",
"config",
"[",
"\"uqbar_book_use_cache\"",
"]",
":",
"return",
"logger",
".",
"info",
"(",
"\"\"",
")",
"for",
"row",
"in",
"app",
".",
"connection",
".",
"execu... | Hooks into Sphinx's ``build-finished`` event. | [
"Hooks",
"into",
"Sphinx",
"s",
"build",
"-",
"finished",
"event",
"."
] | train | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/book.py#L116-L128 |
josiah-wolf-oberholtzer/uqbar | uqbar/sphinx/style.py | handle_class | def handle_class(signature_node, module, object_name, cache):
"""
Styles ``autoclass`` entries.
Adds ``abstract`` prefix to abstract classes.
"""
class_ = getattr(module, object_name, None)
if class_ is None:
return
if class_ not in cache:
cache[class_] = {}
attribut... | python | def handle_class(signature_node, module, object_name, cache):
"""
Styles ``autoclass`` entries.
Adds ``abstract`` prefix to abstract classes.
"""
class_ = getattr(module, object_name, None)
if class_ is None:
return
if class_ not in cache:
cache[class_] = {}
attribut... | [
"def",
"handle_class",
"(",
"signature_node",
",",
"module",
",",
"object_name",
",",
"cache",
")",
":",
"class_",
"=",
"getattr",
"(",
"module",
",",
"object_name",
",",
"None",
")",
"if",
"class_",
"is",
"None",
":",
"return",
"if",
"class_",
"not",
"i... | Styles ``autoclass`` entries.
Adds ``abstract`` prefix to abstract classes. | [
"Styles",
"autoclass",
"entries",
"."
] | train | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/style.py#L22-L38 |
josiah-wolf-oberholtzer/uqbar | uqbar/sphinx/style.py | handle_method | def handle_method(signature_node, module, object_name, cache):
"""
Styles ``automethod`` entries.
Adds ``abstract`` prefix to abstract methods.
Adds link to originating class for inherited methods.
"""
*class_names, attr_name = object_name.split(".") # Handle nested classes
class_ = modul... | python | def handle_method(signature_node, module, object_name, cache):
"""
Styles ``automethod`` entries.
Adds ``abstract`` prefix to abstract methods.
Adds link to originating class for inherited methods.
"""
*class_names, attr_name = object_name.split(".") # Handle nested classes
class_ = modul... | [
"def",
"handle_method",
"(",
"signature_node",
",",
"module",
",",
"object_name",
",",
"cache",
")",
":",
"*",
"class_names",
",",
"attr_name",
"=",
"object_name",
".",
"split",
"(",
"\".\"",
")",
"# Handle nested classes",
"class_",
"=",
"module",
"for",
"cla... | Styles ``automethod`` entries.
Adds ``abstract`` prefix to abstract methods.
Adds link to originating class for inherited methods. | [
"Styles",
"automethod",
"entries",
"."
] | train | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/style.py#L41-L89 |
josiah-wolf-oberholtzer/uqbar | uqbar/sphinx/style.py | on_doctree_read | def on_doctree_read(app, document):
"""
Hooks into Sphinx's ``doctree-read`` event.
"""
cache: Dict[type, Dict[str, object]] = {}
for desc_node in document.traverse(addnodes.desc):
if desc_node.get("domain") != "py":
continue
signature_node = desc_node.traverse(addnodes.d... | python | def on_doctree_read(app, document):
"""
Hooks into Sphinx's ``doctree-read`` event.
"""
cache: Dict[type, Dict[str, object]] = {}
for desc_node in document.traverse(addnodes.desc):
if desc_node.get("domain") != "py":
continue
signature_node = desc_node.traverse(addnodes.d... | [
"def",
"on_doctree_read",
"(",
"app",
",",
"document",
")",
":",
"cache",
":",
"Dict",
"[",
"type",
",",
"Dict",
"[",
"str",
",",
"object",
"]",
"]",
"=",
"{",
"}",
"for",
"desc_node",
"in",
"document",
".",
"traverse",
"(",
"addnodes",
".",
"desc",
... | Hooks into Sphinx's ``doctree-read`` event. | [
"Hooks",
"into",
"Sphinx",
"s",
"doctree",
"-",
"read",
"event",
"."
] | train | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/style.py#L92-L108 |
josiah-wolf-oberholtzer/uqbar | uqbar/sphinx/style.py | on_builder_inited | def on_builder_inited(app):
"""
Hooks into Sphinx's ``builder-inited`` event.
Used for copying over CSS files to theme directory.
"""
local_css_path = pathlib.Path(__file__).parent / "uqbar.css"
theme_css_path = (
pathlib.Path(app.srcdir) / app.config.html_static_path[0] / "uqbar.css"
... | python | def on_builder_inited(app):
"""
Hooks into Sphinx's ``builder-inited`` event.
Used for copying over CSS files to theme directory.
"""
local_css_path = pathlib.Path(__file__).parent / "uqbar.css"
theme_css_path = (
pathlib.Path(app.srcdir) / app.config.html_static_path[0] / "uqbar.css"
... | [
"def",
"on_builder_inited",
"(",
"app",
")",
":",
"local_css_path",
"=",
"pathlib",
".",
"Path",
"(",
"__file__",
")",
".",
"parent",
"/",
"\"uqbar.css\"",
"theme_css_path",
"=",
"(",
"pathlib",
".",
"Path",
"(",
"app",
".",
"srcdir",
")",
"/",
"app",
".... | Hooks into Sphinx's ``builder-inited`` event.
Used for copying over CSS files to theme directory. | [
"Hooks",
"into",
"Sphinx",
"s",
"builder",
"-",
"inited",
"event",
"."
] | train | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/style.py#L111-L123 |
josiah-wolf-oberholtzer/uqbar | uqbar/sphinx/style.py | setup | def setup(app) -> Dict[str, Any]:
"""
Sets up Sphinx extension.
"""
app.connect("doctree-read", on_doctree_read)
app.connect("builder-inited", on_builder_inited)
app.add_css_file("uqbar.css")
app.add_node(
nodes.classifier, override=True, html=(visit_classifier, depart_classifier)
... | python | def setup(app) -> Dict[str, Any]:
"""
Sets up Sphinx extension.
"""
app.connect("doctree-read", on_doctree_read)
app.connect("builder-inited", on_builder_inited)
app.add_css_file("uqbar.css")
app.add_node(
nodes.classifier, override=True, html=(visit_classifier, depart_classifier)
... | [
"def",
"setup",
"(",
"app",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"app",
".",
"connect",
"(",
"\"doctree-read\"",
",",
"on_doctree_read",
")",
"app",
".",
"connect",
"(",
"\"builder-inited\"",
",",
"on_builder_inited",
")",
"app",
".",
"ad... | Sets up Sphinx extension. | [
"Sets",
"up",
"Sphinx",
"extension",
"."
] | train | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/style.py#L164-L182 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | init_xena | def init_xena(api, logger, owner, ip=None, port=57911):
""" Create XenaManager object.
:param api: cli/rest
:param logger: python logger
:param owner: owner of the scripting session
:param ip: rest server IP
:param port: rest server TCP port
:return: Xena object
:rtype: XenaApp
"""
... | python | def init_xena(api, logger, owner, ip=None, port=57911):
""" Create XenaManager object.
:param api: cli/rest
:param logger: python logger
:param owner: owner of the scripting session
:param ip: rest server IP
:param port: rest server TCP port
:return: Xena object
:rtype: XenaApp
"""
... | [
"def",
"init_xena",
"(",
"api",
",",
"logger",
",",
"owner",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"57911",
")",
":",
"if",
"api",
"==",
"ApiType",
".",
"socket",
":",
"api_wrapper",
"=",
"XenaCliWrapper",
"(",
"logger",
")",
"elif",
"api",
"==",... | Create XenaManager object.
:param api: cli/rest
:param logger: python logger
:param owner: owner of the scripting session
:param ip: rest server IP
:param port: rest server TCP port
:return: Xena object
:rtype: XenaApp | [
"Create",
"XenaManager",
"object",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L17-L33 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaSession.add_chassis | def add_chassis(self, chassis, port=22611, password='xena'):
""" Add chassis.
XenaManager-2G -> Add Chassis.
:param chassis: chassis IP address
:param port: chassis port number
:param password: chassis password
:return: newly created chassis
:rtype: xenamanager.... | python | def add_chassis(self, chassis, port=22611, password='xena'):
""" Add chassis.
XenaManager-2G -> Add Chassis.
:param chassis: chassis IP address
:param port: chassis port number
:param password: chassis password
:return: newly created chassis
:rtype: xenamanager.... | [
"def",
"add_chassis",
"(",
"self",
",",
"chassis",
",",
"port",
"=",
"22611",
",",
"password",
"=",
"'xena'",
")",
":",
"if",
"chassis",
"not",
"in",
"self",
".",
"chassis_list",
":",
"try",
":",
"XenaChassis",
"(",
"self",
",",
"chassis",
",",
"port",... | Add chassis.
XenaManager-2G -> Add Chassis.
:param chassis: chassis IP address
:param port: chassis port number
:param password: chassis password
:return: newly created chassis
:rtype: xenamanager.xena_app.XenaChassis | [
"Add",
"chassis",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L74-L92 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaSession.inventory | def inventory(self):
""" Get inventory for all chassis. """
for chassis in self.chassis_list.values():
chassis.inventory(modules_inventory=True) | python | def inventory(self):
""" Get inventory for all chassis. """
for chassis in self.chassis_list.values():
chassis.inventory(modules_inventory=True) | [
"def",
"inventory",
"(",
"self",
")",
":",
"for",
"chassis",
"in",
"self",
".",
"chassis_list",
".",
"values",
"(",
")",
":",
"chassis",
".",
"inventory",
"(",
"modules_inventory",
"=",
"True",
")"
] | Get inventory for all chassis. | [
"Get",
"inventory",
"for",
"all",
"chassis",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L100-L104 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaSession.reserve_ports | def reserve_ports(self, locations, force=False, reset=True):
""" Reserve ports and reset factory defaults.
XenaManager-2G -> Reserve/Relinquish Port.
XenaManager-2G -> Reserve Port.
:param locations: list of ports locations in the form <ip/slot/port> to reserve
:param force: Tr... | python | def reserve_ports(self, locations, force=False, reset=True):
""" Reserve ports and reset factory defaults.
XenaManager-2G -> Reserve/Relinquish Port.
XenaManager-2G -> Reserve Port.
:param locations: list of ports locations in the form <ip/slot/port> to reserve
:param force: Tr... | [
"def",
"reserve_ports",
"(",
"self",
",",
"locations",
",",
"force",
"=",
"False",
",",
"reset",
"=",
"True",
")",
":",
"for",
"location",
"in",
"locations",
":",
"ip",
",",
"module",
",",
"port",
"=",
"location",
".",
"split",
"(",
"'/'",
")",
"self... | Reserve ports and reset factory defaults.
XenaManager-2G -> Reserve/Relinquish Port.
XenaManager-2G -> Reserve Port.
:param locations: list of ports locations in the form <ip/slot/port> to reserve
:param force: True - take forcefully. False - fail if port is reserved by other user
... | [
"Reserve",
"ports",
"and",
"reset",
"factory",
"defaults",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L106-L122 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaSession.start_traffic | def start_traffic(self, blocking=False, *ports):
""" Start traffic on list of ports.
:param blocking: True - start traffic and wait until traffic ends, False - start traffic and return.
:param ports: list of ports to start traffic on. Default - all session ports.
"""
for chassi... | python | def start_traffic(self, blocking=False, *ports):
""" Start traffic on list of ports.
:param blocking: True - start traffic and wait until traffic ends, False - start traffic and return.
:param ports: list of ports to start traffic on. Default - all session ports.
"""
for chassi... | [
"def",
"start_traffic",
"(",
"self",
",",
"blocking",
"=",
"False",
",",
"*",
"ports",
")",
":",
"for",
"chassis",
",",
"chassis_ports",
"in",
"self",
".",
"_per_chassis_ports",
"(",
"*",
"self",
".",
"_get_operation_ports",
"(",
"*",
"ports",
")",
")",
... | Start traffic on list of ports.
:param blocking: True - start traffic and wait until traffic ends, False - start traffic and return.
:param ports: list of ports to start traffic on. Default - all session ports. | [
"Start",
"traffic",
"on",
"list",
"of",
"ports",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L133-L144 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaSession.stop_traffic | def stop_traffic(self, *ports):
""" Stop traffic on list of ports.
:param ports: list of ports to stop traffic on. Default - all session ports.
"""
for chassis, chassis_ports in self._per_chassis_ports(*self._get_operation_ports(*ports)).items():
chassis.stop_traffic(*chass... | python | def stop_traffic(self, *ports):
""" Stop traffic on list of ports.
:param ports: list of ports to stop traffic on. Default - all session ports.
"""
for chassis, chassis_ports in self._per_chassis_ports(*self._get_operation_ports(*ports)).items():
chassis.stop_traffic(*chass... | [
"def",
"stop_traffic",
"(",
"self",
",",
"*",
"ports",
")",
":",
"for",
"chassis",
",",
"chassis_ports",
"in",
"self",
".",
"_per_chassis_ports",
"(",
"*",
"self",
".",
"_get_operation_ports",
"(",
"*",
"ports",
")",
")",
".",
"items",
"(",
")",
":",
"... | Stop traffic on list of ports.
:param ports: list of ports to stop traffic on. Default - all session ports. | [
"Stop",
"traffic",
"on",
"list",
"of",
"ports",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L146-L153 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaSession.ports | def ports(self):
"""
:return: dictionary {name: object} of all ports.
"""
ports = {}
for chassis in self.chassis_list.values():
ports.update({str(p): p for p in chassis.get_objects_by_type('port')})
return ports | python | def ports(self):
"""
:return: dictionary {name: object} of all ports.
"""
ports = {}
for chassis in self.chassis_list.values():
ports.update({str(p): p for p in chassis.get_objects_by_type('port')})
return ports | [
"def",
"ports",
"(",
"self",
")",
":",
"ports",
"=",
"{",
"}",
"for",
"chassis",
"in",
"self",
".",
"chassis_list",
".",
"values",
"(",
")",
":",
"ports",
".",
"update",
"(",
"{",
"str",
"(",
"p",
")",
":",
"p",
"for",
"p",
"in",
"chassis",
"."... | :return: dictionary {name: object} of all ports. | [
":",
"return",
":",
"dictionary",
"{",
"name",
":",
"object",
"}",
"of",
"all",
"ports",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L195-L203 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaChassis.inventory | def inventory(self, modules_inventory=False):
""" Get chassis inventory.
:param modules_inventory: True - read modules inventory, false - don't read.
"""
self.c_info = self.get_attributes()
for m_index, m_portcounts in enumerate(self.c_info['c_portcounts'].split()):
... | python | def inventory(self, modules_inventory=False):
""" Get chassis inventory.
:param modules_inventory: True - read modules inventory, false - don't read.
"""
self.c_info = self.get_attributes()
for m_index, m_portcounts in enumerate(self.c_info['c_portcounts'].split()):
... | [
"def",
"inventory",
"(",
"self",
",",
"modules_inventory",
"=",
"False",
")",
":",
"self",
".",
"c_info",
"=",
"self",
".",
"get_attributes",
"(",
")",
"for",
"m_index",
",",
"m_portcounts",
"in",
"enumerate",
"(",
"self",
".",
"c_info",
"[",
"'c_portcount... | Get chassis inventory.
:param modules_inventory: True - read modules inventory, false - don't read. | [
"Get",
"chassis",
"inventory",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L258-L269 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaChassis.reserve_ports | def reserve_ports(self, locations, force=False, reset=True):
""" Reserve ports and reset factory defaults.
XenaManager-2G -> Reserve/Relinquish Port.
XenaManager-2G -> Reset port.
:param locations: list of ports locations in the form <module/port> to reserve
:param force: True ... | python | def reserve_ports(self, locations, force=False, reset=True):
""" Reserve ports and reset factory defaults.
XenaManager-2G -> Reserve/Relinquish Port.
XenaManager-2G -> Reset port.
:param locations: list of ports locations in the form <module/port> to reserve
:param force: True ... | [
"def",
"reserve_ports",
"(",
"self",
",",
"locations",
",",
"force",
"=",
"False",
",",
"reset",
"=",
"True",
")",
":",
"for",
"location",
"in",
"locations",
":",
"port",
"=",
"XenaPort",
"(",
"parent",
"=",
"self",
",",
"index",
"=",
"location",
")",
... | Reserve ports and reset factory defaults.
XenaManager-2G -> Reserve/Relinquish Port.
XenaManager-2G -> Reset port.
:param locations: list of ports locations in the form <module/port> to reserve
:param force: True - take forcefully, False - fail if port is reserved by other user
... | [
"Reserve",
"ports",
"and",
"reset",
"factory",
"defaults",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L271-L289 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaChassis.start_traffic | def start_traffic(self, blocking=False, *ports):
""" Start traffic on list of ports.
:param blocking: True - start traffic and wait until traffic ends, False - start traffic and return.
:param ports: list of ports to start traffic on. Default - all session ports.
"""
self._traf... | python | def start_traffic(self, blocking=False, *ports):
""" Start traffic on list of ports.
:param blocking: True - start traffic and wait until traffic ends, False - start traffic and return.
:param ports: list of ports to start traffic on. Default - all session ports.
"""
self._traf... | [
"def",
"start_traffic",
"(",
"self",
",",
"blocking",
"=",
"False",
",",
"*",
"ports",
")",
":",
"self",
".",
"_traffic_command",
"(",
"'on'",
",",
"*",
"ports",
")",
"if",
"blocking",
":",
"self",
".",
"wait_traffic",
"(",
"*",
"ports",
")"
] | Start traffic on list of ports.
:param blocking: True - start traffic and wait until traffic ends, False - start traffic and return.
:param ports: list of ports to start traffic on. Default - all session ports. | [
"Start",
"traffic",
"on",
"list",
"of",
"ports",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L300-L309 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaChassis.modules | def modules(self):
"""
:return: dictionary {index: object} of all modules.
"""
if not self.get_objects_by_type('module'):
self.inventory()
return {int(c.index): c for c in self.get_objects_by_type('module')} | python | def modules(self):
"""
:return: dictionary {index: object} of all modules.
"""
if not self.get_objects_by_type('module'):
self.inventory()
return {int(c.index): c for c in self.get_objects_by_type('module')} | [
"def",
"modules",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"get_objects_by_type",
"(",
"'module'",
")",
":",
"self",
".",
"inventory",
"(",
")",
"return",
"{",
"int",
"(",
"c",
".",
"index",
")",
":",
"c",
"for",
"c",
"in",
"self",
".",
"... | :return: dictionary {index: object} of all modules. | [
":",
"return",
":",
"dictionary",
"{",
"index",
":",
"object",
"}",
"of",
"all",
"modules",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L339-L346 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaModule.inventory | def inventory(self):
""" Get module inventory. """
self.m_info = self.get_attributes()
if 'NOTCFP' in self.m_info['m_cfptype']:
a = self.get_attribute('m_portcount')
m_portcount = int(a)
else:
m_portcount = int(self.get_attribute('m_cfpconfig').split(... | python | def inventory(self):
""" Get module inventory. """
self.m_info = self.get_attributes()
if 'NOTCFP' in self.m_info['m_cfptype']:
a = self.get_attribute('m_portcount')
m_portcount = int(a)
else:
m_portcount = int(self.get_attribute('m_cfpconfig').split(... | [
"def",
"inventory",
"(",
"self",
")",
":",
"self",
".",
"m_info",
"=",
"self",
".",
"get_attributes",
"(",
")",
"if",
"'NOTCFP'",
"in",
"self",
".",
"m_info",
"[",
"'m_cfptype'",
"]",
":",
"a",
"=",
"self",
".",
"get_attribute",
"(",
"'m_portcount'",
"... | Get module inventory. | [
"Get",
"module",
"inventory",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L386-L396 |
xenadevel/PyXenaManager | xenamanager/xena_app.py | XenaModule.ports | def ports(self):
"""
:return: dictionary {index: object} of all ports.
"""
if not self.get_objects_by_type('port'):
self.inventory()
return {int(p.index.split('/')[1]): p for p in self.get_objects_by_type('port')} | python | def ports(self):
"""
:return: dictionary {index: object} of all ports.
"""
if not self.get_objects_by_type('port'):
self.inventory()
return {int(p.index.split('/')[1]): p for p in self.get_objects_by_type('port')} | [
"def",
"ports",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"get_objects_by_type",
"(",
"'port'",
")",
":",
"self",
".",
"inventory",
"(",
")",
"return",
"{",
"int",
"(",
"p",
".",
"index",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
")",
... | :return: dictionary {index: object} of all ports. | [
":",
"return",
":",
"dictionary",
"{",
"index",
":",
"object",
"}",
"of",
"all",
"ports",
"."
] | train | https://github.com/xenadevel/PyXenaManager/blob/384ca265f73044b8a8b471f5dd7a6103fc54f4df/xenamanager/xena_app.py#L403-L410 |
MainRo/cyclotron-aio | cyclotron_aio/runner.py | run | def run(entry_point, drivers, loop = None):
''' This is a runner wrapping the cyclotron "run" implementation. It takes
an additional parameter to provide a custom asyncio mainloop.
'''
program = setup(entry_point, drivers)
dispose = program.run()
if loop == None:
loop = asyncio.get_event... | python | def run(entry_point, drivers, loop = None):
''' This is a runner wrapping the cyclotron "run" implementation. It takes
an additional parameter to provide a custom asyncio mainloop.
'''
program = setup(entry_point, drivers)
dispose = program.run()
if loop == None:
loop = asyncio.get_event... | [
"def",
"run",
"(",
"entry_point",
",",
"drivers",
",",
"loop",
"=",
"None",
")",
":",
"program",
"=",
"setup",
"(",
"entry_point",
",",
"drivers",
")",
"dispose",
"=",
"program",
".",
"run",
"(",
")",
"if",
"loop",
"==",
"None",
":",
"loop",
"=",
"... | This is a runner wrapping the cyclotron "run" implementation. It takes
an additional parameter to provide a custom asyncio mainloop. | [
"This",
"is",
"a",
"runner",
"wrapping",
"the",
"cyclotron",
"run",
"implementation",
".",
"It",
"takes",
"an",
"additional",
"parameter",
"to",
"provide",
"a",
"custom",
"asyncio",
"mainloop",
"."
] | train | https://github.com/MainRo/cyclotron-aio/blob/4401076aafe4a72de1d3c4ad6bb7ffa648506f7e/cyclotron_aio/runner.py#L4-L14 |
developersociety/django-glitter | glitter/blockadmin/blocks.py | register | def register(model, admin=None, category=None):
""" Decorator to registering you Admin class. """
def _model_admin_wrapper(admin_class):
site.register(model, admin_class=admin_class)
if category:
site.register_block(model, category)
return admin_class
return _model_adm... | python | def register(model, admin=None, category=None):
""" Decorator to registering you Admin class. """
def _model_admin_wrapper(admin_class):
site.register(model, admin_class=admin_class)
if category:
site.register_block(model, category)
return admin_class
return _model_adm... | [
"def",
"register",
"(",
"model",
",",
"admin",
"=",
"None",
",",
"category",
"=",
"None",
")",
":",
"def",
"_model_admin_wrapper",
"(",
"admin_class",
")",
":",
"site",
".",
"register",
"(",
"model",
",",
"admin_class",
"=",
"admin_class",
")",
"if",
"ca... | Decorator to registering you Admin class. | [
"Decorator",
"to",
"registering",
"you",
"Admin",
"class",
"."
] | train | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/blockadmin/blocks.py#L390-L400 |
developersociety/django-glitter | glitter/blockadmin/blocks.py | BlockAdmin.has_glitter_edit_permission | def has_glitter_edit_permission(self, request, obj):
"""
Return a boolean if a user has edit access to the glitter object/page this object is on.
"""
# We're testing for the edit permission here with the glitter object - not the current
# object, not the change permission. Once ... | python | def has_glitter_edit_permission(self, request, obj):
"""
Return a boolean if a user has edit access to the glitter object/page this object is on.
"""
# We're testing for the edit permission here with the glitter object - not the current
# object, not the change permission. Once ... | [
"def",
"has_glitter_edit_permission",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"# We're testing for the edit permission here with the glitter object - not the current",
"# object, not the change permission. Once a user has edit access to an object they can edit",
"# all content on ... | Return a boolean if a user has edit access to the glitter object/page this object is on. | [
"Return",
"a",
"boolean",
"if",
"a",
"user",
"has",
"edit",
"access",
"to",
"the",
"glitter",
"object",
"/",
"page",
"this",
"object",
"is",
"on",
"."
] | train | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/blockadmin/blocks.py#L201-L216 |
developersociety/django-glitter | glitter/blockadmin/blocks.py | BlockAdmin.change_view | def change_view(self, request, object_id, form_url='', extra_context=None):
"""The 'change' admin view for this model."""
obj = self.get_object(request, unquote(object_id))
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
... | python | def change_view(self, request, object_id, form_url='', extra_context=None):
"""The 'change' admin view for this model."""
obj = self.get_object(request, unquote(object_id))
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
... | [
"def",
"change_view",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"form_url",
"=",
"''",
",",
"extra_context",
"=",
"None",
")",
":",
"obj",
"=",
"self",
".",
"get_object",
"(",
"request",
",",
"unquote",
"(",
"object_id",
")",
")",
"if",
"obj"... | The 'change' admin view for this model. | [
"The",
"change",
"admin",
"view",
"for",
"this",
"model",
"."
] | train | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/blockadmin/blocks.py#L264-L285 |
developersociety/django-glitter | glitter/blockadmin/blocks.py | BlockAdmin.response_change | def response_change(self, request, obj):
"""Determine the HttpResponse for the change_view stage."""
opts = self.opts.app_label, self.opts.model_name
pk_value = obj._get_pk_val()
if '_continue' in request.POST:
msg = _(
'The %(name)s block was changed success... | python | def response_change(self, request, obj):
"""Determine the HttpResponse for the change_view stage."""
opts = self.opts.app_label, self.opts.model_name
pk_value = obj._get_pk_val()
if '_continue' in request.POST:
msg = _(
'The %(name)s block was changed success... | [
"def",
"response_change",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"opts",
"=",
"self",
".",
"opts",
".",
"app_label",
",",
"self",
".",
"opts",
".",
"model_name",
"pk_value",
"=",
"obj",
".",
"_get_pk_val",
"(",
")",
"if",
"'_continue'",
"in... | Determine the HttpResponse for the change_view stage. | [
"Determine",
"the",
"HttpResponse",
"for",
"the",
"change_view",
"stage",
"."
] | train | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/blockadmin/blocks.py#L287-L309 |
Karaage-Cluster/python-tldap | tldap/query.py | get_filter_item | def get_filter_item(name: str, operation: bytes, value: bytes) -> bytes:
"""
A field could be found for this term, try to get filter string for it.
"""
assert isinstance(name, str)
assert isinstance(value, bytes)
if operation is None:
return filter_format(b"(%s=%s)", [name, value])
e... | python | def get_filter_item(name: str, operation: bytes, value: bytes) -> bytes:
"""
A field could be found for this term, try to get filter string for it.
"""
assert isinstance(name, str)
assert isinstance(value, bytes)
if operation is None:
return filter_format(b"(%s=%s)", [name, value])
e... | [
"def",
"get_filter_item",
"(",
"name",
":",
"str",
",",
"operation",
":",
"bytes",
",",
"value",
":",
"bytes",
")",
"->",
"bytes",
":",
"assert",
"isinstance",
"(",
"name",
",",
"str",
")",
"assert",
"isinstance",
"(",
"value",
",",
"bytes",
")",
"if",... | A field could be found for this term, try to get filter string for it. | [
"A",
"field",
"could",
"be",
"found",
"for",
"this",
"term",
"try",
"to",
"get",
"filter",
"string",
"for",
"it",
"."
] | train | https://github.com/Karaage-Cluster/python-tldap/blob/61f1af74a3648cb6491e7eeb1ee2eb395d67bf59/tldap/query.py#L28-L40 |
Karaage-Cluster/python-tldap | tldap/query.py | get_filter | def get_filter(q: tldap.Q, fields: Dict[str, tldap.fields.Field], pk: str):
"""
Translate the Q tree into a filter string to search for, or None
if no results possible.
"""
# check the details are valid
if q.negated and len(q.children) == 1:
op = b"!"
elif q.connector == tldap.Q.AND:... | python | def get_filter(q: tldap.Q, fields: Dict[str, tldap.fields.Field], pk: str):
"""
Translate the Q tree into a filter string to search for, or None
if no results possible.
"""
# check the details are valid
if q.negated and len(q.children) == 1:
op = b"!"
elif q.connector == tldap.Q.AND:... | [
"def",
"get_filter",
"(",
"q",
":",
"tldap",
".",
"Q",
",",
"fields",
":",
"Dict",
"[",
"str",
",",
"tldap",
".",
"fields",
".",
"Field",
"]",
",",
"pk",
":",
"str",
")",
":",
"# check the details are valid",
"if",
"q",
".",
"negated",
"and",
"len",
... | Translate the Q tree into a filter string to search for, or None
if no results possible. | [
"Translate",
"the",
"Q",
"tree",
"into",
"a",
"filter",
"string",
"to",
"search",
"for",
"or",
"None",
"if",
"no",
"results",
"possible",
"."
] | train | https://github.com/Karaage-Cluster/python-tldap/blob/61f1af74a3648cb6491e7eeb1ee2eb395d67bf59/tldap/query.py#L43-L120 |
josiah-wolf-oberholtzer/uqbar | uqbar/cli/CLI.py | CLI.program_name | def program_name(self):
r"""The name of the script, callable from the command line.
"""
name = "-".join(
word.lower() for word in uqbar.strings.delimit_words(type(self).__name__)
)
return name | python | def program_name(self):
r"""The name of the script, callable from the command line.
"""
name = "-".join(
word.lower() for word in uqbar.strings.delimit_words(type(self).__name__)
)
return name | [
"def",
"program_name",
"(",
"self",
")",
":",
"name",
"=",
"\"-\"",
".",
"join",
"(",
"word",
".",
"lower",
"(",
")",
"for",
"word",
"in",
"uqbar",
".",
"strings",
".",
"delimit_words",
"(",
"type",
"(",
"self",
")",
".",
"__name__",
")",
")",
"ret... | r"""The name of the script, callable from the command line. | [
"r",
"The",
"name",
"of",
"the",
"script",
"callable",
"from",
"the",
"command",
"line",
"."
] | train | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/cli/CLI.py#L137-L143 |
jamescooke/flake8-aaa | src/flake8_aaa/helpers.py | node_is_result_assignment | def node_is_result_assignment(node: ast.AST) -> bool:
"""
Args:
node: An ``ast`` node.
Returns:
bool: ``node`` corresponds to the code ``result =``, assignment to the
``result `` variable.
Note:
Performs a very weak test that the line starts with 'result =' rather
... | python | def node_is_result_assignment(node: ast.AST) -> bool:
"""
Args:
node: An ``ast`` node.
Returns:
bool: ``node`` corresponds to the code ``result =``, assignment to the
``result `` variable.
Note:
Performs a very weak test that the line starts with 'result =' rather
... | [
"def",
"node_is_result_assignment",
"(",
"node",
":",
"ast",
".",
"AST",
")",
"->",
"bool",
":",
"# `.first_token` is added by asttokens",
"token",
"=",
"node",
".",
"first_token",
"# type: ignore",
"return",
"token",
".",
"line",
".",
"strip",
"(",
")",
".",
... | Args:
node: An ``ast`` node.
Returns:
bool: ``node`` corresponds to the code ``result =``, assignment to the
``result `` variable.
Note:
Performs a very weak test that the line starts with 'result =' rather
than testing the tokens. | [
"Args",
":",
"node",
":",
"An",
"ast",
"node",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/helpers.py#L63-L78 |
jamescooke/flake8-aaa | src/flake8_aaa/helpers.py | node_is_noop | def node_is_noop(node: ast.AST) -> bool:
"""
Node does nothing.
"""
return isinstance(node.value, ast.Str) if isinstance(node, ast.Expr) else isinstance(node, ast.Pass) | python | def node_is_noop(node: ast.AST) -> bool:
"""
Node does nothing.
"""
return isinstance(node.value, ast.Str) if isinstance(node, ast.Expr) else isinstance(node, ast.Pass) | [
"def",
"node_is_noop",
"(",
"node",
":",
"ast",
".",
"AST",
")",
"->",
"bool",
":",
"return",
"isinstance",
"(",
"node",
".",
"value",
",",
"ast",
".",
"Str",
")",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Expr",
")",
"else",
"isinstance",
... | Node does nothing. | [
"Node",
"does",
"nothing",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/helpers.py#L105-L109 |
jamescooke/flake8-aaa | src/flake8_aaa/helpers.py | function_is_noop | def function_is_noop(function_node: ast.FunctionDef) -> bool:
"""
Function does nothing - is just ``pass`` or docstring.
"""
return all(node_is_noop(n) for n in function_node.body) | python | def function_is_noop(function_node: ast.FunctionDef) -> bool:
"""
Function does nothing - is just ``pass`` or docstring.
"""
return all(node_is_noop(n) for n in function_node.body) | [
"def",
"function_is_noop",
"(",
"function_node",
":",
"ast",
".",
"FunctionDef",
")",
"->",
"bool",
":",
"return",
"all",
"(",
"node_is_noop",
"(",
"n",
")",
"for",
"n",
"in",
"function_node",
".",
"body",
")"
] | Function does nothing - is just ``pass`` or docstring. | [
"Function",
"does",
"nothing",
"-",
"is",
"just",
"pass",
"or",
"docstring",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/helpers.py#L112-L116 |
jamescooke/flake8-aaa | src/flake8_aaa/helpers.py | add_node_parents | def add_node_parents(root: ast.AST) -> None:
"""
Adds "parent" attribute to all child nodes of passed node.
Code taken from https://stackoverflow.com/a/43311383/1286705
"""
for node in ast.walk(root):
for child in ast.iter_child_nodes(node):
child.parent = node | python | def add_node_parents(root: ast.AST) -> None:
"""
Adds "parent" attribute to all child nodes of passed node.
Code taken from https://stackoverflow.com/a/43311383/1286705
"""
for node in ast.walk(root):
for child in ast.iter_child_nodes(node):
child.parent = node | [
"def",
"add_node_parents",
"(",
"root",
":",
"ast",
".",
"AST",
")",
"->",
"None",
":",
"for",
"node",
"in",
"ast",
".",
"walk",
"(",
"root",
")",
":",
"for",
"child",
"in",
"ast",
".",
"iter_child_nodes",
"(",
"node",
")",
":",
"child",
".",
"pare... | Adds "parent" attribute to all child nodes of passed node.
Code taken from https://stackoverflow.com/a/43311383/1286705 | [
"Adds",
"parent",
"attribute",
"to",
"all",
"child",
"nodes",
"of",
"passed",
"node",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/helpers.py#L146-L154 |
jamescooke/flake8-aaa | src/flake8_aaa/helpers.py | build_footprint | def build_footprint(node: ast.AST, first_line_no: int) -> Set[int]:
"""
Generates a list of lines that the passed node covers, relative to the
marked lines list - i.e. start of function is line 0.
"""
return set(
range(
get_first_token(node).start[0] - first_line_no,
... | python | def build_footprint(node: ast.AST, first_line_no: int) -> Set[int]:
"""
Generates a list of lines that the passed node covers, relative to the
marked lines list - i.e. start of function is line 0.
"""
return set(
range(
get_first_token(node).start[0] - first_line_no,
... | [
"def",
"build_footprint",
"(",
"node",
":",
"ast",
".",
"AST",
",",
"first_line_no",
":",
"int",
")",
"->",
"Set",
"[",
"int",
"]",
":",
"return",
"set",
"(",
"range",
"(",
"get_first_token",
"(",
"node",
")",
".",
"start",
"[",
"0",
"]",
"-",
"fir... | Generates a list of lines that the passed node covers, relative to the
marked lines list - i.e. start of function is line 0. | [
"Generates",
"a",
"list",
"of",
"lines",
"that",
"the",
"passed",
"node",
"covers",
"relative",
"to",
"the",
"marked",
"lines",
"list",
"-",
"i",
".",
"e",
".",
"start",
"of",
"function",
"is",
"line",
"0",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/helpers.py#L157-L167 |
jamescooke/flake8-aaa | src/flake8_aaa/helpers.py | filter_arrange_nodes | def filter_arrange_nodes(nodes: List[ast.stmt], max_line_number: int) -> List[ast.stmt]:
"""
Finds all nodes that are before the ``max_line_number`` and are not
docstrings or ``pass``.
"""
return [
node for node in nodes if node.lineno < max_line_number and not isinstance(node, ast.Pass)
... | python | def filter_arrange_nodes(nodes: List[ast.stmt], max_line_number: int) -> List[ast.stmt]:
"""
Finds all nodes that are before the ``max_line_number`` and are not
docstrings or ``pass``.
"""
return [
node for node in nodes if node.lineno < max_line_number and not isinstance(node, ast.Pass)
... | [
"def",
"filter_arrange_nodes",
"(",
"nodes",
":",
"List",
"[",
"ast",
".",
"stmt",
"]",
",",
"max_line_number",
":",
"int",
")",
"->",
"List",
"[",
"ast",
".",
"stmt",
"]",
":",
"return",
"[",
"node",
"for",
"node",
"in",
"nodes",
"if",
"node",
".",
... | Finds all nodes that are before the ``max_line_number`` and are not
docstrings or ``pass``. | [
"Finds",
"all",
"nodes",
"that",
"are",
"before",
"the",
"max_line_number",
"and",
"are",
"not",
"docstrings",
"or",
"pass",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/helpers.py#L170-L178 |
jamescooke/flake8-aaa | src/flake8_aaa/helpers.py | filter_assert_nodes | def filter_assert_nodes(nodes: List[ast.stmt], min_line_number: int) -> List[ast.stmt]:
"""
Finds all nodes that are after the ``min_line_number``
"""
return [node for node in nodes if node.lineno > min_line_number] | python | def filter_assert_nodes(nodes: List[ast.stmt], min_line_number: int) -> List[ast.stmt]:
"""
Finds all nodes that are after the ``min_line_number``
"""
return [node for node in nodes if node.lineno > min_line_number] | [
"def",
"filter_assert_nodes",
"(",
"nodes",
":",
"List",
"[",
"ast",
".",
"stmt",
"]",
",",
"min_line_number",
":",
"int",
")",
"->",
"List",
"[",
"ast",
".",
"stmt",
"]",
":",
"return",
"[",
"node",
"for",
"node",
"in",
"nodes",
"if",
"node",
".",
... | Finds all nodes that are after the ``min_line_number`` | [
"Finds",
"all",
"nodes",
"that",
"are",
"after",
"the",
"min_line_number"
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/helpers.py#L181-L185 |
jamescooke/flake8-aaa | src/flake8_aaa/helpers.py | find_stringy_lines | def find_stringy_lines(tree: ast.AST, first_line_no: int) -> Set[int]:
"""
Finds all lines that contain a string in a tree, usually a function. These
lines will be ignored when searching for blank lines.
"""
str_footprints = set()
for node in ast.walk(tree):
if isinstance(node, ast.Str):... | python | def find_stringy_lines(tree: ast.AST, first_line_no: int) -> Set[int]:
"""
Finds all lines that contain a string in a tree, usually a function. These
lines will be ignored when searching for blank lines.
"""
str_footprints = set()
for node in ast.walk(tree):
if isinstance(node, ast.Str):... | [
"def",
"find_stringy_lines",
"(",
"tree",
":",
"ast",
".",
"AST",
",",
"first_line_no",
":",
"int",
")",
"->",
"Set",
"[",
"int",
"]",
":",
"str_footprints",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"ast",
".",
"walk",
"(",
"tree",
")",
":",
"if"... | Finds all lines that contain a string in a tree, usually a function. These
lines will be ignored when searching for blank lines. | [
"Finds",
"all",
"lines",
"that",
"contain",
"a",
"string",
"in",
"a",
"tree",
"usually",
"a",
"function",
".",
"These",
"lines",
"will",
"be",
"ignored",
"when",
"searching",
"for",
"blank",
"lines",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/helpers.py#L188-L197 |
jamescooke/flake8-aaa | src/flake8_aaa/function.py | Function.check_all | def check_all(self) -> Generator[AAAError, None, None]:
"""
Run everything required for checking this function.
Returns:
A generator of errors.
Raises:
ValidationError: A non-recoverable linting error is found.
"""
# Function def
if funct... | python | def check_all(self) -> Generator[AAAError, None, None]:
"""
Run everything required for checking this function.
Returns:
A generator of errors.
Raises:
ValidationError: A non-recoverable linting error is found.
"""
# Function def
if funct... | [
"def",
"check_all",
"(",
"self",
")",
"->",
"Generator",
"[",
"AAAError",
",",
"None",
",",
"None",
"]",
":",
"# Function def",
"if",
"function_is_noop",
"(",
"self",
".",
"node",
")",
":",
"return",
"self",
".",
"mark_bl",
"(",
")",
"self",
".",
"mark... | Run everything required for checking this function.
Returns:
A generator of errors.
Raises:
ValidationError: A non-recoverable linting error is found. | [
"Run",
"everything",
"required",
"for",
"checking",
"this",
"function",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/function.py#L64-L99 |
jamescooke/flake8-aaa | src/flake8_aaa/function.py | Function.load_act_node | def load_act_node(self) -> ActNode:
"""
Raises:
ValidationError: AAA01 when no act block is found and AAA02 when
multiple act blocks are found.
"""
act_nodes = ActNode.build_body(self.node.body)
if not act_nodes:
raise ValidationError(self... | python | def load_act_node(self) -> ActNode:
"""
Raises:
ValidationError: AAA01 when no act block is found and AAA02 when
multiple act blocks are found.
"""
act_nodes = ActNode.build_body(self.node.body)
if not act_nodes:
raise ValidationError(self... | [
"def",
"load_act_node",
"(",
"self",
")",
"->",
"ActNode",
":",
"act_nodes",
"=",
"ActNode",
".",
"build_body",
"(",
"self",
".",
"node",
".",
"body",
")",
"if",
"not",
"act_nodes",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"first_line_no",
",",
... | Raises:
ValidationError: AAA01 when no act block is found and AAA02 when
multiple act blocks are found. | [
"Raises",
":",
"ValidationError",
":",
"AAA01",
"when",
"no",
"act",
"block",
"is",
"found",
"and",
"AAA02",
"when",
"multiple",
"act",
"blocks",
"are",
"found",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/function.py#L101-L122 |
jamescooke/flake8-aaa | src/flake8_aaa/function.py | Function.get_line_relative_to_node | def get_line_relative_to_node(self, target_node: ast.AST, offset: int) -> str:
"""
Raises:
IndexError: when ``offset`` takes the request out of bounds of this
Function's lines.
"""
return self.lines[target_node.lineno - self.node.lineno + offset] | python | def get_line_relative_to_node(self, target_node: ast.AST, offset: int) -> str:
"""
Raises:
IndexError: when ``offset`` takes the request out of bounds of this
Function's lines.
"""
return self.lines[target_node.lineno - self.node.lineno + offset] | [
"def",
"get_line_relative_to_node",
"(",
"self",
",",
"target_node",
":",
"ast",
".",
"AST",
",",
"offset",
":",
"int",
")",
"->",
"str",
":",
"return",
"self",
".",
"lines",
"[",
"target_node",
".",
"lineno",
"-",
"self",
".",
"node",
".",
"lineno",
"... | Raises:
IndexError: when ``offset`` takes the request out of bounds of this
Function's lines. | [
"Raises",
":",
"IndexError",
":",
"when",
"offset",
"takes",
"the",
"request",
"out",
"of",
"bounds",
"of",
"this",
"Function",
"s",
"lines",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/function.py#L124-L130 |
jamescooke/flake8-aaa | src/flake8_aaa/function.py | Function.mark_def | def mark_def(self) -> int:
"""
Marks up this Function's definition lines (including decorators) into
the ``line_markers`` attribute.
Returns:
Number of lines found for the definition.
Note:
Does not spot the closing ``):`` of a function when it occurs on... | python | def mark_def(self) -> int:
"""
Marks up this Function's definition lines (including decorators) into
the ``line_markers`` attribute.
Returns:
Number of lines found for the definition.
Note:
Does not spot the closing ``):`` of a function when it occurs on... | [
"def",
"mark_def",
"(",
"self",
")",
"->",
"int",
":",
"first_line",
"=",
"get_first_token",
"(",
"self",
".",
"node",
")",
".",
"start",
"[",
"0",
"]",
"-",
"self",
".",
"first_line_no",
"# Should usually be 0",
"try",
":",
"end_token",
"=",
"get_last_tok... | Marks up this Function's definition lines (including decorators) into
the ``line_markers`` attribute.
Returns:
Number of lines found for the definition.
Note:
Does not spot the closing ``):`` of a function when it occurs on
its own line.
Note:
... | [
"Marks",
"up",
"this",
"Function",
"s",
"definition",
"lines",
"(",
"including",
"decorators",
")",
"into",
"the",
"line_markers",
"attribute",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/function.py#L132-L157 |
jamescooke/flake8-aaa | src/flake8_aaa/function.py | Function.mark_bl | def mark_bl(self) -> int:
"""
Mark unprocessed lines that have no content and no string nodes
covering them as blank line BL.
Returns:
Number of blank lines found with no stringy parent node.
"""
counter = 0
stringy_lines = find_stringy_lines(self.nod... | python | def mark_bl(self) -> int:
"""
Mark unprocessed lines that have no content and no string nodes
covering them as blank line BL.
Returns:
Number of blank lines found with no stringy parent node.
"""
counter = 0
stringy_lines = find_stringy_lines(self.nod... | [
"def",
"mark_bl",
"(",
"self",
")",
"->",
"int",
":",
"counter",
"=",
"0",
"stringy_lines",
"=",
"find_stringy_lines",
"(",
"self",
".",
"node",
",",
"self",
".",
"first_line_no",
")",
"for",
"relative_line_number",
",",
"line",
"in",
"enumerate",
"(",
"se... | Mark unprocessed lines that have no content and no string nodes
covering them as blank line BL.
Returns:
Number of blank lines found with no stringy parent node. | [
"Mark",
"unprocessed",
"lines",
"that",
"have",
"no",
"content",
"and",
"no",
"string",
"nodes",
"covering",
"them",
"as",
"blank",
"line",
"BL",
"."
] | train | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/function.py#L159-L174 |
davidblaisonneau-orange/foreman | foreman/itemHost.py | ItemHost.enhance | def enhance(self):
""" Function enhance
Enhance the object with new item or enhanced items
"""
self.update({'puppetclasses':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemPuppetClasses)})
... | python | def enhance(self):
""" Function enhance
Enhance the object with new item or enhanced items
"""
self.update({'puppetclasses':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemPuppetClasses)})
... | [
"def",
"enhance",
"(",
"self",
")",
":",
"self",
".",
"update",
"(",
"{",
"'puppetclasses'",
":",
"SubDict",
"(",
"self",
".",
"api",
",",
"self",
".",
"objName",
",",
"self",
".",
"payloadObj",
",",
"self",
".",
"key",
",",
"SubItemPuppetClasses",
")"... | Function enhance
Enhance the object with new item or enhanced items | [
"Function",
"enhance",
"Enhance",
"the",
"object",
"with",
"new",
"item",
"or",
"enhanced",
"items"
] | train | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/itemHost.py#L39-L58 |
davidblaisonneau-orange/foreman | foreman/itemHost.py | ItemHost.getParamFromEnv | def getParamFromEnv(self, var, default=''):
""" Function getParamFromEnv
Search a parameter in the host environment
@param var: the var name
@param hostgroup: the hostgroup item linked to this host
@param default: default value
@return RETURN: the value
"""
... | python | def getParamFromEnv(self, var, default=''):
""" Function getParamFromEnv
Search a parameter in the host environment
@param var: the var name
@param hostgroup: the hostgroup item linked to this host
@param default: default value
@return RETURN: the value
"""
... | [
"def",
"getParamFromEnv",
"(",
"self",
",",
"var",
",",
"default",
"=",
"''",
")",
":",
"if",
"self",
".",
"getParam",
"(",
"var",
")",
":",
"return",
"self",
".",
"getParam",
"(",
"var",
")",
"if",
"self",
".",
"hostgroup",
":",
"if",
"self",
".",... | Function getParamFromEnv
Search a parameter in the host environment
@param var: the var name
@param hostgroup: the hostgroup item linked to this host
@param default: default value
@return RETURN: the value | [
"Function",
"getParamFromEnv",
"Search",
"a",
"parameter",
"in",
"the",
"host",
"environment"
] | train | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/itemHost.py#L114-L131 |
davidblaisonneau-orange/foreman | foreman/itemHost.py | ItemHost.getUserData | def getUserData(self,
hostgroup,
domain,
defaultPwd='',
defaultSshKey='',
proxyHostname='',
tplFolder='metadata/templates/'):
""" Function getUserData
Generate a userdata script for me... | python | def getUserData(self,
hostgroup,
domain,
defaultPwd='',
defaultSshKey='',
proxyHostname='',
tplFolder='metadata/templates/'):
""" Function getUserData
Generate a userdata script for me... | [
"def",
"getUserData",
"(",
"self",
",",
"hostgroup",
",",
"domain",
",",
"defaultPwd",
"=",
"''",
",",
"defaultSshKey",
"=",
"''",
",",
"proxyHostname",
"=",
"''",
",",
"tplFolder",
"=",
"'metadata/templates/'",
")",
":",
"if",
"'user-data'",
"in",
"self",
... | Function getUserData
Generate a userdata script for metadata server from Foreman API
@param domain: the domain item linked to this host
@param hostgroup: the hostgroup item linked to this host
@param defaultPwd: the default password if no password is specified
... | [
"Function",
"getUserData",
"Generate",
"a",
"userdata",
"script",
"for",
"metadata",
"server",
"from",
"Foreman",
"API"
] | train | https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/itemHost.py#L133-L177 |
MatterMiners/cobald | cobald/daemon/runners/meta_runner.py | MetaRunner.register_payload | def register_payload(self, *payloads, flavour: ModuleType):
"""Queue one or more payload for execution after its runner is started"""
for payload in payloads:
self._logger.debug('registering payload %s (%s)', NameRepr(payload), NameRepr(flavour))
self.runners[flavour].register_pa... | python | def register_payload(self, *payloads, flavour: ModuleType):
"""Queue one or more payload for execution after its runner is started"""
for payload in payloads:
self._logger.debug('registering payload %s (%s)', NameRepr(payload), NameRepr(flavour))
self.runners[flavour].register_pa... | [
"def",
"register_payload",
"(",
"self",
",",
"*",
"payloads",
",",
"flavour",
":",
"ModuleType",
")",
":",
"for",
"payload",
"in",
"payloads",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'registering payload %s (%s)'",
",",
"NameRepr",
"(",
"payload",
"... | Queue one or more payload for execution after its runner is started | [
"Queue",
"one",
"or",
"more",
"payload",
"for",
"execution",
"after",
"its",
"runner",
"is",
"started"
] | train | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/meta_runner.py#L35-L39 |
MatterMiners/cobald | cobald/daemon/runners/meta_runner.py | MetaRunner.run_payload | def run_payload(self, payload, *, flavour: ModuleType):
"""Execute one payload after its runner is started and return its output"""
return self.runners[flavour].run_payload(payload) | python | def run_payload(self, payload, *, flavour: ModuleType):
"""Execute one payload after its runner is started and return its output"""
return self.runners[flavour].run_payload(payload) | [
"def",
"run_payload",
"(",
"self",
",",
"payload",
",",
"*",
",",
"flavour",
":",
"ModuleType",
")",
":",
"return",
"self",
".",
"runners",
"[",
"flavour",
"]",
".",
"run_payload",
"(",
"payload",
")"
] | Execute one payload after its runner is started and return its output | [
"Execute",
"one",
"payload",
"after",
"its",
"runner",
"is",
"started",
"and",
"return",
"its",
"output"
] | train | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/meta_runner.py#L41-L43 |
MatterMiners/cobald | cobald/daemon/runners/meta_runner.py | MetaRunner.run | def run(self):
"""Run all runners, blocking until completion or error"""
self._logger.info('starting all runners')
try:
with self._lock:
assert not self.running.set(), 'cannot re-run: %s' % self
self.running.set()
thread_runner = self.runne... | python | def run(self):
"""Run all runners, blocking until completion or error"""
self._logger.info('starting all runners')
try:
with self._lock:
assert not self.running.set(), 'cannot re-run: %s' % self
self.running.set()
thread_runner = self.runne... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'starting all runners'",
")",
"try",
":",
"with",
"self",
".",
"_lock",
":",
"assert",
"not",
"self",
".",
"running",
".",
"set",
"(",
")",
",",
"'cannot re-run: %s'",
"%",... | Run all runners, blocking until completion or error | [
"Run",
"all",
"runners",
"blocking",
"until",
"completion",
"or",
"error"
] | train | https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/daemon/runners/meta_runner.py#L45-L66 |
developersociety/django-glitter | glitter/blocks/image/admin.py | ImageBlockAdmin.formfield_for_dbfield | def formfield_for_dbfield(self, db_field, **kwargs):
"""
Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor.
"""
formfield = super().formfield_for_dbfield(db_field, **kwargs... | python | def formfield_for_dbfield(self, db_field, **kwargs):
"""
Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor.
"""
formfield = super().formfield_for_dbfield(db_field, **kwargs... | [
"def",
"formfield_for_dbfield",
"(",
"self",
",",
"db_field",
",",
"*",
"*",
"kwargs",
")",
":",
"formfield",
"=",
"super",
"(",
")",
".",
"formfield_for_dbfield",
"(",
"db_field",
",",
"*",
"*",
"kwargs",
")",
"if",
"db_field",
".",
"name",
"==",
"'imag... | Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor. | [
"Hook",
"for",
"specifying",
"the",
"form",
"Field",
"instance",
"for",
"a",
"given",
"database",
"Field",
"instance",
"."
] | train | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/blocks/image/admin.py#L21-L34 |
beregond/jsonmodels | jsonmodels/utilities.py | compare_schemas | def compare_schemas(one, two):
"""Compare two structures that represents JSON schemas.
For comparison you can't use normal comparison, because in JSON schema
lists DO NOT keep order (and Python lists do), so this must be taken into
account during comparison.
Note this wont check all configurations... | python | def compare_schemas(one, two):
"""Compare two structures that represents JSON schemas.
For comparison you can't use normal comparison, because in JSON schema
lists DO NOT keep order (and Python lists do), so this must be taken into
account during comparison.
Note this wont check all configurations... | [
"def",
"compare_schemas",
"(",
"one",
",",
"two",
")",
":",
"one",
"=",
"_normalize_string_type",
"(",
"one",
")",
"two",
"=",
"_normalize_string_type",
"(",
"two",
")",
"_assert_same_types",
"(",
"one",
",",
"two",
")",
"if",
"isinstance",
"(",
"one",
","... | Compare two structures that represents JSON schemas.
For comparison you can't use normal comparison, because in JSON schema
lists DO NOT keep order (and Python lists do), so this must be taken into
account during comparison.
Note this wont check all configurations, only first one that seems to
mat... | [
"Compare",
"two",
"structures",
"that",
"represents",
"JSON",
"schemas",
"."
] | train | https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/utilities.py#L60-L90 |
beregond/jsonmodels | jsonmodels/utilities.py | is_ecma_regex | def is_ecma_regex(regex):
"""Check if given regex is of type ECMA 262 or not.
:rtype: bool
"""
parts = regex.split('/')
if len(parts) == 1:
return False
if len(parts) < 3:
raise ValueError('Given regex isn\'t ECMA regex nor Python regex.')
parts.pop()
parts.append('')... | python | def is_ecma_regex(regex):
"""Check if given regex is of type ECMA 262 or not.
:rtype: bool
"""
parts = regex.split('/')
if len(parts) == 1:
return False
if len(parts) < 3:
raise ValueError('Given regex isn\'t ECMA regex nor Python regex.')
parts.pop()
parts.append('')... | [
"def",
"is_ecma_regex",
"(",
"regex",
")",
":",
"parts",
"=",
"regex",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"return",
"False",
"if",
"len",
"(",
"parts",
")",
"<",
"3",
":",
"raise",
"ValueError",
"(",
"'... | Check if given regex is of type ECMA 262 or not.
:rtype: bool | [
"Check",
"if",
"given",
"regex",
"is",
"of",
"type",
"ECMA",
"262",
"or",
"not",
"."
] | train | https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/utilities.py#L93-L112 |
beregond/jsonmodels | jsonmodels/utilities.py | convert_ecma_regex_to_python | def convert_ecma_regex_to_python(value):
"""Convert ECMA 262 regex to Python tuple with regex and flags.
If given value is already Python regex it will be returned unchanged.
:param string value: ECMA regex.
:return: 2-tuple with `regex` and `flags`
:rtype: namedtuple
"""
if not is_ecma_r... | python | def convert_ecma_regex_to_python(value):
"""Convert ECMA 262 regex to Python tuple with regex and flags.
If given value is already Python regex it will be returned unchanged.
:param string value: ECMA regex.
:return: 2-tuple with `regex` and `flags`
:rtype: namedtuple
"""
if not is_ecma_r... | [
"def",
"convert_ecma_regex_to_python",
"(",
"value",
")",
":",
"if",
"not",
"is_ecma_regex",
"(",
"value",
")",
":",
"return",
"PythonRegex",
"(",
"value",
",",
"[",
"]",
")",
"parts",
"=",
"value",
".",
"split",
"(",
"'/'",
")",
"flags",
"=",
"parts",
... | Convert ECMA 262 regex to Python tuple with regex and flags.
If given value is already Python regex it will be returned unchanged.
:param string value: ECMA regex.
:return: 2-tuple with `regex` and `flags`
:rtype: namedtuple | [
"Convert",
"ECMA",
"262",
"regex",
"to",
"Python",
"tuple",
"with",
"regex",
"and",
"flags",
"."
] | train | https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/utilities.py#L115-L136 |
beregond/jsonmodels | jsonmodels/utilities.py | convert_python_regex_to_ecma | def convert_python_regex_to_ecma(value, flags=[]):
"""Convert Python regex to ECMA 262 regex.
If given value is already ECMA regex it will be returned unchanged.
:param string value: Python regex.
:param list flags: List of flags (allowed flags: `re.I`, `re.M`)
:return: ECMA 262 regex
:rtype: ... | python | def convert_python_regex_to_ecma(value, flags=[]):
"""Convert Python regex to ECMA 262 regex.
If given value is already ECMA regex it will be returned unchanged.
:param string value: Python regex.
:param list flags: List of flags (allowed flags: `re.I`, `re.M`)
:return: ECMA 262 regex
:rtype: ... | [
"def",
"convert_python_regex_to_ecma",
"(",
"value",
",",
"flags",
"=",
"[",
"]",
")",
":",
"if",
"is_ecma_regex",
"(",
"value",
")",
":",
"return",
"value",
"result_flags",
"=",
"[",
"PYTHON_TO_ECMA_FLAGS",
"[",
"f",
"]",
"for",
"f",
"in",
"flags",
"]",
... | Convert Python regex to ECMA 262 regex.
If given value is already ECMA regex it will be returned unchanged.
:param string value: Python regex.
:param list flags: List of flags (allowed flags: `re.I`, `re.M`)
:return: ECMA 262 regex
:rtype: str | [
"Convert",
"Python",
"regex",
"to",
"ECMA",
"262",
"regex",
"."
] | train | https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/utilities.py#L139-L156 |
beregond/jsonmodels | jsonmodels/models.py | Base.populate | def populate(self, **values):
"""Populate values to fields. Skip non-existing."""
values = values.copy()
fields = list(self.iterate_with_name())
for _, structure_name, field in fields:
if structure_name in values:
field.__set__(self, values.pop(structure_name)... | python | def populate(self, **values):
"""Populate values to fields. Skip non-existing."""
values = values.copy()
fields = list(self.iterate_with_name())
for _, structure_name, field in fields:
if structure_name in values:
field.__set__(self, values.pop(structure_name)... | [
"def",
"populate",
"(",
"self",
",",
"*",
"*",
"values",
")",
":",
"values",
"=",
"values",
".",
"copy",
"(",
")",
"fields",
"=",
"list",
"(",
"self",
".",
"iterate_with_name",
"(",
")",
")",
"for",
"_",
",",
"structure_name",
",",
"field",
"in",
"... | Populate values to fields. Skip non-existing. | [
"Populate",
"values",
"to",
"fields",
".",
"Skip",
"non",
"-",
"existing",
"."
] | train | https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/models.py#L36-L45 |
beregond/jsonmodels | jsonmodels/models.py | Base.get_field | def get_field(self, field_name):
"""Get field associated with given attribute."""
for attr_name, field in self:
if field_name == attr_name:
return field
raise errors.FieldNotFound('Field not found', field_name) | python | def get_field(self, field_name):
"""Get field associated with given attribute."""
for attr_name, field in self:
if field_name == attr_name:
return field
raise errors.FieldNotFound('Field not found', field_name) | [
"def",
"get_field",
"(",
"self",
",",
"field_name",
")",
":",
"for",
"attr_name",
",",
"field",
"in",
"self",
":",
"if",
"field_name",
"==",
"attr_name",
":",
"return",
"field",
"raise",
"errors",
".",
"FieldNotFound",
"(",
"'Field not found'",
",",
"field_n... | Get field associated with given attribute. | [
"Get",
"field",
"associated",
"with",
"given",
"attribute",
"."
] | train | https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/models.py#L47-L53 |
beregond/jsonmodels | jsonmodels/models.py | Base.validate | def validate(self):
"""Explicitly validate all the fields."""
for name, field in self:
try:
field.validate_for_object(self)
except ValidationError as error:
raise ValidationError(
"Error for field '{name}'.".format(name=name),
... | python | def validate(self):
"""Explicitly validate all the fields."""
for name, field in self:
try:
field.validate_for_object(self)
except ValidationError as error:
raise ValidationError(
"Error for field '{name}'.".format(name=name),
... | [
"def",
"validate",
"(",
"self",
")",
":",
"for",
"name",
",",
"field",
"in",
"self",
":",
"try",
":",
"field",
".",
"validate_for_object",
"(",
"self",
")",
"except",
"ValidationError",
"as",
"error",
":",
"raise",
"ValidationError",
"(",
"\"Error for field ... | Explicitly validate all the fields. | [
"Explicitly",
"validate",
"all",
"the",
"fields",
"."
] | train | https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/models.py#L60-L69 |
beregond/jsonmodels | jsonmodels/models.py | Base.iterate_over_fields | def iterate_over_fields(cls):
"""Iterate through fields as `(attribute_name, field_instance)`."""
for attr in dir(cls):
clsattr = getattr(cls, attr)
if isinstance(clsattr, BaseField):
yield attr, clsattr | python | def iterate_over_fields(cls):
"""Iterate through fields as `(attribute_name, field_instance)`."""
for attr in dir(cls):
clsattr = getattr(cls, attr)
if isinstance(clsattr, BaseField):
yield attr, clsattr | [
"def",
"iterate_over_fields",
"(",
"cls",
")",
":",
"for",
"attr",
"in",
"dir",
"(",
"cls",
")",
":",
"clsattr",
"=",
"getattr",
"(",
"cls",
",",
"attr",
")",
"if",
"isinstance",
"(",
"clsattr",
",",
"BaseField",
")",
":",
"yield",
"attr",
",",
"clsa... | Iterate through fields as `(attribute_name, field_instance)`. | [
"Iterate",
"through",
"fields",
"as",
"(",
"attribute_name",
"field_instance",
")",
"."
] | train | https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/models.py#L72-L77 |
beregond/jsonmodels | jsonmodels/models.py | Base.iterate_with_name | def iterate_with_name(cls):
"""Iterate over fields, but also give `structure_name`.
Format is `(attribute_name, structue_name, field_instance)`.
Structure name is name under which value is seen in structure and
schema (in primitives) and only there.
"""
for attr_name, fi... | python | def iterate_with_name(cls):
"""Iterate over fields, but also give `structure_name`.
Format is `(attribute_name, structue_name, field_instance)`.
Structure name is name under which value is seen in structure and
schema (in primitives) and only there.
"""
for attr_name, fi... | [
"def",
"iterate_with_name",
"(",
"cls",
")",
":",
"for",
"attr_name",
",",
"field",
"in",
"cls",
".",
"iterate_over_fields",
"(",
")",
":",
"structure_name",
"=",
"field",
".",
"structue_name",
"(",
"attr_name",
")",
"yield",
"attr_name",
",",
"structure_name"... | Iterate over fields, but also give `structure_name`.
Format is `(attribute_name, structue_name, field_instance)`.
Structure name is name under which value is seen in structure and
schema (in primitives) and only there. | [
"Iterate",
"over",
"fields",
"but",
"also",
"give",
"structure_name",
"."
] | train | https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/models.py#L80-L89 |
beregond/jsonmodels | jsonmodels/fields.py | IntField.parse_value | def parse_value(self, value):
"""Cast value to `int`, e.g. from string or long"""
parsed = super(IntField, self).parse_value(value)
if parsed is None:
return parsed
return int(parsed) | python | def parse_value(self, value):
"""Cast value to `int`, e.g. from string or long"""
parsed = super(IntField, self).parse_value(value)
if parsed is None:
return parsed
return int(parsed) | [
"def",
"parse_value",
"(",
"self",
",",
"value",
")",
":",
"parsed",
"=",
"super",
"(",
"IntField",
",",
"self",
")",
".",
"parse_value",
"(",
"value",
")",
"if",
"parsed",
"is",
"None",
":",
"return",
"parsed",
"return",
"int",
"(",
"parsed",
")"
] | Cast value to `int`, e.g. from string or long | [
"Cast",
"value",
"to",
"int",
"e",
".",
"g",
".",
"from",
"string",
"or",
"long"
] | train | https://github.com/beregond/jsonmodels/blob/97a1a6b90a49490fc5a6078f49027055d2e13541/jsonmodels/fields.py#L157-L162 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.