_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q44400 | reconfigArg | train | def reconfigArg(ArgConfig):
r"""Reconfigures an argument based on its configuration.
"""
_type = ArgConfig.get('type')
if _type:
if hasattr(_type, '__ec_config__'): # pass the ArgConfig to the CustomType:
_type.__ec_config__(ArgConfig)
if not 'type_str' in ArgConfig:
ArgConfig['type_str'] = (_... | python | {
"resource": ""
} |
q44401 | getTaskHelp | train | def getTaskHelp(_Task):
r"""Gets help on the given task member.
"""
Ret = []
for k in ['name', 'desc']:
v = _Task.Config.get(k)
if v is not None:
Ret.append('%s: %s' % (k, v))
Args = _Task.Args
if Args:
Ret.append('\nArgs:')
for argName, Arg in Args.items():
Ret.append(' %s... | python | {
"resource": ""
} |
q44402 | restart_in_venv | train | def restart_in_venv(venv, base, site_packages, args):
"""
Restart this script using the interpreter in the given virtual environment
"""
if base and not os.path.isabs(venv) and not venv.startswith('~'):
base = os.path.expanduser(base)
# ensure we have an abs basepath at this point:
... | python | {
"resource": ""
} |
q44403 | history | train | async def history(client: Client, pubkey: str) -> dict:
"""
Get transactions history of public key
:param client: Client to connect to the api
:param pubkey: Public key
:return:
"""
return await client.get(MODULE + '/history/%s' % pubkey, schema=HISTORY_SCHEMA) | python | {
"resource": ""
} |
q44404 | process | train | async def process(client: Client, transaction_signed_raw: str) -> ClientResponse:
"""
POST a transaction raw document
:param client: Client to connect to the api
:param transaction_signed_raw: Transaction signed raw document
:return:
"""
return await client.post(MODULE + '/process', {'trans... | python | {
"resource": ""
} |
q44405 | sources | train | async def sources(client: Client, pubkey: str) -> dict:
"""
GET transaction sources
:param client: Client to connect to the api
:param pubkey: Public key
:return:
"""
return await client.get(MODULE + '/sources/%s' % pubkey, schema=SOURCES_SCHEMA) | python | {
"resource": ""
} |
q44406 | blocks | train | async def blocks(client: Client, pubkey: str, start: int, end: int) -> dict:
"""
GET public key transactions history between start and end block number
:param client: Client to connect to the api
:param pubkey: Public key
:param start: Start from block number
:param end: End to block number
... | python | {
"resource": ""
} |
q44407 | ReportCommand._ndays | train | def _ndays(self, start_date, ndays):
"""
Compute an end date given a start date and a number of days.
"""
if not getattr(self.args, 'start-date') and not self.config.get('start-date', None):
raise Exception('start-date must be provided when ndays is used.')
d = date(... | python | {
"resource": ""
} |
q44408 | ReportCommand.report | train | def report(self):
"""
Query analytics and stash data in a format suitable for serializing.
"""
output = OrderedDict()
for arg in GLOBAL_ARGUMENTS:
output[arg] = getattr(self.args, arg) or self.config.get(arg, None)
output['title'] = getattr(self.args, 'title... | python | {
"resource": ""
} |
q44409 | ReportCommand.html | train | def html(self, report, f):
"""
Write report data to an HTML file.
"""
env = Environment(loader=PackageLoader('clan', 'templates'))
template = env.get_template('report.html')
context = {
'report': report,
'GLOBAL_ARGUMENTS': GLOBAL_ARGUMENTS,
... | python | {
"resource": ""
} |
q44410 | ensure_exe | train | def ensure_exe(exe_name: str, *paths: str): # pragma: no cover
"""
Makes sure that an executable can be found on the system path.
Will exit the program if the executable cannot be found
Args:
exe_name: name of the executable
paths: optional path(s) to be searched; if not specified, sea... | python | {
"resource": ""
} |
q44411 | APISession.handle_captcha | train | def handle_captcha(self, query_params: dict,
html: str,
login_data: dict) -> requests.Response:
"""
Handling CAPTCHA request
"""
check_url = get_base_url(html)
captcha_url = '{}?s={}&sid={}'.format(self.CAPTCHA_URI,
... | python | {
"resource": ""
} |
q44412 | APISession.handle_two_factor_check | train | def handle_two_factor_check(self, html: str) -> requests.Response:
"""
Handling two factor authorization request
"""
action_url = get_base_url(html)
code = input(self.TWO_FACTOR_PROMPT).strip()
data = {'code': code, '_ajax': '1', 'remember': '1'}
post_url = '/'.jo... | python | {
"resource": ""
} |
q44413 | APISession.handle_phone_number_check | train | def handle_phone_number_check(self, html: str) -> requests.Response:
"""
Handling phone number request
"""
action_url = get_base_url(html)
phone_number = input(self.PHONE_PROMPT)
url_params = get_url_params(action_url)
data = {'code': phone_number,
... | python | {
"resource": ""
} |
q44414 | APISession.check_for_additional_actions | train | def check_for_additional_actions(self, url_params: dict,
html: str,
login_data: dict) -> None:
"""
Checks the url for a request for additional actions,
if so, calls the event handler
"""
action_response = '... | python | {
"resource": ""
} |
q44415 | APISession.login | train | def login(self) -> bool:
"""
Authorizes a user and returns a bool value of the result
"""
response = self.get(self.LOGIN_URL)
login_url = get_base_url(response.text)
login_data = {'email': self._login, 'pass': self._password}
login_response = self.post(login_url, ... | python | {
"resource": ""
} |
q44416 | APISession.auth_oauth2 | train | def auth_oauth2(self) -> dict:
"""
Authorizes a user by OAuth2 to get access token
"""
oauth_data = {
'client_id': self._app_id,
'display': 'mobile',
'response_type': 'token',
'scope': '+66560',
'v': self.API_VERSION
}
... | python | {
"resource": ""
} |
q44417 | APISession.get_access_token | train | def get_access_token(self) -> str:
"""
Returns the access token in case of successful authorization
"""
if self._service_token:
return self._service_token
if self._app_id and self._login and self._password:
try:
if self.login():
... | python | {
"resource": ""
} |
q44418 | APISession.send_method_request | train | def send_method_request(self, method: str, method_params: dict) -> dict:
"""
Sends user-defined method and method params
"""
url = '/'.join((self.METHOD_URL, method))
method_params['v'] = self.API_VERSION
if self._access_token:
method_params['access_token'] = ... | python | {
"resource": ""
} |
q44419 | PhraseClassificationTrainer.train | train | def train(self, net_sizes, epochs, batchsize):
""" Initialize the base trainer """
self.trainer = ClassificationTrainer(self.data, self.targets, net_sizes)
self.trainer.learn(epochs, batchsize)
return self.trainer.evaluate(batchsize) | python | {
"resource": ""
} |
q44420 | PhraseClassifier.classify | train | def classify(self, phrase, cut_to_len=True):
""" Classify a phrase based on the loaded model. If cut_to_len is True, cut to
desired length."""
if (len(phrase) > self.max_phrase_len):
if not cut_to_len:
raise Exception("Phrase too long.")
phrase = phrase[0:self.max... | python | {
"resource": ""
} |
q44421 | popen_wrapper | train | def popen_wrapper(args):
"""
Friendly wrapper around Popen.
Returns stdout output, stderr output and OS status code.
"""
try:
p = Popen(args,
shell=False,
stdout=PIPE,
stderr=PIPE,
close_fds=os.name != 'nt',
... | python | {
"resource": ""
} |
q44422 | getPackages | train | def getPackages(plist):
"""
Cleans up input from the command line tool and returns a list of package
names
"""
nlist = plist.split('\n')
pkgs = []
for i in nlist:
if i.find('===') > 0: continue
pkg = i.split()[0]
if pkg == 'Warning:': continue
elif pkg == 'Could': continue
elif pkg == 'Some': continu... | python | {
"resource": ""
} |
q44423 | pip | train | def pip(usr_pswd=None):
"""
This updates one package at a time.
Could do all at once:
pip list --outdated | cut -d' ' -f1 | xargs pip install --upgrade
"""
# see if pip is installed
try: cmd('which pip')
except:
return
print('-[pip]----------')
p = cmd('pip list --outdated')
if not p: return
pkgs = get... | python | {
"resource": ""
} |
q44424 | brew | train | def brew(clean=False):
"""
Handle homebrew on macOS
"""
# see if homebrew is installed
try: cmd('which brew')
except:
return
print('-[brew]----------')
cmd('brew update')
p = cmd('brew outdated')
if not p: return
pkgs = getPackages(p)
for p in pkgs:
cmd('brew upgrade {}'.format(p), run=global_run)
if... | python | {
"resource": ""
} |
q44425 | kernel | train | def kernel():
"""
Handle linux kernel update
"""
print('================================')
print(' WARNING: upgrading the kernel')
print('================================')
time.sleep(5)
print('-[kernel]----------')
cmd('rpi-update', True)
print(' >> You MUST reboot to load the new kernel <<') | python | {
"resource": ""
} |
q44426 | npm | train | def npm(usr_pwd=None, clean=False):
"""
Handle npm for Node.js
"""
# see if node is installed
try: cmd('which npm')
except:
return
print('-[npm]----------')
# awk, ignore 1st line and grab 1st word
p = cmd("npm outdated -g | awk 'NR>1 {print $1}'")
if not p: return
pkgs = getPackages(p)
for p in pkgs:
... | python | {
"resource": ""
} |
q44427 | Interval.split | train | def split(self):
"""Immediately stop the current interval and start a new interval that
has a start_instant equivalent to the stop_interval of self"""
self.stop()
interval = Interval()
interval._start_instant = self.stop_instant
return interval | python | {
"resource": ""
} |
q44428 | Interval.stop | train | def stop(self):
"""Mark the stop of the interval.
Calling stop on an already stopped interval has no effect.
An interval can only be stopped once.
:returns: the duration if the interval is truely stopped otherwise ``False``.
"""
if self._start_instant is None:
... | python | {
"resource": ""
} |
q44429 | Interval.duration_so_far | train | def duration_so_far(self):
"""Return how the duration so far.
:returns: the duration from the time the Interval was started if the
interval is running, otherwise ``False``.
"""
if self._start_instant is None:
return False
if self._stop_instant is None:
... | python | {
"resource": ""
} |
q44430 | Interval.duration | train | def duration(self):
"""Returns the integer value of the interval, the value is in milliseconds.
If the interval has not had stop called yet,
it will report the number of milliseconds in the interval up to the current point in time.
"""
if self._stop_instant is None:
... | python | {
"resource": ""
} |
q44431 | Bridge.import_module | train | def import_module(self, name):
"""Import a module into the bridge."""
if name not in self._objects:
module = _import_module(name)
self._objects[name] = module
self._object_references[id(module)] = name
return self._objects[name] | python | {
"resource": ""
} |
q44432 | _component_of | train | def _component_of(name):
"""Get the root package or module of the passed module.
"""
# Get the registered package this model belongs to.
segments = name.split('.')
while segments:
# Is this name a registered package?
test = '.'.join(segments)
if test in settings.get('COMPONE... | python | {
"resource": ""
} |
q44433 | Model.save | train | def save(self, commit=False):
"""Save the changes to the model.
If the model has not been persisted
then it adds the model to the declared session. Then it flushes the
object session and optionally commits it.
"""
if not has_identity(self):
# Object has not b... | python | {
"resource": ""
} |
q44434 | team | train | def team(page):
"""
Return the team name
"""
soup = BeautifulSoup(page)
try:
return soup.find('title').text.split(' | ')[0].split(' - ')[1]
except:
return None | python | {
"resource": ""
} |
q44435 | league | train | def league(page):
"""
Return the league name
"""
soup = BeautifulSoup(page)
try:
return soup.find('title').text.split(' | ')[0].split(' - ')[0]
except:
return None | python | {
"resource": ""
} |
q44436 | date | train | def date(page):
"""
Return the date, nicely-formatted
"""
soup = BeautifulSoup(page)
try:
page_date = soup.find('input', attrs={'name': 'date'})['value']
parsed_date = datetime.strptime(page_date, '%Y-%m-%d')
return parsed_date.strftime('%a, %b %d, %Y')
except:
re... | python | {
"resource": ""
} |
q44437 | start_active_players_path | train | def start_active_players_path(page):
"""
Return the path in the "Start Active Players" button
"""
soup = BeautifulSoup(page)
try:
return soup.find('a', href=True, text='Start Active Players')['href']
except:
return None | python | {
"resource": ""
} |
q44438 | PluginServerStorageEntryHookABC._migrateStorageSchema | train | def _migrateStorageSchema(self, metadata: MetaData) -> None:
""" Initialise the DB
This method is called by the platform between the load() and start() calls.
There should be no need for a plugin to call this method it's self.
:param metadata: the SQLAlchemy metadata for this plugins s... | python | {
"resource": ""
} |
q44439 | PluginServerStorageEntryHookABC.prefetchDeclarativeIds | train | def prefetchDeclarativeIds(self, Declarative, count) -> Deferred:
""" Get PG Sequence Generator
A PostGreSQL sequence generator returns a chunk of IDs for the given
declarative.
:return: A generator that will provide the IDs
:rtype: an iterator, yielding the numbers to assign
... | python | {
"resource": ""
} |
q44440 | run_once | train | def run_once(func):
"""
Simple decorator to ensure a function is ran only once
"""
def _inner(*args, **kwargs):
if func.__name__ in CTX.run_once:
LOGGER.info('skipping %s', func.__name__)
return CTX.run_once[func.__name__]
LOGGER.info('running: %s', func.__name_... | python | {
"resource": ""
} |
q44441 | score_x_of_a_kind_yahtzee | train | def score_x_of_a_kind_yahtzee(dice: List[int], min_same_faces: int) -> int:
"""Return sum of dice if there are a minimum of equal min_same_faces dice, otherwise
return zero. Only works for 3 or more min_same_faces.
"""
for die, count in Counter(dice).most_common(1):
if count >= min_same_faces:
... | python | {
"resource": ""
} |
q44442 | score_x_of_a_kind_yatzy | train | def score_x_of_a_kind_yatzy(dice: List[int], min_same_faces: int) -> int:
"""Similar to yahtzee, but only return the sum of the dice that satisfy min_same_faces
"""
for die, count in Counter(dice).most_common(1):
if count >= min_same_faces:
return die * min_same_faces
return 0 | python | {
"resource": ""
} |
q44443 | score_small_straight_yahztee | train | def score_small_straight_yahztee(dice: List[int]) -> int:
"""
Small straight scoring according to regular yahtzee rules
"""
global CONSTANT_SCORES_YAHTZEE
dice_set = set(dice)
if _are_two_sets_equal({1, 2, 3, 4}, dice_set) or \
_are_two_sets_equal({2, 3, 4, 5}, dice_set) or \
... | python | {
"resource": ""
} |
q44444 | score_small_straight_yatzy | train | def score_small_straight_yatzy(dice: List[int]) -> int:
"""
Small straight scoring according to yatzy rules
"""
dice_set = set(dice)
if _are_two_sets_equal({1, 2, 3, 4, 5}, dice_set):
return sum(dice)
return 0 | python | {
"resource": ""
} |
q44445 | score_large_straight_yahtzee | train | def score_large_straight_yahtzee(dice: List[int]) -> int:
"""
Large straight scoring according to regular yahtzee rules
"""
global CONSTANT_SCORES_YAHTZEE
dice_set = set(dice)
if _are_two_sets_equal({1, 2, 3, 4, 5}, dice_set) or \
_are_two_sets_equal({2, 3, 4, 5, 6}, dice_set):
... | python | {
"resource": ""
} |
q44446 | score_large_straight_yatzy | train | def score_large_straight_yatzy(dice: List[int]) -> int:
"""
Large straight scoring according to yatzy rules
"""
dice_set = set(dice)
if _are_two_sets_equal({2, 3, 4, 5, 6}, dice_set):
return sum(dice)
return 0 | python | {
"resource": ""
} |
q44447 | select_dict | train | def select_dict(coll, key, value):
"""
Given an iterable of dictionaries, return the dictionaries
where the values at a given key match the given value.
If the value is an iterable of objects, the function will
consider any to be a match.
This is especially useful when calling REST APIs which
... | python | {
"resource": ""
} |
q44448 | inside_brain | train | def inside_brain(stat_dset,atlas=None,p=0.001):
'''calculates the percentage of voxels above a statistical threshold inside a brain mask vs. outside it
if ``atlas`` is ``None``, it will try to find ``TT_N27``'''
atlas = find_atlas(atlas)
if atlas==None:
return None
mask_dset = nl.suffix... | python | {
"resource": ""
} |
q44449 | auto_qc | train | def auto_qc(dset,inside_perc=60,atlas=None,p=0.001):
'''returns ``False`` if ``dset`` fails minimum checks, or returns a float from ``0.0`` to ``100.0`` describing data quality'''
with nl.notify('Running quality check on %s:' % dset):
if not os.path.exists(dset):
nl.notify('Error: cannot fin... | python | {
"resource": ""
} |
q44450 | StoneRedis._multi_lpop_pipeline | train | def _multi_lpop_pipeline(self, pipe, queue, number):
''' Pops multiple elements from a list in a given pipeline'''
pipe.lrange(queue, 0, number - 1)
pipe.ltrim(queue, number, -1) | python | {
"resource": ""
} |
q44451 | StoneRedis.multi_lpop | train | def multi_lpop(self, queue, number, transaction=False):
''' Pops multiple elements from a list
This operation will be atomic if transaction=True is passed
'''
try:
pipe = self.pipeline(transaction=transaction)
pipe.multi()
self._multi_lpop_p... | python | {
"resource": ""
} |
q44452 | StoneRedis._multi_rpush_pipeline | train | def _multi_rpush_pipeline(self, pipe, queue, values, bulk_size=0):
''' Pushes multiple elements to a list in a given pipeline
If bulk_size is set it will execute the pipeline every bulk_size elements
'''
cont = 0
for value in values:
pipe.rpush(queue, value)... | python | {
"resource": ""
} |
q44453 | StoneRedis.multi_rpush | train | def multi_rpush(self, queue, values, bulk_size=0, transaction=False):
''' Pushes multiple elements to a list
If bulk_size is set it will execute the pipeline every bulk_size elements
This operation will be atomic if transaction=True is passed
'''
# Check that what we... | python | {
"resource": ""
} |
q44454 | StoneRedis.rpush_limit | train | def rpush_limit(self, queue, value, limit=100000):
''' Pushes an element to a list in an atomic way until it reaches certain size
Once limit is reached, the function will lpop the oldest elements
This operation runs in LUA, so is always atomic
'''
lua = '''
... | python | {
"resource": ""
} |
q44455 | StoneRedis.get_lock | train | def get_lock(self, lockname, locktime=60, auto_renewal=False):
''' Gets a lock and returns if it can be stablished. Returns false otherwise '''
pid = os.getpid()
caller = inspect.stack()[0][3]
try:
# rl = redlock.Redlock([{"host": settings.REDIS_SERVERS['std_redis']['hos... | python | {
"resource": ""
} |
q44456 | StoneRedis.wait_for_lock | train | def wait_for_lock(self, lockname, locktime=60, auto_renewal=False):
''' Gets a lock or waits until it is able to get it '''
pid = os.getpid()
caller = inspect.stack()[0][3]
try:
# rl = redlock.Redlock([{"host": settings.REDIS_SERVERS['std_redis']['host'], "port": setting... | python | {
"resource": ""
} |
q44457 | StoneRedis.release_lock | train | def release_lock(self, lock, force=False):
''' Frees a lock '''
pid = os.getpid()
caller = inspect.stack()[0][3]
# try:
# rl = redlock.Redlock([{"host": settings.REDIS_SERVERS['std_redis']['host'], "port": settings.REDIS_SERVERS['std_redis']['port'], "db": settings.REDIS_S... | python | {
"resource": ""
} |
q44458 | StoneRedis.pipeline | train | def pipeline(self, transaction=True, shard_hint=None):
''' Return a pipeline that support StoneRedis custom methods '''
args_dict = {
'connection_pool': self.connection_pool,
'response_callbacks': self.response_callbacks,
'transaction': transaction,
... | python | {
"resource": ""
} |
q44459 | StonePipeline.multi_lpop | train | def multi_lpop(self, queue, number, transaction=False):
''' Pops multiple elements from a list '''
try:
self._multi_lpop_pipeline(self, queue, number)
except:
raise | python | {
"resource": ""
} |
q44460 | StonePipeline.multi_rpush | train | def multi_rpush(self, queue, values, bulk_size=0, transaction=False):
''' Pushes multiple elements to a list '''
# Check that what we receive is iterable
if hasattr(values, '__iter__'):
self._multi_rpush_pipeline(self, queue, values, 0)
else:
raise ValueErro... | python | {
"resource": ""
} |
q44461 | _deserialize_dict | train | def _deserialize_dict(data, boxed_type):
"""Deserializes a dict and its elements.
:param data: dict to deserialize.
:type data: dict
:param boxed_type: class literal.
:return: deserialized dict.
:rtype: dict
"""
return {k: _deserialize(v, boxed_type)
for k, v in six.iterite... | python | {
"resource": ""
} |
q44462 | ObserverStore.remove | train | def remove(self, what, call):
"""
remove an observer
what: (string | array) state fields to observe
call: (function) when not given, decorator usage is assumed.
The call function should have 2 parameters:
- previousValue,
- actualValue
"""
... | python | {
"resource": ""
} |
q44463 | ObserverStore.getObservers | train | def getObservers(self):
"""
Get the list of observer to the instance of the class.
:return: Subscribed Obversers.
:rtype: Array
"""
result = []
for observer in self._observers:
result.append(
{
"... | python | {
"resource": ""
} |
q44464 | add_job | train | def add_job(session, command_line, name = 'job', dependencies = [], array = None, exec_dir=None, log_dir = None, stop_on_failure = False, **kwargs):
"""Helper function to create a job, add the dependencies and the array jobs."""
job = Job(command_line=command_line, name=name, exec_dir=exec_dir, log_dir=log_dir, arr... | python | {
"resource": ""
} |
q44465 | Job.submit | train | def submit(self, new_queue = None):
"""Sets the status of this job to 'submitted'."""
self.status = 'submitted'
self.result = None
self.machine_name = None
if new_queue is not None:
self.queue_name = new_queue
for array_job in self.array:
array_job.status = 'submitted'
array_jo... | python | {
"resource": ""
} |
q44466 | Job.queue | train | def queue(self, new_job_id = None, new_job_name = None, queue_name = None):
"""Sets the status of this job to 'queued' or 'waiting'."""
# update the job id (i.e., when the job is executed in the grid)
if new_job_id is not None:
self.id = new_job_id
if new_job_name is not None:
self.name = n... | python | {
"resource": ""
} |
q44467 | Job.execute | train | def execute(self, array_id = None, machine_name = None):
"""Sets the status of this job to 'executing'."""
self.status = 'executing'
if array_id is not None:
for array_job in self.array:
if array_job.id == array_id:
array_job.status = 'executing'
if machine_name is not None... | python | {
"resource": ""
} |
q44468 | Job.finish | train | def finish(self, result, array_id = None):
"""Sets the status of this job to 'success' or 'failure'."""
# check if there is any array job still running
new_status = 'success' if result == 0 else 'failure'
new_result = result
finished = True
if array_id is not None:
for array_job in self.ar... | python | {
"resource": ""
} |
q44469 | Job.refresh | train | def refresh(self):
"""Refreshes the status information."""
if self.status == 'executing' and self.array:
new_result = 0
for array_job in self.array:
if array_job.status == 'failure' and new_result is not None:
new_result = array_job.result
elif array_job.status not in ('suc... | python | {
"resource": ""
} |
q44470 | Job.get_array | train | def get_array(self):
"""Returns the array arguments for the job; usually a string."""
# In python 2, the command line is unicode, which needs to be converted to string before pickling;
# In python 3, the command line is bytes, which can be pickled directly
return loads(self.array_string) if isinstance(s... | python | {
"resource": ""
} |
q44471 | next_departures | train | def next_departures(bus_number, stop_code, date, time, nb_departure, db_file):
"""
Getting the 10 next departures
How to check with tools database
sqlite3 stm.db
SELECT "t2"."departure_time"
FROM "trips" AS t1 INNER JOIN "stop_times" AS t2 ON ("t1"."trip_id" = "t2"."trip_id")
INN... | python | {
"resource": ""
} |
q44472 | random_ipv4 | train | def random_ipv4(cidr='10.0.0.0/8'):
"""
Return a random IPv4 address from the given CIDR block.
:key str cidr: CIDR block
:returns: An IPv4 address from the given CIDR block
:rtype: ipaddress.IPv4Address
"""
try:
u_cidr = unicode(cidr)
except NameError:
u_cidr = cidr
... | python | {
"resource": ""
} |
q44473 | _compile_qt_resources | train | def _compile_qt_resources():
"""
Compiles PyQT resources file
"""
if config.QT_RES_SRC():
epab.utils.ensure_exe('pyrcc5')
LOGGER.info('compiling Qt resources')
elib_run.run(f'pyrcc5 {config.QT_RES_SRC()} -o {config.QT_RES_TGT()}') | python | {
"resource": ""
} |
q44474 | to_json | train | def to_json(msg):
"""
Returns a JSON string representation of this message
"""
result = {}
# herald specification version
#result[herald.MESSAGE_HERALD_VERSION] = herald.HERALD_SPECIFICATION_VERSION
# headers
result[herald.MESSAGE_HEADERS] = {}
if msg.headers is not... | python | {
"resource": ""
} |
q44475 | from_json | train | def from_json(json_string):
"""
Returns a new MessageReceived from the provided json_string string
"""
# parse the provided json_message
try:
parsed_msg = json.loads(json_string)
except ValueError as ex:
# if the provided json_message is not a ... | python | {
"resource": ""
} |
q44476 | Naming.new_type | train | def new_type(type_name: str, prefix: str or None = None) -> str:
"""
Creates a resource type with optionally a prefix.
Using the rules of JSON-LD, we use prefixes to disambiguate between different types with the same name:
one can Accept a device or a project. In eReuse.org ... | python | {
"resource": ""
} |
q44477 | Naming.hid | train | def hid(manufacturer: str, serial_number: str, model: str) -> str:
"""Computes the HID for the given properties of a device. The HID is suitable to use to an URI."""
return Naming.url_word(manufacturer) + '-' + Naming.url_word(serial_number) + '-' + Naming.url_word(model) | python | {
"resource": ""
} |
q44478 | get_membership_document | train | def get_membership_document(membership_type: str, current_block: dict, identity: Identity, salt: str,
password: str) -> Membership:
"""
Get a Membership document
:param membership_type: "IN" to ask for membership or "OUT" to cancel membership
:param current_block: Current bl... | python | {
"resource": ""
} |
q44479 | getvar | train | def getvar(syntree, targetvar):
"""Scan an ast object for targetvar and return its value.
Only handles single direct assignment of python literal types. See docs on
ast.literal_eval for more info:
http://docs.python.org/2/library/ast.html#ast.literal_eval
Args:
syntree: ast.Module object
... | python | {
"resource": ""
} |
q44480 | findObjects | train | def findObjects(path):
"""Finds objects in pairtree.
Given a path that corresponds to a pairtree, walk it and look for
non-shorty (it's ya birthday) directories.
"""
objects = []
if not os.path.isdir(path):
return []
contents = os.listdir(path)
for item in contents:
full... | python | {
"resource": ""
} |
q44481 | get_pair_path | train | def get_pair_path(meta_id):
"""Determines the pair path for the digital object meta-id."""
pair_tree = pair_tree_creator(meta_id)
pair_path = os.path.join(pair_tree, meta_id)
return pair_path | python | {
"resource": ""
} |
q44482 | pair_tree_creator | train | def pair_tree_creator(meta_id):
"""Splits string into a pairtree path."""
chunks = []
for x in range(0, len(meta_id)):
if x % 2:
continue
if (len(meta_id) - 1) == x:
chunk = meta_id[x]
else:
chunk = meta_id[x: x + 2]
chunks.append(chunk)
... | python | {
"resource": ""
} |
q44483 | deSanitizeString | train | def deSanitizeString(name):
"""Reverses sanitization process.
Reverses changes made to a string that has been sanitized for use
as a pairtree identifier.
"""
oldString = name
# first pass
replaceTable2 = [
("/", "="),
(":", "+"),
(".", ","),
]
for r in replac... | python | {
"resource": ""
} |
q44484 | sanitizeString | train | def sanitizeString(name):
"""Cleans string in preparation for splitting for use as a pairtree
identifier."""
newString = name
# string cleaning, pass 1
replaceTable = [
('^', '^5e'), # we need to do this one first
('"', '^22'),
('<', '^3c'),
('?', '^3f'),
('*... | python | {
"resource": ""
} |
q44485 | toPairTreePath | train | def toPairTreePath(name):
"""Cleans a string, and then splits it into a pairtree path."""
sName = sanitizeString(name)
chunks = []
for x in range(0, len(sName)):
if x % 2:
continue
if (len(sName) - 1) == x:
chunk = sName[x]
else:
chunk = sName[... | python | {
"resource": ""
} |
q44486 | create_paired_dir | train | def create_paired_dir(output_dir, meta_id, static=False, needwebdir=True):
"""Creates the meta or static dirs.
Adds an "even" or "odd" subdirectory to the static path
based on the meta-id.
"""
# get the absolute root path
root_path = os.path.abspath(output_dir)
# if it's a static directory,... | python | {
"resource": ""
} |
q44487 | add_to_pairtree | train | def add_to_pairtree(output_path, meta_id):
"""Creates pairtree dir structure within pairtree for new
element."""
# create the pair path
paired_path = pair_tree_creator(meta_id)
path_append = ''
# for each directory in the pair path
for pair_dir in paired_path.split(os.sep):
# append ... | python | {
"resource": ""
} |
q44488 | get_pairtree_prefix | train | def get_pairtree_prefix(pairtree_store):
"""Returns the prefix given in pairtree_prefix file."""
prefix_path = os.path.join(pairtree_store, 'pairtree_prefix')
with open(prefix_path, 'r') as prefixf:
prefix = prefixf.read().strip()
return prefix | python | {
"resource": ""
} |
q44489 | Document.parse_field | train | def parse_field(cls: Type[DocumentType], field_name: str, line: str) -> Any:
"""
Parse a document field with regular expression and return the value
:param field_name: Name of the field
:param line: Line string to parse
:return:
"""
try:
match = cls.f... | python | {
"resource": ""
} |
q44490 | Document.sha_hash | train | def sha_hash(self) -> str:
"""
Return uppercase hex sha256 hash from signed raw document
:return:
"""
return hashlib.sha256(self.signed_raw().encode("ascii")).hexdigest().upper() | python | {
"resource": ""
} |
q44491 | SavageLogMixin.build_row_dict | train | def build_row_dict(cls, row, dialect, deleted=False, user_id=None, use_dirty=True):
"""
Builds a dictionary of archive data from row which is suitable for insert.
NOTE: If `deleted` is False, version ID will be set to an AsIs SQL construct.
:param row: instance of :class:`~SavageModelM... | python | {
"resource": ""
} |
q44492 | SavageLogMixin.bulk_archive_rows | train | def bulk_archive_rows(cls, rows, session, user_id=None, chunk_size=1000, commit=True):
"""
Bulk archives data previously written to DB.
:param rows: iterable of previously saved model instances to archive
:param session: DB session to use for inserts
:param user_id: ID of user r... | python | {
"resource": ""
} |
q44493 | SavageLogMixin._validate | train | def _validate(cls, engine, *version_cols):
"""
Validates the archive table.
Validates the following criteria:
- all version columns exist in the archive table
- the python types of the user table and archive table columns are the same
- a user_id column exist... | python | {
"resource": ""
} |
q44494 | self_aware | train | def self_aware(fn):
''' decorating a function with this allows it to
refer to itself as 'self' inside the function
body.
'''
if isgeneratorfunction(fn):
@wraps(fn)
def wrapper(*a,**k):
generator = fn(*a,**k)
if hasattr(
generator,
... | python | {
"resource": ""
} |
q44495 | FetchTransformSaveApp._infinite_iterator | train | def _infinite_iterator(self):
"""this iterator wraps the "_basic_iterator" when the configuration
specifies that the "number_of_submissions" is set to "forever".
Whenever the "_basic_iterator" is exhausted, it is called again to
restart the iteration. It is up to the implementation of t... | python | {
"resource": ""
} |
q44496 | FetchTransformSaveApp._limited_iterator | train | def _limited_iterator(self):
"""this is the iterator for the case when "number_of_submissions" is
set to an integer. It goes through the innermost iterator exactly the
number of times specified by "number_of_submissions" To do that, it
might run the innermost iterator to exhaustion. I... | python | {
"resource": ""
} |
q44497 | FetchTransformSaveApp._transform | train | def _transform(self, crash_id):
"""this default transform function only transfers raw data from the
source to the destination without changing the data. While this may
be good enough for the raw crashmover, the processor would override
this method to create and save processed crashes"""... | python | {
"resource": ""
} |
q44498 | FetchTransformSaveApp._setup_source_and_destination | train | def _setup_source_and_destination(self):
"""instantiate the classes that implement the source and destination
crash storage systems."""
try:
self.source = self.config.source.crashstorage_class(
self.config.source,
quit_check_callback=self.quit_check
... | python | {
"resource": ""
} |
q44499 | FetchTransformSaveApp.main | train | def main(self):
"""this main routine sets up the signal handlers, the source and
destination crashstorage systems at the theaded task manager. That
starts a flock of threads that are ready to shepherd crashes from
the source to the destination."""
self._setup_task_manager()
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.