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 _login(self):
'''Login to the SMTP server specified at instantiation
Returns an authenticated SMTP instance.
'''
server, port, mode, debug = self.connection_details
if mode == 'SSL':
smtp_class = smtplib.SMTP_SSL
else:
smtp_class = smtplib.SM... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def column_types(self):
"""Return a dict mapping column name to type for all columns in table """ |
column_types = {}
for c in self.sqla_columns:
column_types[c.name] = c.type
return column_types |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop(self):
"""Drop the table from the database """ |
if self._is_dropped is False:
self.table.drop(self.engine)
self._is_dropped = 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 dotkey(obj: dict, path: str, default=None, separator='.'):
""" Provides an interface to traverse nested dict values by dot-separated paths. Wrapper for ``dpa... |
try:
return get(obj, path, separator=separator)
except KeyError:
return default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coerce_str_to_bool(val: t.Union[str, int, bool, None], strict: bool = False) -> bool: """ Converts a given string ``val`` into a boolean. :param val: any stri... |
if isinstance(val, str):
val = val.lower()
flag = ENV_STR_BOOL_COERCE_MAP.get(val, None)
if flag is not None:
return flag
if strict:
raise ValueError('Unsupported value for boolean flag: `%s`' % val)
return bool(val) |
<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_dockerized(flag_name: str = 'DOCKERIZED', strict: bool = False):
""" Reads env ``DOCKERIZED`` variable as a boolean. :param flag_name: environment variabl... |
return env_bool_flag(flag_name, strict=strict) |
<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_production(flag_name: str = 'PRODUCTION', strict: bool = False):
""" Reads env ``PRODUCTION`` variable as a boolean. :param flag_name: environment variabl... |
return env_bool_flag(flag_name, strict=strict) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def runcode(code):
"""Run the given code line by line with printing, as list of lines, and return variable 'ans'.""" |
for line in code:
print('# '+line)
exec(line,globals())
print('# return ans')
return ans |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exec_all_endpoints(self, *args, **kwargs):
"""Execute each passed endpoint and collect the results. If a result is anoter `MultipleResults` it will extend th... |
results = []
for handler in self.endpoints:
if isinstance(handler, weakref.ref):
handler = handler()
if self.adapt_params:
bind = self._adapt_call_params(handler, args, kwargs)
res = handler(*bind.args, **bind.kwargs)
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 run(self, *args, **kwargs):
"""Call all the registered handlers with the arguments passed. If this signal is a class member, call also the handlers registere... |
if self.fvalidation is not None:
try:
if self.fvalidation(*args, **kwargs) is False:
raise ExecutionError("Validation returned ``False``")
except Exception as e:
if __debug__:
logger.exception("Validation failed")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login_defs():
"""Discover the minimum and maximum UID number.""" |
uid_min = None
uid_max = None
login_defs_path = '/etc/login.defs'
if os.path.exists(login_defs_path):
with io.open(text_type(login_defs_path), encoding=text_type('utf-8')) as log_defs_file:
login_data = log_defs_file.readlines()
for line in login_data:
if PY3: #... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect_static() -> bool: """ Runs Django ``collectstatic`` command in silent mode. :return: always ``True`` """ |
from django.core.management import execute_from_command_line
# from django.conf import settings
# if not os.listdir(settings.STATIC_ROOT):
wf('Collecting static files... ', False)
execute_from_command_line(['./manage.py', 'collectstatic', '-c', '--noinput', '-v0'])
wf('[+]\n')
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 generate_add_user_command(proposed_user=None, manage_home=None):
"""Generate command to add a user. args: proposed_user (User):
User manage_home: bool retur... |
command = None
if get_platform() in ('Linux', 'OpenBSD'):
command = '{0} {1}'.format(sudo_check(), LINUX_CMD_USERADD)
if proposed_user.uid:
command = '{0} -u {1}'.format(command, proposed_user.uid)
if proposed_user.gid:
command = '{0} -g {1}'.format(command, prop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_modify_user_command(task=None, manage_home=None):
"""Generate command to modify existing user to become the proposed user. args: task (dict):
A pro... |
name = task['proposed_user'].name
comparison_result = task['user_comparison']['result']
command = None
if get_platform() in ('Linux', 'OpenBSD'):
command = '{0} {1}'.format(sudo_check(), LINUX_CMD_USERMOD)
if comparison_result.get('replacement_uid_value'):
command = '{0} -u ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_delete_user_command(username=None, manage_home=None):
"""Generate command to delete a user. args: username (str):
user name manage_home (bool):
ma... |
command = None
remove_home = '-r' if manage_home else ''
if get_platform() in ('Linux', 'OpenBSD'):
command = '{0} {1} {2} {3}'.format(sudo_check(), LINUX_CMD_USERDEL, remove_home, username)
elif get_platform() == 'FreeBSD': # pragma: FreeBSD
command = '{0} {1} userdel {2} -n {3}'.for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare_user(passed_user=None, user_list=None):
"""Check if supplied User instance exists in supplied Users list and, if so, return the differences. args: pa... |
# Check if user exists
returned = user_list.describe_users(users_filter=dict(name=passed_user.name))
replace_keys = False
# User exists, so compare attributes
comparison_result = dict()
if passed_user.uid and (not returned[0].uid == passed_user.uid):
comparison_result['uid_action'] = '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 gecos(self):
"""Force double quoted gecos. returns: str: The double quoted gecos. """ |
if not self._gecos:
return None
if self._gecos.startswith(text_type('\'')) and self._gecos.endswith(text_type('\'')):
self._gecos = '\"{0}\"'.format(self._gecos[1:-1])
return self._gecos
elif self._gecos.startswith(text_type('\"')) and self._gecos.endswith(te... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self):
""" Return the user as a dict. """ |
public_keys = [public_key.b64encoded for public_key in self.public_keys]
return dict(name=self.name, passwd=self.passwd, uid=self.uid, gid=self.gid, gecos=self.gecos,
home_dir=self.home_dir, shell=self.shell, public_keys=public_keys) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert(self, index, value):
"""Insert an instance of User into the collection.""" |
self.check(value)
self._user_list.insert(index, 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 remove(self, username=None):
"""Remove User instance based on supplied user name.""" |
self._user_list = [user for user in self._user_list if user.name != username] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_yaml(cls, file_path=None):
"""Create collection from a YAML file.""" |
try:
import yaml
except ImportError: # pragma: no cover
yaml = None
if not yaml:
import sys
sys.exit('PyYAML is not installed, but is required in order to parse YAML files.'
'\nTo install, run:\n$ pip install PyYAML\nor visit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_json(cls, file_path=None):
"""Create collection from a JSON file.""" |
with io.open(file_path, encoding=text_type('utf-8')) as stream:
try:
users_json = json.load(stream)
except ValueError:
raise ValueError('No JSON object could be decoded')
return cls.construct_user_list(raw_users=users_json.get('users')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def construct_user_list(raw_users=None):
"""Construct a list of User objects from a list of dicts.""" |
users = Users(oktypes=User)
for user_dict in raw_users:
public_keys = None
if user_dict.get('public_keys'):
public_keys = [PublicKey(b64encoded=x, raw=None)
for x in user_dict.get('public_keys')]
users.append(User(name=u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self):
""" Return a dict of the users. """ |
users = dict(users=list())
for user in self:
users['users'].append(user.to_dict())
return users |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export(self, file_path=None, export_format=None):
""" Write the users to a file. """ |
with io.open(file_path, mode='w', encoding="utf-8") as export_file:
if export_format == 'yaml':
import yaml
yaml.safe_dump(self.to_dict(), export_file, default_flow_style=False)
elif export_format == 'json':
export_file.write(text_type(jso... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def write(path, doc, mode=MODE_TSV, **kwargs):
''' Helper function to write doc to TTL-TXT format '''
if mode == MODE_TSV:
with TxtWriter.from_path(path) as writer:
writer.write_doc(doc)
elif mode == MODE_JSON:
write_json(path, doc, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tcmap(self):
''' Create a tokens-concepts map '''
tcmap = dd(list)
for concept in self.__concept_map.values():
for w in concept.tokens:
tcmap[w].append(concept)
return tcmap |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def msw(self):
''' Return a generator of tokens with more than one sense. '''
return (t for t, c in self.tcmap().items() if len(c) > 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 surface(self, tag):
''' Get surface string that is associated with a tag object '''
if tag.cfrom is not None and tag.cto is not None and tag.cfrom >= 0 and tag.cto >= 0:
return self.text[tag.cfrom:tag.cto]
else:
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 new_tag(self, label, cfrom=-1, cto=-1, tagtype='', **kwargs):
''' Create a sentence-level tag '''
tag_obj = Tag(label, cfrom, cto, tagtype=tagtype, **kwargs)
return self.add_tag(tag_obj) |
<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_tag(self, tagtype):
''' Get the first tag of a particular type'''
for tag in self.__tags:
if tag.tagtype == tagtype:
return tag
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_tags(self, tagtype):
''' Get all tags of a type '''
return [t for t in self.__tags if t.tagtype == tagtype] |
<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_token_object(self, token):
''' Add a token object into this sentence '''
token.sent = self # take ownership of given token
self.__tokens.append(token)
return token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def new_concept(self, tag, clemma="", tokens=None, cidx=None, **kwargs):
''' Create a new concept object and add it to concept list
tokens can be a list of Token objects or token indices
'''
if cidx is None:
cidx = self.new_concept_id()
if tokens:
tokens =... |
<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_concept(self, concept_obj):
''' Add a concept to current concept list '''
if concept_obj is None:
raise Exception("Concept object cannot be None")
elif concept_obj in self.__concepts:
raise Exception("Concept object is already inside")
elif concept_obj.cid... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def concept(self, cid, **kwargs):
''' Get concept by concept ID '''
if cid not in self.__concept_map:
if 'default' in kwargs:
return kwargs['default']
else:
raise KeyError("Invalid cid")
else:
return self.__concept_map[cid] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def import_tokens(self, tokens, import_hook=None, ignorecase=True):
''' Import a list of string as tokens '''
text = self.text.lower() if ignorecase else self.text
has_hooker = import_hook and callable(import_hook)
cfrom = 0
if self.__tokens:
for tk in self.__tokens:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tag_map(self):
''' Build a map from tagtype to list of tags '''
tm = dd(list)
for tag in self.__tags:
tm[tag.tagtype].append(tag)
return tm |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def find(self, tagtype, **kwargs):
'''Get the first tag with a type in this token '''
for t in self.__tags:
if t.tagtype == tagtype:
return t
if 'default' in kwargs:
return kwargs['default']
else:
raise LookupError("Token {} is not tagg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def find_all(self, tagtype):
''' Find all token-level tags with the specified tagtype '''
return [t for t in self.__tags if t.tagtype == tagtype] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def new_tag(self, label, cfrom=None, cto=None, tagtype=None, **kwargs):
''' Create a new tag on this token '''
if cfrom is None:
cfrom = self.cfrom
if cto is None:
cto = self.cto
tag = Tag(label=label, cfrom=cfrom, cto=cto, tagtype=tagtype, **kwargs)
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 add_sent(self, sent_obj):
''' Add a ttl.Sentence object to this document '''
if sent_obj is None:
raise Exception("Sentence object cannot be None")
elif sent_obj.ID is None:
# if sentID is None, create a new ID
sent_obj.ID = next(self.__idgen)
elif... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def new_sent(self, text, ID=None, **kwargs):
''' Create a new sentence and add it to this Document '''
if ID is None:
ID = next(self.__idgen)
return self.add_sent(Sentence(text, ID=ID, **kwargs)) |
<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_attributes(qpi):
"""Check QPimage attributes Parameters qpi: qpimage.core.QPImage Raises ------ IntegrityCheckError if the check fails """ |
missing_attrs = []
for key in DATA_KEYS:
if key not in qpi.meta:
missing_attrs.append(key)
if missing_attrs:
msg = "Attributes are missing: {} ".format(missing_attrs) \
+ "in {}!".format(qpi)
raise IntegrityCheckError(msg) |
<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_background(qpi):
"""Check QPimage background data Parameters qpi: qpimage.core.QPImage Raises ------ IntegrityCheckError if the check fails """ |
for imdat in [qpi._amp, qpi._pha]:
try:
fit, attrs = imdat.get_bg(key="fit", ret_attrs=True)
except KeyError:
# No bg correction performed
pass
else:
kwargs = dict(attrs)
# check if we have a user-defined mask image
bin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_image_dataset(group, key, data, h5dtype=None):
"""Write an image to an hdf5 group as a dataset This convenience function sets all attributes such that ... |
if h5dtype is None:
h5dtype = data.dtype
if key in group:
del group[key]
if group.file.driver == "core":
kwargs = {}
else:
kwargs = {"fletcher32": True,
"chunks": data.shape}
kwargs.update(COMPRESSION)
dset = group.create_dataset(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 info(self):
"""list of background correction parameters""" |
info = []
name = self.__class__.__name__.lower()
# get bg information
for key in VALID_BG_KEYS:
if key in self.h5["bg_data"]:
attrs = self.h5["bg_data"][key].attrs
for akey in attrs:
atr = attrs[akey]
va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_bg(self, key):
"""Remove the background image data Parameters key: str One of :const:`VALID_BG_KEYS` """ |
if key not in VALID_BG_KEYS:
raise ValueError("Invalid bg key: {}".format(key))
if key in self.h5["bg_data"]:
del self.h5["bg_data"][key]
else:
msg = "No bg data to clear for '{}' in {}.".format(key, self)
warnings.warn(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def estimate_bg(self, fit_offset="mean", fit_profile="tilt", border_px=0, from_mask=None, ret_mask=False):
"""Estimate image background Parameters fit_profile: s... |
# remove existing bg before accessing imdat.image
self.set_bg(bg=None, key="fit")
# compute bg
bgimage, mask = bg_estimate.estimate(data=self.image,
fit_offset=fit_offset,
fit_profile=fit_profile,
... |
<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_bg(self, key=None, ret_attrs=False):
"""Get the background data Parameters key: None or str A user-defined key that identifies the background data. Examp... |
if key is None:
if ret_attrs:
raise ValueError("No attributes for combined background!")
return self.bg
else:
if key not in VALID_BG_KEYS:
raise ValueError("Invalid bg key: {}".format(key))
if key in self.h5["bg_data"]:
... |
<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_bg(self, bg, key="data", attrs={}):
"""Set the background data Parameters bg: numbers.Real, 2d ndarray, ImageData, or h5py.Dataset The background data. I... |
if key not in VALID_BG_KEYS:
raise ValueError("Invalid bg key: {}".format(key))
# remove previous background key
if key in self.h5["bg_data"]:
del self.h5["bg_data"][key]
# set background
if isinstance(bg, (numbers.Real, np.ndarray)):
dset = w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bg_combine(self, bgs):
"""Combine several background amplitude images""" |
out = np.ones(self.h5["raw"].shape, dtype=float)
# bg is an h5py.DataSet
for bg in bgs:
out *= bg[:]
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_str(cls, version_str: str):
""" Alternate constructor that accepts a string SemVer. """ |
o = cls()
o.version = version_str
return o |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def estimate(data, fit_offset="mean", fit_profile="tilt", border_px=0, from_mask=None, ret_mask=False):
"""Estimate the background value of an image Parameters d... |
if fit_profile not in VALID_FIT_PROFILES:
msg = "`fit_profile` must be one of {}, got '{}'".format(
VALID_FIT_PROFILES,
fit_profile)
raise ValueError(msg)
if fit_offset not in VALID_FIT_OFFSETS:
msg = "`fit_offset` must be one of {}, got '{}'".format(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def offset_gaussian(data):
"""Fit a gaussian model to `data` and return its center""" |
nbins = 2 * int(np.ceil(np.sqrt(data.size)))
mind, maxd = data.min(), data.max()
drange = (mind - (maxd - mind) / 2, maxd + (maxd - mind) / 2)
histo = np.histogram(data, nbins, density=True, range=drange)
dx = abs(histo[1][1] - histo[1][2]) / 2
hx = histo[1][1:] - dx
hy = histo[0]
# fit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def poly2o_model(params, shape):
"""lmfit 2nd order polynomial model""" |
mx = params["mx"].value
my = params["my"].value
mxy = params["mxy"].value
ax = params["ax"].value
ay = params["ay"].value
off = params["off"].value
bg = np.zeros(shape, dtype=float) + off
x = np.arange(bg.shape[0]) - bg.shape[0] // 2
y = np.arange(bg.shape[1]) - bg.shape[1] // 2
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def poly2o_residual(params, data, mask):
"""lmfit 2nd order polynomial residuals""" |
bg = poly2o_model(params, shape=data.shape)
res = (data - bg)[mask]
return res.flatten() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tilt_model(params, shape):
"""lmfit tilt model""" |
mx = params["mx"].value
my = params["my"].value
off = params["off"].value
bg = np.zeros(shape, dtype=float) + off
x = np.arange(bg.shape[0]) - bg.shape[0] // 2
y = np.arange(bg.shape[1]) - bg.shape[1] // 2
x = x.reshape(-1, 1)
y = y.reshape(1, -1)
bg += mx * x + my * y
return bg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tilt_residual(params, data, mask):
"""lmfit tilt residuals""" |
bg = tilt_model(params, shape=data.shape)
res = (data - bg)[mask]
return res.flatten() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_sideband(ft_data, which=+1, copy=True):
"""Find the side band position of a hologram The hologram is Fourier-transformed and the side band is determined... |
if copy:
ft_data = ft_data.copy()
if which not in [+1, -1]:
raise ValueError("`which` must be +1 or -1!")
ox, oy = ft_data.shape
cx = ox // 2
cy = oy // 2
minlo = max(int(np.ceil(ox / 42)), 5)
if which == +1:
# remove lower part
ft_data[cx - minlo:] = 0
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fourier2dpad(data, zero_pad=True):
"""Compute the 2D Fourier transform with zero padding Parameters data: 2d fload ndarray real-valued image data zero_pad: b... |
if zero_pad:
# zero padding size is next order of 2
(N, M) = data.shape
order = np.int(max(64., 2**np.ceil(np.log(2 * max(N, M)) / np.log(2))))
# this is faster than np.pad
datapad = np.zeros((order, order), dtype=float)
datapad[:data.shape[0], :data.shape[1]] = dat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copyh5(inh5, outh5):
"""Recursively copy all hdf5 data from one group to another Data from links is copied. Parameters inh5: str, h5py.File, or h5py.Group Th... |
if not isinstance(inh5, h5py.Group):
inh5 = h5py.File(inh5, mode="r")
if outh5 is None:
# create file in memory
h5kwargs = {"name": "qpimage{}.h5".format(QPImage._instances),
"driver": "core",
"backing_store": False,
"mode": "a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _conv_which_data(which_data):
"""Convert which data to string or tuple This function improves user convenience, as `which_data` may be of several types (str,... |
if isinstance(which_data, str):
which_data = which_data.lower().strip()
if which_data.count(","):
# convert comma string to list
which_data = [w.strip() for w in which_data.split(",")]
# remove empty strings
which_data = [w... |
<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_amp_pha(self, data, which_data):
"""Convert input data to phase and amplitude Parameters data: 2d ndarray (float or complex) or list The experimental da... |
which_data = QPImage._conv_which_data(which_data)
if which_data not in VALID_INPUT_DATA:
msg = "`which_data` must be one of {}!".format(VALID_INPUT_DATA)
raise ValueError(msg)
if which_data == "field":
amp = np.abs(data)
pha = np.angle(data)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info(self):
"""list of tuples with QPImage meta data""" |
info = []
# meta data
meta = self.meta
for key in meta:
info.append((key, self.meta[key]))
# background correction
for imdat in [self._amp, self._pha]:
info += imdat.info
return info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_bg(self, which_data=("amplitude", "phase"), keys="fit"):
"""Clear background correction Parameters which_data: str or list of str From which type of da... |
which_data = QPImage._conv_which_data(which_data)
if isinstance(keys, str):
# make sure keys is a list of strings
keys = [keys]
# Get image data for clearing
imdats = []
if "amplitude" in which_data:
imdats.append(self._amp)
if "phase... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_bg(self, which_data="phase", fit_offset="mean", fit_profile="tilt", border_m=0, border_perc=0, border_px=0, from_mask=None, ret_mask=False):
"""Compu... |
which_data = QPImage._conv_which_data(which_data)
# check validity
if not ("amplitude" in which_data or
"phase" in which_data):
msg = "`which_data` must contain 'phase' or 'amplitude'!"
raise ValueError(msg)
# get border in px
border_list ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self, h5file=None):
"""Create a copy of the current instance This is done by recursively copying the underlying hdf5 data. Parameters h5file: str, h5py.... |
h5 = copyh5(self.h5, h5file)
return QPImage(h5file=h5, h5dtype=self.h5dtype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refocus(self, distance, method="helmholtz", h5file=None, h5mode="a"):
"""Compute a numerically refocused QPImage Parameters distance: float Focusing distance... |
field2 = nrefocus.refocus(field=self.field,
d=distance/self["pixel size"],
nm=self["medium index"],
res=self["wavelength"]/self["pixel size"],
method=method
... |
<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_bg_data(self, bg_data, which_data=None):
"""Set background amplitude and phase data Parameters bg_data: 2d ndarray (float or complex), list, QPImage, or ... |
if isinstance(bg_data, QPImage):
if which_data is not None:
msg = "`which_data` must not be set if `bg_data` is QPImage!"
raise ValueError(msg)
pha, amp = bg_data.pha, bg_data.amp
elif bg_data is None:
# Reset phase and amplitude
... |
<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_qpimage(self, qpi, identifier=None, bg_from_idx=None):
"""Add a QPImage instance to the QPSeries Parameters qpi: qpimage.QPImage The QPImage that is adde... |
if not isinstance(qpi, QPImage):
raise ValueError("`fli` must be instance of QPImage!")
if "identifier" in qpi and identifier is None:
identifier = qpi["identifier"]
if identifier and identifier in self:
msg = "The identifier '{}' already ".format(identifier)... |
<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_qpimage(self, index):
"""Return a single QPImage of the series Parameters index: int or str Index or identifier of the QPImage Notes ----- Instead of ``q... |
if isinstance(index, str):
# search for the identifier
for ii in range(len(self)):
qpi = self[ii]
if "identifier" in qpi and qpi["identifier"] == index:
group = self.h5["qpi_{}".format(ii)]
break
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 _collapse_invariants(bases: List[type], namespace: MutableMapping[str, Any]) -> None: """Collect invariants from the bases and merge them with the invariants ... |
invariants = [] # type: List[Contract]
# Add invariants of the bases
for base in bases:
if hasattr(base, "__invariants__"):
invariants.extend(getattr(base, "__invariants__"))
# Add invariants in the current namespace
if '__invariants__' in namespace:
invariants.extend... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _collapse_preconditions(base_preconditions: List[List[Contract]], bases_have_func: bool, """ Collapse function preconditions with the preconditions collected ... |
if not base_preconditions and bases_have_func and preconditions:
raise TypeError(("The function {} can not weaken the preconditions because the bases specify "
"no preconditions at all. Hence this function must accept all possible input since "
"the precond... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _collapse_snapshots(base_snapshots: List[Snapshot], snapshots: List[Snapshot]) -> List[Snapshot]: """ Collapse snapshots of pre-invocation values with the sna... |
seen_names = set() # type: Set[str]
collapsed = base_snapshots + snapshots
for snap in collapsed:
if snap.name in seen_names:
raise ValueError("There are conflicting snapshots with the name: {!r}.\n\n"
"Please mind that the snapshots are inherited from the... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _collapse_postconditions(base_postconditions: List[Contract], postconditions: List[Contract]) -> List[Contract]: """ Collapse function postconditions with the... |
return base_postconditions + postconditions |
<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_namespace_function(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None: """Collect preconditions and postconditions from the b... |
# pylint: disable=too-many-branches
# pylint: disable=too-many-locals
value = namespace[key]
assert inspect.isfunction(value) or isinstance(value, (staticmethod, classmethod))
# Determine the function to be decorated
if inspect.isfunction(value):
func = value
elif isinstance(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 _dbc_decorate_namespace(bases: List[type], namespace: MutableMapping[str, Any]) -> None: """ Collect invariants, preconditions and postconditions from the bas... |
_collapse_invariants(bases=bases, namespace=namespace)
for key, value in namespace.items():
if inspect.isfunction(value) or isinstance(value, (staticmethod, classmethod)):
_decorate_namespace_function(bases=bases, namespace=namespace, key=key)
elif isinstance(value, property):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _representable(value: Any) -> bool: """ Check whether we want to represent the value in the error message on contract breach. We do not want to represent clas... |
return not inspect.isclass(value) and not inspect.isfunction(value) and not inspect.ismethod(value) and not \
inspect.ismodule(value) and not inspect.isbuiltin(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 inspect_decorator(lines: List[str], lineno: int, filename: str) -> DecoratorInspection: """ Parse the file in which the decorator is called and figure out the... |
if lineno < 0 or lineno >= len(lines):
raise ValueError(("Given line number {} of one of the decorator lines "
"is not within the range [{}, {}) of lines in {}").format(lineno, 0, len(lines), filename))
# Go up till a line starts with a decorator
decorator_lineno = 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 find_lambda_condition(decorator_inspection: DecoratorInspection) -> Optional[ConditionLambdaInspection]: """ Inspect the decorator and extract the condition a... |
call_node = decorator_inspection.node
lambda_node = None # type: Optional[ast.Lambda]
if len(call_node.args) > 0:
assert isinstance(call_node.args[0], ast.Lambda), \
("Expected the first argument to the decorator to be a condition as lambda AST node, "
"but got: {}").for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
condition_kwargs: Mapping[str, Any], a_repr: reprlib.Repr) -> List[str]: # pylint: disable=too-many-locals """ Represent function arguments and frame values in th... |
if _is_lambda(a_function=condition):
assert lambda_inspection is not None, "Expected a lambda inspection when given a condition as a lambda function"
else:
assert lambda_inspection is None, "Expected no lambda inspection in a condition given as a non-lambda function"
reprs = dict() # 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 generate_message(contract: Contract, condition_kwargs: Mapping[str, Any]) -> str: """Generate the message upon contract violation.""" |
# pylint: disable=protected-access
parts = [] # type: List[str]
if contract.location is not None:
parts.append("{}:\n".format(contract.location))
if contract.description is not None:
parts.append("{}: ".format(contract.description))
lambda_inspection = None # type: Optional[Con... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Name(self, node: ast.Name) -> None: """ Resolve the name from the variable look-up and the built-ins. Due to possible branching (e.g., If-expressions), ... |
if node in self._recomputed_values:
value = self._recomputed_values[node]
# Check if it is a non-built-in
is_builtin = True
for lookup in self._variable_lookup:
if node.id in lookup:
is_builtin = False
brea... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Attribute(self, node: ast.Attribute) -> None: """Represent the attribute by dumping its source code.""" |
if node in self._recomputed_values:
value = self._recomputed_values[node]
if _representable(value=value):
text = self._atok.get_text(node)
self.reprs[text] = value
self.generic_visit(node=node) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Call(self, node: ast.Call) -> None: """Represent the call by dumping its source code.""" |
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.generic_visit(node=node) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_ListComp(self, node: ast.ListComp) -> None: """Represent the list comprehension by dumping its source code.""" |
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.generic_visit(node=node) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_DictComp(self, node: ast.DictComp) -> None: """Represent the dictionary comprehension by dumping its source code.""" |
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.generic_visit(node=node) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _walk_decorator_stack(func: CallableT) -> Iterable['CallableT']: """ Iterate through the stack of decorated functions until the original function. Assume that... |
while hasattr(func, "__wrapped__"):
yield func
func = getattr(func, "__wrapped__")
yield func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_checker(func: CallableT) -> Optional[CallableT]: """Iterate through the decorator stack till we find the contract checker.""" |
contract_checker = None # type: Optional[CallableT]
for a_wrapper in _walk_decorator_stack(func):
if hasattr(a_wrapper, "__preconditions__") or hasattr(a_wrapper, "__postconditions__"):
contract_checker = a_wrapper
return contract_checker |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
kwargs: Dict[str, Any]) -> MutableMapping[str, Any]: """ Inspect the input values received at the wrapper for the actual function call. :param param_names: parame... |
# pylint: disable=too-many-arguments
mapping = dict() # type: MutableMapping[str, Any]
# Set the default argument values as condition parameters.
for param_name, param_value in kwdefaults.items():
mapping[param_name] = param_value
# Override the defaults with the values actually suplied ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any]) -> None: """ Assert that the contract holds as a precondition. :param contract: c... |
# Check that all arguments to the condition function have been set.
missing_args = [arg_name for arg_name in contract.condition_args if arg_name not in resolved_kwargs]
if missing_args:
raise TypeError(
("The argument(s) of the precondition have not been set: {}. "
"Does th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _assert_invariant(contract: Contract, instance: Any) -> None: """Assert that the contract holds as a class invariant given the instance of the class.""" |
if 'self' in contract.condition_arg_set:
check = contract.condition(self=instance)
else:
check = contract.condition()
if not check:
if contract.error is not None and (inspect.ismethod(contract.error) or inspect.isfunction(contract.error)):
assert contract.error_arg_set ... |
<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_with_checker(func: CallableT) -> CallableT: """Decorate the function with a checker that verifies the preconditions and postconditions.""" |
assert not hasattr(func, "__preconditions__"), \
"Expected func to have no list of preconditions (there should be only a single contract checker per function)."
assert not hasattr(func, "__postconditions__"), \
"Expected func to have no list of postconditions (there should be only a single con... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""Find the instance of ``self`` in the arguments.""" |
instance_i = param_names.index("self")
if instance_i < len(args):
instance = args[instance_i]
else:
instance = kwargs["self"]
return instance |
<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_with_invariants(func: CallableT, is_init: bool) -> CallableT: """ Decorate the function ``func`` of the class ``cls`` with invariant checks. If the ... |
if _already_decorated_with_invariants(func=func):
return func
sign = inspect.signature(func)
param_names = list(sign.parameters.keys())
if is_init:
def wrapper(*args, **kwargs):
"""Wrap __init__ method of a class by checking the invariants *after* the invocation."""
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _already_decorated_with_invariants(func: CallableT) -> bool: """Check if the function has been already decorated with an invariant check by going through its ... |
already_decorated = False
for a_decorator in _walk_decorator_stack(func=func):
if getattr(a_decorator, "__is_invariant_check__", False):
already_decorated = True
break
return already_decorated |
<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_invariant_checks(cls: type) -> None: """Decorate each of the class functions with invariant checks if not already decorated.""" |
# Candidates for the decoration as list of (name, dir() value)
init_name_func = None # type: Optional[Tuple[str, Callable[..., None]]]
names_funcs = [] # type: List[Tuple[str, Callable[..., None]]]
names_properties = [] # type: List[Tuple[str, property]]
# Filter out entries in the directory wh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Num(self, node: ast.Num) -> Union[int, float]: """Recompute the value as the number at the node.""" |
result = node.n
self.recomputed_values[node] = 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 visit_Str(self, node: ast.Str) -> str: """Recompute the value as the string at the node.""" |
result = node.s
self.recomputed_values[node] = result
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.