_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q56100 | pair_distance_centile | train | def pair_distance_centile(X, centile, max_pairs=5000):
"""
Calculate centiles of distances between random pairs in a dataset.
This an alternative to the median kNN distance for setting the kernel
length scale.
"""
N = X.shape[0]
n_pairs = min(max_pairs, N**2)
# randorder1 = np.random.pe... | python | {
"resource": ""
} |
q56101 | LSAnomaly.fit | train | def fit(self, X, y=None):
"""
Fit the inlier model given training data.
This function attempts to choose reasonable defaults for parameters
sigma and rho if none are specified, which could then be adjusted
to improve performance.
Parameters
----------
X ... | python | {
"resource": ""
} |
q56102 | LSAnomaly.predict | train | def predict(self, X):
"""
Assign classes to test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns
-------
y_predicted : array
A vector of ... | python | {
"resource": ""
} |
q56103 | LSAnomaly.predict_proba | train | def predict_proba(self, X):
"""
Calculate posterior probabilities of test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
y_prob : array
... | python | {
"resource": ""
} |
q56104 | LSAnomaly.decision_function | train | def decision_function(self, X):
"""
Generate an inlier score for each test data example.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
scores : ... | python | {
"resource": ""
} |
q56105 | LSAnomaly.score | train | def score(self, X, y):
"""
Calculate accuracy score.
Needed because of bug in metrics.accuracy_score when comparing
list with numpy array.
"""
predictions = self.predict(X)
true = 0.0
total = 0.0
for i in range(len(predictions)):
total... | python | {
"resource": ""
} |
q56106 | LSAnomaly.predict_sequence | train | def predict_sequence(self, X, A, pi, inference='smoothing'):
"""
Calculate class probabilities for a sequence of data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are time frames, columns
are data dimensions)
A : class ... | python | {
"resource": ""
} |
q56107 | toggle_sensor | train | def toggle_sensor(request, sensorname):
"""
This is used only if websocket fails
"""
if service.read_only:
service.logger.warning("Could not perform operation: read only mode enabled")
raise Http404
source = request.GET.get('source', 'main')
sensor = service.system.namespace[sens... | python | {
"resource": ""
} |
q56108 | toggle_value | train | def toggle_value(request, name):
"""
For manual shortcut links to perform toggle actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.read_only:
raise Http404
new_status = obj.status = not obj.status
if service.redirect_from_setters:
return HttpRes... | python | {
"resource": ""
} |
q56109 | set_value | train | def set_value(request, name, value):
"""
For manual shortcut links to perform set value actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.read_only:
raise Http404
obj.status = value
if service.redirect_from_setters:
return HttpResponseRedirect(r... | python | {
"resource": ""
} |
q56110 | SystemObject.object_type | train | def object_type(self):
"""
A read-only property that gives the object type as string; sensor, actuator, program, other.
Used by WEB interface templates.
"""
from .statusobject import AbstractSensor, AbstractActuator
from .program import Program
if isinsta... | python | {
"resource": ""
} |
q56111 | SystemObject.get_as_datadict | train | def get_as_datadict(self):
"""
Get information about this object as a dictionary. Used by WebSocket interface to pass some
relevant information to client applications.
"""
return dict(type=self.__class__.__name__, tags=list(self.tags)) | python | {
"resource": ""
} |
q56112 | SystemObject.setup_system | train | def setup_system(self, system, name_from_system='', **kwargs):
"""
Set system attribute and do some initialization. Used by System.
"""
if not self.system:
self.system = system
name, traits = self._passed_arguments
new_name = self.system.get_unique_name(s... | python | {
"resource": ""
} |
q56113 | SystemObject.setup_callables | train | def setup_callables(self):
"""
Setup Callable attributes that belong to this object.
"""
defaults = self.get_default_callables()
for key, value in list(defaults.items()):
self._postponed_callables.setdefault(key, value)
for key in self.callables:
... | python | {
"resource": ""
} |
q56114 | grab_keyfile | train | def grab_keyfile(cert_url):
"""
Function to acqure the keyfile
SNS keys expire and Amazon does not promise they will use the same key
for all SNS requests. So we need to keep a copy of the cert in our
cache
"""
key_cache = caches[getattr(settings, 'BOUNCY_KEY_CACHE', 'default')]
pemfil... | python | {
"resource": ""
} |
q56115 | verify_notification | train | def verify_notification(data):
"""
Function to verify notification came from a trusted source
Returns True if verfied, False if not verified
"""
pemfile = grab_keyfile(data['SigningCertURL'])
cert = crypto.load_certificate(crypto.FILETYPE_PEM, pemfile)
signature = base64.decodestring(six.b(... | python | {
"resource": ""
} |
q56116 | approve_subscription | train | def approve_subscription(data):
"""
Function to approve a SNS subscription with Amazon
We don't do a ton of verification here, past making sure that the endpoint
we're told to go to to verify the subscription is on the correct host
"""
url = data['SubscribeURL']
domain = urlparse(url).netl... | python | {
"resource": ""
} |
q56117 | clean_time | train | def clean_time(time_string):
"""Return a datetime from the Amazon-provided datetime string"""
# Get a timezone-aware datetime object from the string
time = dateutil.parser.parse(time_string)
if not settings.USE_TZ:
# If timezone support is not active, convert the time to UTC and
# remove... | python | {
"resource": ""
} |
q56118 | parse_selectors | train | def parse_selectors(model, fields=None, exclude=None, key_map=None, **options):
"""Validates fields are valid and maps pseudo-fields to actual fields
for a given model class.
"""
fields = fields or DEFAULT_SELECTORS
exclude = exclude or ()
key_map = key_map or {}
validated = []
for alia... | python | {
"resource": ""
} |
q56119 | ModelFieldResolver._get_local_fields | train | def _get_local_fields(self, model):
"Return the names of all locally defined fields on the model class."
local = [f for f in model._meta.fields]
m2m = [f for f in model._meta.many_to_many]
fields = local + m2m
names = tuple([x.name for x in fields])
return {
... | python | {
"resource": ""
} |
q56120 | ModelFieldResolver._get_related_fields | train | def _get_related_fields(self, model):
"Returns the names of all related fields for model class."
reverse_fk = self._get_all_related_objects(model)
reverse_m2m = self._get_all_related_many_to_many_objects(model)
fields = tuple(reverse_fk + reverse_m2m)
names = tuple([x.get_access... | python | {
"resource": ""
} |
q56121 | HTMLTable.to_html | train | def to_html(self, index=False, escape=False, header=True,
collapse_table=True, class_outer="table_outer", **kargs):
"""Return HTML version of the table
This is a wrapper of the to_html method of the pandas dataframe.
:param bool index: do not include the index
:param bool e... | python | {
"resource": ""
} |
q56122 | HTMLTable.add_bgcolor | train | def add_bgcolor(self, colname, cmap='copper', mode='absmax',
threshold=2):
"""Change column content into HTML paragraph with background color
:param colname:
:param cmap: a colormap (matplotlib) or created using
colormap package (from pypi).
:param mode: type of ... | python | {
"resource": ""
} |
q56123 | TrackingEventAdmin.changelist_view | train | def changelist_view(self, request, extra_context=None):
""" Get object currently tracked and add a button to get back to it """
extra_context = extra_context or {}
if 'object' in request.GET.keys():
value = request.GET['object'].split(':')
content_type = get_object_or_404... | python | {
"resource": ""
} |
q56124 | ConfigsService.list | train | def list(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin
"""Get a list of configs.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) Sort fields ... | python | {
"resource": ""
} |
q56125 | ConfigsService.iter_list | train | def iter_list(self, *args, **kwargs):
"""Get a list of configs. Whereas ``list`` fetches a single page of
configs according to its ``limit`` and ``page`` arguments,
``iter_list`` returns all configs by internally making
successive calls to ``list``.
:param args: Arguments that ... | python | {
"resource": ""
} |
q56126 | ConfigsService.get_plaintext | train | def get_plaintext(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Get a config as plaintext.
:param id: Config ID as an int.
:rtype: string
"""
return self.service.get_id(self.base, id, params={'format': 'text'}).text | python | {
"resource": ""
} |
q56127 | ConfigsService.create | train | def create(self, resource):
"""Create a new config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config
"""
schema = self.CREATE_SCHEMA
json = self.service.encode(schema,... | python | {
"resource": ""
} |
q56128 | ConfigsService.edit | train | def edit(self, resource):
"""Edit a config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config
"""
schema = self.EDIT_SCHEMA
json = self.service.encode(schema, resource)... | python | {
"resource": ""
} |
q56129 | ConfigsService.edit_shares | train | def edit_shares(self, id, user_ids): # pylint: disable=invalid-name,redefined-builtin
"""Edit shares for a config.
:param id: Config ID as an int.
:param user_ids: User IDs as int list.
:return: :class:`cdrouter.Share <cdrouter.Share>` list
"""
return self.service.edit_s... | python | {
"resource": ""
} |
q56130 | ConfigsService.check_config | train | def check_config(self, contents):
"""Process config contents with cdrouter-cli -check-config.
:param contents: Config contents as string.
:return: :class:`configs.CheckConfig <configs.CheckConfig>` object
:rtype: configs.CheckConfig
"""
schema = CheckConfigSchema()
... | python | {
"resource": ""
} |
q56131 | ConfigsService.upgrade_config | train | def upgrade_config(self, contents):
"""Process config contents with cdrouter-cli -upgrade-config.
:param contents: Config contents as string.
:return: :class:`configs.UpgradeConfig <configs.UpgradeConfig>` object
:rtype: configs.UpgradeConfig
"""
schema = UpgradeConfigSc... | python | {
"resource": ""
} |
q56132 | ConfigsService.get_networks | train | def get_networks(self, contents):
"""Process config contents with cdrouter-cli -print-networks-json.
:param contents: Config contents as string.
:return: :class:`configs.Networks <configs.Networks>` object
:rtype: configs.Networks
"""
schema = NetworksSchema()
re... | python | {
"resource": ""
} |
q56133 | ConfigsService.bulk_copy | train | def bulk_copy(self, ids):
"""Bulk copy a set of configs.
:param ids: Int list of config IDs.
:return: :class:`configs.Config <configs.Config>` list
"""
schema = self.GET_SCHEMA
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | python | {
"resource": ""
} |
q56134 | ConfigsService.bulk_edit | train | def bulk_edit(self, _fields, ids=None, filter=None, type=None, all=False, testvars=None): # pylint: disable=redefined-builtin
"""Bulk edit a set of configs.
:param _fields: :class:`configs.Config <configs.Config>` object
:param ids: (optional) Int list of config IDs.
:param filter: (opt... | python | {
"resource": ""
} |
q56135 | ConfigsService.bulk_delete | train | def bulk_delete(self, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin
"""Bulk delete a set of configs.
:param ids: (optional) Int list of config IDs.
:param filter: (optional) String list of filters.
:param type: (optional) `union` or `inter` as string.... | python | {
"resource": ""
} |
q56136 | response_token_setter | train | def response_token_setter(remote, resp):
"""Extract token from response and set it for the user.
:param remote: The remote application.
:param resp: The response.
:raises invenio_oauthclient.errors.OAuthClientError: If authorization with
remote service failed.
:raises invenio_oauthclient.er... | python | {
"resource": ""
} |
q56137 | oauth1_token_setter | train | def oauth1_token_setter(remote, resp, token_type='', extra_data=None):
"""Set an OAuth1 token.
:param remote: The remote application.
:param resp: The response.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ``None``)
:returns: A :class:`inv... | python | {
"resource": ""
} |
q56138 | oauth2_token_setter | train | def oauth2_token_setter(remote, resp, token_type='', extra_data=None):
"""Set an OAuth2 token.
The refresh_token can be used to obtain a new access_token after
the old one is expired. It is saved in the database for long term use.
A refresh_token will be present only if `access_type=offline` is include... | python | {
"resource": ""
} |
q56139 | token_setter | train | def token_setter(remote, token, secret='', token_type='', extra_data=None,
user=None):
"""Set token for user.
:param remote: The remote application.
:param token: The token to set.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ... | python | {
"resource": ""
} |
q56140 | token_getter | train | def token_getter(remote, token=''):
"""Retrieve OAuth access token.
Used by flask-oauthlib to get the access token when making requests.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default... | python | {
"resource": ""
} |
q56141 | token_delete | train | def token_delete(remote, token=''):
"""Remove OAuth access tokens from session.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default: ``''``)
:returns: The token.
"""
session_key = t... | python | {
"resource": ""
} |
q56142 | oauth_error_handler | train | def oauth_error_handler(f):
"""Decorator to handle exceptions."""
@wraps(f)
def inner(*args, **kwargs):
# OAuthErrors should not happen, so they are not caught here. Hence
# they will result in a 500 Internal Server Error which is what we
# are interested in.
try:
... | python | {
"resource": ""
} |
q56143 | authorized_default_handler | train | def authorized_default_handler(resp, remote, *args, **kwargs):
"""Store access token in session.
Default authorized handler.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response.
"""
response_token_setter(remote, resp)
db.session.commit()
re... | python | {
"resource": ""
} |
q56144 | signup_handler | train | def signup_handler(remote, *args, **kwargs):
"""Handle extra signup information.
:param remote: The remote application.
:returns: Redirect response or the template rendered.
"""
# User already authenticated so move on
if current_user.is_authenticated:
return redirect('/')
# Retriev... | python | {
"resource": ""
} |
q56145 | oauth_logout_handler | train | def oauth_logout_handler(sender_app, user=None):
"""Remove all access tokens from session on logout."""
oauth = current_app.extensions['oauthlib.client']
for remote in oauth.remote_apps.values():
token_delete(remote)
db.session.commit() | python | {
"resource": ""
} |
q56146 | make_handler | train | def make_handler(f, remote, with_response=True):
"""Make a handler for authorized and disconnect callbacks.
:param f: Callable or an import path to a callable
"""
if isinstance(f, six.string_types):
f = import_string(f)
@wraps(f)
def inner(*args, **kwargs):
if with_response:
... | python | {
"resource": ""
} |
q56147 | _enable_lock | train | def _enable_lock(func):
"""
The decorator for ensuring thread-safe when current cache instance is concurrent status.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if self.is_concurrent:
only_read = kwargs.get('only_read')
if only_rea... | python | {
"resource": ""
} |
q56148 | _enable_cleanup | train | def _enable_cleanup(func):
"""
Execute cleanup operation when the decorated function completed.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
result = func(*args, **kwargs)
self.cleanup(self)
return result
return wrapper | python | {
"resource": ""
} |
q56149 | _enable_thread_pool | train | def _enable_thread_pool(func):
"""
Use thread pool for executing a task if self.enable_thread_pool is True.
Return an instance of future when flag is_async is True otherwise will to
block waiting for the result until timeout then returns the result.
"""
@functools.wraps(func)
def wrapper(*... | python | {
"resource": ""
} |
q56150 | Cache.statistic_record | train | def statistic_record(self, desc=True, timeout=3, is_async=False, only_read=True, *keys):
"""
Returns a list that each element is a dictionary of the statistic info of the cache item.
"""
if len(keys) == 0:
records = self._generate_statistic_records()
else:
... | python | {
"resource": ""
} |
q56151 | signature_unsafe | train | def signature_unsafe(m, sk, pk, hash_func=H):
"""
Not safe to use with secret keys or secret data.
See module docstring. This function should be used for testing only.
"""
h = hash_func(sk)
a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2))
r = Hint(bytearray([h[j] for j in... | python | {
"resource": ""
} |
q56152 | checkvalid | train | def checkvalid(s, m, pk):
"""
Not safe to use when any argument is secret.
See module docstring. This function should be used only for
verifying public signatures of public messages.
"""
if len(s) != b // 4:
raise ValueError("signature length is wrong")
if len(pk) != b // 8:
... | python | {
"resource": ""
} |
q56153 | dict | train | def dict():
"""
Compatibility with NLTK.
Returns the cmudict lexicon as a dictionary, whose keys are
lowercase words and whose values are lists of pronunciations.
"""
default = defaultdict(list)
for key, value in entries():
default[key].append(value)
return default | python | {
"resource": ""
} |
q56154 | symbols | train | def symbols():
"""Return a list of symbols."""
symbols = []
for line in symbols_stream():
symbols.append(line.decode('utf-8').strip())
return symbols | python | {
"resource": ""
} |
q56155 | Dagger.connect_inputs | train | def connect_inputs(self, datas):
"""
Connects input ``Pipers`` to "datas" input data in the correct order
determined, by the ``Piper.ornament`` attribute and the ``Dagger._cmp``
function.
It is assumed that the input data is in the form of an iterator and
that all inp... | python | {
"resource": ""
} |
q56156 | Dagger.start | train | def start(self):
"""
Given the pipeline topology starts ``Pipers`` in the order input ->
output. See ``Piper.start``. ``Pipers`` instances are started in two
stages, which allows them to share ``NuMaps``.
"""
# top - > bottom of pipeline
pipers = self.p... | python | {
"resource": ""
} |
q56157 | Dagger.stop | train | def stop(self):
"""
Stops the ``Pipers`` according to pipeline topology.
"""
self.log.debug('%s begins stopping routine' % repr(self))
self.log.debug('%s triggers stopping in input pipers' % repr(self))
inputs = self.get_inputs()
for piper in inputs:
... | python | {
"resource": ""
} |
q56158 | Dagger.del_piper | train | def del_piper(self, piper, forced=False):
"""
Removes a ``Piper`` from the ``Dagger`` instance.
Arguments:
- piper(``Piper`` or id(``Piper``)) ``Piper`` instance or ``Piper``
instance id.
- forced(bool) [default: ``False``] If "forced" is ``True``, wil... | python | {
"resource": ""
} |
q56159 | Plumber.start | train | def start(self, datas):
"""
Starts the pipeline by connecting the input ``Pipers`` of the pipeline
to the input data, connecting the pipeline and starting the ``NuMap``
instances.
The order of items in the "datas" argument sequence should correspond
to the orde... | python | {
"resource": ""
} |
q56160 | Plumber.pause | train | def pause(self):
"""
Pauses a running pipeline. This will stop retrieving results from the
pipeline. Parallel parts of the pipeline will stop after the ``NuMap``
buffer is has been filled. A paused pipeline can be run or stopped.
"""
# 1. stop the plumbing thr... | python | {
"resource": ""
} |
q56161 | Plumber.stop | train | def stop(self):
"""
Stops a paused pipeline. This will a trigger a ``StopIteration`` in the
inputs of the pipeline. And retrieve the buffered results. This will
stop all ``Pipers`` and ``NuMaps``. Python will not terminate cleanly
if a pipeline is running or paused.
... | python | {
"resource": ""
} |
q56162 | _Consume.next | train | def next(self):
"""
Returns the next sequence of results, given stride and n.
"""
try:
results = self._stride_buffer.pop()
except (IndexError, AttributeError):
self._rebuffer()
results = self._stride_buffer.pop()
if not results... | python | {
"resource": ""
} |
q56163 | _Chain.next | train | def next(self):
"""
Returns the next result from the chained iterables given ``"stride"``.
"""
if self.s:
self.s -= 1
else:
self.s = self.stride - 1
self.i = (self.i + 1) % self.l # new iterable
return self.iterables[self.i].ne... | python | {
"resource": ""
} |
q56164 | ResultsService.list_csv | train | def list_csv(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin
"""Get a list of results as CSV.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) S... | python | {
"resource": ""
} |
q56165 | ResultsService.updates | train | def updates(self, id, update_id=None): # pylint: disable=invalid-name,redefined-builtin
"""Get updates of a running result via long-polling. If no updates are available, CDRouter waits up to 10 seconds before sending an empty response.
:param id: Result ID as an int.
:param update_id: (optiona... | python | {
"resource": ""
} |
q56166 | ResultsService.pause | train | def pause(self, id, when=None): # pylint: disable=invalid-name,redefined-builtin
"""Pause a running result.
:param id: Result ID as an int.
:param when: Must be string `end-of-test` or `end-of-loop`.
"""
return self.service.post(self.base+str(id)+'/pause/', params={'when': when}... | python | {
"resource": ""
} |
q56167 | ResultsService.unpause | train | def unpause(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Unpause a running result.
:param id: Result ID as an int.
"""
return self.service.post(self.base+str(id)+'/unpause/') | python | {
"resource": ""
} |
q56168 | ResultsService.export | train | def export(self, id, exclude_captures=False): # pylint: disable=invalid-name,redefined-builtin
"""Export a result.
:param id: Result ID as an int.
:param exclude_captures: If bool `True`, don't export capture files
:rtype: tuple `(io.BytesIO, 'filename')`
"""
return self... | python | {
"resource": ""
} |
q56169 | ResultsService.bulk_export | train | def bulk_export(self, ids, exclude_captures=False):
"""Bulk export a set of results.
:param ids: Int list of result IDs.
:rtype: tuple `(io.BytesIO, 'filename')`
"""
return self.service.bulk_export(self.base, ids, params={'exclude_captures': exclude_captures}) | python | {
"resource": ""
} |
q56170 | ResultsService.bulk_copy | train | def bulk_copy(self, ids):
"""Bulk copy a set of results.
:param ids: Int list of result IDs.
:return: :class:`results.Result <results.Result>` list
"""
schema = ResultSchema()
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | python | {
"resource": ""
} |
q56171 | ResultsService.all_stats | train | def all_stats(self):
"""Compute stats for all results.
:return: :class:`results.AllStats <results.AllStats>` object
:rtype: results.AllStats
"""
schema = AllStatsSchema()
resp = self.service.post(self.base, params={'stats': 'all'})
return self.service.decode(sche... | python | {
"resource": ""
} |
q56172 | ResultsService.set_stats | train | def set_stats(self, ids):
"""Compute stats for a set of results.
:param id: Result IDs as int list.
:return: :class:`results.SetStats <results.SetStats>` object
:rtype: results.SetStats
"""
schema = SetStatsSchema()
resp = self.service.post(self.base, params={'st... | python | {
"resource": ""
} |
q56173 | ResultsService.diff_stats | train | def diff_stats(self, ids):
"""Compute diff stats for a set of results.
:param id: Result IDs as int list.
:return: :class:`results.DiffStats <results.DiffStats>` object
:rtype: results.DiffStats
"""
schema = DiffStatsSchema()
resp = self.service.post(self.base, p... | python | {
"resource": ""
} |
q56174 | ResultsService.single_stats | train | def single_stats(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Compute stats for a result.
:param id: Result ID as an int.
:return: :class:`results.SingleStats <results.SingleStats>` object
:rtype: results.SingleStats
"""
schema = SingleStatsSchema()
... | python | {
"resource": ""
} |
q56175 | ResultsService.progress_stats | train | def progress_stats(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Compute progress stats for a result.
:param id: Result ID as an int.
:return: :class:`results.Progress <results.Progress>` object
:rtype: results.Progress
"""
schema = ProgressSchema()
... | python | {
"resource": ""
} |
q56176 | ResultsService.summary_stats | train | def summary_stats(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Compute summary stats for a result.
:param id: Result ID as an int.
:return: :class:`results.SummaryStats <results.SummaryStats>` object
:rtype: results.SummaryStats
"""
schema = SummaryStat... | python | {
"resource": ""
} |
q56177 | ResultsService.list_logdir | train | def list_logdir(self, id, filter=None, sort=None): # pylint: disable=invalid-name,redefined-builtin
"""Get a list of logdir files.
:param id: Result ID as an int.
:param filter: Filter to apply as string.
:param sort: Sort field to apply as string.
:return: :class:`results.LogDi... | python | {
"resource": ""
} |
q56178 | ResultsService.get_logdir_file | train | def get_logdir_file(self, id, filename): # pylint: disable=invalid-name,redefined-builtin
"""Download a logdir file.
:param id: Result ID as an int.
:param filename: Logdir filename as string.
:rtype: tuple `(io.BytesIO, 'filename')`
"""
resp = self.service.get(self.base... | python | {
"resource": ""
} |
q56179 | ResultsService.download_logdir_archive | train | def download_logdir_archive(self, id, format='zip', exclude_captures=False): # pylint: disable=invalid-name,redefined-builtin
"""Download logdir archive in tgz or zip format.
:param id: Result ID as an int.
:param format: (optional) Format to download, must be string `zip` or `tgz`.
:pa... | python | {
"resource": ""
} |
q56180 | logout | train | def logout():
"""CERN logout view."""
logout_url = REMOTE_APP['logout_url']
apps = current_app.config.get('OAUTHCLIENT_REMOTE_APPS')
if apps:
cern_app = apps.get('cern', REMOTE_APP)
logout_url = cern_app['logout_url']
return redirect(logout_url, code=302) | python | {
"resource": ""
} |
q56181 | find_remote_by_client_id | train | def find_remote_by_client_id(client_id):
"""Return a remote application based with given client ID."""
for remote in current_oauthclient.oauth.remote_apps.values():
if remote.name == 'cern' and remote.consumer_key == client_id:
return remote | python | {
"resource": ""
} |
q56182 | fetch_groups | train | def fetch_groups(groups):
"""Prepare list of allowed group names.
:param groups: The complete list of groups.
:returns: A filtered list of groups.
"""
hidden_groups = current_app.config.get(
'OAUTHCLIENT_CERN_HIDDEN_GROUPS', OAUTHCLIENT_CERN_HIDDEN_GROUPS)
hidden_groups_re = current_app... | python | {
"resource": ""
} |
q56183 | fetch_extra_data | train | def fetch_extra_data(resource):
"""Return a dict with extra data retrieved from cern oauth."""
person_id = resource.get('PersonID', [None])[0]
identity_class = resource.get('IdentityClass', [None])[0]
department = resource.get('Department', [None])[0]
return dict(
person_id=person_id,
... | python | {
"resource": ""
} |
q56184 | account_groups_and_extra_data | train | def account_groups_and_extra_data(account, resource,
refresh_timedelta=None):
"""Fetch account groups and extra data from resource if necessary."""
updated = datetime.utcnow()
modified_since = updated
if refresh_timedelta is not None:
modified_since += refresh_t... | python | {
"resource": ""
} |
q56185 | extend_identity | train | def extend_identity(identity, groups):
"""Extend identity with roles based on CERN groups."""
provides = set([UserNeed(current_user.email)] + [
RoleNeed('{0}@cern.ch'.format(name)) for name in groups
])
identity.provides |= provides
session[OAUTHCLIENT_CERN_SESSION_KEY] = provides | python | {
"resource": ""
} |
q56186 | get_dict_from_response | train | def get_dict_from_response(response):
"""Prepare new mapping with 'Value's groupped by 'Type'."""
result = {}
if getattr(response, '_resp') and response._resp.code > 400:
return result
for i in response.data:
# strip the schema from the key
k = i['Type'].replace(REMOTE_APP_RESOU... | python | {
"resource": ""
} |
q56187 | get_resource | train | def get_resource(remote):
"""Query CERN Resources to get user info and groups."""
cached_resource = session.pop('cern_resource', None)
if cached_resource:
return cached_resource
response = remote.get(REMOTE_APP_RESOURCE_API_URL)
dict_response = get_dict_from_response(response)
session['... | python | {
"resource": ""
} |
q56188 | on_identity_changed | train | def on_identity_changed(sender, identity):
"""Store groups in session whenever identity changes.
:param identity: The user identity where information are stored.
"""
if isinstance(identity, AnonymousIdentity):
return
client_id = current_app.config['CERN_APP_CREDENTIALS']['consumer_key']
... | python | {
"resource": ""
} |
q56189 | RemoteAccount.get | train | def get(cls, user_id, client_id):
"""Get RemoteAccount object for user.
:param user_id: User id
:param client_id: Client id.
:returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance.
"""
return cls.query.filter_by(
user_id=user_id,
c... | python | {
"resource": ""
} |
q56190 | RemoteAccount.create | train | def create(cls, user_id, client_id, extra_data):
"""Create new remote account for user.
:param user_id: User id.
:param client_id: Client id.
:param extra_data: JSON-serializable dictionary of any extra data that
needs to be save together with this link.
:returns: A ... | python | {
"resource": ""
} |
q56191 | RemoteToken.update_token | train | def update_token(self, token, secret):
"""Update token with new values.
:param token: The token value.
:param secret: The secret key.
"""
if self.access_token != token or self.secret != secret:
with db.session.begin_nested():
self.access_token = token... | python | {
"resource": ""
} |
q56192 | RemoteToken.get | train | def get(cls, user_id, client_id, token_type='', access_token=None):
"""Get RemoteToken for user.
:param user_id: The user id.
:param client_id: The client id.
:param token_type: The token type. (Default: ``''``)
:param access_token: If set, will filter also by access token.
... | python | {
"resource": ""
} |
q56193 | RemoteToken.get_by_token | train | def get_by_token(cls, client_id, access_token, token_type=''):
"""Get RemoteAccount object for token.
:param client_id: The client id.
:param access_token: The access token.
:param token_type: The token type. (Default: ``''``)
:returns: A :class:`invenio_oauthclient.models.Remot... | python | {
"resource": ""
} |
q56194 | ExportsService.bulk_export | train | def bulk_export(self, config_ids=None, device_ids=None, package_ids=None, result_ids=None, exclude_captures=False):
"""Bulk export a set of configs, devices, packages and results.
:param config_ids: (optional) Int list of config IDs.
:param device_ids: (optional) Int list of device IDs.
... | python | {
"resource": ""
} |
q56195 | Report._init_report | train | def _init_report(self):
"""create the report directory and return the directory name"""
self.sections = []
self.section_names = []
# if the directory already exists, print a warning
try:
if os.path.isdir(self.directory) is False:
if self.verbose:
... | python | {
"resource": ""
} |
q56196 | Report.get_time_now | train | def get_time_now(self):
"""Returns a time stamp"""
import datetime
import getpass
username = getpass.getuser()
# this is not working on some systems: os.environ["USERNAME"]
timenow = str(datetime.datetime.now())
timenow = timenow.split('.')[0]
msg = '<div ... | python | {
"resource": ""
} |
q56197 | _track_class_related_field | train | def _track_class_related_field(cls, field):
""" Track a field on a related model """
# field = field on current model
# related_field = field on related model
(field, related_field) = field.split('__', 1)
field_obj = cls._meta.get_field(field)
related_cls = field_obj.remote_field.model
relat... | python | {
"resource": ""
} |
q56198 | _track_class_field | train | def _track_class_field(cls, field):
""" Track a field on the current model """
if '__' in field:
_track_class_related_field(cls, field)
return
# Will raise FieldDoesNotExist if there is an error
cls._meta.get_field(field)
# Detect m2m fields changes
if isinstance(cls._meta.get_fi... | python | {
"resource": ""
} |
q56199 | _track_class | train | def _track_class(cls, fields):
""" Track fields on the specified model """
# Small tests to ensure everything is all right
assert not getattr(cls, '_is_tracked', False)
for field in fields:
_track_class_field(cls, field)
_add_signals_to_cls(cls)
# Mark the class as tracked
cls._is... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.