text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_memory(log, pref=None, lvl=logging.DEBUG, raise_flag=True):
"""Log the current memory usage. """ |
import os
import sys
cyc_str = ""
KB = 1024.0
if pref is not None:
cyc_str += "{}: ".format(pref)
# Linux returns units in Bytes; OSX in kilobytes
UNIT = KB*KB if sys.platform == 'darwin' else KB
good = False
# Use the `resource` module to check the maximum memory usage of... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_args(self, args, clargs):
"""Parse arguments and return configuration settings. """ |
# Parse All Arguments
args = self.parser.parse_args(args=clargs, namespace=args)
# Print the help information if no subcommand is given
# subcommand is required for operation
if args.subcommand is None:
self.parser.print_help()
args = None
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup_argparse(self):
"""Create `argparse` instance, and setup with appropriate parameters. """ |
parser = argparse.ArgumentParser(
prog='catalog', description='Parent Catalog class for astrocats.')
subparsers = parser.add_subparsers(
description='valid subcommands', dest='subcommand')
# Data Import
# -----------
# Add the 'import' command, and rela... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_parser_arguments_import(self, subparsers):
"""Create parser for 'import' subcommand, and associated arguments. """ |
import_pars = subparsers.add_parser(
"import", help="Import data.")
import_pars.add_argument(
'--update', '-u', dest='update',
default=False, action='store_true',
help='Only update catalog using live sources.')
import_pars.add_argument(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_parser_arguments_git(self, subparsers):
"""Create a sub-parsers for git subcommands. """ |
subparsers.add_parser(
"git-clone",
help="Clone all defined data repositories if they dont exist.")
subparsers.add_parser(
"git-push",
help="Add all files to data repositories, commit, and push.")
subparsers.add_parser(
"git-pull",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_parser_arguments_analyze(self, subparsers):
"""Create a parser for the 'analyze' subcommand. """ |
lyze_pars = subparsers.add_parser(
"analyze",
help="Perform basic analysis on this catalog.")
lyze_pars.add_argument(
'--count', '-c', dest='count',
default=False, action='store_true',
help='Determine counts of entries, files, etc.')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compress_gz(fname):
"""Compress the file with the given name and delete the uncompressed file. The compressed filename is simply the input filename with '.gz... |
import shutil
import gzip
comp_fname = fname + '.gz'
with codecs.open(fname, 'rb') as f_in, gzip.open(
comp_fname, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
os.remove(fname)
return comp_fname |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def IOC_TYPECHECK(t):
""" Returns the size of given type, and check its suitability for use in an ioctl command number. """ |
result = ctypes.sizeof(t)
assert result <= _IOC_SIZEMASK, result
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def IOR(type, nr, size):
""" An ioctl with read parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ |
return IOC(IOC_READ, type, nr, IOC_TYPECHECK(size)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def IOW(type, nr, size):
""" An ioctl with write parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ |
return IOC(IOC_WRITE, type, nr, IOC_TYPECHECK(size)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def IOWR(type, nr, size):
""" An ioctl with both read an writes parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" ... |
return IOC(IOC_READ | IOC_WRITE, type, nr, IOC_TYPECHECK(size)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_last_dirs(path, num=1):
"""Get a path including only the trailing `num` directories. Returns ------- last_path : str """ |
head, tail = os.path.split(path)
last_path = str(tail)
for ii in range(num):
head, tail = os.path.split(head)
last_path = os.path.join(tail, last_path)
last_path = "..." + last_path
return last_path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def analyze(self, args):
"""Run the analysis routines determined from the given `args`. """ |
self.log.info("Running catalog analysis")
if args.count:
self.count()
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count(self):
Returns ------- retvals : dict Dictionary of 'property-name: counts' pairs for further processing """ |
self.log.info("Running 'count'")
retvals = {}
# Numbers of 'tasks'
num_tasks = self._count_tasks()
retvals['num_tasks'] = num_tasks
# Numbers of 'files'
num_files = self._count_repo_files()
retvals['num_files'] = num_files
return retvals |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _count_tasks(self):
"""Count the number of tasks, both in the json and directory. Returns ------- num_tasks : int The total number of all tasks included in t... |
self.log.warning("Tasks:")
tasks, task_names = self.catalog._load_task_list_from_file()
# Total number of all tasks
num_tasks = len(tasks)
# Number which are active by default
num_tasks_act = len([tt for tt, vv in tasks.items() if vv.active])
# Number of python f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _count_repo_files(self):
"""Count the number of files in the data repositories. `_COUNT_FILE_TYPES` are used to determine which file types are checked explic... |
self.log.warning("Files:")
num_files = 0
repos = self.catalog.PATHS.get_all_repo_folders()
num_type = np.zeros(len(self._COUNT_FILE_TYPES), dtype=int)
num_ign = 0
for rep in repos:
# Get the last portion of the filepath for this repo
last_path = _... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _file_nums_str(self, n_all, n_type, n_ign):
"""Construct a string showing the number of different file types. Returns ------- f_str : str """ |
# 'other' is the difference between all and named
n_oth = n_all - np.sum(n_type)
f_str = "{} Files".format(n_all) + " ("
if len(n_type):
f_str += ", ".join("{} {}".format(name, num) for name, num in
zip(self._COUNT_FILE_TYPES, n_type))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _count_files_by_type(self, path, pattern, ignore=True):
"""Count files in the given path, with the given pattern. If `ignore = True`, skip files in the `_IGN... |
# Get all files matching the given path and pattern
files = glob(os.path.join(path, pattern))
# Count the files
files = [ff for ff in files
if os.path.split(ff)[-1] not in self._IGNORE_FILES
or not ignore]
num_files = len(files)
return n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bibcode_from_url(cls, url):
"""Given a URL, try to find the ADS bibcode. Currently: only `ads` URLs will work, e.g. Returns ------- code : str or 'None' The ... |
try:
code = url.split('/abs/')
code = code[1].strip()
return code
except:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_save_path(self, bury=False):
"""Return the path that this Entry should be saved to.""" |
filename = self.get_filename(self[self._KEYS.NAME])
# Put objects that shouldn't belong in this catalog in the boneyard
if bury:
outdir = self.catalog.get_repo_boneyard()
# Get normal repository save directory
else:
repo_folders = self.catalog.PATHS.get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ordered(self, odict):
"""Convert the object into a plain OrderedDict.""" |
ndict = OrderedDict()
if isinstance(odict, CatDict) or isinstance(odict, Entry):
key = odict.sort_func
else:
key = None
nkeys = list(sorted(odict.keys(), key=key))
for key in nkeys:
if isinstance(odict[key], OrderedDict):
odi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_hash(self, keys=[]):
"""Return a unique hash associated with the listed keys.""" |
if not len(keys):
keys = list(self.keys())
string_rep = ''
oself = self._ordered(deepcopy(self))
for key in keys:
string_rep += json.dumps(oself.get(key, ''), sort_keys=True)
return hashlib.sha512(string_rep.encode()).hexdigest()[:16] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clean_quantity(self, quantity):
"""Clean quantity value before it is added to entry.""" |
value = quantity.get(QUANTITY.VALUE, '').strip()
error = quantity.get(QUANTITY.E_VALUE, '').strip()
unit = quantity.get(QUANTITY.U_VALUE, '').strip()
kind = quantity.get(QUANTITY.KIND, '')
if isinstance(kind, list) and not isinstance(kind, string_types):
kind = [x.s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_cat_dict_source(self, cat_dict_class, key_in_self, **kwargs):
"""Check that a source exists and that a quantity isn't erroneous.""" |
# Make sure that a source is given
source = kwargs.get(cat_dict_class._KEYS.SOURCE, None)
if source is None:
raise CatDictError(
"{}: `source` must be provided!".format(self[self._KEYS.NAME]),
warn=True)
# Check that source is a list of intege... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_cat_dict(self, cat_dict_class, key_in_self, check_for_dupes=True, compare_to_existing=True, **kwargs):
"""Add a `CatDict` to this `Entry`. CatDict only ... |
# Make sure that a source is given, and is valid (nor erroneous)
if cat_dict_class != Error:
try:
source = self._check_cat_dict_source(cat_dict_class,
key_in_self, **kwargs)
except CatDictError as err:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_from_file(cls, catalog, name=None, path=None, clean=False, merge=True, pop_schema=True, ignore_keys=[], compare_to_existing=True, try_gzip=False, filter_... |
if not catalog:
from astrocats.catalog.catalog import Catalog
log = logging.getLogger()
catalog = Catalog(None, log)
catalog.log.debug("init_from_file()")
if name is None and path is None:
err = ("Either entry `name` or `path` must be specified t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_alias(self, alias, source, clean=True):
"""Add an alias, optionally 'cleaning' the alias string. Calls the parent `catalog` method `clean_entry_name` - t... |
if clean:
alias = self.catalog.clean_entry_name(alias)
self.add_quantity(self._KEYS.ALIAS, alias, source)
return alias |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_error(self, value, **kwargs):
"""Add an `Error` instance to this entry.""" |
kwargs.update({ERROR.VALUE: value})
self._add_cat_dict(Error, self._KEYS.ERRORS, **kwargs)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_photometry(self, compare_to_existing=True, **kwargs):
"""Add a `Photometry` instance to this entry.""" |
self._add_cat_dict(
Photometry,
self._KEYS.PHOTOMETRY,
compare_to_existing=compare_to_existing,
**kwargs)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_dupes(self):
"""Merge two entries that correspond to the same entry.""" |
for dupe in self.dupe_of:
if dupe in self.catalog.entries:
if self.catalog.entries[dupe]._stub:
# merge = False to avoid infinite recursion
self.catalog.load_entry_from_name(
dupe, delete=True, merge=False)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_quantity(self, quantities, value, source, check_for_dupes=True, compare_to_existing=True, **kwargs):
"""Add an `Quantity` instance to this entry.""" |
success = True
for quantity in listify(quantities):
kwargs.update({QUANTITY.VALUE: value, QUANTITY.SOURCE: source})
cat_dict = self._add_cat_dict(
Quantity,
quantity,
compare_to_existing=compare_to_existing,
check_f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_self_source(self):
"""Add a source that refers to the catalog itself. For now this points to the Open Supernova Catalog by default. """ |
return self.add_source(
bibcode=self.catalog.OSC_BIBCODE,
name=self.catalog.OSC_NAME,
url=self.catalog.OSC_URL,
secondary=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_source(self, allow_alias=False, **kwargs):
"""Add a `Source` instance to this entry.""" |
if not allow_alias and SOURCE.ALIAS in kwargs:
err_str = "`{}` passed in kwargs, this shouldn't happen!".format(
SOURCE.ALIAS)
self._log.error(err_str)
raise RuntimeError(err_str)
# Set alias number to be +1 of current number of sources
if SO... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_model(self, allow_alias=False, **kwargs):
"""Add a `Model` instance to this entry.""" |
if not allow_alias and MODEL.ALIAS in kwargs:
err_str = "`{}` passed in kwargs, this shouldn't happen!".format(
SOURCE.ALIAS)
self._log.error(err_str)
raise RuntimeError(err_str)
# Set alias number to be +1 of current number of models
if MODE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_spectrum(self, compare_to_existing=True, **kwargs):
"""Add a `Spectrum` instance to this entry.""" |
spec_key = self._KEYS.SPECTRA
# Make sure that a source is given, and is valid (nor erroneous)
source = self._check_cat_dict_source(Spectrum, spec_key, **kwargs)
if source is None:
return None
# Try to create a new instance of `Spectrum`
new_spectrum = self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self):
"""Check that the entry has the required fields.""" |
# Make sure there is a schema key in dict
if self._KEYS.SCHEMA not in self:
self[self._KEYS.SCHEMA] = self.catalog.SCHEMA.URL
# Make sure there is a name key in dict
if (self._KEYS.NAME not in self or len(self[self._KEYS.NAME]) == 0):
raise ValueError("Entry name... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_aliases(self, includename=True):
"""Retrieve the aliases of this object as a list of strings. Arguments --------- includename : bool Include the 'name' p... |
# empty list if doesnt exist
alias_quanta = self.get(self._KEYS.ALIAS, [])
aliases = [aq[QUANTITY.VALUE] for aq in alias_quanta]
if includename and self[self._KEYS.NAME] not in aliases:
aliases = [self[self._KEYS.NAME]] + aliases
return aliases |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_entry_text(self, fname):
"""Retrieve the raw text from a file.""" |
if fname.split('.')[-1] == 'gz':
with gz.open(fname, 'rt') as f:
filetext = f.read()
else:
with codecs.open(fname, 'r') as f:
filetext = f.read()
return filetext |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_source_by_alias(self, alias):
"""Given an alias, find the corresponding source in this entry. If the given alias doesn't exist (e.g. there are no sources... |
for source in self.get(self._KEYS.SOURCES, []):
if source[self._KEYS.ALIAS] == alias:
return source
raise ValueError("Source '{}': alias '{}' not found!".format(self[
self._KEYS.NAME], alias)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_stub(self):
"""Get a new `Entry` which contains the 'stub' of this one. The 'stub' is only the name and aliases. Usage: ----- To convert a normal entry i... |
stub = type(self)(self.catalog, self[self._KEYS.NAME], stub=True)
if self._KEYS.ALIAS in self:
stub[self._KEYS.ALIAS] = self[self._KEYS.ALIAS]
if self._KEYS.DISTINCT_FROM in self:
stub[self._KEYS.DISTINCT_FROM] = self[self._KEYS.DISTINCT_FROM]
if self._KEYS.RA in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_erroneous(self, field, sources):
"""Check if attribute has been marked as being erroneous.""" |
if self._KEYS.ERRORS in self:
my_errors = self[self._KEYS.ERRORS]
for alias in sources.split(','):
source = self.get_source_by_alias(alias)
bib_err_values = [
err[ERROR.VALUE] for err in my_errors
if err[ERROR.KIND]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_private(self, key, sources):
"""Check if attribute is private.""" |
# aliases are always public.
if key == ENTRY.ALIAS:
return False
return all([
SOURCE.PRIVATE in self.get_source_by_alias(x)
for x in sources.split(',')
]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, bury=False, final=False):
"""Write entry to JSON file in the proper location. Arguments --------- bury : bool final : bool If this is the 'final' ... |
outdir, filename = self._get_save_path(bury=bury)
if final:
self.sanitize()
# FIX: use 'dump' not 'dumps'
jsonstring = json.dumps(
{
self[self._KEYS.NAME]: self._ordered(self)
},
indent='\t' if sys.version_info[0] >= 3 el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort_func(self, key):
"""Used to sort keys when writing Entry to JSON format. Should be supplemented/overridden by inheriting classes. """ |
if key == self._KEYS.SCHEMA:
return 'aaa'
if key == self._KEYS.NAME:
return 'aab'
if key == self._KEYS.SOURCES:
return 'aac'
if key == self._KEYS.ALIAS:
return 'aad'
if key == self._KEYS.MODELS:
return 'aae'
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_pd_mag_from_counts(photodict, c='', ec='', lec='', uec='', zp=DEFAULT_ZP, sig=DEFAULT_UL_SIGMA):
"""Set photometry dictionary from a counts measurement."... |
with localcontext() as ctx:
if lec == '' or uec == '':
lec = ec
uec = ec
prec = max(
get_sig_digits(str(c), strip_zeroes=False),
get_sig_digits(str(lec), strip_zeroes=False),
get_sig_digits(str(uec), strip_zeroes=False)) + 1
ctx.pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_pd_mag_from_flux_density(photodict, fd='', efd='', lefd='', uefd='', sig=DEFAULT_UL_SIGMA):
"""Set photometry dictionary from a flux density measurement.... |
with localcontext() as ctx:
if lefd == '' or uefd == '':
lefd = efd
uefd = efd
prec = max(
get_sig_digits(str(fd), strip_zeroes=False),
get_sig_digits(str(lefd), strip_zeroes=False),
get_sig_digits(str(uefd), strip_zeroes=False)) + 1
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check(self):
"""Check that entry attributes are legal.""" |
# Run the super method
super(Photometry, self)._check()
err_str = None
has_flux = self._KEYS.FLUX in self
has_flux_dens = self._KEYS.FLUX_DENSITY in self
has_u_flux = self._KEYS.U_FLUX in self
has_u_flux_dens = self._KEYS.U_FLUX_DENSITY in self
has_freq... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort_func(self, key):
"""Specify order for attributes.""" |
if key == self._KEYS.TIME:
return 'aaa'
if key == self._KEYS.MODEL:
return 'zzy'
if key == self._KEYS.SOURCE:
return 'zzz'
return key |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_resource_user_and_perm( cls, user_id, perm_name, resource_id, db_session=None ):
""" return all instances by user name, perm name and resource id :param u... |
db_session = get_db_session(db_session)
query = db_session.query(cls.model).filter(cls.model.user_id == user_id)
query = query.filter(cls.model.resource_id == resource_id)
query = query.filter(cls.model.perm_name == perm_name)
return query.first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tdSensor(self):
"""Get the next sensor while iterating. :return: a dict with the keys: protocol, model, id, datatypes. """ |
protocol = create_string_buffer(20)
model = create_string_buffer(20)
sid = c_int()
datatypes = c_int()
self._lib.tdSensor(protocol, sizeof(protocol), model, sizeof(model),
byref(sid), byref(datatypes))
return {'protocol': self._to_str(protocol... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tdSensorValue(self, protocol, model, sid, datatype):
"""Get the sensor value for a given sensor. :return: a dict with the keys: value, timestamp. """ |
value = create_string_buffer(20)
timestamp = c_int()
self._lib.tdSensorValue(protocol, model, sid, datatype,
value, sizeof(value), byref(timestamp))
return {'value': self._to_str(value), 'timestamp': timestamp.value} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tdController(self):
"""Get the next controller while iterating. :return: a dict with the keys: id, type, name, available. """ |
cid = c_int()
ctype = c_int()
name = create_string_buffer(255)
available = c_int()
self._lib.tdController(byref(cid), byref(ctype), name, sizeof(name),
byref(available))
return {'id': cid.value, 'type': ctype.value,
'name':... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ziggurat_model_init( user=None, group=None, user_group=None, group_permission=None, user_permission=None, user_resource_permission=None, group_resource_permis... |
models = ModelProxy()
models.User = user
models.Group = group
models.UserGroup = user_group
models.GroupPermission = group_permission
models.UserPermission = user_permission
models.UserResourcePermission = user_resource_permission
models.GroupResourcePermission = group_resource_permissi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def messages(request, year=None, month=None, day=None, template="gnotty/messages.html"):
""" Show messages for the given query or day. """ |
query = request.REQUEST.get("q")
prev_url, next_url = None, None
messages = IRCMessage.objects.all()
if hide_joins_and_leaves(request):
messages = messages.filter(join_or_leave=False)
if query:
search = Q(message__icontains=query) | Q(nickname__icontains=query)
messages = m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_expired_locks(self):
""" Deletes all expired mutex locks if a ttl is provided. """ |
ttl_seconds = self.get_mutex_ttl_seconds()
if ttl_seconds is not None:
DBMutex.objects.filter(creation_time__lte=timezone.now() - timedelta(seconds=ttl_seconds)).delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
""" Acquires the db mutex lock. Takes the necessary steps to delete any stale locks. Throws a DBMutexError if it can't acquire the lock. """ |
# Delete any expired locks first
self.delete_expired_locks()
try:
with transaction.atomic():
self.lock = DBMutex.objects.create(lock_id=self.lock_id)
except IntegrityError:
raise DBMutexError('Could not acquire lock: {0}'.format(self.lock_id)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
""" Releases the db mutex lock. Throws an error if the lock was released before the function finished. """ |
if not DBMutex.objects.filter(id=self.lock.id).exists():
raise DBMutexTimeoutError('Lock {0} expired before function completed'.format(self.lock_id))
else:
self.lock.delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decorate_callable(self, func):
""" Decorates a function with the db_mutex decorator by using this class as a context manager around it. """ |
def wrapper(*args, **kwargs):
try:
with self:
result = func(*args, **kwargs)
return result
except DBMutexError as e:
if self.suppress_acquisition_exceptions:
LOG.error(e)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groupfinder(userid, request):
""" Default groupfinder implementaion for pyramid applications :param userid: :param request: :return: """ |
if userid and hasattr(request, "user") and request.user:
groups = ["group:%s" % g.id for g in request.user.groups]
return groups
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_repulsion(repulsion, nodes, barnes_hut_optimize=False, region=None, barnes_hut_theta=1.2):
""" Iterate through the nodes or edges and apply the forces ... |
if not barnes_hut_optimize:
for i in range(0, len(nodes)):
for j in range(0, i):
repulsion.apply_node_to_node(nodes[i], nodes[j])
else:
for i in range(0, len(nodes)):
region.apply_force(nodes[i], repulsion, barnes_hut_theta) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_gravity(repulsion, nodes, gravity, scaling_ratio):
""" Iterate through the nodes or edges and apply the gravity directly to the node objects. """ |
for i in range(0, len(nodes)):
repulsion.apply_gravitation(nodes[i], gravity / scaling_ratio) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_external_id_and_provider(cls, external_id, provider_name, db_session=None):
""" Returns ExternalIdentity instance based on search params :param external_i... |
db_session = get_db_session(db_session)
query = db_session.query(cls.model)
query = query.filter(cls.model.external_id == external_id)
query = query.filter(cls.model.provider_name == provider_name)
return query.first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user_by_external_id_and_provider( cls, external_id, provider_name, db_session=None ):
""" Returns User instance based on search params :param external_id: :p... |
db_session = get_db_session(db_session)
query = db_session.query(cls.models_proxy.User)
query = query.filter(cls.model.external_id == external_id)
query = query.filter(cls.model.provider_name == provider_name)
query = query.filter(cls.models_proxy.User.id == cls.model.local_user... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_user_and_perm(cls, user_id, perm_name, db_session=None):
""" return by user and permission name :param user_id: :param perm_name: :param db_session: :retu... |
db_session = get_db_session(db_session)
query = db_session.query(cls.model).filter(cls.model.user_id == user_id)
query = query.filter(cls.model.perm_name == perm_name)
return query.first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node_is_subclass(cls, *subclass_names):
"""Checks if cls node has parent with subclass_name.""" |
if not isinstance(cls, (ClassDef, Instance)):
return False
# if cls.bases == YES:
# return False
for base_cls in cls.bases:
try:
for inf in base_cls.inferred(): # pragma no branch
if inf.qname() in subclass_names:
return True
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_field_method(node):
"""Checks if a call to a field instance method is valid. A call is valid if the call is a method of the underlying type. So, in a Stri... |
name = node.attrname
parent = node.last_child()
inferred = safe_infer(parent)
if not inferred:
return False
for cls_name, inst in FIELD_TYPES.items():
if node_is_instance(inferred, cls_name) and hasattr(inst, name):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_node_parent_class(node):
"""Supposes that node is a mongoengine field in a class and tries to get its parent class""" |
while node.parent: # pragma no branch
if isinstance(node, ClassDef):
return node
node = node.parent |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_field_definition(node):
""""node is a class attribute that is a mongoengine. Returns the definition statement for the attribute """ |
name = node.attrname
cls = get_node_parent_class(node)
definition = cls.lookup(name)[1][0].statement()
return definition |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_field_embedded_doc(node):
"""Returns de ClassDef for the related embedded document in a embedded document field.""" |
definition = get_field_definition(node)
cls_name = definition.last_child().last_child()
cls = next(cls_name.infer())
return cls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node_is_embedded_doc_attr(node):
"""Checks if a node is a valid field or method in a embedded document. """ |
embedded_doc = get_field_embedded_doc(node.last_child())
name = node.attrname
try:
r = bool(embedded_doc.lookup(name)[1][0])
except IndexError:
r = False
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dispatcher(self, connection, event):
""" This is the method in ``SimpleIRCClient`` that all IRC events get passed through. Here we map events to our own cus... |
super(BaseBot, self)._dispatcher(connection, event)
for handler in self.events[event.eventtype()]:
handler(self, connection, event) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def message_channel(self, message):
""" We won't receive our own messages, so log them manually. """ |
self.log(None, message)
super(BaseBot, self).message_channel(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_pubmsg(self, connection, event):
""" Log any public messages, and also handle the command event. """ |
for message in event.arguments():
self.log(event, message)
command_args = filter(None, message.split())
command_name = command_args.pop(0)
for handler in self.events["command"]:
if handler.event.args["command"] == command_name:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_command_event(self, event, command, args):
""" Command handler - treats each word in the message that triggered the command as an argument to the comm... |
argspec = getargspec(command)
num_all_args = len(argspec.args) - 2 # Ignore self/event args
num_pos_args = num_all_args - len(argspec.defaults or [])
if num_pos_args <= len(args) <= num_all_args:
response = command(self, event, *args)
elif num_all_args == num_pos_ar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_timer_event(self, handler):
""" Runs each timer handler in a separate greenlet thread. """ |
while True:
handler(self)
sleep(handler.event.args["seconds"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_webhook_event(self, environ, url, params):
""" Webhook handler - each handler for the webhook event takes an initial pattern argument for matching the... |
for handler in self.events["webhook"]:
urlpattern = handler.event.args["urlpattern"]
if not urlpattern or match(urlpattern, url):
response = handler(self, environ, url, params)
if response:
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DeviceFactory(id, lib=None):
"""Create the correct device instance based on device type and return it. :return: a :class:`Device` or :class:`DeviceGroup` ins... |
lib = lib or Library()
if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP:
return DeviceGroup(id, lib=lib)
return Device(id, lib=lib) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_callback(self, block=True):
"""Dispatch a single callback in the current thread. :param boolean block: If True, blocks waiting for a callback to come... |
try:
(callback, args) = self._queue.get(block=block)
try:
callback(*args)
finally:
self._queue.task_done()
except queue.Empty:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def devices(self):
"""Return all known devices. :return: list of :class:`Device` or :class:`DeviceGroup` instances. """ |
devices = []
count = self.lib.tdGetNumberOfDevices()
for i in range(count):
device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)
devices.append(device)
return devices |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sensors(self):
"""Return all known sensors. :return: list of :class:`Sensor` instances. """ |
sensors = []
try:
while True:
sensor = self.lib.tdSensor()
sensors.append(Sensor(lib=self.lib, **sensor))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND:
raise
return sensors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def controllers(self):
"""Return all known controllers. Requires Telldus core library version >= 2.1.2. :return: list of :class:`Controller` instances. """ |
controllers = []
try:
while True:
controller = self.lib.tdController()
del controller["name"]
del controller["available"]
controllers.append(Controller(lib=self.lib, **controller))
except TelldusError as e:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_device(self, name, protocol, model=None, **parameters):
"""Add a new device. :return: a :class:`Device` or :class:`DeviceGroup` instance. """ |
device = Device(self.lib.tdAddDevice(), lib=self.lib)
try:
device.name = name
device.protocol = protocol
if model:
device.model = model
for key, value in parameters.items():
device.set_parameter(key, value)
# R... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_group(self, name, devices):
"""Add a new device group. :return: a :class:`DeviceGroup` instance. """ |
device = self.add_device(name, "group")
device.add_to_group(devices)
return device |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_controller(self, vid, pid, serial):
"""Connect a controller.""" |
self.lib.tdConnectTellStickController(vid, pid, serial) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect_controller(self, vid, pid, serial):
"""Disconnect a controller.""" |
self.lib.tdDisconnectTellStickController(vid, pid, serial) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parameters(self):
"""Get dict with all set parameters.""" |
parameters = {}
for name in self.PARAMETERS:
try:
parameters[name] = self.get_parameter(name)
except AttributeError:
pass
return parameters |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_parameter(self, name):
"""Get a parameter.""" |
default_value = "$%!)(INVALID)(!%$"
value = self.lib.tdGetDeviceParameter(self.id, name, default_value)
if value == default_value:
raise AttributeError(name)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_parameter(self, name, value):
"""Set a parameter.""" |
self.lib.tdSetDeviceParameter(self.id, name, str(value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def devices_in_group(self):
"""Fetch list of devices in group.""" |
try:
devices = self.get_parameter('devices')
except AttributeError:
return []
ctor = DeviceFactory
return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepPointsForSegments(points):
""" Move any off curves at the end of the contour to the beginning of the contour. This makes segmentation easier. """ |
while 1:
point = points[-1]
if point.segmentType:
break
else:
point = points.pop()
points.insert(0, point)
continue
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reversePoints(points):
""" Reverse the points. This differs from the reversal point pen in RoboFab in that it doesn't worry about maintaing the start point ... |
# copy the points
points = _copyPoints(points)
# find the first on curve type and recycle
# it for the last on curve type
firstOnCurve = None
for index, point in enumerate(points):
if point.segmentType is not None:
firstOnCurve = index
break
lastSegmentType =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _convertPointsToSegments(points, willBeReversed=False):
""" Compile points into InputSegment objects. """ |
# get the last on curve
previousOnCurve = None
for point in reversed(points):
if point.segmentType is not None:
previousOnCurve = point.coordinates
break
assert previousOnCurve is not None
# gather the segments
offCurves = []
segments = []
for point in po... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _tValueForPointOnCubicCurve(point, cubicCurve, isHorizontal=0):
""" Finds a t value on a curve from a point. The points must be originaly be a point on the c... |
pt1, pt2, pt3, pt4 = cubicCurve
a, b, c, d = bezierTools.calcCubicParameters(pt1, pt2, pt3, pt4)
solutions = bezierTools.solveCubic(a[isHorizontal], b[isHorizontal], c[isHorizontal],
d[isHorizontal] - point[isHorizontal])
solutions = [t for t in solutions if 0 <= t < 1]
if not solutions and... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _scalePoints(points, scale=1, convertToInteger=True):
""" Scale points and optionally convert them to integers. """ |
if convertToInteger:
points = [
(int(round(x * scale)), int(round(y * scale)))
for (x, y) in points
]
else:
points = [(x * scale, y * scale) for (x, y) in points]
return points |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _scaleSinglePoint(point, scale=1, convertToInteger=True):
""" Scale a single point """ |
x, y = point
if convertToInteger:
return int(round(x * scale)), int(round(y * scale))
else:
return (x * scale, y * scale) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _estimateCubicCurveLength(pt0, pt1, pt2, pt3, precision=10):
""" Estimate the length of this curve by iterating through it and averaging the length of the fl... |
points = []
length = 0
step = 1.0 / precision
factors = range(0, precision + 1)
for i in factors:
points.append(_getCubicPoint(i * step, pt0, pt1, pt2, pt3))
for i in range(len(points) - 1):
pta = points[i]
ptb = points[i + 1]
length += _distance(pta, ptb)
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split(self, tValues):
""" Split the segment according the t values """ |
if self.segmentType == "curve":
on1 = self.previousOnCurve
off1 = self.points[0].coordinates
off2 = self.points[1].coordinates
on2 = self.points[2].coordinates
return bezierTools.splitCubicAtT(on1, off1, off2, on2, *tValues)
elif self.segmentT... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getData(self):
""" Return a list of normalized InputPoint objects for the contour drawn with this pen. """ |
# organize the points into segments
# 1. make sure there is an on curve
haveOnCurve = False
for point in self._points:
if point.segmentType is not None:
haveOnCurve = True
break
# 2. move the off curves to front of the list
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reCurveFromEntireInputContour(self, inputContour):
""" Match if entire input contour matches entire output contour, allowing for different start point. """ |
if self.clockwise:
inputFlat = inputContour.clockwiseFlat
else:
inputFlat = inputContour.counterClockwiseFlat
outputFlat = []
for segment in self.segments:
# XXX this could be expensive
assert segment.segmentType == "flat"
outp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_custom_qs_manager(funcdef):
"""Checks if a function definition is a queryset manager created with the @queryset_manager decorator.""" |
decors = getattr(funcdef, 'decorators', None)
if decors:
for dec in decors.get_children():
try:
if dec.name == 'queryset_manager': # pragma no branch
return True
except AttributeError:
continue
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.