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 |
|---|---|---|---|---|---|---|---|---|---|---|
Parsely/birding | src/birding/follow.py | follow_topic | def follow_topic(kafka_class, name, retry_interval=1, **kafka_init):
"""Dump each message from kafka topic to stdio."""
while True:
try:
client = kafka_class(**kafka_init)
topic = client.topics[name]
consumer = topic.get_simple_consumer(reset_offset_on_start=True)
... | python | def follow_topic(kafka_class, name, retry_interval=1, **kafka_init):
"""Dump each message from kafka topic to stdio."""
while True:
try:
client = kafka_class(**kafka_init)
topic = client.topics[name]
consumer = topic.get_simple_consumer(reset_offset_on_start=True)
... | [
"def",
"follow_topic",
"(",
"kafka_class",
",",
"name",
",",
"retry_interval",
"=",
"1",
",",
"*",
"*",
"kafka_init",
")",
":",
"while",
"True",
":",
"try",
":",
"client",
"=",
"kafka_class",
"(",
"*",
"*",
"kafka_init",
")",
"topic",
"=",
"client",
".... | Dump each message from kafka topic to stdio. | [
"Dump",
"each",
"message",
"from",
"kafka",
"topic",
"to",
"stdio",
"."
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/follow.py#L30-L55 |
Parsely/birding | src/birding/follow.py | follow_fd | def follow_fd(fd):
"""Dump each line of input to stdio."""
dump = Dump()
for line in fd:
if not line.strip():
continue
with flushing(sys.stdout, sys.stderr):
status = load(line)
if status:
dump(status) | python | def follow_fd(fd):
"""Dump each line of input to stdio."""
dump = Dump()
for line in fd:
if not line.strip():
continue
with flushing(sys.stdout, sys.stderr):
status = load(line)
if status:
dump(status) | [
"def",
"follow_fd",
"(",
"fd",
")",
":",
"dump",
"=",
"Dump",
"(",
")",
"for",
"line",
"in",
"fd",
":",
"if",
"not",
"line",
".",
"strip",
"(",
")",
":",
"continue",
"with",
"flushing",
"(",
"sys",
".",
"stdout",
",",
"sys",
".",
"stderr",
")",
... | Dump each line of input to stdio. | [
"Dump",
"each",
"line",
"of",
"input",
"to",
"stdio",
"."
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/follow.py#L58-L68 |
Parsely/birding | src/birding/follow.py | should_try_kafka_again | def should_try_kafka_again(error):
"""Determine if the error means to retry or fail, True to retry."""
msg = 'Unable to retrieve'
return isinstance(error, KafkaException) and str(error).startswith(msg) | python | def should_try_kafka_again(error):
"""Determine if the error means to retry or fail, True to retry."""
msg = 'Unable to retrieve'
return isinstance(error, KafkaException) and str(error).startswith(msg) | [
"def",
"should_try_kafka_again",
"(",
"error",
")",
":",
"msg",
"=",
"'Unable to retrieve'",
"return",
"isinstance",
"(",
"error",
",",
"KafkaException",
")",
"and",
"str",
"(",
"error",
")",
".",
"startswith",
"(",
"msg",
")"
] | Determine if the error means to retry or fail, True to retry. | [
"Determine",
"if",
"the",
"error",
"means",
"to",
"retry",
"or",
"fail",
"True",
"to",
"retry",
"."
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/follow.py#L97-L100 |
koreyou/word_embedding_loader | word_embedding_loader/loader/glove.py | check_valid | def check_valid(line0, line1):
"""
Check if a file is valid Glove format.
Args:
line0 (bytes): First line of the file
line1 (bytes): Second line of the file
Returns:
boo: ``True`` if it is valid. ``False`` if it is invalid.
"""
data = line0.strip().split(b' ')
if l... | python | def check_valid(line0, line1):
"""
Check if a file is valid Glove format.
Args:
line0 (bytes): First line of the file
line1 (bytes): Second line of the file
Returns:
boo: ``True`` if it is valid. ``False`` if it is invalid.
"""
data = line0.strip().split(b' ')
if l... | [
"def",
"check_valid",
"(",
"line0",
",",
"line1",
")",
":",
"data",
"=",
"line0",
".",
"strip",
"(",
")",
".",
"split",
"(",
"b' '",
")",
"if",
"len",
"(",
"data",
")",
"<=",
"2",
":",
"return",
"False",
"# check if data[2:] is float values",
"try",
":... | Check if a file is valid Glove format.
Args:
line0 (bytes): First line of the file
line1 (bytes): Second line of the file
Returns:
boo: ``True`` if it is valid. ``False`` if it is invalid. | [
"Check",
"if",
"a",
"file",
"is",
"valid",
"Glove",
"format",
"."
] | train | https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/loader/glove.py#L17-L37 |
koreyou/word_embedding_loader | word_embedding_loader/loader/glove.py | load_with_vocab | def load_with_vocab(fin, vocab, dtype=np.float32):
"""
Load word embedding file with predefined vocabulary
Args:
fin (File): File object to read. File should be open for reading ascii.
vocab (dict): Mapping from words (``bytes``) to vector indices
(``int``).
dtype (numpy... | python | def load_with_vocab(fin, vocab, dtype=np.float32):
"""
Load word embedding file with predefined vocabulary
Args:
fin (File): File object to read. File should be open for reading ascii.
vocab (dict): Mapping from words (``bytes``) to vector indices
(``int``).
dtype (numpy... | [
"def",
"load_with_vocab",
"(",
"fin",
",",
"vocab",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
":",
"arr",
"=",
"None",
"for",
"line",
"in",
"fin",
":",
"try",
":",
"token",
",",
"v",
"=",
"_parse_line",
"(",
"line",
",",
"dtype",
")",
"except",... | Load word embedding file with predefined vocabulary
Args:
fin (File): File object to read. File should be open for reading ascii.
vocab (dict): Mapping from words (``bytes``) to vector indices
(``int``).
dtype (numpy.dtype): Element data type to use for the array.
Returns:
... | [
"Load",
"word",
"embedding",
"file",
"with",
"predefined",
"vocabulary"
] | train | https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/loader/glove.py#L47-L73 |
koreyou/word_embedding_loader | word_embedding_loader/loader/glove.py | load | def load(fin, dtype=np.float32, max_vocab=None):
"""
Load word embedding file.
Args:
fin (File): File object to read. File should be open for reading ascii.
dtype (numpy.dtype): Element data type to use for the array.
max_vocab (int): Number of vocabulary to read.
Returns:
... | python | def load(fin, dtype=np.float32, max_vocab=None):
"""
Load word embedding file.
Args:
fin (File): File object to read. File should be open for reading ascii.
dtype (numpy.dtype): Element data type to use for the array.
max_vocab (int): Number of vocabulary to read.
Returns:
... | [
"def",
"load",
"(",
"fin",
",",
"dtype",
"=",
"np",
".",
"float32",
",",
"max_vocab",
"=",
"None",
")",
":",
"vocab",
"=",
"{",
"}",
"arr",
"=",
"None",
"i",
"=",
"0",
"for",
"line",
"in",
"fin",
":",
"if",
"max_vocab",
"is",
"not",
"None",
"an... | Load word embedding file.
Args:
fin (File): File object to read. File should be open for reading ascii.
dtype (numpy.dtype): Element data type to use for the array.
max_vocab (int): Number of vocabulary to read.
Returns:
numpy.ndarray: Word embedding representation vectors
... | [
"Load",
"word",
"embedding",
"file",
"."
] | train | https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/loader/glove.py#L76-L111 |
ministryofjustice/money-to-prisoners-common | build_tasks.py | python_dependencies | def python_dependencies(context: Context, extras=None):
"""
Updates python dependencies
"""
with mock.patch('setuptools.setup'):
from setup import install_requires, extras_require
requirements = install_requires.copy()
if extras:
requirements.extend(extras_require[ex... | python | def python_dependencies(context: Context, extras=None):
"""
Updates python dependencies
"""
with mock.patch('setuptools.setup'):
from setup import install_requires, extras_require
requirements = install_requires.copy()
if extras:
requirements.extend(extras_require[ex... | [
"def",
"python_dependencies",
"(",
"context",
":",
"Context",
",",
"extras",
"=",
"None",
")",
":",
"with",
"mock",
".",
"patch",
"(",
"'setuptools.setup'",
")",
":",
"from",
"setup",
"import",
"install_requires",
",",
"extras_require",
"requirements",
"=",
"i... | Updates python dependencies | [
"Updates",
"python",
"dependencies"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/build_tasks.py#L107-L117 |
ministryofjustice/money-to-prisoners-common | build_tasks.py | set_version | def set_version(context: Context, version=None, bump=False):
"""
Updates the version of MTP-common
"""
if bump and version:
raise TaskError('You cannot bump and set a specific version')
if bump:
from mtp_common import VERSION
version = list(VERSION)
version[-1] += 1
... | python | def set_version(context: Context, version=None, bump=False):
"""
Updates the version of MTP-common
"""
if bump and version:
raise TaskError('You cannot bump and set a specific version')
if bump:
from mtp_common import VERSION
version = list(VERSION)
version[-1] += 1
... | [
"def",
"set_version",
"(",
"context",
":",
"Context",
",",
"version",
"=",
"None",
",",
"bump",
"=",
"False",
")",
":",
"if",
"bump",
"and",
"version",
":",
"raise",
"TaskError",
"(",
"'You cannot bump and set a specific version'",
")",
"if",
"bump",
":",
"f... | Updates the version of MTP-common | [
"Updates",
"the",
"version",
"of",
"MTP",
"-",
"common"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/build_tasks.py#L140-L173 |
ministryofjustice/money-to-prisoners-common | build_tasks.py | docs | def docs(context: Context):
"""
Generates static documentation
"""
try:
from sphinx.application import Sphinx
except ImportError:
context.pip_command('install', 'Sphinx')
from sphinx.application import Sphinx
context.shell('cp', 'README.rst', 'docs/README.rst')
app =... | python | def docs(context: Context):
"""
Generates static documentation
"""
try:
from sphinx.application import Sphinx
except ImportError:
context.pip_command('install', 'Sphinx')
from sphinx.application import Sphinx
context.shell('cp', 'README.rst', 'docs/README.rst')
app =... | [
"def",
"docs",
"(",
"context",
":",
"Context",
")",
":",
"try",
":",
"from",
"sphinx",
".",
"application",
"import",
"Sphinx",
"except",
"ImportError",
":",
"context",
".",
"pip_command",
"(",
"'install'",
",",
"'Sphinx'",
")",
"from",
"sphinx",
".",
"appl... | Generates static documentation | [
"Generates",
"static",
"documentation"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/build_tasks.py#L177-L190 |
ministryofjustice/money-to-prisoners-common | build_tasks.py | clean | def clean(context: Context, delete_dependencies: bool = False):
"""
Deletes build outputs
"""
paths = ['docs/build', 'build', 'dist', '.eggs'] + glob.glob('*.egg-info')
context.shell('rm -rf %s' % paths_for_shell(paths))
context.shell('find %s -name "*.pyc" -or -name __pycache__ -delete' % conte... | python | def clean(context: Context, delete_dependencies: bool = False):
"""
Deletes build outputs
"""
paths = ['docs/build', 'build', 'dist', '.eggs'] + glob.glob('*.egg-info')
context.shell('rm -rf %s' % paths_for_shell(paths))
context.shell('find %s -name "*.pyc" -or -name __pycache__ -delete' % conte... | [
"def",
"clean",
"(",
"context",
":",
"Context",
",",
"delete_dependencies",
":",
"bool",
"=",
"False",
")",
":",
"paths",
"=",
"[",
"'docs/build'",
",",
"'build'",
",",
"'dist'",
",",
"'.eggs'",
"]",
"+",
"glob",
".",
"glob",
"(",
"'*.egg-info'",
")",
... | Deletes build outputs | [
"Deletes",
"build",
"outputs"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/build_tasks.py#L202-L213 |
ministryofjustice/money-to-prisoners-common | mtp_common/auth/backends.py | MojBackend.authenticate | def authenticate(self, username=None, password=None):
"""
Returns a valid `MojUser` if the authentication is successful
or None if the credentials were wrong.
"""
data = api_client.authenticate(username, password)
if not data:
return
return User(
... | python | def authenticate(self, username=None, password=None):
"""
Returns a valid `MojUser` if the authentication is successful
or None if the credentials were wrong.
"""
data = api_client.authenticate(username, password)
if not data:
return
return User(
... | [
"def",
"authenticate",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"data",
"=",
"api_client",
".",
"authenticate",
"(",
"username",
",",
"password",
")",
"if",
"not",
"data",
":",
"return",
"return",
"User",
"(",
... | Returns a valid `MojUser` if the authentication is successful
or None if the credentials were wrong. | [
"Returns",
"a",
"valid",
"MojUser",
"if",
"the",
"authentication",
"is",
"successful",
"or",
"None",
"if",
"the",
"credentials",
"were",
"wrong",
"."
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/backends.py#L17-L28 |
ministryofjustice/money-to-prisoners-common | mtp_common/nomis.py | get_client_token | def get_client_token():
"""
Requests and stores the NOMIS API client token from mtp-api
"""
if getattr(settings, 'NOMIS_API_CLIENT_TOKEN', ''):
return settings.NOMIS_API_CLIENT_TOKEN
global client_token
if not client_token or client_token['expires'] and client_token['expires'] - now() < ... | python | def get_client_token():
"""
Requests and stores the NOMIS API client token from mtp-api
"""
if getattr(settings, 'NOMIS_API_CLIENT_TOKEN', ''):
return settings.NOMIS_API_CLIENT_TOKEN
global client_token
if not client_token or client_token['expires'] and client_token['expires'] - now() < ... | [
"def",
"get_client_token",
"(",
")",
":",
"if",
"getattr",
"(",
"settings",
",",
"'NOMIS_API_CLIENT_TOKEN'",
",",
"''",
")",
":",
"return",
"settings",
".",
"NOMIS_API_CLIENT_TOKEN",
"global",
"client_token",
"if",
"not",
"client_token",
"or",
"client_token",
"[",... | Requests and stores the NOMIS API client token from mtp-api | [
"Requests",
"and",
"stores",
"the",
"NOMIS",
"API",
"client",
"token",
"from",
"mtp",
"-",
"api"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/nomis.py#L29-L53 |
chrisseto/django-include | include/query.py | IncludeQuerySet.include | def include(self, *fields, **kwargs):
"""
Return a new QuerySet instance that will include related objects.
If fields are specified, they must be non-hidden relationships.
If select_related(None) is called, clear the list.
"""
clone = self._clone()
# Preserve t... | python | def include(self, *fields, **kwargs):
"""
Return a new QuerySet instance that will include related objects.
If fields are specified, they must be non-hidden relationships.
If select_related(None) is called, clear the list.
"""
clone = self._clone()
# Preserve t... | [
"def",
"include",
"(",
"self",
",",
"*",
"fields",
",",
"*",
"*",
"kwargs",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"# Preserve the stickiness of related querysets",
"# NOTE: by default _clone will clear this attribute",
"# .include does not modify the ac... | Return a new QuerySet instance that will include related objects.
If fields are specified, they must be non-hidden relationships.
If select_related(None) is called, clear the list. | [
"Return",
"a",
"new",
"QuerySet",
"instance",
"that",
"will",
"include",
"related",
"objects",
"."
] | train | https://github.com/chrisseto/django-include/blob/0cf095f9e827d8be406c16f2ec0c17b6c4c301ba/include/query.py#L93-L135 |
harvard-nrg/yaxil | yaxil/dicom/__init__.py | search | def search(d, recursive=True, store_meta=True):
'''
Search for DICOM files within a given directory and receive back a
dictionary of {StudyInstanceUID: {SeriesNumber: [files]}}
Example usage::
>>> import yaxil.dicom
>>> yaxil.dicom.search("~/dicoms").keys()
['1.2.340.500067... | python | def search(d, recursive=True, store_meta=True):
'''
Search for DICOM files within a given directory and receive back a
dictionary of {StudyInstanceUID: {SeriesNumber: [files]}}
Example usage::
>>> import yaxil.dicom
>>> yaxil.dicom.search("~/dicoms").keys()
['1.2.340.500067... | [
"def",
"search",
"(",
"d",
",",
"recursive",
"=",
"True",
",",
"store_meta",
"=",
"True",
")",
":",
"# say this fast three times",
"scans",
"=",
"col",
".",
"defaultdict",
"(",
"lambda",
":",
"col",
".",
"defaultdict",
"(",
"lambda",
":",
"col",
".",
"de... | Search for DICOM files within a given directory and receive back a
dictionary of {StudyInstanceUID: {SeriesNumber: [files]}}
Example usage::
>>> import yaxil.dicom
>>> yaxil.dicom.search("~/dicoms").keys()
['1.2.340.500067.8.9.10.11012.13000001401516017181900000200']
:... | [
"Search",
"for",
"DICOM",
"files",
"within",
"a",
"given",
"directory",
"and",
"receive",
"back",
"a",
"dictionary",
"of",
"{",
"StudyInstanceUID",
":",
"{",
"SeriesNumber",
":",
"[",
"files",
"]",
"}}",
"Example",
"usage",
"::",
">>>",
"import",
"yaxil",
... | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/dicom/__init__.py#L14-L46 |
ministryofjustice/money-to-prisoners-common | mtp_common/forms/__init__.py | replace_default_error_messages | def replace_default_error_messages():
"""
Replace Django's generic error messages with MTP-specific versions
NB: avoid trailing full stops visually, they are added for screen readers in templates
"""
forms.Field.default_error_messages['required'] = _('This field is required')
forms.CharField.def... | python | def replace_default_error_messages():
"""
Replace Django's generic error messages with MTP-specific versions
NB: avoid trailing full stops visually, they are added for screen readers in templates
"""
forms.Field.default_error_messages['required'] = _('This field is required')
forms.CharField.def... | [
"def",
"replace_default_error_messages",
"(",
")",
":",
"forms",
".",
"Field",
".",
"default_error_messages",
"[",
"'required'",
"]",
"=",
"_",
"(",
"'This field is required'",
")",
"forms",
".",
"CharField",
".",
"default_error_messages",
"[",
"'min_length'",
"]",
... | Replace Django's generic error messages with MTP-specific versions
NB: avoid trailing full stops visually, they are added for screen readers in templates | [
"Replace",
"Django",
"s",
"generic",
"error",
"messages",
"with",
"MTP",
"-",
"specific",
"versions",
"NB",
":",
"avoid",
"trailing",
"full",
"stops",
"visually",
"they",
"are",
"added",
"for",
"screen",
"readers",
"in",
"templates"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/forms/__init__.py#L6-L27 |
koreyou/word_embedding_loader | word_embedding_loader/loader/vocab.py | load_vocab | def load_vocab(fin):
"""
Load vocabulary from vocab file created by word2vec with
``-save-vocab <file>`` option.
Args:
fin (File): File-like object to read from.
encoding (bytes): Encoding of the input file as defined in ``codecs``
module of Python standard library.
... | python | def load_vocab(fin):
"""
Load vocabulary from vocab file created by word2vec with
``-save-vocab <file>`` option.
Args:
fin (File): File-like object to read from.
encoding (bytes): Encoding of the input file as defined in ``codecs``
module of Python standard library.
... | [
"def",
"load_vocab",
"(",
"fin",
")",
":",
"vocab",
"=",
"OrderedDict",
"(",
")",
"for",
"line",
"in",
"fin",
":",
"v",
",",
"c",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"vocab",
"[",
"v",
"]",
"=",
"int",
"(",
"c",
")",
... | Load vocabulary from vocab file created by word2vec with
``-save-vocab <file>`` option.
Args:
fin (File): File-like object to read from.
encoding (bytes): Encoding of the input file as defined in ``codecs``
module of Python standard library.
errors (bytes): Set the error han... | [
"Load",
"vocabulary",
"from",
"vocab",
"file",
"created",
"by",
"word2vec",
"with",
"-",
"save",
"-",
"vocab",
"<file",
">",
"option",
"."
] | train | https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/loader/vocab.py#L8-L30 |
ministryofjustice/money-to-prisoners-common | mtp_common/auth/api_client.py | authenticate | def authenticate(username, password):
"""
Returns:
a dict with:
pk: the pk of the user
token: dict containing all the data from the api
(access_token, refresh_token, expires_at etc.)
user_data: dict containing user data such as
first_na... | python | def authenticate(username, password):
"""
Returns:
a dict with:
pk: the pk of the user
token: dict containing all the data from the api
(access_token, refresh_token, expires_at etc.)
user_data: dict containing user data such as
first_na... | [
"def",
"authenticate",
"(",
"username",
",",
"password",
")",
":",
"session",
"=",
"MoJOAuth2Session",
"(",
"client",
"=",
"LegacyApplicationClient",
"(",
"client_id",
"=",
"settings",
".",
"API_CLIENT_ID",
")",
")",
"token",
"=",
"session",
".",
"fetch_token",
... | Returns:
a dict with:
pk: the pk of the user
token: dict containing all the data from the api
(access_token, refresh_token, expires_at etc.)
user_data: dict containing user data such as
first_name, last_name etc.
if the authentication s... | [
"Returns",
":",
"a",
"dict",
"with",
":",
"pk",
":",
"the",
"pk",
"of",
"the",
"user",
"token",
":",
"dict",
"containing",
"all",
"the",
"data",
"from",
"the",
"api",
"(",
"access_token",
"refresh_token",
"expires_at",
"etc",
".",
")",
"user_data",
":",
... | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/api_client.py#L84-L117 |
ministryofjustice/money-to-prisoners-common | mtp_common/auth/api_client.py | revoke_token | def revoke_token(access_token):
"""
Instructs the API to delete this access token and associated refresh token
"""
response = requests.post(
get_revoke_token_url(),
data={
'token': access_token,
'client_id': settings.API_CLIENT_ID,
'client_secret': set... | python | def revoke_token(access_token):
"""
Instructs the API to delete this access token and associated refresh token
"""
response = requests.post(
get_revoke_token_url(),
data={
'token': access_token,
'client_id': settings.API_CLIENT_ID,
'client_secret': set... | [
"def",
"revoke_token",
"(",
"access_token",
")",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"get_revoke_token_url",
"(",
")",
",",
"data",
"=",
"{",
"'token'",
":",
"access_token",
",",
"'client_id'",
":",
"settings",
".",
"API_CLIENT_ID",
",",
"'cl... | Instructs the API to delete this access token and associated refresh token | [
"Instructs",
"the",
"API",
"to",
"delete",
"this",
"access",
"token",
"and",
"associated",
"refresh",
"token"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/api_client.py#L120-L133 |
ministryofjustice/money-to-prisoners-common | mtp_common/auth/api_client.py | get_authenticated_api_session | def get_authenticated_api_session(username, password):
"""
:return: an authenticated api session
"""
session = MoJOAuth2Session(
client=LegacyApplicationClient(
client_id=settings.API_CLIENT_ID
)
)
session.fetch_token(
token_url=get_request_token_url(),
... | python | def get_authenticated_api_session(username, password):
"""
:return: an authenticated api session
"""
session = MoJOAuth2Session(
client=LegacyApplicationClient(
client_id=settings.API_CLIENT_ID
)
)
session.fetch_token(
token_url=get_request_token_url(),
... | [
"def",
"get_authenticated_api_session",
"(",
"username",
",",
"password",
")",
":",
"session",
"=",
"MoJOAuth2Session",
"(",
"client",
"=",
"LegacyApplicationClient",
"(",
"client_id",
"=",
"settings",
".",
"API_CLIENT_ID",
")",
")",
"session",
".",
"fetch_token",
... | :return: an authenticated api session | [
":",
"return",
":",
"an",
"authenticated",
"api",
"session"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/api_client.py#L162-L180 |
harvard-nrg/yaxil | yaxil/functools/__init__.py | lru_cache | def lru_cache(fn):
'''
Memoization wrapper that can handle function attributes, mutable arguments,
and can be applied either as a decorator or at runtime.
:param fn: Function
:type fn: function
:returns: Memoized function
:rtype: function
'''
@wraps(fn)
def memoized_fn(*args):
... | python | def lru_cache(fn):
'''
Memoization wrapper that can handle function attributes, mutable arguments,
and can be applied either as a decorator or at runtime.
:param fn: Function
:type fn: function
:returns: Memoized function
:rtype: function
'''
@wraps(fn)
def memoized_fn(*args):
... | [
"def",
"lru_cache",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"memoized_fn",
"(",
"*",
"args",
")",
":",
"pargs",
"=",
"pickle",
".",
"dumps",
"(",
"args",
")",
"if",
"pargs",
"not",
"in",
"memoized_fn",
".",
"cache",
":",
"memoized... | Memoization wrapper that can handle function attributes, mutable arguments,
and can be applied either as a decorator or at runtime.
:param fn: Function
:type fn: function
:returns: Memoized function
:rtype: function | [
"Memoization",
"wrapper",
"that",
"can",
"handle",
"function",
"attributes",
"mutable",
"arguments",
"and",
"can",
"be",
"applied",
"either",
"as",
"a",
"decorator",
"or",
"at",
"runtime",
"."
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/functools/__init__.py#L4-L25 |
koreyou/word_embedding_loader | word_embedding_loader/loader/word2vec_text.py | check_valid | def check_valid(line0, line1):
"""
Check :func:`word_embedding_loader.loader.glove.check_valid` for the API.
"""
data0 = line0.split(b' ')
if len(data0) != 2:
return False
# check if data0 is int values
try:
map(int, data0)
_parse_line(line1, float)
except:
... | python | def check_valid(line0, line1):
"""
Check :func:`word_embedding_loader.loader.glove.check_valid` for the API.
"""
data0 = line0.split(b' ')
if len(data0) != 2:
return False
# check if data0 is int values
try:
map(int, data0)
_parse_line(line1, float)
except:
... | [
"def",
"check_valid",
"(",
"line0",
",",
"line1",
")",
":",
"data0",
"=",
"line0",
".",
"split",
"(",
"b' '",
")",
"if",
"len",
"(",
"data0",
")",
"!=",
"2",
":",
"return",
"False",
"# check if data0 is int values",
"try",
":",
"map",
"(",
"int",
",",
... | Check :func:`word_embedding_loader.loader.glove.check_valid` for the API. | [
"Check",
":",
"func",
":",
"word_embedding_loader",
".",
"loader",
".",
"glove",
".",
"check_valid",
"for",
"the",
"API",
"."
] | train | https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/loader/word2vec_text.py#L17-L30 |
koreyou/word_embedding_loader | word_embedding_loader/loader/word2vec_text.py | load_with_vocab | def load_with_vocab(fin, vocab, dtype=np.float32):
"""
Refer to :func:`word_embedding_loader.loader.glove.load_with_vocab` for the API.
"""
line = next(fin)
data = line.strip().split(b' ')
assert len(data) == 2
size = int(data[1])
arr = np.empty((len(vocab), size), dtype=dtype)
arr.f... | python | def load_with_vocab(fin, vocab, dtype=np.float32):
"""
Refer to :func:`word_embedding_loader.loader.glove.load_with_vocab` for the API.
"""
line = next(fin)
data = line.strip().split(b' ')
assert len(data) == 2
size = int(data[1])
arr = np.empty((len(vocab), size), dtype=dtype)
arr.f... | [
"def",
"load_with_vocab",
"(",
"fin",
",",
"vocab",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
":",
"line",
"=",
"next",
"(",
"fin",
")",
"data",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"b' '",
")",
"assert",
"len",
"(",
"data"... | Refer to :func:`word_embedding_loader.loader.glove.load_with_vocab` for the API. | [
"Refer",
"to",
":",
"func",
":",
"word_embedding_loader",
".",
"loader",
".",
"glove",
".",
"load_with_vocab",
"for",
"the",
"API",
"."
] | train | https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/loader/word2vec_text.py#L52-L68 |
koreyou/word_embedding_loader | word_embedding_loader/loader/word2vec_text.py | load | def load(fin, dtype=np.float32, max_vocab=None):
"""
Refer to :func:`word_embedding_loader.loader.glove.load` for the API.
"""
vocab = {}
line = next(fin)
data = line.strip().split(b' ')
assert len(data) == 2
words = int(data[0])
if max_vocab is not None:
words = min(max_voca... | python | def load(fin, dtype=np.float32, max_vocab=None):
"""
Refer to :func:`word_embedding_loader.loader.glove.load` for the API.
"""
vocab = {}
line = next(fin)
data = line.strip().split(b' ')
assert len(data) == 2
words = int(data[0])
if max_vocab is not None:
words = min(max_voca... | [
"def",
"load",
"(",
"fin",
",",
"dtype",
"=",
"np",
".",
"float32",
",",
"max_vocab",
"=",
"None",
")",
":",
"vocab",
"=",
"{",
"}",
"line",
"=",
"next",
"(",
"fin",
")",
"data",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"b' '",
... | Refer to :func:`word_embedding_loader.loader.glove.load` for the API. | [
"Refer",
"to",
":",
"func",
":",
"word_embedding_loader",
".",
"loader",
".",
"glove",
".",
"load",
"for",
"the",
"API",
"."
] | train | https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/loader/word2vec_text.py#L71-L103 |
harvard-nrg/yaxil | yaxil/__init__.py | auth | def auth(alias=None, url=None, cfg="~/.xnat_auth"):
'''
Read connection details from an xnat_auth XML file
Example:
>>> import yaxil
>>> auth = yaxil.auth('xnatastic')
>>> auth.url, auth.username, auth.password
('https://www.xnatastic.org/', 'username', '********')
:par... | python | def auth(alias=None, url=None, cfg="~/.xnat_auth"):
'''
Read connection details from an xnat_auth XML file
Example:
>>> import yaxil
>>> auth = yaxil.auth('xnatastic')
>>> auth.url, auth.username, auth.password
('https://www.xnatastic.org/', 'username', '********')
:par... | [
"def",
"auth",
"(",
"alias",
"=",
"None",
",",
"url",
"=",
"None",
",",
"cfg",
"=",
"\"~/.xnat_auth\"",
")",
":",
"if",
"not",
"alias",
"and",
"not",
"url",
":",
"raise",
"ValueError",
"(",
"'you must provide an alias or url argument'",
")",
"if",
"alias",
... | Read connection details from an xnat_auth XML file
Example:
>>> import yaxil
>>> auth = yaxil.auth('xnatastic')
>>> auth.url, auth.username, auth.password
('https://www.xnatastic.org/', 'username', '********')
:param alias: XNAT alias
:type alias: str
:param url: XNAT U... | [
"Read",
"connection",
"details",
"from",
"an",
"xnat_auth",
"XML",
"file"
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L80-L138 |
harvard-nrg/yaxil | yaxil/__init__.py | subjects | def subjects(auth, label=None, project=None):
'''
Retrieve Subject tuples for subjects returned by this function.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.subjects(auth, 'AB1234C')
Subject(uri=u'/data/experi... | python | def subjects(auth, label=None, project=None):
'''
Retrieve Subject tuples for subjects returned by this function.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.subjects(auth, 'AB1234C')
Subject(uri=u'/data/experi... | [
"def",
"subjects",
"(",
"auth",
",",
"label",
"=",
"None",
",",
"project",
"=",
"None",
")",
":",
"url",
"=",
"'{0}/data/subjects'",
".",
"format",
"(",
"auth",
".",
"url",
".",
"rstrip",
"(",
"'/'",
")",
")",
"logger",
".",
"debug",
"(",
"'issuing h... | Retrieve Subject tuples for subjects returned by this function.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.subjects(auth, 'AB1234C')
Subject(uri=u'/data/experiments/XNAT_S0001', label=u'AB1234C', id=u'XNAT_S0001',
... | [
"Retrieve",
"Subject",
"tuples",
"for",
"subjects",
"returned",
"by",
"this",
"function",
".",
"Example",
":",
">>>",
"import",
"yaxil",
">>>",
"auth",
"=",
"yaxil",
".",
"XnatAuth",
"(",
"url",
"=",
"...",
"username",
"=",
"...",
"password",
"=",
"...",
... | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L151-L205 |
harvard-nrg/yaxil | yaxil/__init__.py | experiments | def experiments(auth, label=None, project=None, subject=None):
'''
Retrieve Experiment tuples for experiments returned by this function.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.experiment(auth, 'AB1234C')
E... | python | def experiments(auth, label=None, project=None, subject=None):
'''
Retrieve Experiment tuples for experiments returned by this function.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.experiment(auth, 'AB1234C')
E... | [
"def",
"experiments",
"(",
"auth",
",",
"label",
"=",
"None",
",",
"project",
"=",
"None",
",",
"subject",
"=",
"None",
")",
":",
"if",
"subject",
"and",
"(",
"label",
"or",
"project",
")",
":",
"raise",
"ValueError",
"(",
"'cannot provide subject with lab... | Retrieve Experiment tuples for experiments returned by this function.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.experiment(auth, 'AB1234C')
Experiment(uri=u'/data/experiments/XNAT_E0001', label=u'AB1234C', id=u'XNAT_... | [
"Retrieve",
"Experiment",
"tuples",
"for",
"experiments",
"returned",
"by",
"this",
"function",
".",
"Example",
":",
">>>",
"import",
"yaxil",
">>>",
"auth",
"=",
"yaxil",
".",
"XnatAuth",
"(",
"url",
"=",
"...",
"username",
"=",
"...",
"password",
"=",
".... | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L223-L289 |
harvard-nrg/yaxil | yaxil/__init__.py | accession | def accession(auth, label, project=None):
'''
Get the Accession ID for any Experiment label.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.accession(auth, 'AB1234C')
u'XNAT_E00001'
:param auth: XNAT authenticati... | python | def accession(auth, label, project=None):
'''
Get the Accession ID for any Experiment label.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.accession(auth, 'AB1234C')
u'XNAT_E00001'
:param auth: XNAT authenticati... | [
"def",
"accession",
"(",
"auth",
",",
"label",
",",
"project",
"=",
"None",
")",
":",
"return",
"list",
"(",
"experiments",
"(",
"auth",
",",
"label",
",",
"project",
")",
")",
"[",
"0",
"]",
".",
"id"
] | Get the Accession ID for any Experiment label.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.accession(auth, 'AB1234C')
u'XNAT_E00001'
:param auth: XNAT authentication
:type auth: :mod:`yaxil.XnatAuth`
:param la... | [
"Get",
"the",
"Accession",
"ID",
"for",
"any",
"Experiment",
"label",
"."
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L292-L311 |
harvard-nrg/yaxil | yaxil/__init__.py | download | def download(auth, label, scan_ids=None, project=None, aid=None,
out_dir='.', in_mem=True, progress=False, attempts=1):
'''
Download scan data from XNAT.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.downloa... | python | def download(auth, label, scan_ids=None, project=None, aid=None,
out_dir='.', in_mem=True, progress=False, attempts=1):
'''
Download scan data from XNAT.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.downloa... | [
"def",
"download",
"(",
"auth",
",",
"label",
",",
"scan_ids",
"=",
"None",
",",
"project",
"=",
"None",
",",
"aid",
"=",
"None",
",",
"out_dir",
"=",
"'.'",
",",
"in_mem",
"=",
"True",
",",
"progress",
"=",
"False",
",",
"attempts",
"=",
"1",
")",... | Download scan data from XNAT.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.download(auth, 'AB1234C', ['1', '2'], out_dir='./data')
:param auth: XNAT authentication object
:type auth: :mod:`yaxil.XnatAuth`
:param la... | [
"Download",
"scan",
"data",
"from",
"XNAT",
".",
"Example",
":",
">>>",
"import",
"yaxil",
">>>",
"auth",
"=",
"yaxil",
".",
"XnatAuth",
"(",
"url",
"=",
"...",
"username",
"=",
"...",
"password",
"=",
"...",
")",
">>>",
"yaxil",
".",
"download",
"(",
... | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L322-L412 |
harvard-nrg/yaxil | yaxil/__init__.py | extract | def extract(zf, content, out_dir='.'):
'''
Extracting a Java 1.6 XNAT ZIP archive in Python.
:param zf: ZipFile object
:type zf: zipfile.ZipFile
:param out_dir: Output directory
:type out_dir: str
'''
previous_header_offset = 0
compensation = Namespace(value=2**32, factor=0)
for... | python | def extract(zf, content, out_dir='.'):
'''
Extracting a Java 1.6 XNAT ZIP archive in Python.
:param zf: ZipFile object
:type zf: zipfile.ZipFile
:param out_dir: Output directory
:type out_dir: str
'''
previous_header_offset = 0
compensation = Namespace(value=2**32, factor=0)
for... | [
"def",
"extract",
"(",
"zf",
",",
"content",
",",
"out_dir",
"=",
"'.'",
")",
":",
"previous_header_offset",
"=",
"0",
"compensation",
"=",
"Namespace",
"(",
"value",
"=",
"2",
"**",
"32",
",",
"factor",
"=",
"0",
")",
"for",
"i",
",",
"member",
"in"... | Extracting a Java 1.6 XNAT ZIP archive in Python.
:param zf: ZipFile object
:type zf: zipfile.ZipFile
:param out_dir: Output directory
:type out_dir: str | [
"Extracting",
"a",
"Java",
"1",
".",
"6",
"XNAT",
"ZIP",
"archive",
"in",
"Python",
"."
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L414-L464 |
harvard-nrg/yaxil | yaxil/__init__.py | __quick_validate | def __quick_validate(r, check=('ResultSet', 'Result', 'totalRecords')):
'''
Quick validation of JSON result set returned by XNAT.
:param r: Result set data in JSON format
:type r: dict
:param check: Fields to check
:type check: tuple
:returns: Result set is valid
:rtype: bool
'''
... | python | def __quick_validate(r, check=('ResultSet', 'Result', 'totalRecords')):
'''
Quick validation of JSON result set returned by XNAT.
:param r: Result set data in JSON format
:type r: dict
:param check: Fields to check
:type check: tuple
:returns: Result set is valid
:rtype: bool
'''
... | [
"def",
"__quick_validate",
"(",
"r",
",",
"check",
"=",
"(",
"'ResultSet'",
",",
"'Result'",
",",
"'totalRecords'",
")",
")",
":",
"if",
"'ResultSet'",
"in",
"check",
"and",
"'ResultSet'",
"not",
"in",
"r",
":",
"raise",
"ResultSetError",
"(",
"'no ResultSet... | Quick validation of JSON result set returned by XNAT.
:param r: Result set data in JSON format
:type r: dict
:param check: Fields to check
:type check: tuple
:returns: Result set is valid
:rtype: bool | [
"Quick",
"validation",
"of",
"JSON",
"result",
"set",
"returned",
"by",
"XNAT",
"."
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L466-L483 |
harvard-nrg/yaxil | yaxil/__init__.py | scansearch | def scansearch(auth, label, filt, project=None, aid=None):
'''
Search for scans by supplying a set of SQL-based conditionals.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> query = {
... 'eor1': "note LIKE %EOR1%",
... | python | def scansearch(auth, label, filt, project=None, aid=None):
'''
Search for scans by supplying a set of SQL-based conditionals.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> query = {
... 'eor1': "note LIKE %EOR1%",
... | [
"def",
"scansearch",
"(",
"auth",
",",
"label",
",",
"filt",
",",
"project",
"=",
"None",
",",
"aid",
"=",
"None",
")",
":",
"if",
"not",
"aid",
":",
"aid",
"=",
"accession",
"(",
"auth",
",",
"label",
",",
"project",
")",
"# get scans for accession as... | Search for scans by supplying a set of SQL-based conditionals.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> query = {
... 'eor1': "note LIKE %EOR1%",
... 'eor2': "note LIKE %EOR2%",
... 'mpr': "series_descr... | [
"Search",
"for",
"scans",
"by",
"supplying",
"a",
"set",
"of",
"SQL",
"-",
"based",
"conditionals",
"."
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L485-L543 |
harvard-nrg/yaxil | yaxil/__init__.py | scans | def scans(auth, label=None, scan_ids=None, project=None, experiment=None):
'''
Get scan information for a MR Session as a sequence of dictionaries.
Example:
>>> import yaxil
>>> import json
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> for scan in ... | python | def scans(auth, label=None, scan_ids=None, project=None, experiment=None):
'''
Get scan information for a MR Session as a sequence of dictionaries.
Example:
>>> import yaxil
>>> import json
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> for scan in ... | [
"def",
"scans",
"(",
"auth",
",",
"label",
"=",
"None",
",",
"scan_ids",
"=",
"None",
",",
"project",
"=",
"None",
",",
"experiment",
"=",
"None",
")",
":",
"if",
"experiment",
"and",
"(",
"label",
"or",
"project",
")",
":",
"raise",
"ValueError",
"(... | Get scan information for a MR Session as a sequence of dictionaries.
Example:
>>> import yaxil
>>> import json
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> for scan in yaxil.scans2(auth, 'AB1234C'):
... print(json.dumps(scan, indent=2))
:... | [
"Get",
"scan",
"information",
"for",
"a",
"MR",
"Session",
"as",
"a",
"sequence",
"of",
"dictionaries",
"."
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L545-L586 |
harvard-nrg/yaxil | yaxil/__init__.py | extendedboldqc | def extendedboldqc(auth, label, scan_ids=None, project=None, aid=None):
'''
Get ExtendedBOLDQC data as a sequence of dictionaries.
Example:
>>> import yaxil
>>> import json
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> for eqc in yaxil.extendedbold... | python | def extendedboldqc(auth, label, scan_ids=None, project=None, aid=None):
'''
Get ExtendedBOLDQC data as a sequence of dictionaries.
Example:
>>> import yaxil
>>> import json
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> for eqc in yaxil.extendedbold... | [
"def",
"extendedboldqc",
"(",
"auth",
",",
"label",
",",
"scan_ids",
"=",
"None",
",",
"project",
"=",
"None",
",",
"aid",
"=",
"None",
")",
":",
"if",
"not",
"aid",
":",
"aid",
"=",
"accession",
"(",
"auth",
",",
"label",
",",
"project",
")",
"pat... | Get ExtendedBOLDQC data as a sequence of dictionaries.
Example:
>>> import yaxil
>>> import json
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> for eqc in yaxil.extendedboldqc2(auth, 'AB1234C')
... print(json.dumps(eqc, indent=2))
:param au... | [
"Get",
"ExtendedBOLDQC",
"data",
"as",
"a",
"sequence",
"of",
"dictionaries",
"."
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L626-L666 |
harvard-nrg/yaxil | yaxil/__init__.py | _get | def _get(auth, path, fmt, autobox=True, params=None):
'''
Issue a GET request to the XNAT REST API and box the response content.
Example:
>>> import yaxil
>>> from yaxil import Format
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.get(auth... | python | def _get(auth, path, fmt, autobox=True, params=None):
'''
Issue a GET request to the XNAT REST API and box the response content.
Example:
>>> import yaxil
>>> from yaxil import Format
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.get(auth... | [
"def",
"_get",
"(",
"auth",
",",
"path",
",",
"fmt",
",",
"autobox",
"=",
"True",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"url",
"=",
"\"%s/%s\"",
"%",
"(",
"auth",
".",
"url",
".",
"rstrip",
"... | Issue a GET request to the XNAT REST API and box the response content.
Example:
>>> import yaxil
>>> from yaxil import Format
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.get(auth, '/data/experiments', Format.JSON)
:param auth: XNAT authent... | [
"Issue",
"a",
"GET",
"request",
"to",
"the",
"XNAT",
"REST",
"API",
"and",
"box",
"the",
"response",
"content",
".",
"Example",
":",
">>>",
"import",
"yaxil",
">>>",
"from",
"yaxil",
"import",
"Format",
">>>",
"auth",
"=",
"yaxil",
".",
"XnatAuth",
"(",
... | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L739-L776 |
harvard-nrg/yaxil | yaxil/__init__.py | _autobox | def _autobox(content, format):
'''
Autobox response content.
:param content: Response content
:type content: str
:param format: Format to return
:type format: `yaxil.Format`
:returns: Autoboxed content
:rtype: dict|xml.etree.ElementTree.Element|csvreader
'''
if format == Format.... | python | def _autobox(content, format):
'''
Autobox response content.
:param content: Response content
:type content: str
:param format: Format to return
:type format: `yaxil.Format`
:returns: Autoboxed content
:rtype: dict|xml.etree.ElementTree.Element|csvreader
'''
if format == Format.... | [
"def",
"_autobox",
"(",
"content",
",",
"format",
")",
":",
"if",
"format",
"==",
"Format",
".",
"JSON",
":",
"return",
"json",
".",
"loads",
"(",
"content",
")",
"elif",
"format",
"==",
"Format",
".",
"XML",
":",
"return",
"etree",
".",
"fromstring",
... | Autobox response content.
:param content: Response content
:type content: str
:param format: Format to return
:type format: `yaxil.Format`
:returns: Autoboxed content
:rtype: dict|xml.etree.ElementTree.Element|csvreader | [
"Autobox",
"response",
"content",
"."
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L778-L810 |
harvard-nrg/yaxil | yaxil/__init__.py | has | def has(auth, xsitype, project=None):
'''
Test if a project contains any items of a particular xsi:type.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.has(auth, 'neuroinfo:extendedboldqc', project='MyProject')
:param au... | python | def has(auth, xsitype, project=None):
'''
Test if a project contains any items of a particular xsi:type.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.has(auth, 'neuroinfo:extendedboldqc', project='MyProject')
:param au... | [
"def",
"has",
"(",
"auth",
",",
"xsitype",
",",
"project",
"=",
"None",
")",
":",
"path",
"=",
"\"/data/experiments\"",
"params",
"=",
"{",
"\"xsiType\"",
":",
"xsitype",
",",
"\"columns\"",
":",
"'ID'",
"}",
"if",
"project",
":",
"params",
"[",
"\"proje... | Test if a project contains any items of a particular xsi:type.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.has(auth, 'neuroinfo:extendedboldqc', project='MyProject')
:param auth: XNAT authentication
:type auth: :mod:`yaxi... | [
"Test",
"if",
"a",
"project",
"contains",
"any",
"items",
"of",
"a",
"particular",
"xsi",
":",
"type",
"."
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L812-L844 |
ministryofjustice/money-to-prisoners-common | mtp_common/auth/middleware.py | get_user | def get_user(request):
"""
Returns a cached copy of the user if it exists or calls `auth_get_user`
otherwise.
"""
if not hasattr(request, '_cached_user'):
request._cached_user = auth_get_user(request)
return request._cached_user | python | def get_user(request):
"""
Returns a cached copy of the user if it exists or calls `auth_get_user`
otherwise.
"""
if not hasattr(request, '_cached_user'):
request._cached_user = auth_get_user(request)
return request._cached_user | [
"def",
"get_user",
"(",
"request",
")",
":",
"if",
"not",
"hasattr",
"(",
"request",
",",
"'_cached_user'",
")",
":",
"request",
".",
"_cached_user",
"=",
"auth_get_user",
"(",
"request",
")",
"return",
"request",
".",
"_cached_user"
] | Returns a cached copy of the user if it exists or calls `auth_get_user`
otherwise. | [
"Returns",
"a",
"cached",
"copy",
"of",
"the",
"user",
"if",
"it",
"exists",
"or",
"calls",
"auth_get_user",
"otherwise",
"."
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/middleware.py#L11-L18 |
ministryofjustice/money-to-prisoners-common | mtp_common/user_admin/views.py | ensure_compatible_admin | def ensure_compatible_admin(view):
"""
Ensures that the user is in exactly one role.
Other checks could be added, such as requiring one prison if in prison-clerk role.
"""
def wrapper(request, *args, **kwargs):
user_roles = request.user.user_data.get('roles', [])
if len(user_roles) ... | python | def ensure_compatible_admin(view):
"""
Ensures that the user is in exactly one role.
Other checks could be added, such as requiring one prison if in prison-clerk role.
"""
def wrapper(request, *args, **kwargs):
user_roles = request.user.user_data.get('roles', [])
if len(user_roles) ... | [
"def",
"ensure_compatible_admin",
"(",
"view",
")",
":",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"user_roles",
"=",
"request",
".",
"user",
".",
"user_data",
".",
"get",
"(",
"'roles'",
",",
"[",
"]",
")... | Ensures that the user is in exactly one role.
Other checks could be added, such as requiring one prison if in prison-clerk role. | [
"Ensures",
"that",
"the",
"user",
"is",
"in",
"exactly",
"one",
"role",
".",
"Other",
"checks",
"could",
"be",
"added",
"such",
"as",
"requiring",
"one",
"prison",
"if",
"in",
"prison",
"-",
"clerk",
"role",
"."
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/user_admin/views.py#L31-L47 |
Parsely/birding | src/birding/bolt.py | fault_barrier | def fault_barrier(fn):
"""Method decorator to catch and log errors, then send fail message."""
@functools.wraps(fn)
def process(self, tup):
try:
return fn(self, tup)
except Exception as e:
if isinstance(e, KeyboardInterrupt):
return
print(s... | python | def fault_barrier(fn):
"""Method decorator to catch and log errors, then send fail message."""
@functools.wraps(fn)
def process(self, tup):
try:
return fn(self, tup)
except Exception as e:
if isinstance(e, KeyboardInterrupt):
return
print(s... | [
"def",
"fault_barrier",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"process",
"(",
"self",
",",
"tup",
")",
":",
"try",
":",
"return",
"fn",
"(",
"self",
",",
"tup",
")",
"except",
"Exception",
"as",
"e",
":",
"if... | Method decorator to catch and log errors, then send fail message. | [
"Method",
"decorator",
"to",
"catch",
"and",
"log",
"errors",
"then",
"send",
"fail",
"message",
"."
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/bolt.py#L16-L27 |
Parsely/birding | src/birding/bolt.py | TwitterSearchBolt.initialize | def initialize(self, conf, ctx):
"""Initialization steps:
1. Get :func:`~birding.search.search_manager_from_config`.
2. Prepare to track searched terms as to avoid redundant searches.
"""
self.manager = get_search_manager()
config = get_config()['TwitterSearchBolt']
... | python | def initialize(self, conf, ctx):
"""Initialization steps:
1. Get :func:`~birding.search.search_manager_from_config`.
2. Prepare to track searched terms as to avoid redundant searches.
"""
self.manager = get_search_manager()
config = get_config()['TwitterSearchBolt']
... | [
"def",
"initialize",
"(",
"self",
",",
"conf",
",",
"ctx",
")",
":",
"self",
".",
"manager",
"=",
"get_search_manager",
"(",
")",
"config",
"=",
"get_config",
"(",
")",
"[",
"'TwitterSearchBolt'",
"]",
"self",
".",
"term_shelf",
"=",
"shelf_from_config",
"... | Initialization steps:
1. Get :func:`~birding.search.search_manager_from_config`.
2. Prepare to track searched terms as to avoid redundant searches. | [
"Initialization",
"steps",
":"
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/bolt.py#L37-L45 |
Parsely/birding | src/birding/bolt.py | TwitterSearchBolt.process | def process(self, tup):
"""Process steps:
1. Stream in (term, timestamp).
2. Perform :meth:`~birding.search.SearchManager.search` on term.
3. Emit (term, timestamp, search_result).
"""
term, timestamp = tup.values
if term not in self.term_shelf:
self.... | python | def process(self, tup):
"""Process steps:
1. Stream in (term, timestamp).
2. Perform :meth:`~birding.search.SearchManager.search` on term.
3. Emit (term, timestamp, search_result).
"""
term, timestamp = tup.values
if term not in self.term_shelf:
self.... | [
"def",
"process",
"(",
"self",
",",
"tup",
")",
":",
"term",
",",
"timestamp",
"=",
"tup",
".",
"values",
"if",
"term",
"not",
"in",
"self",
".",
"term_shelf",
":",
"self",
".",
"log",
"(",
"'search: {term}, {timestamp}'",
".",
"format",
"(",
"term",
"... | Process steps:
1. Stream in (term, timestamp).
2. Perform :meth:`~birding.search.SearchManager.search` on term.
3. Emit (term, timestamp, search_result). | [
"Process",
"steps",
":"
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/bolt.py#L48-L62 |
Parsely/birding | src/birding/bolt.py | TwitterLookupBolt.process | def process(self, tup):
"""Process steps:
1. Stream in (term, timestamp, search_result).
2. Perform :meth:`~birding.search.SearchManager.lookup_search_result`.
3. Emit (term, timestamp, lookup_result).
"""
term, timestamp, search_result = tup.values
self.log(
... | python | def process(self, tup):
"""Process steps:
1. Stream in (term, timestamp, search_result).
2. Perform :meth:`~birding.search.SearchManager.lookup_search_result`.
3. Emit (term, timestamp, lookup_result).
"""
term, timestamp, search_result = tup.values
self.log(
... | [
"def",
"process",
"(",
"self",
",",
"tup",
")",
":",
"term",
",",
"timestamp",
",",
"search_result",
"=",
"tup",
".",
"values",
"self",
".",
"log",
"(",
"'lookup: {term}, {timestamp}'",
".",
"format",
"(",
"term",
"=",
"term",
",",
"timestamp",
"=",
"tim... | Process steps:
1. Stream in (term, timestamp, search_result).
2. Perform :meth:`~birding.search.SearchManager.lookup_search_result`.
3. Emit (term, timestamp, lookup_result). | [
"Process",
"steps",
":"
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/bolt.py#L74-L86 |
Parsely/birding | src/birding/bolt.py | ElasticsearchIndexBolt.initialize | def initialize(self, conf, ctx):
"""Initialization steps:
1. Prepare elasticsearch connection, including details for indexing.
"""
config = get_config()['ElasticsearchIndexBolt']
elasticsearch_class = import_name(config['elasticsearch_class'])
self.es = elasticsearch_cla... | python | def initialize(self, conf, ctx):
"""Initialization steps:
1. Prepare elasticsearch connection, including details for indexing.
"""
config = get_config()['ElasticsearchIndexBolt']
elasticsearch_class = import_name(config['elasticsearch_class'])
self.es = elasticsearch_cla... | [
"def",
"initialize",
"(",
"self",
",",
"conf",
",",
"ctx",
")",
":",
"config",
"=",
"get_config",
"(",
")",
"[",
"'ElasticsearchIndexBolt'",
"]",
"elasticsearch_class",
"=",
"import_name",
"(",
"config",
"[",
"'elasticsearch_class'",
"]",
")",
"self",
".",
"... | Initialization steps:
1. Prepare elasticsearch connection, including details for indexing. | [
"Initialization",
"steps",
":"
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/bolt.py#L90-L99 |
Parsely/birding | src/birding/bolt.py | ElasticsearchIndexBolt.process | def process(self, tup):
"""Process steps:
1. Index third positional value from input to elasticsearch.
"""
self.es.bulk(
self.generate_bulk_body(tup.values[2]),
index=self.index,
doc_type=self.doc_type) | python | def process(self, tup):
"""Process steps:
1. Index third positional value from input to elasticsearch.
"""
self.es.bulk(
self.generate_bulk_body(tup.values[2]),
index=self.index,
doc_type=self.doc_type) | [
"def",
"process",
"(",
"self",
",",
"tup",
")",
":",
"self",
".",
"es",
".",
"bulk",
"(",
"self",
".",
"generate_bulk_body",
"(",
"tup",
".",
"values",
"[",
"2",
"]",
")",
",",
"index",
"=",
"self",
".",
"index",
",",
"doc_type",
"=",
"self",
"."... | Process steps:
1. Index third positional value from input to elasticsearch. | [
"Process",
"steps",
":"
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/bolt.py#L102-L110 |
Parsely/birding | src/birding/bolt.py | ResultTopicBolt.initialize | def initialize(self, conf, ctx):
"""Initialization steps:
1. Connect to Kafka.
2. Prepare Kafka producer for `tweet` topic.
3. Prepare to track tweets published to topic, to avoid redundant data.
"""
config = get_config()['ResultTopicBolt']
kafka_class = import_n... | python | def initialize(self, conf, ctx):
"""Initialization steps:
1. Connect to Kafka.
2. Prepare Kafka producer for `tweet` topic.
3. Prepare to track tweets published to topic, to avoid redundant data.
"""
config = get_config()['ResultTopicBolt']
kafka_class = import_n... | [
"def",
"initialize",
"(",
"self",
",",
"conf",
",",
"ctx",
")",
":",
"config",
"=",
"get_config",
"(",
")",
"[",
"'ResultTopicBolt'",
"]",
"kafka_class",
"=",
"import_name",
"(",
"config",
"[",
"'kafka_class'",
"]",
")",
"self",
".",
"client",
"=",
"kafk... | Initialization steps:
1. Connect to Kafka.
2. Prepare Kafka producer for `tweet` topic.
3. Prepare to track tweets published to topic, to avoid redundant data. | [
"Initialization",
"steps",
":"
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/bolt.py#L120-L134 |
Parsely/birding | src/birding/bolt.py | ResultTopicBolt.process | def process(self, tup):
"""Process steps:
1. Stream third positional value from input into Kafka topic.
"""
status_seq = self.iter_using_shelf(tup.values[2], self.tweet_shelf)
# This could be more efficient by passing the result from twitter
# straight through to the pro... | python | def process(self, tup):
"""Process steps:
1. Stream third positional value from input into Kafka topic.
"""
status_seq = self.iter_using_shelf(tup.values[2], self.tweet_shelf)
# This could be more efficient by passing the result from twitter
# straight through to the pro... | [
"def",
"process",
"(",
"self",
",",
"tup",
")",
":",
"status_seq",
"=",
"self",
".",
"iter_using_shelf",
"(",
"tup",
".",
"values",
"[",
"2",
"]",
",",
"self",
".",
"tweet_shelf",
")",
"# This could be more efficient by passing the result from twitter",
"# straigh... | Process steps:
1. Stream third positional value from input into Kafka topic. | [
"Process",
"steps",
":"
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/bolt.py#L137-L146 |
Parsely/birding | src/birding/search.py | search_manager_from_config | def search_manager_from_config(config, **default_init):
"""Get a `SearchManager` instance dynamically based on config.
`config` is a dictionary containing ``class`` and ``init`` keys as defined
in :mod:`birding.config`.
"""
manager_cls = import_name(config['class'], default_ns='birding.search')
... | python | def search_manager_from_config(config, **default_init):
"""Get a `SearchManager` instance dynamically based on config.
`config` is a dictionary containing ``class`` and ``init`` keys as defined
in :mod:`birding.config`.
"""
manager_cls = import_name(config['class'], default_ns='birding.search')
... | [
"def",
"search_manager_from_config",
"(",
"config",
",",
"*",
"*",
"default_init",
")",
":",
"manager_cls",
"=",
"import_name",
"(",
"config",
"[",
"'class'",
"]",
",",
"default_ns",
"=",
"'birding.search'",
")",
"init",
"=",
"{",
"}",
"init",
".",
"update",... | Get a `SearchManager` instance dynamically based on config.
`config` is a dictionary containing ``class`` and ``init`` keys as defined
in :mod:`birding.config`. | [
"Get",
"a",
"SearchManager",
"instance",
"dynamically",
"based",
"on",
"config",
"."
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/search.py#L8-L19 |
harvard-nrg/yaxil | yaxil/bids/__init__.py | bids_from_config | def bids_from_config(sess, scans_metadata, config, out_base):
'''
Create a BIDS output directory from configuration file
'''
# get session and subject labels from scan metadata
_item = next(iter(scans_metadata))
session,subject = _item['session_label'],_item['subject_label']
# bids and sourc... | python | def bids_from_config(sess, scans_metadata, config, out_base):
'''
Create a BIDS output directory from configuration file
'''
# get session and subject labels from scan metadata
_item = next(iter(scans_metadata))
session,subject = _item['session_label'],_item['subject_label']
# bids and sourc... | [
"def",
"bids_from_config",
"(",
"sess",
",",
"scans_metadata",
",",
"config",
",",
"out_base",
")",
":",
"# get session and subject labels from scan metadata",
"_item",
"=",
"next",
"(",
"iter",
"(",
"scans_metadata",
")",
")",
"session",
",",
"subject",
"=",
"_it... | Create a BIDS output directory from configuration file | [
"Create",
"a",
"BIDS",
"output",
"directory",
"from",
"configuration",
"file"
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/bids/__init__.py#L14-L44 |
harvard-nrg/yaxil | yaxil/bids/__init__.py | proc_anat | def proc_anat(config, args):
'''
Download anatomical data and convert to BIDS
'''
refs = dict()
for scan in iterconfig(config, 'anat'):
ref = scan.get('id', None)
templ = 'sub-${sub}_ses-${ses}'
if 'acquisition' in scan:
templ += '_acq-${acquisition}'
if '... | python | def proc_anat(config, args):
'''
Download anatomical data and convert to BIDS
'''
refs = dict()
for scan in iterconfig(config, 'anat'):
ref = scan.get('id', None)
templ = 'sub-${sub}_ses-${ses}'
if 'acquisition' in scan:
templ += '_acq-${acquisition}'
if '... | [
"def",
"proc_anat",
"(",
"config",
",",
"args",
")",
":",
"refs",
"=",
"dict",
"(",
")",
"for",
"scan",
"in",
"iterconfig",
"(",
"config",
",",
"'anat'",
")",
":",
"ref",
"=",
"scan",
".",
"get",
"(",
"'id'",
",",
"None",
")",
"templ",
"=",
"'sub... | Download anatomical data and convert to BIDS | [
"Download",
"anatomical",
"data",
"and",
"convert",
"to",
"BIDS"
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/bids/__init__.py#L86-L120 |
harvard-nrg/yaxil | yaxil/bids/__init__.py | iterconfig | def iterconfig(config, scan_type):
'''
Iterate over BIDS configuration file
'''
if scan_type in config:
for modality,scans in iter(config[scan_type].items()):
for scan in scans:
scan.update({
'type': scan_type,
'modality': modal... | python | def iterconfig(config, scan_type):
'''
Iterate over BIDS configuration file
'''
if scan_type in config:
for modality,scans in iter(config[scan_type].items()):
for scan in scans:
scan.update({
'type': scan_type,
'modality': modal... | [
"def",
"iterconfig",
"(",
"config",
",",
"scan_type",
")",
":",
"if",
"scan_type",
"in",
"config",
":",
"for",
"modality",
",",
"scans",
"in",
"iter",
"(",
"config",
"[",
"scan_type",
"]",
".",
"items",
"(",
")",
")",
":",
"for",
"scan",
"in",
"scans... | Iterate over BIDS configuration file | [
"Iterate",
"over",
"BIDS",
"configuration",
"file"
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/bids/__init__.py#L181-L192 |
harvard-nrg/yaxil | yaxil/bids/__init__.py | rename_fmapm | def rename_fmapm(bids_base, basename):
'''
Rename magnitude fieldmap file to BIDS specification
'''
files = dict()
for ext in ['nii.gz', 'json']:
for echo in [1, 2]:
fname = '{0}_e{1}.{2}'.format(basename, echo, ext)
src = os.path.join(bids_base, 'fmap', fname)
... | python | def rename_fmapm(bids_base, basename):
'''
Rename magnitude fieldmap file to BIDS specification
'''
files = dict()
for ext in ['nii.gz', 'json']:
for echo in [1, 2]:
fname = '{0}_e{1}.{2}'.format(basename, echo, ext)
src = os.path.join(bids_base, 'fmap', fname)
... | [
"def",
"rename_fmapm",
"(",
"bids_base",
",",
"basename",
")",
":",
"files",
"=",
"dict",
"(",
")",
"for",
"ext",
"in",
"[",
"'nii.gz'",
",",
"'json'",
"]",
":",
"for",
"echo",
"in",
"[",
"1",
",",
"2",
"]",
":",
"fname",
"=",
"'{0}_e{1}.{2}'",
"."... | Rename magnitude fieldmap file to BIDS specification | [
"Rename",
"magnitude",
"fieldmap",
"file",
"to",
"BIDS",
"specification"
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/bids/__init__.py#L194-L211 |
harvard-nrg/yaxil | yaxil/bids/__init__.py | convert | def convert(input, output):
'''
Run dcm2niix on input file
'''
dirname = os.path.dirname(output)
if not os.path.exists(dirname):
os.makedirs(dirname)
basename = os.path.basename(output)
basename = re.sub('.nii(.gz)?', '', basename)
dcm2niix = commons.which('dcm2niix')
cmd = [... | python | def convert(input, output):
'''
Run dcm2niix on input file
'''
dirname = os.path.dirname(output)
if not os.path.exists(dirname):
os.makedirs(dirname)
basename = os.path.basename(output)
basename = re.sub('.nii(.gz)?', '', basename)
dcm2niix = commons.which('dcm2niix')
cmd = [... | [
"def",
"convert",
"(",
"input",
",",
"output",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"output",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"... | Run dcm2niix on input file | [
"Run",
"dcm2niix",
"on",
"input",
"file"
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/bids/__init__.py#L231-L251 |
ministryofjustice/money-to-prisoners-common | mtp_common/api.py | api_errors_to_messages | def api_errors_to_messages(request, error, fallback_text):
"""
Adds messages for each error returned from the MTP apis
Useful for displaying errors when there's no form on the page
:param request: HttpRequest
:param error: HttpClientError
:param fallback_text: fallback error text
"""
try... | python | def api_errors_to_messages(request, error, fallback_text):
"""
Adds messages for each error returned from the MTP apis
Useful for displaying errors when there's no form on the page
:param request: HttpRequest
:param error: HttpClientError
:param fallback_text: fallback error text
"""
try... | [
"def",
"api_errors_to_messages",
"(",
"request",
",",
"error",
",",
"fallback_text",
")",
":",
"try",
":",
"response_body",
"=",
"json",
".",
"loads",
"(",
"error",
".",
"content",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"for",
"field",
",",
"errors",
"... | Adds messages for each error returned from the MTP apis
Useful for displaying errors when there's no form on the page
:param request: HttpRequest
:param error: HttpClientError
:param fallback_text: fallback error text | [
"Adds",
"messages",
"for",
"each",
"error",
"returned",
"from",
"the",
"MTP",
"apis",
"Useful",
"for",
"displaying",
"errors",
"when",
"there",
"s",
"no",
"form",
"on",
"the",
"page",
":",
"param",
"request",
":",
"HttpRequest",
":",
"param",
"error",
":",... | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/api.py#L14-L31 |
ministryofjustice/money-to-prisoners-common | mtp_common/api.py | retrieve_all_pages | def retrieve_all_pages(api_endpoint, **kwargs):
"""
Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator,
this method loads all pages into a single results list
:param api_endpoint: slumber callable, e.g. `[api_client].cashbook.transactions.locked.get`
:param kwa... | python | def retrieve_all_pages(api_endpoint, **kwargs):
"""
Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator,
this method loads all pages into a single results list
:param api_endpoint: slumber callable, e.g. `[api_client].cashbook.transactions.locked.get`
:param kwa... | [
"def",
"retrieve_all_pages",
"(",
"api_endpoint",
",",
"*",
"*",
"kwargs",
")",
":",
"page_size",
"=",
"getattr",
"(",
"settings",
",",
"'REQUEST_PAGE_SIZE'",
",",
"20",
")",
"loaded_results",
"=",
"[",
"]",
"offset",
"=",
"0",
"while",
"True",
":",
"respo... | Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator,
this method loads all pages into a single results list
:param api_endpoint: slumber callable, e.g. `[api_client].cashbook.transactions.locked.get`
:param kwargs: additional arguments to pass into api callable | [
"Some",
"MTP",
"apis",
"are",
"paginated",
"using",
"Django",
"Rest",
"Framework",
"s",
"LimitOffsetPagination",
"paginator",
"this",
"method",
"loads",
"all",
"pages",
"into",
"a",
"single",
"results",
"list",
":",
"param",
"api_endpoint",
":",
"slumber",
"call... | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/api.py#L34-L54 |
ministryofjustice/money-to-prisoners-common | mtp_common/api.py | retrieve_all_pages_for_path | def retrieve_all_pages_for_path(session, path, **params):
"""
Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator,
this method loads all pages into a single results list
:param session: Requests Session object
:param path: URL path
:param params: additional ... | python | def retrieve_all_pages_for_path(session, path, **params):
"""
Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator,
this method loads all pages into a single results list
:param session: Requests Session object
:param path: URL path
:param params: additional ... | [
"def",
"retrieve_all_pages_for_path",
"(",
"session",
",",
"path",
",",
"*",
"*",
"params",
")",
":",
"page_size",
"=",
"getattr",
"(",
"settings",
",",
"'REQUEST_PAGE_SIZE'",
",",
"20",
")",
"loaded_results",
"=",
"[",
"]",
"offset",
"=",
"0",
"while",
"T... | Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator,
this method loads all pages into a single results list
:param session: Requests Session object
:param path: URL path
:param params: additional URL params | [
"Some",
"MTP",
"apis",
"are",
"paginated",
"using",
"Django",
"Rest",
"Framework",
"s",
"LimitOffsetPagination",
"paginator",
"this",
"method",
"loads",
"all",
"pages",
"into",
"a",
"single",
"results",
"list",
":",
"param",
"session",
":",
"Requests",
"Session"... | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/api.py#L57-L81 |
Parsely/birding | src/birding/spout.py | DispatchSpout | def DispatchSpout(*a, **kw):
"""Factory to dispatch spout class based on config."""
spout_class_name = get_config()['Spout']
spout_class = import_name(spout_class_name, default_ns='birding.spout')
return spout_class(*a, **kw) | python | def DispatchSpout(*a, **kw):
"""Factory to dispatch spout class based on config."""
spout_class_name = get_config()['Spout']
spout_class = import_name(spout_class_name, default_ns='birding.spout')
return spout_class(*a, **kw) | [
"def",
"DispatchSpout",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"spout_class_name",
"=",
"get_config",
"(",
")",
"[",
"'Spout'",
"]",
"spout_class",
"=",
"import_name",
"(",
"spout_class_name",
",",
"default_ns",
"=",
"'birding.spout'",
")",
"return",
... | Factory to dispatch spout class based on config. | [
"Factory",
"to",
"dispatch",
"spout",
"class",
"based",
"on",
"config",
"."
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/spout.py#L11-L15 |
Parsely/birding | src/birding/spout.py | TermCycleSpout.initialize | def initialize(self, stormconf, context):
"""Initialization steps:
1. Prepare sequence of terms based on config: TermCycleSpout/terms.
"""
self.terms = get_config()['TermCycleSpout']['terms']
self.term_seq = itertools.cycle(self.terms) | python | def initialize(self, stormconf, context):
"""Initialization steps:
1. Prepare sequence of terms based on config: TermCycleSpout/terms.
"""
self.terms = get_config()['TermCycleSpout']['terms']
self.term_seq = itertools.cycle(self.terms) | [
"def",
"initialize",
"(",
"self",
",",
"stormconf",
",",
"context",
")",
":",
"self",
".",
"terms",
"=",
"get_config",
"(",
")",
"[",
"'TermCycleSpout'",
"]",
"[",
"'terms'",
"]",
"self",
".",
"term_seq",
"=",
"itertools",
".",
"cycle",
"(",
"self",
".... | Initialization steps:
1. Prepare sequence of terms based on config: TermCycleSpout/terms. | [
"Initialization",
"steps",
":"
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/spout.py#L45-L51 |
Parsely/birding | src/birding/spout.py | TermCycleSpout.next_tuple | def next_tuple(self):
"""Next tuple steps:
1. Emit (term, timestamp) for next term in sequence w/current UTC time.
"""
term = next(self.term_seq)
timestamp = datetime.datetime.utcnow().isoformat()
self.emit([term, timestamp], tup_id=self.pack_tup_id(term, timestamp)) | python | def next_tuple(self):
"""Next tuple steps:
1. Emit (term, timestamp) for next term in sequence w/current UTC time.
"""
term = next(self.term_seq)
timestamp = datetime.datetime.utcnow().isoformat()
self.emit([term, timestamp], tup_id=self.pack_tup_id(term, timestamp)) | [
"def",
"next_tuple",
"(",
"self",
")",
":",
"term",
"=",
"next",
"(",
"self",
".",
"term_seq",
")",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"self",
".",
"emit",
"(",
"[",
"term",
",",
"tim... | Next tuple steps:
1. Emit (term, timestamp) for next term in sequence w/current UTC time. | [
"Next",
"tuple",
"steps",
":"
] | train | https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/spout.py#L53-L60 |
harvard-nrg/yaxil | yaxil/commons/__init__.py | cast | def cast(s):
'''
Cast a basestring to a more appropriate type.
Example::
>>> from yaxil import cast
>>> type(cast("999"))
<type 'int'>
:param s: String
:type s: basestring
:returns: Casted string
:rtype: int|float|str
'''
if not isinstance(s, basestring):... | python | def cast(s):
'''
Cast a basestring to a more appropriate type.
Example::
>>> from yaxil import cast
>>> type(cast("999"))
<type 'int'>
:param s: String
:type s: basestring
:returns: Casted string
:rtype: int|float|str
'''
if not isinstance(s, basestring):... | [
"def",
"cast",
"(",
"s",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"argument must be a string\"",
")",
"for",
"test",
"in",
"[",
"int",
",",
"float",
",",
"str",
"]",
":",
"try",
":",
"re... | Cast a basestring to a more appropriate type.
Example::
>>> from yaxil import cast
>>> type(cast("999"))
<type 'int'>
:param s: String
:type s: basestring
:returns: Casted string
:rtype: int|float|str | [
"Cast",
"a",
"basestring",
"to",
"a",
"more",
"appropriate",
"type",
".",
"Example",
"::",
">>>",
"from",
"yaxil",
"import",
"cast",
">>>",
"type",
"(",
"cast",
"(",
"999",
"))",
"<type",
"int",
">",
":",
"param",
"s",
":",
"String",
":",
"type",
"s"... | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/commons/__init__.py#L26-L46 |
harvard-nrg/yaxil | yaxil/commons/__init__.py | atomic_write | def atomic_write(filename, content, overwrite=True, permissions=0o0644, encoding='utf-8'):
'''
Write a file atomically by writing the file content to a
temporary location first, then renaming the file.
TODO: this relies pretty heavily on os.rename to ensure atomicity, but
os.rename does not s... | python | def atomic_write(filename, content, overwrite=True, permissions=0o0644, encoding='utf-8'):
'''
Write a file atomically by writing the file content to a
temporary location first, then renaming the file.
TODO: this relies pretty heavily on os.rename to ensure atomicity, but
os.rename does not s... | [
"def",
"atomic_write",
"(",
"filename",
",",
"content",
",",
"overwrite",
"=",
"True",
",",
"permissions",
"=",
"0o0644",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"if",
"not",... | Write a file atomically by writing the file content to a
temporary location first, then renaming the file.
TODO: this relies pretty heavily on os.rename to ensure atomicity, but
os.rename does not silently overwrite files that already exist on
Windows natively. For now, the functionality provide... | [
"Write",
"a",
"file",
"atomically",
"by",
"writing",
"the",
"file",
"content",
"to",
"a",
"temporary",
"location",
"first",
"then",
"renaming",
"the",
"file",
".",
"TODO",
":",
"this",
"relies",
"pretty",
"heavily",
"on",
"os",
".",
"rename",
"to",
"ensure... | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/commons/__init__.py#L48-L78 |
harvard-nrg/yaxil | yaxil/commons/__init__.py | which | def which(x):
'''
Same as which command on Linux
'''
for p in os.environ.get('PATH').split(os.pathsep):
p = os.path.join(p, x)
if os.path.exists(p):
return os.path.abspath(p)
return None | python | def which(x):
'''
Same as which command on Linux
'''
for p in os.environ.get('PATH').split(os.pathsep):
p = os.path.join(p, x)
if os.path.exists(p):
return os.path.abspath(p)
return None | [
"def",
"which",
"(",
"x",
")",
":",
"for",
"p",
"in",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
")",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"p",
",",
"x",
")",
"if",
"os",
... | Same as which command on Linux | [
"Same",
"as",
"which",
"command",
"on",
"Linux"
] | train | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/commons/__init__.py#L83-L91 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | serve | def serve(context: Context, port=8000, browsersync_port=3000, browsersync_ui_port=3030):
"""
Starts a development server with auto-building and live-reload
"""
try:
from watchdog.observers import Observer
except ImportError:
context.pip_command('install', 'watchdog>0.8,<0.9')
... | python | def serve(context: Context, port=8000, browsersync_port=3000, browsersync_ui_port=3030):
"""
Starts a development server with auto-building and live-reload
"""
try:
from watchdog.observers import Observer
except ImportError:
context.pip_command('install', 'watchdog>0.8,<0.9')
... | [
"def",
"serve",
"(",
"context",
":",
"Context",
",",
"port",
"=",
"8000",
",",
"browsersync_port",
"=",
"3000",
",",
"browsersync_ui_port",
"=",
"3030",
")",
":",
"try",
":",
"from",
"watchdog",
".",
"observers",
"import",
"Observer",
"except",
"ImportError"... | Starts a development server with auto-building and live-reload | [
"Starts",
"a",
"development",
"server",
"with",
"auto",
"-",
"building",
"and",
"live",
"-",
"reload"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L34-L101 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | create_build_paths | def create_build_paths(context: Context):
"""
Creates directories needed for build outputs
"""
paths = [context.app.asset_build_path, context.app.screenshots_build_path, context.app.collected_assets_path]
for path in filter(None, paths):
os.makedirs(path, exist_ok=True) | python | def create_build_paths(context: Context):
"""
Creates directories needed for build outputs
"""
paths = [context.app.asset_build_path, context.app.screenshots_build_path, context.app.collected_assets_path]
for path in filter(None, paths):
os.makedirs(path, exist_ok=True) | [
"def",
"create_build_paths",
"(",
"context",
":",
"Context",
")",
":",
"paths",
"=",
"[",
"context",
".",
"app",
".",
"asset_build_path",
",",
"context",
".",
"app",
".",
"screenshots_build_path",
",",
"context",
".",
"app",
".",
"collected_assets_path",
"]",
... | Creates directories needed for build outputs | [
"Creates",
"directories",
"needed",
"for",
"build",
"outputs"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L121-L127 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | python_dependencies | def python_dependencies(context: Context, common_path=None):
"""
Updates python dependencies
"""
context.pip_command('install', '-r', context.requirements_file)
if common_path:
context.pip_command('uninstall', '--yes', 'money-to-prisoners-common')
context.pip_command('install', '--fo... | python | def python_dependencies(context: Context, common_path=None):
"""
Updates python dependencies
"""
context.pip_command('install', '-r', context.requirements_file)
if common_path:
context.pip_command('uninstall', '--yes', 'money-to-prisoners-common')
context.pip_command('install', '--fo... | [
"def",
"python_dependencies",
"(",
"context",
":",
"Context",
",",
"common_path",
"=",
"None",
")",
":",
"context",
".",
"pip_command",
"(",
"'install'",
",",
"'-r'",
",",
"context",
".",
"requirements_file",
")",
"if",
"common_path",
":",
"context",
".",
"p... | Updates python dependencies | [
"Updates",
"python",
"dependencies"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L131-L139 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | node_dependencies | def node_dependencies(context: Context):
"""
Updates node.js dependencies
"""
args = ['--loglevel', {0: 'silent', 1: 'warn', 2: 'info'}[context.verbosity]]
if not context.use_colour:
args.append('--color false')
args.append('install')
return context.shell('npm', *args) | python | def node_dependencies(context: Context):
"""
Updates node.js dependencies
"""
args = ['--loglevel', {0: 'silent', 1: 'warn', 2: 'info'}[context.verbosity]]
if not context.use_colour:
args.append('--color false')
args.append('install')
return context.shell('npm', *args) | [
"def",
"node_dependencies",
"(",
"context",
":",
"Context",
")",
":",
"args",
"=",
"[",
"'--loglevel'",
",",
"{",
"0",
":",
"'silent'",
",",
"1",
":",
"'warn'",
",",
"2",
":",
"'info'",
"}",
"[",
"context",
".",
"verbosity",
"]",
"]",
"if",
"not",
... | Updates node.js dependencies | [
"Updates",
"node",
".",
"js",
"dependencies"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L151-L159 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | local_docker | def local_docker(context: Context):
"""
Runs the app in a docker container; for local development only!
Once performed, `docker-compose up` can be used directly
"""
output = io.StringIO()
with contextlib.redirect_stdout(output):
context.shell('docker-machine', 'ip', 'default')
host_m... | python | def local_docker(context: Context):
"""
Runs the app in a docker container; for local development only!
Once performed, `docker-compose up` can be used directly
"""
output = io.StringIO()
with contextlib.redirect_stdout(output):
context.shell('docker-machine', 'ip', 'default')
host_m... | [
"def",
"local_docker",
"(",
"context",
":",
"Context",
")",
":",
"output",
"=",
"io",
".",
"StringIO",
"(",
")",
"with",
"contextlib",
".",
"redirect_stdout",
"(",
"output",
")",
":",
"context",
".",
"shell",
"(",
"'docker-machine'",
",",
"'ip'",
",",
"'... | Runs the app in a docker container; for local development only!
Once performed, `docker-compose up` can be used directly | [
"Runs",
"the",
"app",
"in",
"a",
"docker",
"container",
";",
"for",
"local",
"development",
"only!",
"Once",
"performed",
"docker",
"-",
"compose",
"up",
"can",
"be",
"used",
"directly"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L180-L195 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | bundle_javascript | def bundle_javascript(context: Context):
"""
Compiles javascript
"""
args = ['--bail']
if context.verbosity > 0:
args.append('--verbose')
if not context.use_colour:
args.append('--no-colors')
return context.node_tool('webpack', *args) | python | def bundle_javascript(context: Context):
"""
Compiles javascript
"""
args = ['--bail']
if context.verbosity > 0:
args.append('--verbose')
if not context.use_colour:
args.append('--no-colors')
return context.node_tool('webpack', *args) | [
"def",
"bundle_javascript",
"(",
"context",
":",
"Context",
")",
":",
"args",
"=",
"[",
"'--bail'",
"]",
"if",
"context",
".",
"verbosity",
">",
"0",
":",
"args",
".",
"append",
"(",
"'--verbose'",
")",
"if",
"not",
"context",
".",
"use_colour",
":",
"... | Compiles javascript | [
"Compiles",
"javascript"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L207-L216 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | bundle_stylesheets | def bundle_stylesheets(context: Context):
"""
Compiles stylesheets
"""
args = [
'--output', context.app.scss_build_path,
'--output-style', 'compressed',
]
if context.verbosity == 0:
args.append('--quiet')
if not context.use_colour:
args.append('--no-color')
... | python | def bundle_stylesheets(context: Context):
"""
Compiles stylesheets
"""
args = [
'--output', context.app.scss_build_path,
'--output-style', 'compressed',
]
if context.verbosity == 0:
args.append('--quiet')
if not context.use_colour:
args.append('--no-color')
... | [
"def",
"bundle_stylesheets",
"(",
"context",
":",
"Context",
")",
":",
"args",
"=",
"[",
"'--output'",
",",
"context",
".",
"app",
".",
"scss_build_path",
",",
"'--output-style'",
",",
"'compressed'",
",",
"]",
"if",
"context",
".",
"verbosity",
"==",
"0",
... | Compiles stylesheets | [
"Compiles",
"stylesheets"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L220-L238 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | lint_javascript | def lint_javascript(context: Context):
"""
Tests javascript for code and style errors
"""
args = [
'--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'eslintrc.json'),
'--format', 'stylish',
]
if context.verbosity == 0:
args.append('-... | python | def lint_javascript(context: Context):
"""
Tests javascript for code and style errors
"""
args = [
'--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'eslintrc.json'),
'--format', 'stylish',
]
if context.verbosity == 0:
args.append('-... | [
"def",
"lint_javascript",
"(",
"context",
":",
"Context",
")",
":",
"args",
"=",
"[",
"'--config'",
",",
"os",
".",
"path",
".",
"join",
"(",
"context",
".",
"app",
".",
"common_templates_path",
",",
"'mtp_common'",
",",
"'build_tasks'",
",",
"'eslintrc.json... | Tests javascript for code and style errors | [
"Tests",
"javascript",
"for",
"code",
"and",
"style",
"errors"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L249-L262 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | lint_stylesheets | def lint_stylesheets(context: Context):
"""
Tests stylesheets for code and style errors
"""
args = [
'--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'sass-lint.yml'),
'--format', 'stylish',
'--syntax', 'scss',
]
if context.verbosit... | python | def lint_stylesheets(context: Context):
"""
Tests stylesheets for code and style errors
"""
args = [
'--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'sass-lint.yml'),
'--format', 'stylish',
'--syntax', 'scss',
]
if context.verbosit... | [
"def",
"lint_stylesheets",
"(",
"context",
":",
"Context",
")",
":",
"args",
"=",
"[",
"'--config'",
",",
"os",
".",
"path",
".",
"join",
"(",
"context",
".",
"app",
".",
"common_templates_path",
",",
"'mtp_common'",
",",
"'build_tasks'",
",",
"'sass-lint.ym... | Tests stylesheets for code and style errors | [
"Tests",
"stylesheets",
"for",
"code",
"and",
"style",
"errors"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L266-L278 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | govuk_template | def govuk_template(context: Context, version='0.23.0', replace_fonts=True):
"""
Installs GOV.UK template
"""
if FileSet(os.path.join(context.app.govuk_templates_path, 'base.html')):
# NB: check is only on main template and not the assets included
return
url = 'https://github.com/alph... | python | def govuk_template(context: Context, version='0.23.0', replace_fonts=True):
"""
Installs GOV.UK template
"""
if FileSet(os.path.join(context.app.govuk_templates_path, 'base.html')):
# NB: check is only on main template and not the assets included
return
url = 'https://github.com/alph... | [
"def",
"govuk_template",
"(",
"context",
":",
"Context",
",",
"version",
"=",
"'0.23.0'",
",",
"replace_fonts",
"=",
"True",
")",
":",
"if",
"FileSet",
"(",
"os",
".",
"path",
".",
"join",
"(",
"context",
".",
"app",
".",
"govuk_templates_path",
",",
"'b... | Installs GOV.UK template | [
"Installs",
"GOV",
".",
"UK",
"template"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L289-L313 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | additional_assets | def additional_assets(context: Context):
"""
Collects assets from GOV.UK frontend toolkit
"""
rsync_flags = '-avz' if context.verbosity == 2 else '-az'
for path in context.app.additional_asset_paths:
context.shell('rsync %s %s %s/' % (rsync_flags, path, context.app.asset_build_path)) | python | def additional_assets(context: Context):
"""
Collects assets from GOV.UK frontend toolkit
"""
rsync_flags = '-avz' if context.verbosity == 2 else '-az'
for path in context.app.additional_asset_paths:
context.shell('rsync %s %s %s/' % (rsync_flags, path, context.app.asset_build_path)) | [
"def",
"additional_assets",
"(",
"context",
":",
"Context",
")",
":",
"rsync_flags",
"=",
"'-avz'",
"if",
"context",
".",
"verbosity",
"==",
"2",
"else",
"'-az'",
"for",
"path",
"in",
"context",
".",
"app",
".",
"additional_asset_paths",
":",
"context",
".",... | Collects assets from GOV.UK frontend toolkit | [
"Collects",
"assets",
"from",
"GOV",
".",
"UK",
"frontend",
"toolkit"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L317-L323 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | precompile_python_code | def precompile_python_code(context: Context):
"""
Pre-compiles python modules
"""
from compileall import compile_dir
kwargs = {}
if context.verbosity < 2:
kwargs['quiet'] = True
compile_dir(context.app.django_app_name, **kwargs) | python | def precompile_python_code(context: Context):
"""
Pre-compiles python modules
"""
from compileall import compile_dir
kwargs = {}
if context.verbosity < 2:
kwargs['quiet'] = True
compile_dir(context.app.django_app_name, **kwargs) | [
"def",
"precompile_python_code",
"(",
"context",
":",
"Context",
")",
":",
"from",
"compileall",
"import",
"compile_dir",
"kwargs",
"=",
"{",
"}",
"if",
"context",
".",
"verbosity",
"<",
"2",
":",
"kwargs",
"[",
"'quiet'",
"]",
"=",
"True",
"compile_dir",
... | Pre-compiles python modules | [
"Pre",
"-",
"compiles",
"python",
"modules"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L344-L353 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | make_messages | def make_messages(context: Context, javascript=False, fuzzy=False):
"""
Collects text into translation source files
"""
kwargs = {
'all': True,
'keep_pot': True,
'no_wrap': True,
}
if fuzzy:
kwargs['allow_fuzzy'] = True
if javascript:
kwargs.update(dom... | python | def make_messages(context: Context, javascript=False, fuzzy=False):
"""
Collects text into translation source files
"""
kwargs = {
'all': True,
'keep_pot': True,
'no_wrap': True,
}
if fuzzy:
kwargs['allow_fuzzy'] = True
if javascript:
kwargs.update(dom... | [
"def",
"make_messages",
"(",
"context",
":",
"Context",
",",
"javascript",
"=",
"False",
",",
"fuzzy",
"=",
"False",
")",
":",
"kwargs",
"=",
"{",
"'all'",
":",
"True",
",",
"'keep_pot'",
":",
"True",
",",
"'no_wrap'",
":",
"True",
",",
"}",
"if",
"f... | Collects text into translation source files | [
"Collects",
"text",
"into",
"translation",
"source",
"files"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L357-L371 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | translations | def translations(context: Context, pull=False, push=False):
"""
Synchronises translations with transifex.com
"""
if not (pull or push):
raise TaskError('Specify whether to push or pull translations')
if pull:
context.shell('tx', 'pull')
make_messages(context, javascript=False... | python | def translations(context: Context, pull=False, push=False):
"""
Synchronises translations with transifex.com
"""
if not (pull or push):
raise TaskError('Specify whether to push or pull translations')
if pull:
context.shell('tx', 'pull')
make_messages(context, javascript=False... | [
"def",
"translations",
"(",
"context",
":",
"Context",
",",
"pull",
"=",
"False",
",",
"push",
"=",
"False",
")",
":",
"if",
"not",
"(",
"pull",
"or",
"push",
")",
":",
"raise",
"TaskError",
"(",
"'Specify whether to push or pull translations'",
")",
"if",
... | Synchronises translations with transifex.com | [
"Synchronises",
"translations",
"with",
"transifex",
".",
"com"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L384-L395 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/tasks.py | clean | def clean(context: Context, delete_dependencies: bool = False):
"""
Deletes build outputs
"""
paths = [context.app.asset_build_path, context.app.collected_assets_path, context.app.govuk_templates_path,
'docker-compose.yml', 'package.json', 'package-lock.json', 'webpack.config.js']
conte... | python | def clean(context: Context, delete_dependencies: bool = False):
"""
Deletes build outputs
"""
paths = [context.app.asset_build_path, context.app.collected_assets_path, context.app.govuk_templates_path,
'docker-compose.yml', 'package.json', 'package-lock.json', 'webpack.config.js']
conte... | [
"def",
"clean",
"(",
"context",
":",
"Context",
",",
"delete_dependencies",
":",
"bool",
"=",
"False",
")",
":",
"paths",
"=",
"[",
"context",
".",
"app",
".",
"asset_build_path",
",",
"context",
".",
"app",
".",
"collected_assets_path",
",",
"context",
".... | Deletes build outputs | [
"Deletes",
"build",
"outputs"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L399-L411 |
ministryofjustice/money-to-prisoners-common | mtp_common/auth/csrf.py | csrf_failure | def csrf_failure(request, reason=''):
"""
CSRF-failure view which converts the failed POST request into a GET
and calls the original view with a sensible error message presented
to the user.
:param request: the HttpRequest
:param reason: non-localised failure description
"""
if _csrf_fai... | python | def csrf_failure(request, reason=''):
"""
CSRF-failure view which converts the failed POST request into a GET
and calls the original view with a sensible error message presented
to the user.
:param request: the HttpRequest
:param reason: non-localised failure description
"""
if _csrf_fai... | [
"def",
"csrf_failure",
"(",
"request",
",",
"reason",
"=",
"''",
")",
":",
"if",
"_csrf_failed_view",
".",
"no_moj_csrf",
":",
"from",
"django",
".",
"views",
".",
"csrf",
"import",
"csrf_failure",
"return",
"csrf_failure",
"(",
"request",
",",
"reason",
"="... | CSRF-failure view which converts the failed POST request into a GET
and calls the original view with a sensible error message presented
to the user.
:param request: the HttpRequest
:param reason: non-localised failure description | [
"CSRF",
"-",
"failure",
"view",
"which",
"converts",
"the",
"failed",
"POST",
"request",
"into",
"a",
"GET",
"and",
"calls",
"the",
"original",
"view",
"with",
"a",
"sensible",
"error",
"message",
"presented",
"to",
"the",
"user",
".",
":",
"param",
"reque... | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/csrf.py#L12-L46 |
alejoe91/MEAutility | MEAutility/core.py | get_positions | def get_positions(elinfo, center=True):
'''Computes the positions of the elctrodes based on the elinfo
Parameters
----------
elinfo: dict
Contains electrode information from yaml file (dim, pitch, sortlist, plane, pos)
Returns
-------
positions: np.array
3d points with the ... | python | def get_positions(elinfo, center=True):
'''Computes the positions of the elctrodes based on the elinfo
Parameters
----------
elinfo: dict
Contains electrode information from yaml file (dim, pitch, sortlist, plane, pos)
Returns
-------
positions: np.array
3d points with the ... | [
"def",
"get_positions",
"(",
"elinfo",
",",
"center",
"=",
"True",
")",
":",
"electrode_pos",
"=",
"False",
"# method 1: positions in elinfo",
"if",
"'pos'",
"in",
"elinfo",
".",
"keys",
"(",
")",
":",
"pos",
"=",
"np",
".",
"array",
"(",
"elinfo",
"[",
... | Computes the positions of the elctrodes based on the elinfo
Parameters
----------
elinfo: dict
Contains electrode information from yaml file (dim, pitch, sortlist, plane, pos)
Returns
-------
positions: np.array
3d points with the centers of the electrodes | [
"Computes",
"the",
"positions",
"of",
"the",
"elctrodes",
"based",
"on",
"the",
"elinfo"
] | train | https://github.com/alejoe91/MEAutility/blob/7c2b0da52c2752a3baf04e8e248e26b0769cd088/MEAutility/core.py#L731-L903 |
alejoe91/MEAutility | MEAutility/core.py | add_mea | def add_mea(mea_yaml_path):
'''Adds the mea design defined by the yaml file in the install folder
Parameters
----------
mea_yaml_file
Returns
-------
'''
path = os.path.abspath(mea_yaml_path)
if path.endswith('.yaml') or path.endswith('.yml') and os.path.isfile(path):
wit... | python | def add_mea(mea_yaml_path):
'''Adds the mea design defined by the yaml file in the install folder
Parameters
----------
mea_yaml_file
Returns
-------
'''
path = os.path.abspath(mea_yaml_path)
if path.endswith('.yaml') or path.endswith('.yml') and os.path.isfile(path):
wit... | [
"def",
"add_mea",
"(",
"mea_yaml_path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"mea_yaml_path",
")",
"if",
"path",
".",
"endswith",
"(",
"'.yaml'",
")",
"or",
"path",
".",
"endswith",
"(",
"'.yml'",
")",
"and",
"os",
".",
"pat... | Adds the mea design defined by the yaml file in the install folder
Parameters
----------
mea_yaml_file
Returns
------- | [
"Adds",
"the",
"mea",
"design",
"defined",
"by",
"the",
"yaml",
"file",
"in",
"the",
"install",
"folder"
] | train | https://github.com/alejoe91/MEAutility/blob/7c2b0da52c2752a3baf04e8e248e26b0769cd088/MEAutility/core.py#L1038-L1073 |
alejoe91/MEAutility | MEAutility/core.py | remove_mea | def remove_mea(mea_name):
'''Adds the mea design defined by the yaml file in the install folder
Parameters
----------
mea_yaml_file
Returns
-------
'''
this_dir, this_filename = os.path.split(__file__)
electrodes = [f for f in os.listdir(os.path.join(this_dir, "electrodes"))]
... | python | def remove_mea(mea_name):
'''Adds the mea design defined by the yaml file in the install folder
Parameters
----------
mea_yaml_file
Returns
-------
'''
this_dir, this_filename = os.path.split(__file__)
electrodes = [f for f in os.listdir(os.path.join(this_dir, "electrodes"))]
... | [
"def",
"remove_mea",
"(",
"mea_name",
")",
":",
"this_dir",
",",
"this_filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"__file__",
")",
"electrodes",
"=",
"[",
"f",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"join",
... | Adds the mea design defined by the yaml file in the install folder
Parameters
----------
mea_yaml_file
Returns
------- | [
"Adds",
"the",
"mea",
"design",
"defined",
"by",
"the",
"yaml",
"file",
"in",
"the",
"install",
"folder"
] | train | https://github.com/alejoe91/MEAutility/blob/7c2b0da52c2752a3baf04e8e248e26b0769cd088/MEAutility/core.py#L1076-L1099 |
koreyou/word_embedding_loader | word_embedding_loader/word_embedding.py | _get_two_lines | def _get_two_lines(f):
"""
Get the first and second lines
Args:
f (filelike): File that is opened for ascii.
Returns:
bytes
"""
l0 = f.readline()
l1 = f.readline()
return l0, l1 | python | def _get_two_lines(f):
"""
Get the first and second lines
Args:
f (filelike): File that is opened for ascii.
Returns:
bytes
"""
l0 = f.readline()
l1 = f.readline()
return l0, l1 | [
"def",
"_get_two_lines",
"(",
"f",
")",
":",
"l0",
"=",
"f",
".",
"readline",
"(",
")",
"l1",
"=",
"f",
".",
"readline",
"(",
")",
"return",
"l0",
",",
"l1"
] | Get the first and second lines
Args:
f (filelike): File that is opened for ascii.
Returns:
bytes | [
"Get",
"the",
"first",
"and",
"second",
"lines",
"Args",
":",
"f",
"(",
"filelike",
")",
":",
"File",
"that",
"is",
"opened",
"for",
"ascii",
"."
] | train | https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/word_embedding.py#L48-L60 |
koreyou/word_embedding_loader | word_embedding_loader/word_embedding.py | classify_format | def classify_format(f):
"""
Determine the format of word embedding file by their content. This operation
only looks at the first two lines and does not check the sanity of input
file.
Args:
f (Filelike):
Returns:
class
"""
l0, l1 = _get_two_lines(f)
if loader.glove... | python | def classify_format(f):
"""
Determine the format of word embedding file by their content. This operation
only looks at the first two lines and does not check the sanity of input
file.
Args:
f (Filelike):
Returns:
class
"""
l0, l1 = _get_two_lines(f)
if loader.glove... | [
"def",
"classify_format",
"(",
"f",
")",
":",
"l0",
",",
"l1",
"=",
"_get_two_lines",
"(",
"f",
")",
"if",
"loader",
".",
"glove",
".",
"check_valid",
"(",
"l0",
",",
"l1",
")",
":",
"return",
"_glove",
"elif",
"loader",
".",
"word2vec_text",
".",
"c... | Determine the format of word embedding file by their content. This operation
only looks at the first two lines and does not check the sanity of input
file.
Args:
f (Filelike):
Returns:
class | [
"Determine",
"the",
"format",
"of",
"word",
"embedding",
"file",
"by",
"their",
"content",
".",
"This",
"operation",
"only",
"looks",
"at",
"the",
"first",
"two",
"lines",
"and",
"does",
"not",
"check",
"the",
"sanity",
"of",
"input",
"file",
"."
] | train | https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/word_embedding.py#L63-L84 |
koreyou/word_embedding_loader | word_embedding_loader/word_embedding.py | WordEmbedding.load | def load(cls, path, vocab=None, dtype=np.float32, max_vocab=None,
format=None, binary=False):
"""
Load pretrained word embedding from a file.
Args:
path (str): Path of file to load.
vocab (str or None): Path to vocabulary file created by word2vec
... | python | def load(cls, path, vocab=None, dtype=np.float32, max_vocab=None,
format=None, binary=False):
"""
Load pretrained word embedding from a file.
Args:
path (str): Path of file to load.
vocab (str or None): Path to vocabulary file created by word2vec
... | [
"def",
"load",
"(",
"cls",
",",
"path",
",",
"vocab",
"=",
"None",
",",
"dtype",
"=",
"np",
".",
"float32",
",",
"max_vocab",
"=",
"None",
",",
"format",
"=",
"None",
",",
"binary",
"=",
"False",
")",
":",
"freqs",
"=",
"None",
"if",
"vocab",
"is... | Load pretrained word embedding from a file.
Args:
path (str): Path of file to load.
vocab (str or None): Path to vocabulary file created by word2vec
with ``-save-vocab <file>`` option. If vocab is given,
:py:attr:`~vectors` and :py:attr:`~vocab` is ordere... | [
"Load",
"pretrained",
"word",
"embedding",
"from",
"a",
"file",
"."
] | train | https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/word_embedding.py#L129-L184 |
koreyou/word_embedding_loader | word_embedding_loader/word_embedding.py | WordEmbedding.save | def save(self, path, format, binary=False, use_load_condition=False):
"""
Save object as word embedding file. For most arguments, you should refer
to :func:`~word_embedding_loader.word_embedding.WordEmbedding.load`.
Args:
use_load_condition (bool): If `True`, options from
... | python | def save(self, path, format, binary=False, use_load_condition=False):
"""
Save object as word embedding file. For most arguments, you should refer
to :func:`~word_embedding_loader.word_embedding.WordEmbedding.load`.
Args:
use_load_condition (bool): If `True`, options from
... | [
"def",
"save",
"(",
"self",
",",
"path",
",",
"format",
",",
"binary",
"=",
"False",
",",
"use_load_condition",
"=",
"False",
")",
":",
"if",
"use_load_condition",
":",
"if",
"self",
".",
"_load_cond",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"b\"u... | Save object as word embedding file. For most arguments, you should refer
to :func:`~word_embedding_loader.word_embedding.WordEmbedding.load`.
Args:
use_load_condition (bool): If `True`, options from
:func:`~word_embedding_loader.word_embedding.WordEmbedding.load`
... | [
"Save",
"object",
"as",
"word",
"embedding",
"file",
".",
"For",
"most",
"arguments",
"you",
"should",
"refer",
"to",
":",
"func",
":",
"~word_embedding_loader",
".",
"word_embedding",
".",
"WordEmbedding",
".",
"load",
"."
] | train | https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/word_embedding.py#L186-L222 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/paths.py | paths_for_shell | def paths_for_shell(paths, separator=' '):
"""
Converts a list of paths for use in shell commands
"""
paths = filter(None, paths)
paths = map(shlex.quote, paths)
if separator is None:
return paths
return separator.join(paths) | python | def paths_for_shell(paths, separator=' '):
"""
Converts a list of paths for use in shell commands
"""
paths = filter(None, paths)
paths = map(shlex.quote, paths)
if separator is None:
return paths
return separator.join(paths) | [
"def",
"paths_for_shell",
"(",
"paths",
",",
"separator",
"=",
"' '",
")",
":",
"paths",
"=",
"filter",
"(",
"None",
",",
"paths",
")",
"paths",
"=",
"map",
"(",
"shlex",
".",
"quote",
",",
"paths",
")",
"if",
"separator",
"is",
"None",
":",
"return"... | Converts a list of paths for use in shell commands | [
"Converts",
"a",
"list",
"of",
"paths",
"for",
"use",
"in",
"shell",
"commands"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/paths.py#L19-L27 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | Tasks.register | def register(self, *dependencies, default=False, hidden=False, ignore_return_code=False):
"""
Decorates a callable to turn it into a task
"""
def outer(func):
task = Task(func, *dependencies, default=default, hidden=hidden, ignore_return_code=ignore_return_code)
... | python | def register(self, *dependencies, default=False, hidden=False, ignore_return_code=False):
"""
Decorates a callable to turn it into a task
"""
def outer(func):
task = Task(func, *dependencies, default=default, hidden=hidden, ignore_return_code=ignore_return_code)
... | [
"def",
"register",
"(",
"self",
",",
"*",
"dependencies",
",",
"default",
"=",
"False",
",",
"hidden",
"=",
"False",
",",
"ignore_return_code",
"=",
"False",
")",
":",
"def",
"outer",
"(",
"func",
")",
":",
"task",
"=",
"Task",
"(",
"func",
",",
"*",... | Decorates a callable to turn it into a task | [
"Decorates",
"a",
"callable",
"to",
"turn",
"it",
"into",
"a",
"task"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L56-L69 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | Tasks.lookup_task | def lookup_task(self, task):
"""
Looks up a task by name or by callable
"""
if isinstance(task, str):
try:
return self[task]
except KeyError:
pass
raise TaskError('Unknown task %s' % task) | python | def lookup_task(self, task):
"""
Looks up a task by name or by callable
"""
if isinstance(task, str):
try:
return self[task]
except KeyError:
pass
raise TaskError('Unknown task %s' % task) | [
"def",
"lookup_task",
"(",
"self",
",",
"task",
")",
":",
"if",
"isinstance",
"(",
"task",
",",
"str",
")",
":",
"try",
":",
"return",
"self",
"[",
"task",
"]",
"except",
"KeyError",
":",
"pass",
"raise",
"TaskError",
"(",
"'Unknown task %s'",
"%",
"ta... | Looks up a task by name or by callable | [
"Looks",
"up",
"a",
"task",
"by",
"name",
"or",
"by",
"callable"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L71-L80 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | Tasks.get_default_task | def get_default_task(self):
"""
Returns the default task if there is only one
"""
default_tasks = list(filter(lambda task: task.default, self.values()))
if len(default_tasks) == 1:
return default_tasks[0] | python | def get_default_task(self):
"""
Returns the default task if there is only one
"""
default_tasks = list(filter(lambda task: task.default, self.values()))
if len(default_tasks) == 1:
return default_tasks[0] | [
"def",
"get_default_task",
"(",
"self",
")",
":",
"default_tasks",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"task",
":",
"task",
".",
"default",
",",
"self",
".",
"values",
"(",
")",
")",
")",
"if",
"len",
"(",
"default_tasks",
")",
"==",
"1",
":",... | Returns the default task if there is only one | [
"Returns",
"the",
"default",
"task",
"if",
"there",
"is",
"only",
"one"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L82-L88 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | ParameterGroup.from_callable | def from_callable(cls, func, ignored_parameters=set()):
"""
Reads a function or method signature to produce a set of parameters
"""
group = cls()
signature = inspect.signature(func)
for parameter in signature.parameters.values():
if parameter.name.startswith('... | python | def from_callable(cls, func, ignored_parameters=set()):
"""
Reads a function or method signature to produce a set of parameters
"""
group = cls()
signature = inspect.signature(func)
for parameter in signature.parameters.values():
if parameter.name.startswith('... | [
"def",
"from_callable",
"(",
"cls",
",",
"func",
",",
"ignored_parameters",
"=",
"set",
"(",
")",
")",
":",
"group",
"=",
"cls",
"(",
")",
"signature",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"for",
"parameter",
"in",
"signature",
".",
"par... | Reads a function or method signature to produce a set of parameters | [
"Reads",
"a",
"function",
"or",
"method",
"signature",
"to",
"produce",
"a",
"set",
"of",
"parameters"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L137-L148 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | ParameterGroup.from_mapping | def from_mapping(cls, mapping):
"""
Produces a set of parameters from a mapping
"""
group = cls()
for name, value in mapping.items():
if name.startswith('_'):
continue
group[name] = Parameter(
name=name,
valu... | python | def from_mapping(cls, mapping):
"""
Produces a set of parameters from a mapping
"""
group = cls()
for name, value in mapping.items():
if name.startswith('_'):
continue
group[name] = Parameter(
name=name,
valu... | [
"def",
"from_mapping",
"(",
"cls",
",",
"mapping",
")",
":",
"group",
"=",
"cls",
"(",
")",
"for",
"name",
",",
"value",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'_'",
")",
":",
"continue",
"group",
"[",
... | Produces a set of parameters from a mapping | [
"Produces",
"a",
"set",
"of",
"parameters",
"from",
"a",
"mapping"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L151-L164 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | ParameterGroup.to_dict | def to_dict(self):
"""
Converts the set of parameters into a dict
"""
return dict((parameter.name, parameter.value) for parameter in self.values()) | python | def to_dict(self):
"""
Converts the set of parameters into a dict
"""
return dict((parameter.name, parameter.value) for parameter in self.values()) | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"parameter",
".",
"name",
",",
"parameter",
".",
"value",
")",
"for",
"parameter",
"in",
"self",
".",
"values",
"(",
")",
")"
] | Converts the set of parameters into a dict | [
"Converts",
"the",
"set",
"of",
"parameters",
"into",
"a",
"dict"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L189-L193 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | ParameterGroup.consume_arguments | def consume_arguments(self, argument_list):
"""
Takes arguments from a list while there are parameters that can accept them
"""
while True:
argument_count = len(argument_list)
for parameter in self.values():
argument_list = parameter.consume_argume... | python | def consume_arguments(self, argument_list):
"""
Takes arguments from a list while there are parameters that can accept them
"""
while True:
argument_count = len(argument_list)
for parameter in self.values():
argument_list = parameter.consume_argume... | [
"def",
"consume_arguments",
"(",
"self",
",",
"argument_list",
")",
":",
"while",
"True",
":",
"argument_count",
"=",
"len",
"(",
"argument_list",
")",
"for",
"parameter",
"in",
"self",
".",
"values",
"(",
")",
":",
"argument_list",
"=",
"parameter",
".",
... | Takes arguments from a list while there are parameters that can accept them | [
"Takes",
"arguments",
"from",
"a",
"list",
"while",
"there",
"are",
"parameters",
"that",
"can",
"accept",
"them"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L195-L204 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | ParameterGroup.update_from | def update_from(self, mapping):
"""
Updates the set of parameters from a mapping for keys that already exist
"""
for key, value in mapping.items():
if key in self:
if isinstance(value, Parameter):
value = value.value
self[ke... | python | def update_from(self, mapping):
"""
Updates the set of parameters from a mapping for keys that already exist
"""
for key, value in mapping.items():
if key in self:
if isinstance(value, Parameter):
value = value.value
self[ke... | [
"def",
"update_from",
"(",
"self",
",",
"mapping",
")",
":",
"for",
"key",
",",
"value",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
":",
"if",
"isinstance",
"(",
"value",
",",
"Parameter",
")",
":",
"value",
"=",
"valu... | Updates the set of parameters from a mapping for keys that already exist | [
"Updates",
"the",
"set",
"of",
"parameters",
"from",
"a",
"mapping",
"for",
"keys",
"that",
"already",
"exist"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L206-L214 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | Parameter.from_callable_parameter | def from_callable_parameter(cls, parameter):
"""
Produces a parameter from a function or method
"""
if parameter.kind == parameter.KEYWORD_ONLY or \
parameter.kind == parameter.POSITIONAL_OR_KEYWORD and parameter.default is not parameter.empty:
if parameter.an... | python | def from_callable_parameter(cls, parameter):
"""
Produces a parameter from a function or method
"""
if parameter.kind == parameter.KEYWORD_ONLY or \
parameter.kind == parameter.POSITIONAL_OR_KEYWORD and parameter.default is not parameter.empty:
if parameter.an... | [
"def",
"from_callable_parameter",
"(",
"cls",
",",
"parameter",
")",
":",
"if",
"parameter",
".",
"kind",
"==",
"parameter",
".",
"KEYWORD_ONLY",
"or",
"parameter",
".",
"kind",
"==",
"parameter",
".",
"POSITIONAL_OR_KEYWORD",
"and",
"parameter",
".",
"default",... | Produces a parameter from a function or method | [
"Produces",
"a",
"parameter",
"from",
"a",
"function",
"or",
"method"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L223-L239 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | Parameter.constraint_from_type | def constraint_from_type(cls, value):
"""
Returns the constraint callable given a value
"""
if value is None:
return None
value_type = type(value)
if value_type in (str, int, bool):
return value_type
raise ParameterError('Parameter type can... | python | def constraint_from_type(cls, value):
"""
Returns the constraint callable given a value
"""
if value is None:
return None
value_type = type(value)
if value_type in (str, int, bool):
return value_type
raise ParameterError('Parameter type can... | [
"def",
"constraint_from_type",
"(",
"cls",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"value_type",
"=",
"type",
"(",
"value",
")",
"if",
"value_type",
"in",
"(",
"str",
",",
"int",
",",
"bool",
")",
":",
"return",
"v... | Returns the constraint callable given a value | [
"Returns",
"the",
"constraint",
"callable",
"given",
"a",
"value"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L242-L251 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | Parameter.constraint_from_choices | def constraint_from_choices(cls, value_type: type, choices: collections.Sequence):
"""
Returns a constraint callable based on choices of a given type
"""
choices_str = ', '.join(map(str, choices))
def constraint(value):
value = value_type(value)
if value ... | python | def constraint_from_choices(cls, value_type: type, choices: collections.Sequence):
"""
Returns a constraint callable based on choices of a given type
"""
choices_str = ', '.join(map(str, choices))
def constraint(value):
value = value_type(value)
if value ... | [
"def",
"constraint_from_choices",
"(",
"cls",
",",
"value_type",
":",
"type",
",",
"choices",
":",
"collections",
".",
"Sequence",
")",
":",
"choices_str",
"=",
"', '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"choices",
")",
")",
"def",
"constraint",
"... | Returns a constraint callable based on choices of a given type | [
"Returns",
"a",
"constraint",
"callable",
"based",
"on",
"choices",
"of",
"a",
"given",
"type"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L254-L268 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | Parameter.arg_name | def arg_name(self):
"""
Returns the name of the parameter as a command line flag
"""
if self.constraint is bool and self.value:
return '--no-%s' % self.name.replace('_', '-')
return '--%s' % self.name.replace('_', '-') | python | def arg_name(self):
"""
Returns the name of the parameter as a command line flag
"""
if self.constraint is bool and self.value:
return '--no-%s' % self.name.replace('_', '-')
return '--%s' % self.name.replace('_', '-') | [
"def",
"arg_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"constraint",
"is",
"bool",
"and",
"self",
".",
"value",
":",
"return",
"'--no-%s'",
"%",
"self",
".",
"name",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"return",
"'--%s'",
"%",
"self",
... | Returns the name of the parameter as a command line flag | [
"Returns",
"the",
"name",
"of",
"the",
"parameter",
"as",
"a",
"command",
"line",
"flag"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L280-L286 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | Parameter.consume_arguments | def consume_arguments(self, argument_list):
"""
Takes arguments from a list while this parameter can accept them
"""
if len(argument_list) == 0:
return []
if argument_list[0] == self.arg_name:
argument_list = argument_list[1:]
if self.constrain... | python | def consume_arguments(self, argument_list):
"""
Takes arguments from a list while this parameter can accept them
"""
if len(argument_list) == 0:
return []
if argument_list[0] == self.arg_name:
argument_list = argument_list[1:]
if self.constrain... | [
"def",
"consume_arguments",
"(",
"self",
",",
"argument_list",
")",
":",
"if",
"len",
"(",
"argument_list",
")",
"==",
"0",
":",
"return",
"[",
"]",
"if",
"argument_list",
"[",
"0",
"]",
"==",
"self",
".",
"arg_name",
":",
"argument_list",
"=",
"argument... | Takes arguments from a list while this parameter can accept them | [
"Takes",
"arguments",
"from",
"a",
"list",
"while",
"this",
"parameter",
"can",
"accept",
"them"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L314-L330 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | Context.pip_command | def pip_command(self, command, *args):
"""
Runs a pip command
"""
try:
from pip._internal import main as pip_main
except ImportError:
from pip import main as pip_main
args = [command] + list(args)
if self.verbosity == 0:
args.i... | python | def pip_command(self, command, *args):
"""
Runs a pip command
"""
try:
from pip._internal import main as pip_main
except ImportError:
from pip import main as pip_main
args = [command] + list(args)
if self.verbosity == 0:
args.i... | [
"def",
"pip_command",
"(",
"self",
",",
"command",
",",
"*",
"args",
")",
":",
"try",
":",
"from",
"pip",
".",
"_internal",
"import",
"main",
"as",
"pip_main",
"except",
"ImportError",
":",
"from",
"pip",
"import",
"main",
"as",
"pip_main",
"args",
"=",
... | Runs a pip command | [
"Runs",
"a",
"pip",
"command"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L418-L432 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | Context.shell | def shell(self, command, *args, environment=None):
"""
Runs a shell command
"""
command += ' ' + ' '.join(args)
command = command.strip()
self.debug(self.yellow_style('$ %s' % command))
env = self.env.copy()
env.update(environment or {})
return sub... | python | def shell(self, command, *args, environment=None):
"""
Runs a shell command
"""
command += ' ' + ' '.join(args)
command = command.strip()
self.debug(self.yellow_style('$ %s' % command))
env = self.env.copy()
env.update(environment or {})
return sub... | [
"def",
"shell",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"environment",
"=",
"None",
")",
":",
"command",
"+=",
"' '",
"+",
"' '",
".",
"join",
"(",
"args",
")",
"command",
"=",
"command",
".",
"strip",
"(",
")",
"self",
".",
"debug",
... | Runs a shell command | [
"Runs",
"a",
"shell",
"command"
] | train | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L434-L443 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.