_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q44200 | Unlock.from_inline | train | def from_inline(cls: Type[UnlockType], inline: str) -> UnlockType:
"""
Return an Unlock instance from inline string format
:param inline: Inline string format
:return:
"""
data = Unlock.re_inline.match(inline)
if data is None:
raise MalformedDocument... | python | {
"resource": ""
} |
q44201 | Unlock.inline | train | def inline(self) -> str:
"""
Return inline string format of the instance
:return:
"""
return "{0}:{1}".format(self.index, ' '.join([str(p) for p in self.parameters])) | python | {
"resource": ""
} |
q44202 | Transaction.from_compact | train | def from_compact(cls: Type[TransactionType], currency: str, compact: str) -> TransactionType:
"""
Return Transaction instance from compact string format
:param currency: Name of the currency
:param compact: Compact format string
:return:
"""
lines = compact.split... | python | {
"resource": ""
} |
q44203 | Transaction.from_signed_raw | train | def from_signed_raw(cls: Type[TransactionType], raw: str) -> TransactionType:
"""
Return a Transaction instance from a raw string format
:param raw: Raw string format
:return:
"""
lines = raw.splitlines(True)
n = 0
version = int(Transaction.parse_field(... | python | {
"resource": ""
} |
q44204 | Transaction.compact | train | def compact(self) -> str:
"""
Return a transaction in its compact format from the instance
:return:
"""
"""TX:VERSION:NB_ISSUERS:NB_INPUTS:NB_UNLOCKS:NB_OUTPUTS:HAS_COMMENT:LOCKTIME
PUBLIC_KEY:INDEX
...
INDEX:SOURCE:FINGERPRINT:AMOUNT
...
PUBLIC_KEY:AMOUNT
...
COMMENT
"""
... | python | {
"resource": ""
} |
q44205 | SimpleTransaction.is_simple | train | def is_simple(tx: Transaction) -> bool:
"""
Filter a transaction and checks if it is a basic one
A simple transaction is a tx which has only one issuer
and two outputs maximum. The unlocks must be done with
simple "SIG" functions, and the outputs must be simple
SIG condit... | python | {
"resource": ""
} |
q44206 | Exec.retry | train | def retry(self, retries, task_f, check_f=bool, wait_f=None):
"""
Try a function up to n times.
Raise an exception if it does not pass in time
:param retries int: The number of times to retry
:param task_f func: The function to be run and observed
:param func()bool check_... | python | {
"resource": ""
} |
q44207 | Exec.gather | train | def gather(self, cmd):
"""
Runs a command and returns rc,stdout,stderr as a tuple.
If called while the `Dir` context manager is in effect, guarantees that the
process is executed in that directory, even if it is no longer the current
directory of the process (i.e. it is thread-s... | python | {
"resource": ""
} |
q44208 | JSONFeed.json_serial | train | def json_serial(obj):
"""
Custom JSON serializer for objects not serializable by default.
"""
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
raise TypeError('Type {} not serializable.'.format(type(obj))) | python | {
"resource": ""
} |
q44209 | train_weather_predictor | train | def train_weather_predictor(
location='Portland, OR',
years=range(2013, 2016,),
delays=(1, 2, 3),
inputs=('Min Temperature', 'Max Temperature', 'Min Sea Level Pressure', u'Max Sea Level Pressure', 'WindDirDegrees',),
outputs=(u'Max TemperatureF',),
N_hidden=6,
epo... | python | {
"resource": ""
} |
q44210 | oneday_weather_forecast | train | def oneday_weather_forecast(
location='Portland, OR',
inputs=('Min Temperature', 'Mean Temperature', 'Max Temperature', 'Max Humidity', 'Mean Humidity', 'Min Humidity', 'Max Sea Level Pressure', 'Mean Sea Level Pressure', 'Min Sea Level Pressure', 'Wind Direction'),
outputs=('Min Temperature', '... | python | {
"resource": ""
} |
q44211 | run_competition | train | def run_competition(builders=[], task=BalanceTask(), Optimizer=HillClimber, rounds=3, max_eval=20, N_hidden=3, verbosity=0):
""" pybrain buildNetwork builds a subtly different network structhan build_ann... so compete them!
Arguments:
task (Task): task to compete at
Optimizer (class): pybrain.O... | python | {
"resource": ""
} |
q44212 | environ | train | def environ(context):
"""Retrieves the environment for a particular SETSHELL context"""
if 'BASEDIRSETSHELL' not in os.environ:
# It seems that we are in a hostile environment
# try to source the Idiap-wide shell
idiap_source = "/idiap/resource/software/initfiles/shrc"
if os.path.exists(idiap_source... | python | {
"resource": ""
} |
q44213 | sexec | train | def sexec(context, command, error_on_nonzero=True):
"""Executes a command within a particular Idiap SETSHELL context"""
import six
if isinstance(context, six.string_types): E = environ(context)
else: E = context
try:
logger.debug("Executing: '%s'", ' '.join(command))
p = subprocess.Popen(command, st... | python | {
"resource": ""
} |
q44214 | get_dates_in_period | train | def get_dates_in_period(start=None, top=None, step=1, step_dict={}):
"""Return a list of dates from the `start` to `top`."""
delta = relativedelta(**step_dict) if step_dict else timedelta(days=step)
start = start or datetime.today()
top = top or start + delta
dates = []
current = start
whi... | python | {
"resource": ""
} |
q44215 | localize_date | train | def localize_date(date, city):
""" Localize date into city
Date: datetime
City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'..
"""
local = pytz.timezone(city)
local_dt = local.localize(date, is_dst=None)
return local_dt | python | {
"resource": ""
} |
q44216 | get_month_from_date_str | train | def get_month_from_date_str(date_str, lang=DEFAULT_DATE_LANG):
"""Find the month name for the given locale, in the given string.
Returns a tuple ``(number_of_month, abbr_name)``.
"""
date_str = date_str.lower()
with calendar.different_locale(LOCALES[lang]):
month_abbrs = list(calendar.month... | python | {
"resource": ""
} |
q44217 | replace_month_abbr_with_num | train | def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG):
"""Replace month strings occurrences with month number."""
num, abbr = get_month_from_date_str(date_str, lang)
return re.sub(abbr, str(num), date_str, flags=re.IGNORECASE) | python | {
"resource": ""
} |
q44218 | translate_month_abbr | train | def translate_month_abbr(
date_str,
source_lang=DEFAULT_DATE_LANG,
target_lang=DEFAULT_DATE_LANG):
"""Translate the month abbreviation from one locale to another."""
month_num, month_abbr = get_month_from_date_str(date_str, source_lang)
with calendar.different_locale(LOCALES[target_l... | python | {
"resource": ""
} |
q44219 | merge_datetime | train | def merge_datetime(date, time='', date_format='%d/%m/%Y', time_format='%H:%M'):
"""Create ``datetime`` object from date and time strings."""
day = datetime.strptime(date, date_format)
if time:
time = datetime.strptime(time, time_format)
time = datetime.time(time)
day = datetime.date(... | python | {
"resource": ""
} |
q44220 | display_list | train | def display_list(prefix, l, color):
""" Prints a file list to terminal, allows colouring output. """
for itm in l: print colored(prefix + itm['path'], color) | python | {
"resource": ""
} |
q44221 | pfx_path | train | def pfx_path(path):
""" Prefix a path with the OS path separator if it is not already """
if path[0] != os.path.sep: return os.path.sep + path
else: return path | python | {
"resource": ""
} |
q44222 | file_or_default | train | def file_or_default(path, default, function = None):
""" Return a default value if a file does not exist """
try:
result = file_get_contents(path)
if function != None: return function(result)
return result
except IOError as e:
if e.errno == errno.ENOENT: return default
... | python | {
"resource": ""
} |
q44223 | make_dirs_if_dont_exist | train | def make_dirs_if_dont_exist(path):
""" Create directories in path if they do not exist """
if path[-1] not in ['/']: path += '/'
path = os.path.dirname(path)
if path != '':
try: os.makedirs(path)
except OSError: pass | python | {
"resource": ""
} |
q44224 | cpjoin | train | def cpjoin(*args):
""" custom path join """
rooted = True if args[0].startswith('/') else False
def deslash(a): return a[1:] if a.startswith('/') else a
newargs = [deslash(arg) for arg in args]
path = os.path.join(*newargs)
if rooted: path = os.path.sep + path
return path | python | {
"resource": ""
} |
q44225 | get_single_file_info | train | def get_single_file_info(f_path, int_path):
""" Gets the creates and last change times for a single file,
f_path is the path to the file on disk, int_path is an internal
path relative to a root directory. """
return { 'path' : force_unicode(int_path),
'created' : os.path.getctime(f_pa... | python | {
"resource": ""
} |
q44226 | hash_file | train | def hash_file(file_path, block_size = 65536):
""" Hashes a file with sha256 """
sha = hashlib.sha256()
with open(file_path, 'rb') as h_file:
file_buffer = h_file.read(block_size)
while len(file_buffer) > 0:
sha.update(file_buffer)
file_buffer = h_file.read(block_size)... | python | {
"resource": ""
} |
q44227 | get_file_list | train | def get_file_list(path):
""" Recursively lists all files in a file system below 'path'. """
f_list = []
def recur_dir(path, newpath = os.path.sep):
files = os.listdir(path)
for fle in files:
f_path = cpjoin(path, fle)
if os.path.isdir(f_path): recur_dir(f_path, cpjoin... | python | {
"resource": ""
} |
q44228 | find_manifest_changes | train | def find_manifest_changes(new_file_state, old_file_state):
""" Find what has changed between two sets of files """
prev_state_dict = copy.deepcopy(old_file_state)
changed_files = {}
# Find files which are new on the server
for itm in new_file_state:
if itm['path'] in prev_state_dict:
... | python | {
"resource": ""
} |
q44229 | is_archive | train | def is_archive(filename):
'''returns boolean of whether this filename looks like an archive'''
for archive in archive_formats:
if filename.endswith(archive_formats[archive]['suffix']):
return True
return False | python | {
"resource": ""
} |
q44230 | unarchive | train | def unarchive(filename,output_dir='.'):
'''unpacks the given archive into ``output_dir``'''
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for archive in archive_formats:
if filename.endswith(archive_formats[archive]['suffix']):
return subprocess.call(archive_formats[... | python | {
"resource": ""
} |
q44231 | flatten | train | def flatten(nested_list):
'''converts a list-of-lists to a single flat list'''
return_list = []
for i in nested_list:
if isinstance(i,list):
return_list += flatten(i)
else:
return_list.append(i)
return return_list | python | {
"resource": ""
} |
q44232 | log | train | def log(fname,msg):
''' generic logging function '''
with open(fname,'a') as f:
f.write(datetime.datetime.now().strftime('%m-%d-%Y %H:%M:\n') + msg + '\n') | python | {
"resource": ""
} |
q44233 | hash | train | def hash(filename):
'''returns string of MD5 hash of given filename'''
buffer_size = 10*1024*1024
m = hashlib.md5()
with open(filename) as f:
buff = f.read(buffer_size)
while len(buff)>0:
m.update(buff)
buff = f.read(buffer_size)
dig = m.digest()
return ''... | python | {
"resource": ""
} |
q44234 | hash_str | train | def hash_str(string):
'''returns string of MD5 hash of given string'''
m = hashlib.md5()
m.update(string)
dig = m.digest()
return ''.join(['%x' % ord(x) for x in dig]) | python | {
"resource": ""
} |
q44235 | find | train | def find(file):
'''tries to find ``file`` using OS-specific searches and some guessing'''
# Try MacOS Spotlight:
mdfind = which('mdfind')
if mdfind:
out = run([mdfind,'-name',file],stderr=None,quiet=None)
if out.return_code==0 and out.output:
for fname in out.output.split... | python | {
"resource": ""
} |
q44236 | get_hexagram | train | def get_hexagram(method='THREE COIN'):
"""
Return one or two hexagrams using any of a variety of divination methods.
The ``NAIVE`` method simply returns a uniformally random ``int`` between
``1`` and ``64``.
All other methods return a 2-tuple where the first value
represents the starting hexag... | python | {
"resource": ""
} |
q44237 | get_supported_resources | train | def get_supported_resources(netid):
"""
Returns list of Supported resources
"""
url = _netid_supported_url(netid)
response = get_resource(url)
return _json_to_supported(response) | python | {
"resource": ""
} |
q44238 | _json_to_supported | train | def _json_to_supported(response_body):
"""
Returns a list of Supported objects
"""
data = json.loads(response_body)
supported = []
for supported_data in data.get("supportedList", []):
supported.append(Supported().from_json(
supported_data))
return supported | python | {
"resource": ""
} |
q44239 | add_arguments | train | def add_arguments(parser):
"""Adds stock arguments to argparse parsers from scripts that submit grid
jobs."""
default_log_path = os.path.realpath('logs')
parser.add_argument('--log-dir', metavar='LOG', type=str,
dest='logdir', default=default_log_path,
help='Base directory used for logging (defaul... | python | {
"resource": ""
} |
q44240 | submit | train | def submit(jman, command, arguments, deps=[], array=None):
"""An easy submission option for grid-enabled scripts. Create the log
directories using random hash codes. Use the arguments as parsed by the main
script."""
logdir = os.path.join(os.path.realpath(arguments.logdir),
tools.random_logdir())
jobn... | python | {
"resource": ""
} |
q44241 | Markov.add_to_dict | train | def add_to_dict(self, text):
""" Generate word n-tuple and next word probability dict """
n = self.n
sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|!)\s', text)
# '' is a special symbol for the start of a sentence like pymarkovchain uses
for sentence in sentences:... | python | {
"resource": ""
} |
q44242 | Markov.next_word | train | def next_word(self, previous_words):
"""The next word that is generated by the Markov Chain
depends on a tuple of the previous words from the Chain"""
# The previous words may never have appeared in order in the corpus used to
# generate the word_dict. Consequently, we want to try to fin... | python | {
"resource": ""
} |
q44243 | get_transaction_document | train | def get_transaction_document(current_block: dict, source: dict, from_pubkey: str, to_pubkey: str) -> Transaction:
"""
Return a Transaction document
:param current_block: Current block infos
:param source: Source to send
:param from_pubkey: Public key of the issuer
:param to_pubkey: Public key o... | python | {
"resource": ""
} |
q44244 | check_type | train | def check_type(obj: Any,
candidate_type: Any,
reltype: str = 'invariant') -> bool:
"""Tell wether a value correspond to a type,
optionally specifying the type as contravariant or covariant.
Args:
obj (Any): The value to check.
candidate_type (Any): The type to ... | python | {
"resource": ""
} |
q44245 | BaseField.get_source | train | def get_source(self, key, name_spaces=None, default_prefix=''):
"""Generates the dictionary key for the serialized representation
based on the instance variable source and a provided key.
:param str key: name of the field in model
:returns: self.source or key
"""
source ... | python | {
"resource": ""
} |
q44246 | IntegerField.validate | train | def validate(self, raw_data, **kwargs):
"""Convert the raw_data to an integer.
"""
try:
converted_data = int(raw_data)
return super(IntegerField, self).validate(converted_data)
except ValueError:
raise ValidationException(self.messages['invalid'], rep... | python | {
"resource": ""
} |
q44247 | FloatField.validate | train | def validate(self, raw_data, **kwargs):
"""Convert the raw_data to a float.
"""
try:
converted_data = float(raw_data)
super(FloatField, self).validate(converted_data, **kwargs)
return raw_data
except ValueError:
raise ValidationException(s... | python | {
"resource": ""
} |
q44248 | DateTimeField.validate | train | def validate(self, raw_data, **kwargs):
"""The raw_data is returned unchanged."""
super(DateTimeField, self).validate(raw_data, **kwargs)
try:
if isinstance(raw_data, datetime.datetime):
self.converted = raw_data
elif self.serial_format is None:
... | python | {
"resource": ""
} |
q44249 | _clean_post_content | train | def _clean_post_content(blog_url, content):
"""
Replace import path with something relative to blog.
"""
content = re.sub(
"<img.src=\"%s(.*)\"" % blog_url,
lambda s: "<img src=\"%s\"" % _get_relative_upload(s.groups(1)[0]),
content)
return content | python | {
"resource": ""
} |
q44250 | JobManagerSGE.submit | train | def submit(self, command_line, name = None, array = None, dependencies = [], exec_dir = None, log_dir = "logs", dry_run = False, verbosity = 0, stop_on_failure = False, **kwargs):
"""Submits a job that will be executed in the grid."""
# add job to database
self.lock()
job = add_job(self.session, command... | python | {
"resource": ""
} |
q44251 | JobManagerSGE.run_job | train | def run_job(self, job_id, array_id = None):
"""Overwrites the run-job command from the manager to extract the correct job id before calling base class implementation."""
# get the unique job id from the given grid id
self.lock()
jobs = list(self.session.query(Job).filter(Job.id == job_id))
if len(jo... | python | {
"resource": ""
} |
q44252 | JobManagerSGE.stop_jobs | train | def stop_jobs(self, job_ids):
"""Stops the jobs in the grid."""
self.lock()
jobs = self.get_jobs(job_ids)
for job in jobs:
if job.status in ('executing', 'queued', 'waiting'):
qdel(job.id, context=self.context)
logger.info("Stopped job '%s' in the SGE grid." % job)
job.sub... | python | {
"resource": ""
} |
q44253 | SecretKey.encrypt | train | def encrypt(self, pubkey: str, nonce: Union[str, bytes], text: Union[str, bytes]) -> str:
"""
Encrypt message text with the public key of the recipient and a nonce
The nonce must be a 24 character string (you can use libnacl.utils.rand_nonce() to get one)
and unique for each encrypted m... | python | {
"resource": ""
} |
q44254 | SecretKey.decrypt | train | def decrypt(self, pubkey: str, nonce: Union[str, bytes], text: str) -> str:
"""
Decrypt encrypted message text with recipient public key and the unique nonce used by the sender.
:param pubkey: Public key of the recipient
:param nonce: Unique nonce used by the sender
:param text:... | python | {
"resource": ""
} |
q44255 | PublicKey.encrypt_seal | train | def encrypt_seal(self, data: Union[str, bytes]) -> bytes:
"""
Encrypt data with a curve25519 version of the ed25519 public key
:param data: Bytes data to encrypt
"""
curve25519_public_key = libnacl.crypto_sign_ed25519_pk_to_curve25519(self.pk)
return libnacl.crypto_box_s... | python | {
"resource": ""
} |
q44256 | Command.override_default_templates | train | def override_default_templates(self):
"""
Override the default emails already defined by other apps
"""
if plugs_mail_settings['OVERRIDE_TEMPLATE_DIR']:
dir_ = plugs_mail_settings['OVERRIDE_TEMPLATE_DIR']
for file_ in os.listdir(dir_):
if file_.end... | python | {
"resource": ""
} |
q44257 | Command.get_apps | train | def get_apps(self):
"""
Get the list of installed apps
and return the apps that have
an emails module
"""
templates = []
for app in settings.INSTALLED_APPS:
try:
app = import_module(app + '.emails')
templates += self.get... | python | {
"resource": ""
} |
q44258 | Command.get_plugs_mail_classes | train | def get_plugs_mail_classes(self, app):
"""
Returns a list of tuples, but it should
return a list of dicts
"""
classes = []
members = self.get_members(app)
for member in members:
name, cls = member
if inspect.isclass(cls) and issubclass(cls,... | python | {
"resource": ""
} |
q44259 | Command.create_templates | train | def create_templates(self, templates):
"""
Gets a list of templates to insert into the database
"""
count = 0
for template in templates:
if not self.template_exists_db(template):
name, location, description, language = template
text = s... | python | {
"resource": ""
} |
q44260 | Command.open_file | train | def open_file(self, file_):
"""
Receives a file path has input and returns a
string with the contents of the file
"""
with open(file_, 'r', encoding='utf-8') as file:
text = ''
for line in file:
text += line
return text | python | {
"resource": ""
} |
q44261 | Command.template_exists_db | train | def template_exists_db(self, template):
"""
Receives a template and checks if it exists in the database
using the template name and language
"""
name = utils.camel_to_snake(template[0]).upper()
language = utils.camel_to_snake(template[3])
try:
models.E... | python | {
"resource": ""
} |
q44262 | PathFinder2._path_hooks | train | def _path_hooks(cls, path): # from importlib.PathFinder
"""Search sys.path_hooks for a finder for 'path'."""
if sys.path_hooks is not None and not sys.path_hooks:
warnings.warn('sys.path_hooks is empty', ImportWarning)
for hook in sys.path_hooks:
try:
ret... | python | {
"resource": ""
} |
q44263 | PathFinder2._path_importer_cache | train | def _path_importer_cache(cls, path): # from importlib.PathFinder
"""Get the finder for the path entry from sys.path_importer_cache.
If the path entry is not in the cache, find the appropriate finder
and cache it. If no finder is available, store None.
"""
if path == '':
... | python | {
"resource": ""
} |
q44264 | PathFinder2.find_module | train | def find_module(cls, fullname, path=None):
"""find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache.
This method is for python2 only
"""
spec = cls.find_spec(fullname, path)
if spec is None:
return None
elif spec.loa... | python | {
"resource": ""
} |
q44265 | PathFinder2.find_spec | train | def find_spec(cls, fullname, path=None, target=None):
"""find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache."""
if path is None:
path = sys.path
spec = cls._get_spec(fullname, path, target)
if spec is None:
return Non... | python | {
"resource": ""
} |
q44266 | FileFinder2.find_spec | train | def find_spec(self, fullname, target=None):
"""Try to find a spec for the specified module. Returns the
matching spec, or None if not found."""
is_namespace = False
tail_module = fullname.rpartition('.')[2]
base_path = os.path.join(self.path, tail_module)
for suffix, lo... | python | {
"resource": ""
} |
q44267 | FileFinder2.find_module | train | def find_module(self, fullname):
"""Try to find a loader for the specified module, or the namespace
package portions. Returns loader.
"""
spec = self.find_spec(fullname)
if spec is None:
return None
# We need to handle the namespace case here for python2
... | python | {
"resource": ""
} |
q44268 | FileFinder2.path_hook | train | def path_hook(cls, *loader_details):
"""A class method which returns a closure to use on sys.path_hook
which will return an instance using the specified loaders and the path
called on the closure.
If the path called on the closure is not a directory, ImportError is
raised.
... | python | {
"resource": ""
} |
q44269 | Uniq.getid | train | def getid(self, idtype):
'''
idtype in Uniq constants
'''
memorable_id = None
while memorable_id in self._ids:
l=[]
for _ in range(4):
l.append(str(randint(0, 19)))
memorable_id = ''.join(l)
self._ids.append(memorable_id... | python | {
"resource": ""
} |
q44270 | register_deregister | train | def register_deregister(notifier, event_type, callback=None,
args=None, kwargs=None, details_filter=None,
weak=False):
"""Context manager that registers a callback, then deregisters on exit.
NOTE(harlowja): if the callback is none, then this registers nothing, wh... | python | {
"resource": ""
} |
q44271 | Listener.dead | train | def dead(self):
"""Whether the callback no longer exists.
If the callback is maintained via a weak reference, and that
weak reference has been collected, this will be true
instead of false.
"""
if not self._weak:
return False
cb = self._callback()
... | python | {
"resource": ""
} |
q44272 | Listener.is_equivalent | train | def is_equivalent(self, callback, details_filter=None):
"""Check if the callback provided is the same as the internal one.
:param callback: callback used for comparison
:param details_filter: callback used for comparison
:returns: false if not the same callback, otherwise true
:... | python | {
"resource": ""
} |
q44273 | Notifier.is_registered | train | def is_registered(self, event_type, callback, details_filter=None):
"""Check if a callback is registered.
:param event_type: event type callback was registered to
:param callback: callback that was used during registration
:param details_filter: details filter that was used during
... | python | {
"resource": ""
} |
q44274 | Notifier._do_dispatch | train | def _do_dispatch(self, listeners, event_type, details):
"""Calls into listeners, handling failures and logging as needed."""
possible_calls = len(listeners)
call_failures = 0
for listener in listeners:
try:
listener(event_type, details.copy())
exce... | python | {
"resource": ""
} |
q44275 | Notifier.notify | train | def notify(self, event_type, details):
"""Notify about an event occurrence.
All callbacks registered to receive notifications about given
event type will be called. If the provided event type can not be
used to emit notifications (this is checked via
the :meth:`.can_be_registere... | python | {
"resource": ""
} |
q44276 | Notifier.register | train | def register(self, event_type, callback,
args=None, kwargs=None, details_filter=None,
weak=False):
"""Register a callback to be called when event of a given type occurs.
Callback will be called with provided ``args`` and ``kwargs`` and
when event type occurs (o... | python | {
"resource": ""
} |
q44277 | Notifier.listeners_iter | train | def listeners_iter(self):
"""Return an iterator over the mapping of event => listeners bound.
The listener list(s) returned should **not** be mutated.
NOTE(harlowja): Each listener in the yielded (event, listeners)
tuple is an instance of the :py:class:`~.Listener` type, which
... | python | {
"resource": ""
} |
q44278 | read_local_files | train | def read_local_files(*file_paths: str) -> str:
"""
Reads one or more text files and returns them joined together.
A title is automatically created based on the file name.
Args:
*file_paths: list of files to aggregate
Returns: content of files
"""
def _read_single_file(file_path):
... | python | {
"resource": ""
} |
q44279 | LangID._readfile | train | def _readfile(cls, filename):
""" Reads a file a utf-8 file,
and retuns character tokens.
:param filename: Name of file to be read.
"""
f = codecs.open(filename, encoding='utf-8')
filedata = f.read()
f.close()
tokenz = LM.tokenize(filedata, mode='... | python | {
"resource": ""
} |
q44280 | LangID.train | train | def train(self, root=''):
""" Trains our Language Model.
:param root: Path to training data.
"""
self.trainer = Train(root=root)
corpus = self.trainer.get_corpus()
# Show loaded Languages
#print 'Lang Set: ' + ' '.join(train.get_lang_set())
for ite... | python | {
"resource": ""
} |
q44281 | LangID.is_training_modified | train | def is_training_modified(self):
""" Returns `True` if training data
was modified since last training.
Returns `False` otherwise,
or if using builtin training data.
"""
last_modified = self.trainer.get_last_modified()
if last_modified > self.training_t... | python | {
"resource": ""
} |
q44282 | TableAccess.exists | train | def exists(c_table_cd: str, tables: I2B2Tables) -> int:
""" Return the number of records that exist with the table code.
- Ideally this should be zero or one, but the default table doesn't have a key
:param c_table_cd: key to test
:param tables:
:return: number of records found
... | python | {
"resource": ""
} |
q44283 | TableAccess.del_records | train | def del_records(c_table_cd: str, tables: I2B2Tables) -> int:
""" Delete all records with c_table_code
:param c_table_cd: key to delete
:param tables:
:return: number of records deleted
"""
conn = tables.ont_connection
table = tables.schemes
return conn.ex... | python | {
"resource": ""
} |
q44284 | read_config | train | def read_config(filename=None):
"""
Read a config filename into .ini format and return dict of shares.
Keyword arguments:
filename -- the path of config filename (default None)
Return dict.
"""
if not os.path.exists(filename):
raise IOError('Impossibile trovare il filename %s' % fi... | python | {
"resource": ""
} |
q44285 | JobManager.unlock | train | def unlock(self):
"""Closes the session to the database."""
if not hasattr(self, 'session'):
raise RuntimeError('Error detected! The session that you want to close does not exist any more!')
logger.debug("Closed database session of '%s'" % self._database)
self.session.close()
del self.session | python | {
"resource": ""
} |
q44286 | JobManager._create | train | def _create(self):
"""Creates a new and empty database."""
from .tools import makedirs_safe
# create directory for sql database
makedirs_safe(os.path.dirname(self._database))
# create all the tables
Base.metadata.create_all(self._engine)
logger.debug("Created new empty database '%s'" % sel... | python | {
"resource": ""
} |
q44287 | JobManager.get_jobs | train | def get_jobs(self, job_ids = None):
"""Returns a list of jobs that are stored in the database."""
if job_ids is not None and len(job_ids) == 0:
return []
q = self.session.query(Job)
if job_ids is not None:
q = q.filter(Job.unique.in_(job_ids))
return sorted(list(q), key=lambda job: job.u... | python | {
"resource": ""
} |
q44288 | JobManager.list | train | def list(self, job_ids, print_array_jobs = False, print_dependencies = False, long = False, print_times = False, status=Status, names=None, ids_only=False):
"""Lists the jobs currently added to the database."""
# configuration for jobs
fields = ("job-id", "grid-id", "queue", "status", "job-name")
length... | python | {
"resource": ""
} |
q44289 | JobManager.report | train | def report(self, job_ids=None, array_ids=None, output=True, error=True, status=Status, name=None):
"""Iterates through the output and error files and write the results to command line."""
def _write_contents(job):
# Writes the contents of the output and error files to command line
out_file, err_file... | python | {
"resource": ""
} |
q44290 | JobManager.delete | train | def delete(self, job_ids, array_ids = None, delete_logs = True, delete_log_dir = False, status = Status, delete_jobs = True):
"""Deletes the jobs with the given ids from the database."""
def _delete_dir_if_empty(log_dir):
if log_dir and delete_log_dir and os.path.isdir(log_dir) and not os.listdir(log_dir)... | python | {
"resource": ""
} |
q44291 | current | train | def current(config):
"""Display current revision"""
with open(config, 'r'):
main.current(yaml.load(open(config))) | python | {
"resource": ""
} |
q44292 | revision | train | def revision(config, message):
"""Create new revision file in a scripts directory"""
with open(config, 'r'):
main.revision(yaml.load(open(config)), message) | python | {
"resource": ""
} |
q44293 | reapply | train | def reapply(config):
"""Reapply current revision"""
with open(config, 'r'):
main.reapply(yaml.load(open(config))) | python | {
"resource": ""
} |
q44294 | show | train | def show(config):
"""Show revision list"""
with open(config, 'r'):
main.show(yaml.load(open(config))) | python | {
"resource": ""
} |
q44295 | raise_from | train | def raise_from(exc, cause):
"""
Does the same as ``raise LALALA from BLABLABLA`` does in Python 3.
But works in Python 2 also!
Please checkout README on https://github.com/9seconds/pep3134
to get an idea about possible pitfals. But short story is: please
be pretty carefull with tracebacks. If i... | python | {
"resource": ""
} |
q44296 | Command.find_files | train | def find_files(self, root):
"""
Helper method to get all files in the given root.
"""
def is_ignored(path, ignore_patterns):
"""
Check if the given path should be ignored or not.
"""
filename = os.path.basename(path)
ignore = l... | python | {
"resource": ""
} |
q44297 | plotter | train | def plotter(path, show, goodFormat):
'''makes some plots
creates binned histograms of the results of each module
(ie count of results in ranges [(0,40), (40, 50), (50,60), (60, 70), (70, 80), (80, 90), (90, 100)])
Arguments:
path {str} -- path to save plots to
show {boolean} -- whethe... | python | {
"resource": ""
} |
q44298 | myGrades | train | def myGrades(year, candidateNumber, badFormat, length):
'''returns final result of candidateNumber in year
Arguments:
year {int} -- the year candidateNumber is in
candidateNumber {str} -- the candidateNumber of candidateNumber
badFormat {dict} -- candNumber : [results for candidate]
... | python | {
"resource": ""
} |
q44299 | myRank | train | def myRank(grade, badFormat, year, length):
'''rank of candidateNumber in year
Arguments:
grade {int} -- a weighted average for a specific candidate number and year
badFormat {dict} -- candNumber : [results for candidate]
year {int} -- year you are in
length {int} -- length of e... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.