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 svalue(self):
"""Get serialized value. :rtype: str """ |
result = self._svalue
if result is None: # try to get svalue from value if svalue is None
try:
value = self.value
except Parameter.Error:
pass
else:
result = self._svalue = self.serializer(value)
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 svalue(self, value):
"""Change of serialized value. Nonify this value as well. :param str value: serialized value to use. """ |
if value is not None: # if value is not None
self._value = None
self._error = None
self._svalue = 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 resolve( self, configurable=None, conf=None, scope=None, ptype=None, parser=None, error=True, svalue=None, safe=None, besteffort=None ):
"""Resolve this para... |
result = self._value
# if cached value is None and serialiazed value exists
if self._value is None and self._svalue is not None:
self._error = None # nonify error.
if ptype is None:
ptype = self.ptype
if parser is None: # init parser
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self):
"""Get parameter value. If this cached value is None and this serialized value is not None, calculate the new value from the serialized one. :re... |
result = self._value
if result is None and self._svalue is not None:
try:
result = self._value = self.resolve()
except Exception as e:
reraise(
Parameter.Error,
Parameter.Error('Call the method "resolve"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self, value):
"""Change of parameter value. If an error occured, it is stored in this error attribute. :param value: new value to use. If input value i... |
if value is None or (
self.ptype is None or isinstance(value, self.ptype)
):
self._value = value
else:
# raise wrong type error
error = TypeError(
'Wrong value type of {0} ({1}). {2} expected.'.format(
sel... |
<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_cartesian(r, theta, theta_units="radians"):
""" Converts polar r, theta to cartesian x, y. """ |
assert theta_units in ['radians', 'degrees'],\
"kwarg theta_units must specified in radians or degrees"
# Convert to radians
if theta_units == "degrees":
theta = to_radians(theta)
theta = to_proper_radians(theta)
x = r * cos(theta)
y = r * sin(theta)
return x, y |
<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_index(data,col_index):
""" Sets the index if the index is not present :param data: pandas table :param col_index: column name which will be assigned as a... |
if col_index in data:
data=data.reset_index().set_index(col_index)
if 'index' in data:
del data['index']
return data
elif data.index.name==col_index:
return data
else:
logging.error("something's wrong with the df")
df2info(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 fhs2data_combo(fhs,cols,index,labels=None,col_sep=': '):
""" Collates data from multiple csv files :param fhs: list of paths to csv files :param cols: list o... |
if labels is None:
labels=[basename(fh) for fh in fhs]
if len(fhs)>0:
for fhi,fh in enumerate(fhs):
label=labels[fhi]
data=pd.read_csv(fh).set_index(index)
if fhi==0:
data_combo=pd.DataFrame(index=data.index)
for col in cols:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __create_session(username=None, password=None):
"""grabs the configuration, and makes the call to Authentise to create the session""" |
config = Config()
if not username or not password:
username = config.username
password = config.password
payload = {
"username": username,
"password": password,
}
session_resp = requests.post("https://users.{}/sessions/".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 create_user(cls, username, password, name, email):
"""utility class method to create a user""" |
config = Config()
payload = {"username": username,
"email": email,
"name": name,
"password": password, }
user_creation_resp = requests.post("https://users.{}/users/".format(config.host),
json=pay... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_text(paragraph, line_count, min_char_per_line=0):
"""Wraps the given text to the specified number of lines.""" |
one_string = strip_all_white_space(paragraph)
if min_char_per_line:
lines = wrap(one_string, width=min_char_per_line)
try:
return lines[:line_count]
except IndexError:
return lines
else:
return wrap(one_string, len(one_string)/line_count) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jsonify(data, pretty=False, **kwargs):
"""Serialize Python objects to JSON with optional 'pretty' formatting Raises: TypeError: from :mod:`json` lib ValueErr... |
isod = isinstance(data, OrderedDict)
params = {
'for_json': True,
'default': _complex_encode,
}
if pretty:
params['indent'] = 2
params['sort_keys'] = False if isod else True
params.update(kwargs)
try:
return json.dumps(data, ensure_ascii=False, **params)
... |
<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_emit_api(self, action):
"""Build emit api.""" |
args = {'action': action}
args.update(self.context)
return (
'%(scheme)s://%(sender)s:%(token)s@%(domain)s:%(port)d'
'/event/%(project)s/emit/%(action)s' % args
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(data, format: str = 'json', pretty: bool = False):
"""Serialize a stellata object to a string format.""" |
def encode(obj):
if isinstance(obj, stellata.model.Model):
return obj.to_dict()
elif isinstance(obj, datetime.datetime):
return int(obj.timestamp())
elif isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance(obj, decimal.Decimal):... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pretty_exe_doc(program, parser, stack=1, under='-'):
""" Takes the name of a script and a parser that will give the help message for it. The module that call... |
if os.path.basename(sys.argv[0]) == 'sphinx-build':
# Get the calling module
mod = inspect.getmodule(inspect.stack()[stack][0])
# Get parser
_parser = parser() if '__call__' in dir(parser) else parser
# Make the parser use the correct program
_parser.set_usage(mod... |
<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_key(self, key_id):
""" Returns a restclients.Key object for the given key ID. If the key ID isn't found, or if there is an error communicating with the K... |
url = ENCRYPTION_KEY_URL.format(key_id)
return self._key_from_json(self._get_resource(url)) |
<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_current_key(self, resource_name):
""" Returns a restclients.Key object for the given resource. If the resource isn't found, or if there is an error commu... |
url = ENCRYPTION_CURRENT_KEY_URL.format(resource_name)
return self._key_from_json(self._get_resource(url)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _key_from_json(self, data):
""" Internal method, for creating the Key object. """ |
key = Key()
key.algorithm = data["Algorithm"]
key.cipher_mode = data["CipherMode"]
key.expiration = datetime.strptime(data["Expiration"].split(".")[0],
"%Y-%m-%dT%H:%M:%S")
key.key_id = data["ID"]
key.key = data["Key"]
k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def newSession():
""" Returns a new Requests session with pre-loaded default HTTP Headers Generates a new Requests session and consults with the Configuration cl... |
from neolib.config.Configuration import Configuration
s = requests.session()
if not Configuration.loaded():
if not Configuration.initialize():
s.headers.update(Page._defaultVars)
else:
s.headers.update(Configuration.getConfig().co... |
<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_model_id_constraints(model):
"""Returns constraints to target a specific model.""" |
pkname = model.primary_key_name
pkey = model.primary_key
return get_id_constraints(pkname, pkey) |
<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_id_constraints(pkname, pkey):
"""Returns primary key consraints. :pkname: if a string, returns a dict with pkname=pkey. pkname and pkey must be enumerabl... |
if isinstance(pkname, str):
return {pkname: pkey}
else:
return dict(zip(pkname, pkey)) |
<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_model(self, constructor, table_name, constraints=None, *, columns=None, order_by=None):
"""Calls DataAccess.find and passes the results to the given co... |
data = self.find(table_name, constraints, columns=columns, order_by=order_by)
return constructor(data) if data else 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_models(self, constructor, table_name, constraints=None, *, columns=None, order_by=None, limiting=None):
"""Calls DataAccess.find_all and passes the res... |
for record in self.find_all(table_name, constraints, columns=columns, order_by=order_by,
limiting=limiting):
yield constructor(record) |
<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_model(self, constructor, constraints=None, *, columns=None, table_name=None, order_by=None):
"""Specialization of DataAccess.find that returns a model i... |
return self._find_model(constructor, table_name or constructor.table_name, constraints,
columns=columns, order_by=order_by) |
<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_models(self, constructor, constraints=None, *, columns=None, order_by=None, limiting=None, table_name=None):
"""Specialization of DataAccess.find_all th... |
return self._find_models(
constructor, table_name or constructor.table_name, constraints, columns=columns,
order_by=order_by, limiting=limiting) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def page_models(self, constructor, paging, constraints=None, *, columns=None, order_by=None):
"""Specialization of DataAccess.page that returns models instead of... |
records, count = self.page(constructor.table_name, paging, constraints, columns=columns,
order_by=order_by)
return ([constructor(r) for r in records], count) |
<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_model_by_id(self, constructor, id_, *, columns=None):
"""Searches for a model by id, according to its class' primary_key_name. If primary_key_name is a ... |
return self.find_model(
constructor, get_id_constraints(constructor.primary_key_name, id_), columns=columns) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh_model(self, model, *, overwrite=False):
"""Pulls the model's record from the database. If overwrite is True, the model values are overwritten and ret... |
new_model = self.find_model_by_id(model.__class__, model.primary_key)
if overwrite:
model.update(new_model.to_dict(use_default_excludes=False))
return model
else:
return new_model |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_model(self, model, *, include_keys=None):
"""Updates a model. :include_keys: if given, only updates the given attributes. Otherwise, updates all non-i... |
id_constraints = get_model_id_constraints(model)
if include_keys is None:
include_keys = set(
model.attrs.keys()).difference(model.exclude_keys_sql).difference(id_constraints.keys())
# If include_keys was not null but was empty
if not include_keys:
return model
values = model... |
<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_model(self, model, *, upsert=None):
"""Inserts a record for the given model. If model's primary key is auto, the primary key will be set appropriately... |
pkname = model.primary_key_name
include_keys = set(model.attrs.keys()).difference(model.exclude_keys_sql)
if model.primary_key_is_auto:
if pkname in include_keys:
include_keys.remove(pkname)
else:
if isinstance(pkname, str):
include_keys.add(pkname)
else:
incl... |
<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_model(self, model_or_type, id_=None):
"""Deletes a model. :model_or_type: if a model, delete that model. If it is a ModelBase subclass, id_ must be sp... |
if not id_:
constraints = get_model_id_constraints(model_or_type)
else:
constraints = get_id_constraints(model_or_type.primary_key_name, id_)
self.delete(model_or_type.table_name, constraints)
return model_or_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 find_or_build(self, constructor, props):
"""Looks for a model that matches the given dictionary constraints. If it is not found, a new model of the given typ... |
model = self.find_model(constructor, props)
return model or constructor(**props) |
<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_or_create(self, constructor, props, *, comp=None):
"""Looks for a model taht matches the given dictionary constraints. If it is not found, a new model o... |
model = self.find_model(constructor, comp or props)
if model is None:
model = constructor(**props)
self.insert_model(model)
return model |
<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_or_upsert(self, constructor, props, *, comp=None, return_status=False):
"""This finds or upserts a model with an auto primary key, and is a bit more fle... |
model = self.find_model(constructor, comp or props)
status = _UPSERT_STATUS_FOUND
if model is None:
model = constructor(**props)
status = _UPSERT_STATUS_CREATED
self.insert_model(model, upsert=Upsert(Upsert.DO_NOTHING))
if model.is_new:
model = self.find_model(constructor, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def temp_copy(self):
"""Yields a new Vcs object that represents a temporary, disposable copy of the current repository. The copy is deleted at the end of the con... |
with contextmanagers.temp_dir() as temp_dir:
temp_root_path = os.path.join(temp_dir, 'root')
path = os.path.join(self.path, '') # adds trailing slash
check_call(['rsync', '-r', "--exclude={}".format(self.private_dir()), "--filter=dir-merge,- {}".format(
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 published(self, for_user=None, include_login_required=False):
""" Override ``DisplayableManager.published`` to exclude pages with ``login_required`` set to `... |
published = super(PageManager, self).published(for_user=for_user)
unauthenticated = for_user and not for_user.is_authenticated()
if (unauthenticated and not include_login_required and
not settings.PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED):
published = published.exclude... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def atomic_symlink(src, dst):
"""Create or update a symbolic link atomically. This function is similar to :py:func:`os.symlink` but will update a symlink atomica... |
dst_dir = os.path.dirname(dst)
tmp = None
max_tries = getattr(os, 'TMP_MAX', 10000)
try:
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for n in range(max_tries):
try:
# mktemp is described as being unsafe. That is not true in this case si... |
<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():
#pylint: disable=too-many-locals """Execute the command loop """ |
store = EventStore(STORE_PATH)
with open(CREDENTIAL_PATH, 'r') as cred_file:
creds = json.load(cred_file)
uname, pword = creds['uname'], creds['pword']
mgr = KindleProgressMgr(store, uname, pword)
print 'Detecting updates to Kindle progress:'
events = mgr.detect_events()
if eve... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _change_state_prompt(mgr):
"""Runs a prompt to change the state of books. Registers `Event`s with `mgr` as they are requested. Args: mgr: A `KindleProgressMg... |
cmd = ''
book_range = range(1, len(mgr.books) + 1)
ind_to_book = dict(zip(book_range, mgr.books))
get_book = lambda cmd_str: ind_to_book[int(cmd_str.split()[1])]
while cmd != 'q':
print 'Books:'
for i in book_range:
print '\t%d: %s' % (i, ind_to_book[i])
print 'C... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_sheet(self, sheet_name_or_num):
""" Calling this method changes the sheet in anticipation for the next time you create an iterator. If you change the ... |
if isinstance(sheet_name_or_num, int):
self._sheet = self.__wb[self.__wb.sheetnames[sheet_name_or_num]]
elif isinstance(sheet_name_or_num, basestring):
self._sheet = self.__wb[sheet_name_or_num]
else:
reason = "Must enter either sheet name or sheet number."
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _os_install(self, package_file):
""" take in a dict return a string of docker build RUN directives one RUN per package type one package type per JSON key """ |
packages = " ".join(json.load(package_file.open()))
if packages:
for packager in self.pkg_install_cmds:
if packager in self.context.externalbasis:
installer = self.pkg_install_cmds[packager]
return f"RUN {installer} {packages}"
else... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def connect(self):
""" Create new asynchronous connection to the RabbitMQ instance. This will connect, declare exchange and bind itself to the configured q... |
if self.connected or self.is_connecting:
return
self._is_connecting = True
try:
logger.info("Connecting to RabbitMQ...")
self._transport, self._protocol = await aioamqp.connect(**self._connection_parameters)
logger.info("Getting channel...")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def consume_queue(self, subscriber: AbstractSubscriber) -> None: """ Subscribe to the queue consuming. :param subscriber: :return: """ |
queue_name = subscriber.name
topics = subscriber.requested_topics
if queue_name in self._known_queues:
raise exceptions.ConsumerError("Queue '%s' already being consumed" % queue_name)
await self._declare_queue(queue_name)
# TODO: There is a lot of room to improve... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def _bind_key_to_queue(self, routing_key: AnyStr, queue_name: AnyStr) -> None: """ Bind to queue with specified routing key. :param routing_key: Routing key... |
logger.info("Binding key='%s'", routing_key)
result = await self._channel.queue_bind(
exchange_name=self._exchange_name,
queue_name=queue_name,
routing_key=routing_key,
)
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:
async def _on_message(self, channel, body, envelope, properties) -> None: """ Fires up when message is received by this consumer. :param channel: Channel, through... |
subscribers = self._get_subscribers(envelope.routing_key)
if not subscribers:
logger.debug("No route for message with key '%s'", envelope.routing_key)
return
body = self._serializer.deserialize(body)
for subscriber in subscribers:
# Check later 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 parse_this(func, types, args=None, delimiter_chars=":"):
"""Create an ArgParser for the given function converting the command line arguments according to the... |
_LOG.debug("Creating parser for %s", func.__name__)
(func_args, dummy_1, dummy_2, defaults) = getargspec(func)
types, func_args = _check_types(func.__name__, types, func_args, defaults)
args_and_defaults = _get_args_and_defaults(func_args, defaults)
parser = _get_arg_parser(func, types, args_and_de... |
<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_sub_parsers(self, top_level_parser, methods_to_parse, class_name):
"""Add all the sub-parsers to the top_level_parser. Args: top_level_parser: the top l... |
description = "Accessible methods of {}".format(class_name)
sub_parsers = top_level_parser.add_subparsers(description=description,
dest="method")
# Holds the mapping between the name registered for the parser
# and the method real na... |
<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_class_parser(self, init_parser, methods_to_parse, cls):
"""Creates the complete argument parser for the decorated class. Args: init_parser: argument par... |
top_level_parents = [init_parser] if init_parser else []
description = self._description or cls.__doc__
top_level_parser = argparse.ArgumentParser(description=description,
parents=top_level_parents,
... |
<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_parser_call_method(self, parser_to_method):
"""Return the parser special method 'call' that handles sub-command calling. Args: parser_to_method: mapping... |
def inner_call(args=None, instance=None):
"""Allows to call the method invoked from the command line or
provided argument.
Args:
args: list of arguments to parse, defaults to command line
arguments
instance: an instance of 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 gp_lcltpt():
""" example plot to display linecolors, linetypes and pointtypes .. image:: pics/gp_lcltpt.png :width: 450 px """ |
inDir, outDir = getWorkDirs()
nSets = len(default_colors)
make_plot(
data = [
np.array([ [0,i,0,0,0], [1,i,0,0,0] ])
for i in xrange(nSets)
],
properties = [
'with linespoints lw 4 lc %s lt %d pt %d' % (col, i, i)
for i, col in enumerate(default_colors)
],
titles = [''... |
<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_analyses(prepared_analyses=None,log_dir=default_log_dir):
""" If all defaults are ok, this should be the only function needed to run the analyses. """ |
if prepared_analyses == None:
prepared_analyses = prepare_analyses()
state_collection = funtool.state_collection.StateCollection([],{})
for analysis in prepared_analyses:
state_collection= funtool.analysis.run_analysis(analysis, state_collection, log_dir)
return state_collection |
<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_analysis( named_analysis, prepared_analyses=None,log_dir=default_log_dir):
""" Runs just the named analysis. Otherwise just like run_analyses """ |
if prepared_analyses == None:
prepared_analyses = prepare_analyses()
state_collection = funtool.state_collection.StateCollection([],{})
for analysis in prepared_analyses:
if analysis.name == named_analysis:
state_collection= funtool.analysis.run_analysis(analysis, state_collecti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def poll(self):
""" Poll the job status. Returns the changes in this iteration.""" |
self.runner.module_name = 'async_status'
self.runner.module_args = "jid=%s" % self.jid
self.runner.pattern = "*"
self.runner.background = 0
self.runner.inventory.restrict_to(self.hosts_to_poll)
results = self.runner.run()
self.runner.inventory.lift_restriction()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait(self, seconds, poll_interval):
""" Wait a certain time for job completion, check status every poll_interval. """ |
# jid is None when all hosts were skipped
if self.jid is None:
return self.results
clock = seconds - poll_interval
while (clock >= 0 and not self.completed):
time.sleep(poll_interval)
poll_results = self.poll()
for (host, res) in poll_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 get_edit_form(obj, field_names, data=None, files=None):
""" Returns the in-line editing form for editing a single model field. """ |
# Map these form fields to their types defined in the forms app so
# we can make use of their custom widgets.
from yacms.forms import fields
widget_overrides = {
forms.DateField: fields.DATE,
forms.DateTimeField: fields.DATE_TIME,
forms.EmailField: fields.EMAIL,
}
clas... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _filter_disabled_regions(contents):
"""Filter regions that are contained in back-ticks.""" |
contents = list(contents)
in_backticks = False
contents_len = len(contents)
index = 0
while index < contents_len:
character = contents[index]
if character == "`":
# Check to see if we should toggle the in_backticks
# mode here by looking ahead for another 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 spellcheck(contents, technical_terms=None, spellcheck_cache=None):
"""Run spellcheck on the contents of a file. :technical_terms: is a path to a file contain... |
contents = spelling.filter_nonspellcheckable_tokens(contents)
contents = _filter_disabled_regions(contents)
lines = contents.splitlines(True)
user_words, valid_words = valid_words_dictionary.create(spellcheck_cache)
technical_words = technical_words_dictionary.create(technical_terms,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _report_spelling_error(error, file_path):
"""Report a spelling error.""" |
line = error.line_offset + 1
code = "file/spelling_error"
description = _SPELLCHECK_MESSAGES[error.error_type].format(error.word)
if error.suggestions is not None:
description = (description +
", perhaps you meant: " +
", ".join(error.suggestions))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(arguments=None):
# suppress(unused-function) """Entry point for the spellcheck linter.""" |
dictionary_path = os.path.abspath("DICTIONARY")
result = _parse_arguments(arguments)
num_errors = 0
for found_filename in result.files:
file_path = os.path.abspath(found_filename)
with io.open(file_path, "r+", encoding="utf-8") as found_file:
jobstamps_dependencies = [file_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def recover(self, state):
"recompute the actual value, then compare it against the truth"
newval = self.f.recover(state)
return self.errtype(self.value, newval) |
<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_version(value):
""" Determines if the provided version value compares with program version. `value` Version comparison string (e.g. ==1.0, <=1.0, >1.... |
# extract parts from value
import re
res = re.match(r'(<|<=|==|>|>=)(\d{1,2}\.\d{1,2}(\.\d{1,2})?)$',
str(value).strip())
if not res:
return False
operator, value, _ = res.groups()
# break into pieces
value = tuple(int(x) for x in str(value).split('.'))
if l... |
<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_all_publications(return_namedtuples=True):
""" Get list publications from all available source. Args: return_namedtuples (bool, default True):
Convert :... |
sources = [
ben_cz.get_publications,
grada_cz.get_publications,
cpress_cz.get_publications,
zonerpress_cz.get_publications,
]
# get data from all scrappers
publications = []
for source in sources:
publications.extend(
filters.filter_publications(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_cell(self, cell, coords, cell_mode=CellMode.cooked):
"""Parses a cell according to its cell.value_type.""" |
# pylint: disable=too-many-return-statements
if cell_mode == CellMode.cooked:
if cell.covered or cell.value_type is None or cell.value is None:
return None
vtype = cell.value_type
if vtype == 'string':
return cell.value
if vtype == 'float' or vtype == 'percentage' or ... |
<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_row(self, row_index):
"""Returns the row at row_index.""" |
if self._raw_rows is None:
self._raw_rows = list(self.raw_sheet.rows())
return self._raw_rows[row_index] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_config(sections, section_contents):
"""Create a config file from the provided sections and key value pairs. Args: sections (List[str]):
A list of sec... |
sections_length, section_contents_length = len(sections), len(section_contents)
if sections_length != section_contents_length:
raise ValueError("Mismatch between argument lengths.\n"
"len(sections) = {}\n"
"len(section_contents) = {}"
... |
<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_config(config, config_path=CONFIG_PATH):
"""Write the config to the output path. Creates the necessary directories if they aren't there. Args: config (... |
if not os.path.exists(config_path):
os.makedirs(os.path.dirname(config_path))
with open(config_path, 'w', encoding='utf-8') as f:
config.write(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 read_config(config_path=CONFIG_PATH):
"""Read the config information from the config file. Args: config_path (str):
Relative path to the email config file. ... |
if not os.path.isfile(config_path):
raise IOError("No config file found at %s" % config_path)
config_parser = configparser.ConfigParser()
config_parser.read(config_path)
config = _config_parser_to_defaultdict(config_parser)
return config |
<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_config(config):
"""Check that all sections of the config contain the keys that they should. Args: config (defaultdict):
A defaultdict. Raises: Configu... |
for section, expected_section_keys in SECTION_KEYS.items():
section_content = config.get(section)
if not section_content:
raise ConfigurationError("Config file badly formed! Section {} is missing."
.format(section))
elif not _section_is_healt... |
<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_config_diagnostics(config_path=CONFIG_PATH):
"""Run diagnostics on the configuration file. Args: config_path (str):
Path to the configuration file. Retu... |
config = read_config(config_path)
missing_sections = set()
malformed_entries = defaultdict(set)
for section, expected_section_keys in SECTION_KEYS.items():
section_content = config.get(section)
if not section_content:
missing_sections.add(section)
else:
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 get_attribute_from_config(config, section, attribute):
"""Try to parse an attribute of the config file. Args: config (defaultdict):
A defaultdict. section (... |
section = config.get(section)
if section:
option = section.get(attribute)
if option:
return option
raise ConfigurationError("Config file badly formed!\n"
"Failed to get attribute '{}' from section '{}'!"
.format(attribute... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def valid_config_exists(config_path=CONFIG_PATH):
"""Verify that a valid config file exists. Args: config_path (str):
Path to the config file. Returns: boolean:... |
if os.path.isfile(config_path):
try:
config = read_config(config_path)
check_config(config)
except (ConfigurationError, IOError):
return False
else:
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 config_to_string(config):
"""Nice output string for the config, which is a nested defaultdict. Args: config (defaultdict(defaultdict)):
The configuration in... |
output = []
for section, section_content in config.items():
output.append("[{}]".format(section))
for option, option_value in section_content.items():
output.append("{} = {}".format(option, option_value))
return "\n".join(output) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _config_parser_to_defaultdict(config_parser):
"""Convert a ConfigParser to a defaultdict. Args: config_parser (ConfigParser):
A ConfigParser. """ |
config = defaultdict(defaultdict)
for section, section_content in config_parser.items():
if section != 'DEFAULT':
for option, option_value in section_content.items():
config[section][option] = option_value
return config |
<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, *args, **kwargs):
'''
Launch IPython notebook server in background process.
Arguments and keyword arguments are passed on to `Popen` call.
By default, notebook server is launched using current working directory
as the notebook directory.
'''
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 open(self, filename=None):
'''
Open a browser tab with the notebook path specified relative to the
notebook directory.
If no filename is specified, open the root of the notebook server.
'''
if filename is None:
address = self.address + 'tree'
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 get_session(self, notebook_dir=None, no_browser=True, **kwargs):
'''
Return handle to IPython session for specified notebook directory.
If an IPython notebook session has already been launched for the
notebook directory, reuse it. Otherwise, launch a new IPython notebook
se... |
<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_blob(profile, sha):
"""Fetch a blob. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) t... |
resource = "/blobs/" + sha
data = api.get_request(profile, resource)
return prepare(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 create_blob(profile, content):
"""Create a blob. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this modu... |
resource = "/blobs"
payload = {"content": content}
data = api.post_request(profile, resource, payload)
return 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 copy(self):
""" Copy constructor for Sequence objects. """ |
return Sequence(self.name, self.sequenceData, self.start, self.end,
self.strand, self.remaining, self.meta_data,
self.mutableString) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def effective_len(self):
""" Get the length of the sequence if N's are disregarded. """ |
if self._effective_len is None:
self._effective_len = len([nuc for nuc in self.sequenceData
if nuc != "N" and nuc != "n"])
return self._effective_len |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def percentNuc(self, nuc):
""" return the percentage of the sequence which is equal to the passed nuc. :param nuc: the nucleotide to compute percentage compositi... |
count = reduce(lambda x, y: x + 1 if y == nuc else x, self.sequenceData, 0)
return count / float(len(self.sequenceData)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reverseComplement(self, isRNA=None):
""" Reverse complement this sequence in-place. :param isRNA: if True, treat this sequence as RNA. If False, treat it as ... |
isRNA_l = self.isRNA() if isRNA is None else isRNA
tmp = ""
for n in self.sequenceData:
if isRNA_l:
tmp += RNA_COMPLEMENTS[n]
else:
tmp += DNA_COMPLEMENTS[n]
self.sequenceData = tmp[::-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 maskRegion(self, region):
""" Replace nucleotides in this sequence in the regions given by Ns :param region: any object with .start and .end attributes. Co-o... |
if region.start < 0 or region.end < 0 or \
region.start > len(self) or region.end > len(self):
raise SequenceError("cannot mask region " + str(region.start) + " to " +
str(region.end) + " in " + self.name + ". " +
"Region specifies nucleotides not 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 maskRegions(self, regions, verbose=False):
""" Mask the given regions in this sequence with Ns. :param region: iterable of regions to mask. Each region can b... |
if verbose:
pind = ProgressIndicator(totalToDo=len(regions),
messagePrefix="completed",
messageSuffix="of masking regions in " +
self.name)
for region in regions:
self.maskRegion(region)
... |
<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, point=None):
""" Split this sequence into two halves and return them. The original sequence remains unmodified. :param point: defines the split p... |
if point is None:
point = len(self) / 2
r1 = Sequence(self.name + ".1", self.sequenceData[:point])
r2 = Sequence(self.name + ".2", self.sequenceData[point:])
return r1, r2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maskMatch(self, mask):
""" Determine whether this sequence matches the given mask. :param mask: string to match against. Ns in the mask are considered to mat... |
if len(mask) > len(self.sequenceData):
return False
lim = len(mask)
for i in range(0, lim):
if mask[i] == "N" or mask[i] == "n":
continue
if mask[i] != self.sequenceData[i]:
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 walk_recursive(f, data):
""" Recursively apply a function to all dicts in a nested dictionary :param f: Function to apply :param data: Dictionary (possibly n... |
results = {}
if isinstance(data, list):
return [walk_recursive(f, d) for d in data]
elif isinstance(data, dict):
results = funcy.walk_keys(f, data)
for k, v in data.iteritems():
if isinstance(v, dict):
results[f(k)] = walk_recursive(f, v)
eli... |
<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, config, strip_app_name=False, filter_by_app_name=False, key_normalisation_func=default_key_normalisation_func):
""" Add a dict of config data. Valu... |
config = walk_recursive(key_normalisation_func, OrderedDict(config))
if filter_by_app_name:
config = funcy.compact(funcy.select_keys(
lambda k: k.startswith(self._app_name), config))
if strip_app_name:
strip_app_name_regex = re.compile("^%s" % self._app... |
<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_param(self, name, value):
"""Set a GO-PCA Server parameter. Parameters name: str The parameter name. value: ? The parameter value. """ |
if name not in self.param_names:
raise ValueError('No GO-PCA Server parameter named "%s"!' %(param))
self.__params[name] = 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_params(self, params):
"""Sets multiple GO-PCA Server parameters using a dictionary. Parameters params: dict Dictionary containing the parameter values. R... |
for k,v in params.iteritems():
self.set_param(k,v) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset_params(self):
"""Reset all parameters to their default values.""" |
self.__params = dict([p, None] for p in self.param_names)
self.set_params(self.param_defaults) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cli, command, docker_id):
"""Creates waybill shims from a given command name and docker image""" |
content = waybill_template.format(command=command,
docker_id=docker_id)
waybill_dir = cli.get_waybill_dir()
waybill_filename = os.path.join(waybill_dir, command + '.waybill')
with open(waybill_filename, 'wb') as filehandle:
filehandl... |
<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(cli, yaml_filename):
"""Creates waybill shims from a given yaml file definiations""" |
"""Expected Definition:
- name: NAME
docker_id: IMAGE
- name: NAME
docker_id: IMAGE
"""
with open(yaml_filename, 'rb') as filehandle:
for waybill in yaml.load(filehandle.read()):
cli.create(waybill.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 shellinit(cli):
"""Implements the waybill shims in the active shell""" |
output = 'eval echo "Initializing Waybills"'
if which('docker') is None:
raise ValueError("Unable to find program 'docker'. Please make sure it is installed and setup properly")
for waybill in cli.get_waybills():
output += ' && source {0}'.format(waybill)
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 service_data(self):
""" Returns all introspected service data. If the data has been previously accessed, a memoized version of the data is returned. :returns... |
# Lean on the cache first.
if self._loaded_service_data is not None:
return self._loaded_service_data
# We don't have a cache. Build it.
self._loaded_service_data = self._introspect_service(
# We care about the ``botocore.session`` here, not 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 api_version(self):
""" Returns API version introspected from the service data. If the data has been previously accessed, a memoized version of the API versio... |
# Lean on the cache first.
if self._api_version is not None:
return self._api_version
# We don't have a cache. Build it.
self._api_version = self._introspect_api_version(
self.session.core_session,
self.service_name
)
return self._api... |
<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_for(self, service_name):
""" Builds a new, specialized ``Connection`` subclass for a given service. This will introspect a service, determine all t... |
# Construct a new ``ConnectionDetails`` (or similar class) for storing
# the relevant details about the service & its operations.
details = self.details_class(service_name, self.session)
# Make sure the new class gets that ``ConnectionDetails`` instance as a
# ``cls._details`` 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 getMoviesFromJSON(jsonURL):
"""Main function for this library Returns list of Movie classes from apple.com/trailers json URL such as: http://trailers.apple.c... |
response = urllib.request.urlopen(jsonURL)
jsonData = response.read().decode('utf-8')
objects = json.loads(jsonData)
# make it work for search urls
if jsonURL.find('quickfind') != -1:
objects = objects['results']
optionalInfo = ['actors','directors','rating','genre','studio','releasedat... |
<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_description(self):
"""Returns description text as provided by the studio""" |
if self._description:
return self._description
try:
trailerURL= "http://trailers.apple.com%s" % self.baseURL
response = urllib.request.urlopen(trailerURL)
Reader = codecs.getreader("utf-8")
responseReader = Reader(response)
traile... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unwrap_one_layer(r, L, n):
"""For a set of points in a 2 dimensional periodic system, extend the set of points to tile the points at a given period. Paramet... |
try:
L[0]
except (TypeError, IndexError):
L = np.ones([r.shape[1]]) * L
if n == 0:
return list(r)
rcu = []
for x, y in r:
for ix in range(-n, n + 1):
for iy in range(-n, n + 1):
if abs(ix) == n or abs(iy) == n:
rcu.appe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.