code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
clone = self._clone()
# Preserve the stickiness of related querysets
# NOTE: by default _clone will clear this attribute
# .include does not modify the actual query, so we
# should not clear `filter_is_sticky`
if self.query.filter_is_sticky:
clone.qu... | 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. | 6.97724 | 6.806541 | 1.025079 |
'''
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']
... | 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.8.9.10.11012.13000001401516017181900000200']
:... | 3.628133 | 1.748391 | 2.075127 |
forms.Field.default_error_messages['required'] = _('This field is required')
forms.CharField.default_error_messages['min_length'] = _('You’ve entered too few characters')
forms.CharField.default_error_messages['max_length'] = _('You’ve entered too many characters')
forms.IntegerField.default_error_... | 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 | 1.681883 | 1.672559 | 1.005575 |
vocab = OrderedDict()
for line in fin:
v, c = line.strip().split()
vocab[v] = int(c)
return 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.
errors (bytes): Set the error han... | 2.654703 | 4.290141 | 0.618791 |
session = MoJOAuth2Session(
client=LegacyApplicationClient(
client_id=settings.API_CLIENT_ID
)
)
token = session.fetch_token(
token_url=get_request_token_url(),
username=username,
password=password,
auth=HTTPBasicAuth(settings.API_CLIENT_ID, ... | 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_name, last_name etc.
if the authentication s... | 2.946507 | 2.767418 | 1.064713 |
response = requests.post(
get_revoke_token_url(),
data={
'token': access_token,
'client_id': settings.API_CLIENT_ID,
'client_secret': settings.API_CLIENT_SECRET,
},
timeout=15
)
return response.status_code == 200 | def revoke_token(access_token) | Instructs the API to delete this access token and associated refresh token | 2.217077 | 2.322943 | 0.954426 |
session = MoJOAuth2Session(
client=LegacyApplicationClient(
client_id=settings.API_CLIENT_ID
)
)
session.fetch_token(
token_url=get_request_token_url(),
username=username,
password=password,
auth=HTTPBasicAuth(settings.API_CLIENT_ID, settings... | def get_authenticated_api_session(username, password) | :return: an authenticated api session | 3.142207 | 3.138404 | 1.001212 |
'''
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):
pargs = pic... | 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 | 3.538859 | 2.278506 | 1.553149 |
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:
return False
return True | def check_valid(line0, line1) | Check :func:`word_embedding_loader.loader.glove.check_valid` for the API. | 5.004846 | 4.956493 | 1.009755 |
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.fill(np.NaN)
for line in fin:
token, v = _load_line(line, dtype, size)
if token in vocab:
arr[vocab[token], :] = v
... | def load_with_vocab(fin, vocab, dtype=np.float32) | Refer to :func:`word_embedding_loader.loader.glove.load_with_vocab` for the API. | 3.616673 | 3.318701 | 1.089786 |
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_vocab, words)
size = int(data[1])
arr = np.empty((words, size), dtype=dtype)
i = 0
for n_line, line in enumerate(fin):
... | def load(fin, dtype=np.float32, max_vocab=None) | Refer to :func:`word_embedding_loader.loader.glove.load` for the API. | 3.937924 | 3.982521 | 0.988802 |
'''
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... | 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', '********')
:param alias: XNAT alias
:type alias: str
:param url: XNAT U... | 2.212414 | 1.656939 | 1.335242 |
'''
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... | 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/experiments/XNAT_S0001', label=u'AB1234C', id=u'XNAT_S0001',
... | 3.384762 | 2.137378 | 1.583605 |
'''
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'... | 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')
Experiment(uri=u'/data/experiments/XNAT_E0001', label=u'AB1234C', id=u'XNAT_... | 2.942153 | 1.953138 | 1.506372 |
'''
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`
... | 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 authentication
:type auth: :mod:`yaxil.XnatAuth`
:param la... | 3.85083 | 1.475872 | 2.609189 |
'''
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 i,member in enumerate(zf.infolist()):
... | 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 | 5.909119 | 5.197334 | 1.136952 |
'''
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
'''
if 'ResultSet' in check and 'ResultSet' not in r:
raise Result... | 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 | 2.728764 | 1.797219 | 1.518326 |
'''
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': "... | 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%",
... 'eor2': "note LIKE %EOR2%",
... 'mpr': "series_descr... | 3.572232 | 1.918766 | 1.861734 |
'''
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, inden... | 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 yaxil.scans2(auth, 'AB1234C'):
... print(json.dumps(scan, indent=2))
:... | 3.378999 | 2.017038 | 1.675229 |
'''
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))
... | 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.extendedboldqc2(auth, 'AB1234C')
... print(json.dumps(eqc, indent=2))
:param au... | 3.451824 | 1.9625 | 1.758891 |
'''
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: ... | 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, '/data/experiments', Format.JSON)
:param auth: XNAT authent... | 2.959241 | 1.649415 | 1.794115 |
'''
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.JSON:
return json.loads... | 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 | 2.052056 | 1.577467 | 1.300855 |
'''
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... | 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 auth: XNAT authentication
:type auth: :mod:`yaxi... | 4.193101 | 2.331818 | 1.798211 |
if not hasattr(request, '_cached_user'):
request._cached_user = auth_get_user(request)
return request._cached_user | def get_user(request) | Returns a cached copy of the user if it exists or calls `auth_get_user`
otherwise. | 2.728167 | 2.19248 | 1.244329 |
def wrapper(request, *args, **kwargs):
user_roles = request.user.user_data.get('roles', [])
if len(user_roles) != 1:
context = {
'message': 'I need to be able to manage user accounts. '
'My username is %s' % request.user.username
... | 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. | 3.821049 | 3.248018 | 1.176425 |
@functools.wraps(fn)
def process(self, tup):
try:
return fn(self, tup)
except Exception as e:
if isinstance(e, KeyboardInterrupt):
return
print(str(e), file=sys.stderr)
self.fail(tup)
return process | def fault_barrier(fn) | Method decorator to catch and log errors, then send fail message. | 2.941043 | 2.667301 | 1.102629 |
self.manager = get_search_manager()
config = get_config()['TwitterSearchBolt']
self.term_shelf = shelf_from_config(config) | 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. | 16.072395 | 14.650696 | 1.09704 |
term, timestamp = tup.values
if term not in self.term_shelf:
self.log(
'search: {term}, {timestamp}'
.format(term=term, timestamp=timestamp))
search_result = self.manager.search(q=term)
self.emit([term, timestamp, search_result... | 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). | 5.215619 | 3.638333 | 1.433519 |
term, timestamp, search_result = tup.values
self.log(
'lookup: {term}, {timestamp}'
.format(term=term, timestamp=timestamp))
lookup_result = self.manager.lookup_search_result(search_result)
self.emit([term, timestamp, lookup_result]) | 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). | 5.817719 | 3.163545 | 1.838987 |
config = get_config()['ElasticsearchIndexBolt']
elasticsearch_class = import_name(config['elasticsearch_class'])
self.es = elasticsearch_class(**config['elasticsearch_init'])
self.index = config['index']
self.doc_type = config['doc_type'] | def initialize(self, conf, ctx) | Initialization steps:
1. Prepare elasticsearch connection, including details for indexing. | 5.457712 | 4.864989 | 1.121834 |
self.es.bulk(
self.generate_bulk_body(tup.values[2]),
index=self.index,
doc_type=self.doc_type) | def process(self, tup) | Process steps:
1. Index third positional value from input to elasticsearch. | 5.36339 | 3.468862 | 1.546153 |
config = get_config()['ResultTopicBolt']
kafka_class = import_name(config['kafka_class'])
self.client = kafka_class(**config['kafka_init'])
self.topic = self.client.topics[config['topic']]
self.producer = self.topic.get_producer()
# Use own default index value w... | 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. | 11.024198 | 9.791138 | 1.125936 |
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 producer, instead of deserializing and
# reserializing json.
self.producer.produce(json.dumps(status) for statu... | def process(self, tup) | Process steps:
1. Stream third positional value from input into Kafka topic. | 13.436691 | 13.292839 | 1.010822 |
manager_cls = import_name(config['class'], default_ns='birding.search')
init = {}
init.update(default_init)
init.update(config['init'])
manager = manager_cls(**init)
return manager | 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`. | 4.684599 | 4.075194 | 1.14954 |
'''
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 sourcedata base directories
sourcedata_base = os.path.join(
... | def bids_from_config(sess, scans_metadata, config, out_base) | Create a BIDS output directory from configuration file | 3.602392 | 3.403058 | 1.058575 |
'''
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 'run' in scan:
tem... | def proc_anat(config, args) | Download anatomical data and convert to BIDS | 2.790002 | 2.734837 | 1.020171 |
'''
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': modality
})
... | def iterconfig(config, scan_type) | Iterate over BIDS configuration file | 5.11812 | 3.892498 | 1.314868 |
'''
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)
if os.path.exists(src):
... | def rename_fmapm(bids_base, basename) | Rename magnitude fieldmap file to BIDS specification | 2.923942 | 2.466539 | 1.185443 |
'''
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 = [
'dcm2niix',
... | def convert(input, output) | Run dcm2niix on input file | 2.809033 | 2.546104 | 1.103267 |
try:
response_body = json.loads(error.content.decode('utf-8'))
for field, errors in response_body.items():
if isinstance(errors, list):
for error in errors:
messages.error(request, error)
else:
messages.error(request, e... | 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 | 2.028761 | 2.057581 | 0.985993 |
page_size = getattr(settings, 'REQUEST_PAGE_SIZE', 20)
loaded_results = []
offset = 0
while True:
response = api_endpoint(limit=page_size, offset=offset,
**kwargs)
count = response.get('count', 0)
loaded_results += response.get('results', [])... | 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 kwargs: additional arguments to pass into api callable | 2.575736 | 2.759544 | 0.933392 |
page_size = getattr(settings, 'REQUEST_PAGE_SIZE', 20)
loaded_results = []
offset = 0
while True:
response = session.get(
path,
params=dict(limit=page_size, offset=offset, **params)
)
content = response.json()
count = content.get('count', 0)
... | 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 URL params | 2.39228 | 2.438993 | 0.980847 |
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) | Factory to dispatch spout class based on config. | 5.973731 | 5.316891 | 1.123538 |
self.terms = get_config()['TermCycleSpout']['terms']
self.term_seq = itertools.cycle(self.terms) | def initialize(self, stormconf, context) | Initialization steps:
1. Prepare sequence of terms based on config: TermCycleSpout/terms. | 17.897062 | 4.965084 | 3.604584 |
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) | Next tuple steps:
1. Emit (term, timestamp) for next term in sequence w/current UTC time. | 8.420544 | 5.166484 | 1.62984 |
'''
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):
rais... | 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 | 3.795667 | 1.865877 | 2.034253 |
'''
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 functiona... | 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 silently overwrite files that already exist on
Windows natively. For now, the functionality provide... | 3.673024 | 1.534594 | 2.393482 |
'''
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) | Same as which command on Linux | 2.989905 | 2.294114 | 1.303294 |
try:
from watchdog.observers import Observer
except ImportError:
context.pip_command('install', 'watchdog>0.8,<0.9')
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
class RebuildHandler(PatternMatchingEventHandler):
d... | def serve(context: Context, port=8000, browsersync_port=3000, browsersync_ui_port=3030) | Starts a development server with auto-building and live-reload | 2.313079 | 2.284295 | 1.012601 |
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) | Creates directories needed for build outputs | 4.448602 | 3.840019 | 1.158484 |
context.pip_command('install', '-r', context.requirements_file)
if common_path:
context.pip_command('uninstall', '--yes', 'money-to-prisoners-common')
context.pip_command('install', '--force-reinstall', '-e', common_path)
context.shell('rm', '-rf', 'webpack.config.js') | def python_dependencies(context: Context, common_path=None) | Updates python dependencies | 5.067304 | 4.590444 | 1.103881 |
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) | Updates node.js dependencies | 6.656834 | 4.856826 | 1.370614 |
output = io.StringIO()
with contextlib.redirect_stdout(output):
context.shell('docker-machine', 'ip', 'default')
host_machine_ip = output.getvalue().strip() or socket.gethostbyname(socket.gethostname())
args = ()
if context.verbosity > 1:
args += ('--verbose',)
args += ('up'... | 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 | 3.842448 | 3.481631 | 1.103635 |
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) | Compiles javascript | 6.177412 | 5.413653 | 1.14108 |
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')
for path in context.app.scss_include_paths:
args.append('--include-p... | def bundle_stylesheets(context: Context) | Compiles stylesheets | 4.102418 | 3.880808 | 1.057104 |
args = [
'--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'eslintrc.json'),
'--format', 'stylish',
]
if context.verbosity == 0:
args.append('--quiet')
if not context.use_colour:
args.append('--no-color')
args.append(context... | def lint_javascript(context: Context) | Tests javascript for code and style errors | 4.650816 | 4.280139 | 1.086604 |
args = [
'--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'sass-lint.yml'),
'--format', 'stylish',
'--syntax', 'scss',
]
if context.verbosity > 1:
args.append('--verbose')
args.append(os.path.join(context.app.scss_source_path, ... | def lint_stylesheets(context: Context) | Tests stylesheets for code and style errors | 4.230933 | 3.982423 | 1.062402 |
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/alphagov/govuk_template/releases' \
'/download/v{0}/django_govuk_template-{0}.tgz'.format(version)
try:
... | def govuk_template(context: Context, version='0.23.0', replace_fonts=True) | Installs GOV.UK template | 4.671136 | 4.552966 | 1.025955 |
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) | Collects assets from GOV.UK frontend toolkit | 5.280587 | 5.2001 | 1.015478 |
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) | Pre-compiles python modules | 7.472288 | 5.892674 | 1.268064 |
kwargs = {
'all': True,
'keep_pot': True,
'no_wrap': True,
}
if fuzzy:
kwargs['allow_fuzzy'] = True
if javascript:
kwargs.update(domain='djangojs', ignore_patterns=['*.bundle.js'])
with in_dir(context.app.django_app_name):
return context.managemen... | def make_messages(context: Context, javascript=False, fuzzy=False) | Collects text into translation source files | 7.361781 | 6.065809 | 1.213652 |
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)
make_messages(context, javascript=True)
if push:
context.shell('tx', 'push', '--source', '--no-int... | def translations(context: Context, pull=False, push=False) | Synchronises translations with transifex.com | 5.626794 | 4.980878 | 1.129679 |
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']
context.shell('rm -rf %s' % paths_for_shell(paths))
context.shell('find %s -name "*.pyc" -or -name __p... | def clean(context: Context, delete_dependencies: bool = False) | Deletes build outputs | 3.824656 | 3.584955 | 1.066863 |
if _csrf_failed_view.no_moj_csrf:
from django.views.csrf import csrf_failure
return csrf_failure(request, reason=reason)
# present a sensible error message to users
if reason == REASON_NO_CSRF_COOKIE:
reason = _('Please try again.') + ' ' + \
_('Make sure you ... | 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 | 3.938892 | 3.884043 | 1.014122 |
'''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):
with open(path, 'r') as meafile... | def add_mea(mea_yaml_path) | Adds the mea design defined by the yaml file in the install folder
Parameters
----------
mea_yaml_file
Returns
------- | 3.284032 | 2.979966 | 1.102037 |
'''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"))]
for e in electrodes:
... | def remove_mea(mea_name) | Adds the mea design defined by the yaml file in the install folder
Parameters
----------
mea_yaml_file
Returns
------- | 1.99187 | 1.688178 | 1.179893 |
l0 = f.readline()
l1 = f.readline()
return l0, l1 | def _get_two_lines(f) | Get the first and second lines
Args:
f (filelike): File that is opened for ascii.
Returns:
bytes | 3.273892 | 4.904099 | 0.667583 |
l0, l1 = _get_two_lines(f)
if loader.glove.check_valid(l0, l1):
return _glove
elif loader.word2vec_text.check_valid(l0, l1):
return _word2vec_text
elif loader.word2vec_bin.check_valid(l0, l1):
return _word2vec_bin
else:
raise OSError(b"Invalid 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 | 4.001099 | 3.507739 | 1.140649 |
freqs = None
if vocab is not None:
with open(vocab, mode='rb') as f:
freqs = loader.vocab.load_vocab(f)
# Create vocab from freqs
# [:None] gives all the list member
vocab = {k: i for i, (k, v) in enumerate(
so... | 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
with ``-save-vocab <file>`` option. If vocab is given,
:py:attr:`~vectors` and :py:attr:`~vocab` is ordere... | 3.801644 | 3.922195 | 0.969264 |
if use_load_condition:
if self._load_cond is None:
raise ValueError(
b"use_load_condition was specified but the object is not "
b"loaded from a file")
# Use load condition
mod = self._load_cond
else:
... | 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
:func:`~word_embedding_loader.word_embedding.WordEmbedding.load`
... | 3.90601 | 3.789711 | 1.030688 |
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=' ') | Converts a list of paths for use in shell commands | 3.200795 | 2.850925 | 1.122721 |
def outer(func):
task = Task(func, *dependencies, default=default, hidden=hidden, ignore_return_code=ignore_return_code)
overidden_task = self._tasks.pop(task.name, None)
if overidden_task:
self._overidden_tasks[task.name].append(overidden_task)
... | def register(self, *dependencies, default=False, hidden=False, ignore_return_code=False) | Decorates a callable to turn it into a task | 2.981593 | 2.685966 | 1.110064 |
if isinstance(task, str):
try:
return self[task]
except KeyError:
pass
raise TaskError('Unknown task %s' % task) | def lookup_task(self, task) | Looks up a task by name or by callable | 3.753974 | 3.636428 | 1.032325 |
default_tasks = list(filter(lambda task: task.default, self.values()))
if len(default_tasks) == 1:
return default_tasks[0] | def get_default_task(self) | Returns the default task if there is only one | 3.36051 | 2.708368 | 1.240788 |
group = cls()
signature = inspect.signature(func)
for parameter in signature.parameters.values():
if parameter.name.startswith('_') or parameter.name in ignored_parameters:
continue
parameter = Parameter.from_callable_parameter(parameter)
... | def from_callable(cls, func, ignored_parameters=set()) | Reads a function or method signature to produce a set of parameters | 2.611543 | 2.566207 | 1.017667 |
group = cls()
for name, value in mapping.items():
if name.startswith('_'):
continue
group[name] = Parameter(
name=name,
value=value,
constraint=Parameter.constraint_from_type(value),
)
re... | def from_mapping(cls, mapping) | Produces a set of parameters from a mapping | 3.725079 | 3.421307 | 1.088788 |
return dict((parameter.name, parameter.value) for parameter in self.values()) | def to_dict(self) | Converts the set of parameters into a dict | 8.118732 | 5.461703 | 1.486484 |
while True:
argument_count = len(argument_list)
for parameter in self.values():
argument_list = parameter.consume_arguments(argument_list)
if len(argument_list) == argument_count:
return argument_list | def consume_arguments(self, argument_list) | Takes arguments from a list while there are parameters that can accept them | 3.108561 | 2.71422 | 1.145287 |
for key, value in mapping.items():
if key in self:
if isinstance(value, Parameter):
value = value.value
self[key].value = value | def update_from(self, mapping) | Updates the set of parameters from a mapping for keys that already exist | 3.138425 | 2.677952 | 1.17195 |
if parameter.kind == parameter.KEYWORD_ONLY or \
parameter.kind == parameter.POSITIONAL_OR_KEYWORD and parameter.default is not parameter.empty:
if parameter.annotation is not parameter.empty:
constraint = parameter.annotation
else:
... | def from_callable_parameter(cls, parameter) | Produces a parameter from a function or method | 2.852751 | 2.792495 | 1.021578 |
if value is None:
return None
value_type = type(value)
if value_type in (str, int, bool):
return value_type
raise ParameterError('Parameter type cannot be %s' % value_type) | def constraint_from_type(cls, value) | Returns the constraint callable given a value | 3.992558 | 4.020751 | 0.992988 |
choices_str = ', '.join(map(str, choices))
def constraint(value):
value = value_type(value)
if value not in choices:
raise ParameterError('Argument must be one of %s' % choices_str)
return value
constraint.__name__ = 'choices_%s' % v... | def constraint_from_choices(cls, value_type: type, choices: collections.Sequence) | Returns a constraint callable based on choices of a given type | 2.911767 | 2.657773 | 1.095567 |
if self.constraint is bool and self.value:
return '--no-%s' % self.name.replace('_', '-')
return '--%s' % self.name.replace('_', '-') | def arg_name(self) | Returns the name of the parameter as a command line flag | 4.691888 | 4.052645 | 1.157735 |
if len(argument_list) == 0:
return []
if argument_list[0] == self.arg_name:
argument_list = argument_list[1:]
if self.constraint is bool:
self.value = not self.value
else:
try:
value = argument_l... | def consume_arguments(self, argument_list) | Takes arguments from a list while this parameter can accept them | 3.040443 | 2.854834 | 1.065016 |
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.insert(0, '--quiet')
elif self.verbosity == 2:
args.insert(0, ... | def pip_command(self, command, *args) | Runs a pip command | 2.052447 | 2.125821 | 0.965485 |
command += ' ' + ' '.join(args)
command = command.strip()
self.debug(self.yellow_style('$ %s' % command))
env = self.env.copy()
env.update(environment or {})
return subprocess.call(command, shell=True, env=env) | def shell(self, command, *args, environment=None) | Runs a shell command | 3.577072 | 3.872788 | 0.923643 |
self.setup_django()
if 'verbosity' not in kwargs:
kwargs['verbosity'] = self.verbosity
if not self.use_colour:
kwargs['no_color'] = False
self.debug(self.yellow_style('$ manage.py %s' % command))
return call_command(command, *args, **kwargs) | def management_command(self, command, *args, **kwargs) | Runs a Django management command | 4.408083 | 4.169704 | 1.057169 |
context.info('%s\n%s [global options] [task] [task options]...\n' % (self.name, sys.argv[0]))
def print_parameter(prn, p):
if p.description:
suffix = ' - {0.description}'.format(p)
else:
suffix = ''
if p.constraint is bool:... | def help(self, context) | Prints this help (use --verbosity 2 for more details) | 3.349014 | 3.285182 | 1.01943 |
session_auth_hash = ''
if user is None:
user = request.user
if hasattr(user, 'get_session_auth_hash'):
session_auth_hash = user.get_session_auth_hash()
if SESSION_KEY in request.session:
session_key = request.session[SESSION_KEY]
if session_key != user.pk or (
... | def login(request, user) | Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in. | 2.557931 | 2.490533 | 1.027062 |
user = None
try:
user_id = request.session[SESSION_KEY]
token = request.session[AUTH_TOKEN_SESSION_KEY]
user_data = request.session[USER_DATA_SESSION_KEY]
backend_path = request.session[BACKEND_SESSION_KEY]
except KeyError:
pass
else:
if backend_path ... | def get_user(request) | Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `MojAnonymousUser` is returned. | 2.565891 | 2.207627 | 1.162285 |
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, 'user', None)
if hasattr(user, 'is_authenticated') and not user.is_authenticated:
user = None
user_logged_out.send(sender=user.__class__, request=re... | def logout(request) | Removes the authenticated user's ID from the request and flushes their
session data. | 3.865246 | 3.800212 | 1.017113 |
f.write(('%d %d' % (arr.shape[0], arr.shape[1])).encode('utf-8'))
for word, idx in vocab:
_write_line(f, arr[idx], word) | def save(f, arr, vocab) | Save word embedding file.
Check :func:`word_embedding_loader.saver.glove.save` for the API. | 3.551857 | 3.894555 | 0.912006 |
def decorator(func):
context_name = None
keyword_kinds = {inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY}
invalid_body_params = set(body_params)
for name, parameter in inspect.signature(func).parameters.items():
if parameter.kind not in keyw... | def spoolable(*, pre_condition=True, body_params=()) | Decorates a function to make it spoolable using uWSGI, but if no spooling mechanism is available,
the function is called synchronously. All decorated function arguments must be picklable and
the first annotated with `Context` will receive an object that defines the current execution state.
Return values are... | 2.841391 | 2.76107 | 1.02909 |
return {k:getattr(self, k, None) for k in self.schema.fields} | def fields(self) | return all the fields and their raw values for this Orm instance. This
property returns a dict with the field names and their current values
if you want to control the values for outputting to an api, use .jsonable() | 6.068703 | 4.981997 | 1.218127 |
# NOTE -- you cannot use hydrate/populate here because populate alters modified fields
instance = cls(fields, **fields_kwargs)
instance.save()
return instance | def create(cls, fields=None, **fields_kwargs) | create an instance of cls with the passed in fields and set it into the db
fields -- dict -- field_name keys, with their respective values
**fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also | 14.422296 | 12.31672 | 1.170953 |
# this will run all the fields of the Orm, not just the fields in fields
# dict, another name would be hydrate
pop_fields = {}
fields = self.make_dict(fields, fields_kwargs)
for k in self.schema.fields.keys():
pop_fields[k] = fields.get(k, None)
sel... | def populate(self, fields=None, **fields_kwargs) | take the passed in fields, combine them with missing fields that should
be there and then run all those through appropriate methods to hydrate this
orm.
The method replaces cls.hydrate() since it was becoming hard to understand
what was going on with all these methods that did things ju... | 7.890478 | 6.60538 | 1.194553 |
schema = self.schema
for k, v in fields.items():
fields[k] = schema.fields[k].iget(self, v)
self.modify(fields)
self.reset_modified() | def _populate(self, fields) | this runs all the fields through their iget methods to mimic them
freshly coming out of the db, then resets modified
:param fields: dict, the fields that were passed in | 5.897366 | 3.789392 | 1.556283 |
fields = {}
schema = self.schema
for k, field in schema.fields.items():
is_modified = k in self.modified_fields
orig_v = getattr(self, k)
v = field.iset(
self,
orig_v,
is_update=is_update,
... | def depopulate(self, is_update) | Get all the fields that need to be saved
:param is_udpate: bool, True if update query, False if insert
:returns: dict, key is field_name and val is the field value to be saved | 3.293949 | 3.445203 | 0.956097 |
ret = True
schema = self.schema
fields = self.depopulate(False)
q = self.query
q.set_fields(fields)
pk = q.insert()
if pk:
fields = q.fields
fields[schema.pk.name] = pk
self._populate(fields)
else:
... | def insert(self) | persist the field values of this orm | 6.173733 | 5.75498 | 1.072764 |
ret = True
fields = self.depopulate(True)
q = self.query
q.set_fields(fields)
pk = self.pk
if pk:
q.is_field(self.schema.pk.name, pk)
else:
raise ValueError("You cannot update without a primary key")
if q.update():
... | def update(self) | re-persist the updated field values of this orm that has a primary key | 6.511533 | 5.449696 | 1.194843 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.