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 _unwrap_to_layer(r, L, n=1):
"""For a set of points in a 2 dimensional periodic system, extend the set of points to tile the points up to to a given period. ... |
rcu = []
for i_n in range(n + 1):
rcu.extend(_unwrap_one_layer(r, L, i_n))
return rcu |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_medium(r, R, L, n=1, ax=None):
"""Draw circles representing circles in a two-dimensional periodic system. Circles may be tiled up to a number of periods... |
if ax is None:
ax = plt.gca()
for ru in _unwrap_to_layer(r, L, n):
c = plt.Circle(ru, radius=R, alpha=0.2)
ax.add_artist(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 upload(self, # pylint: disable=too-many-arguments path, name=None, resize=False, rotation=False, callback_url=None, callback_method=None, auto_align=False, ):... |
if name is None:
head, tail = ntpath.split(path)
name = tail or ntpath.basename(head)
url = "http://models.{}/model/".format(self.config.host)
payload = {"name": name,
"allowed_transformations": {"resize": resize,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, path):
"""downloads a model resource to the path""" |
service_get_resp = requests.get(self.location, cookies={"session": self.session})
payload = service_get_resp.json()
self._state = payload["status"]
if self._state != "processed":
raise errors.ResourceError("slice resource status is: {}".format(self._state))
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 to_dict(obj):
"""Generate a JSON serialization for the run state object. Returns ------- Json-like object Json serialization of model run state object """ |
# Have text description of state in Json object (for readability)
json_obj = {'type' : repr(obj)}
# Add state-specific elementsTYPE_MODEL_RUN
if obj.is_failed:
json_obj['errors'] = obj.errors
elif obj.is_success:
json_obj['modelOutput'] = obj.model_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 create_object(self, name, experiment_id, model_id, argument_defs, arguments=None, properties=None):
"""Create a model run object with the given list of argum... |
# Create a new object identifier.
identifier = str(uuid.uuid4()).replace('-','')
# Directory for successful model run resource files. Directories are
# simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create the directory if it doe... |
<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_dict(self, document):
"""Create model run object from JSON document retrieved from database. Parameters document : JSON Json document in database Return... |
# Get object identifier from Json document
identifier = str(document['_id'])
# Directories are simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create attachment descriptors
attachments = {}
for obj in document['attachments... |
<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_data_file_attachment(self, identifier, resource_id):
"""Get path to attached data file with given resource identifer. If no data file with given id exist... |
# Get model run to ensure that it exists. If not return None
model_run = self.get_object(identifier)
if model_run is None:
return None, None
# Ensure that attachment with given resource identifier exists.
if not resource_id in model_run.attachments:
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 to_dict(self, model_run):
"""Create a Json-like dictionary for a model run object. Extends the basic object with run state, arguments, and optional predictio... |
# Get the basic Json object from the super class
json_obj = super(DefaultModelRunManager, self).to_dict(model_run)
# Add run state
json_obj['state'] = ModelRunState.to_dict(model_run.state)
# Add run scheduling Timestamps
json_obj['schedule'] = model_run.schedule
... |
<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_state(self, identifier, state):
"""Update state of identified model run. Raises exception if state change results in invalid run life cycle. Parameter... |
# Get model run to ensure that it exists
model_run = self.get_object(identifier)
if model_run is None:
return None
# Set timestamp of state change. Raise exception if state change results
# in invalid life cycle
timestamp = str(datetime.datetime.utcnow().isof... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partial_update(self, request, *args, **kwargs):
""" We do not include the mixin as we want only PATCH and no PUT """ |
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=True, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
serializer.save()
if getattr(instance, '_prefetched_objects_cache', None): #pragma: no cover
instance = 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 connect(self):
''' connect to the remote host '''
vvv("ESTABLISH CONNECTION FOR USER: %s" % self.runner.remote_user, host=self.host)
self.common_args = []
extra_args = C.ANSIBLE_SSH_ARGS
if extra_args is not None:
self.common_args += shlex.split(extra_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 fetch_file(self, in_path, out_path):
''' fetch a file from remote to local '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
cmd = self._password_cmd()
if C.DEFAULT_SCP_IF_SSH:
cmd += ["scp"] + self.common_args
cmd += [self.host + ":" + in_path,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_form(self, request, form, change):
""" Super class ordering is important here - user must get saved first. """ |
OwnableAdmin.save_form(self, request, form, change)
return DisplayableAdmin.save_form(self, request, form, change) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_module_permission(self, request):
""" Hide from the admin menu unless explicitly set in ``ADMIN_MENU_ORDER``. """ |
for (name, items) in settings.ADMIN_MENU_ORDER:
if "blog.BlogCategory" in items:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def env(*vars, **kwargs):
"""Returns the first environment variable set. If none are non-empty, defaults to '' or keyword arg default. """ |
for v in vars:
value = os.environ.get(v)
if value:
return value
return kwargs.get('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 get_client_class(api_name, version, version_map):
"""Returns the client class for the requested API version. :param api_name: the name of the API, e.g. 'comp... |
try:
client_path = version_map[str(version)]
except (KeyError, ValueError):
msg = _("Invalid %(api_name)s client version '%(version)s'. must be "
"one of: %(map_keys)s")
msg = msg % {'api_name': api_name, 'version': version,
'map_keys': ', '.join(ver... |
<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_item_properties(item, fields, mixed_case_fields=(), formatters=None):
"""Return a tuple containing the item properties. :param item: a single item resour... |
if formatters is None:
formatters = {}
row = []
for field in fields:
if field in formatters:
row.append(formatters[field](item))
else:
if field in mixed_case_fields:
field_name = field.replace(' ', '_')
else:
fiel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str2dict(strdict, required_keys=None, optional_keys=None):
:param strdict: string in the form of key1=value1,key2=value2 :param required_keys: list of requir... |
result = {}
if strdict:
for kv in strdict.split(','):
key, sep, value = kv.partition('=')
if not sep:
msg = _("invalid key-value '%s', expected format: key=value")
raise argparse.ArgumentTypeError(msg % kv)
result[key] = value
vali... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def loads(cls, data):
'''Create a feature collection from a CBOR byte string.'''
rep = cbor.loads(data)
if not isinstance(rep, Sequence):
raise SerializationError('expected a CBOR list')
if len(rep) != 2:
raise SerializationError('expected a CBOR list of 2 items')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dumps(self):
'''Create a CBOR byte string from a feature collection.'''
metadata = {'v': 'fc01'}
if self.read_only:
metadata['ro'] = 1
rep = [metadata, self.to_dict()]
return cbor.dumps(rep) |
<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_dict(cls, data, read_only=False):
'''Recreate a feature collection from a dictionary.
The dictionary is of the format dumped by :meth:`to_dict`.
Additional information, such as whether the feature collection
should be read-only, is not included in this dictionary, and
i... |
<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):
'''Dump a feature collection's features to a dictionary.
This does not include additional data, such as whether
or not the collection is read-only. The returned dictionary
is suitable for serialization into JSON, CBOR, or similar
data formats.
'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def merge_with(self, other, multiset_op, other_op=None):
'''Merge this feature collection with another.
Merges two feature collections using the given ``multiset_op``
on each corresponding multiset and returns a new
:class:`FeatureCollection`. The contents of the two original
fe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def total(self):
'''
Returns sum of all counts in all features that are multisets.
'''
feats = imap(lambda name: self[name], self._counters())
return sum(chain(*map(lambda mset: map(abs, mset.values()), feats))) |
<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, name, obj):
'''Register a new feature serializer.
The feature type should be one of the fixed set of feature
representations, and `name` should be one of ``StringCounter``,
``SparseVector``, or ``DenseVector``. `obj` is a describing
object with three fields: `cons... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instance_contains(container, item):
"""Search into instance attributes, properties and return values of no-args methods.""" |
return item in (member for _, member in inspect.getmembers(container)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contains(container, item):
"""Extends ``operator.contains`` by trying very hard to find ``item`` inside container.""" |
# equality counts as containment and is usually non destructive
if container == item:
return True
# testing mapping containment is usually non destructive
if isinstance(container, abc.Mapping) and mapping_contains(container, item):
return True
# standard containment except specia... |
<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_brightness(self, brightness):
|
brightness = min([1.0, max([brightness, 0.0])]) # enforces range 0 ... 1
self.state.brightness = brightness
self._repeat_last_frame()
sequence_number = self.zmq_publisher.publish_brightness(brightness)
logging.debug("Set brightness to {brightPercent:05.1f}%".format(brightPercent... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_animation(self, animation_class):
"""Add a new animation""" |
self.state.animationClasses.append(animation_class)
return len(self.state.animationClasses) - 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 add_scene(self, animation_id, name, color, velocity, config):
"""Add a new scene, returns Scene ID""" |
# check arguments
if animation_id < 0 or animation_id >= len(self.state.animationClasses):
err_msg = "Requested to register scene with invalid Animation ID. Out of range."
logging.info(err_msg)
return(False, 0, err_msg)
if self.state.animationClasses[animatio... |
<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_scene(self, scene_id):
"""remove a scene by Scene ID""" |
if self.state.activeSceneId == scene_id:
err_msg = "Requested to delete scene {sceneNum}, which is currently active. Cannot delete active scene.".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
try:
del self.state.scenes[scene_id... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_scene_name(self, scene_id, name):
"""rename a scene by scene ID""" |
if not scene_id in self.state.scenes: # does that scene_id exist?
err_msg = "Requested to rename scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
self.state.scenes[scene_id] = self.state.scenes[scene_id... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_scene_active(self, scene_id):
"""sets the active scene by scene ID""" |
if self.state.activeSceneId != scene_id: # do nothing if scene has not changed
self._deactivate_scene()
sequence_number = self.zmq_publisher.publish_active_scene(scene_id)
self.state.activeSceneId = scene_id
if self.state.mainswitch is True: # activate scene only... |
<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_mainswitch_state(self, state):
"""Turns output on or off. Also turns hardware on ir off""" |
if self.state.mainswitch == state:
err_msg = "MainSwitch unchanged, already is {sState}".format(sState="On" if state else "Off") # fo obar lorem ipsum
logging.debug(err_msg) # fo obar lorem ipsum
return (False, 0, err_msg) # because nothing changed
self.state.mainswi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self):
"""Execute Main Loop""" |
try:
logging.debug("Entering IOLoop")
self.loop.start()
logging.debug("Leaving IOLoop")
except KeyboardInterrupt:
logging.debug("Leaving IOLoop by KeyboardInterrupt")
finally:
self.hw_communication.disconnect() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish_brightness(self, brightness):
"""publish changed brightness""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.brightness(self.sequence_number, brightness))
return self.sequence_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 publish_mainswitch_state(self, state):
"""publish changed mainswitch state""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.mainswitch_state(self.sequence_number, state))
return self.sequence_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 publish_active_scene(self, scene_id):
"""publish changed active scene""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_active(self.sequence_number, scene_id))
return self.sequence_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 publish_scene_add(self, scene_id, animation_id, name, color, velocity, config):
"""publish added scene""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_add(self.sequence_number, scene_id, animation_id, name, color, velocity, config))
return self.sequence_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 publish_scene_remove(self, scene_id):
"""publish the removal of a scene""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_remove(self.sequence_number, scene_id))
return self.sequence_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 publish_scene_name(self, scene_id, name):
"""publish a changed scene name""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_name(self.sequence_number, scene_id, name))
return self.sequence_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 publish_scene_config(self, scene_id, config):
"""publish a changed scene configuration""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_config(self.sequence_number, scene_id, config))
return self.sequence_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 publish_scene_color(self, scene_id, color):
"""publish a changed scene color""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_color(self.sequence_number, scene_id, color))
return self.sequence_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 publish_scene_velocity(self, scene_id, velocity):
"""publish a changed scene velovity""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_velocity(self.sequence_number, scene_id, velocity))
return self.sequence_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 handle_snapshot(self, msg):
"""Handles a snapshot request""" |
logging.debug("Sending state snapshot request")
identity = msg[0]
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.mainswitch_state(self.sequence_number, self.app.state.mainswitch))
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.brightness(self.sequence_numbe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_collect(self, msg):
"""handle an incoming message""" |
(success, sequence_number, comment) = self._handle_collect(msg)
self.collector.send_multipart(msgs.MessageWriter().bool(success).uint64(sequence_number).string(comment).get()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_uvloop_if_possible(f, *args, **kwargs):
""" Simple decorator to provide optional uvloop usage""" |
try:
import uvloop
import asyncio
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
print('uvloop will be used')
except ImportError:
print('uvloop unavailable')
return f(*args, **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 initialize():
""" Initializes the global NST instance with the current NST and begins tracking """ |
NST.running = True
pg = Page("http://www.neopets.com/")
curtime = pg.find("td", {'id': 'nst'}).text
NST.curTime = datetime.datetime.strptime(curtime.replace(" NST", ""), "%I:%M:%S %p") + datetime.timedelta(0,2)
NST.inst = NST()
NST.daemon = True # Ensur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _attach_to_model(self, model):
""" Check that the model can handle dynamic fields """ |
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(Dyna... |
<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(self):
""" If a dynamic version, delete it the standard way and remove it from the inventory, else delete all dynamic versions. """ |
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part) |
<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_dynamic_versions(self):
""" Call the `delete` method of all dynamic versions of the current field found in the inventory then clean the inventory. ""... |
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_pa... |
<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_name_for(self, dynamic_part):
""" Compute the name of the variation of the current dynamic field based on the given dynamic part. Use the "format" attrib... |
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_for(self, dynamic_part):
""" Return a variation of the current dynamic field based on the given dynamic part. Use the "format" attribute to create the fi... |
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(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 threadsafe_generator(generator_func):
"""A decorator that takes a generator function and makes it thread-safe. """ |
def decoration(*args, **keyword_args):
"""A thread-safe decoration for a generator function."""
return ThreadSafeIter(generator_func(*args, **keyword_args))
return decoration |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lazy_property(function):
"""Cache the first return value of a function for all subsequent calls. This decorator is usefull for argument-less functions that b... |
cached_val = []
def _wrapper(*args):
try:
return cached_val[0]
except IndexError:
ret_val = function(*args)
cached_val.append(ret_val)
return ret_val
return _wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cat(self, numlines=None):
"""Return a list of lines output by this service.""" |
if len(self.titles) == 1:
lines = self.lines()
if numlines is not None:
lines = lines[len(lines)-numlines:]
log("\n".join(lines))
else:
lines = [self._printtuple(line[0], line[1]) for line in self.lines()]
if numlines is not No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _match_service(self, line_with_color):
"""Return line if line matches this service's name, return None otherwise.""" |
line = re.compile("(\x1b\[\d+m)+").sub("", line_with_color) # Strip color codes
regexp = re.compile(r"^\[(.*?)\]\s(.*?)$")
if regexp.match(line):
title = regexp.match(line).group(1).strip()
if title in self.titles:
return (title, regexp.match(line... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json(self):
"""Return a list of JSON objects output by this service.""" |
lines = []
for line in self.lines():
try:
if len(line) == 1:
lines.append(json.loads(line, strict=False))
else:
lines.append(json.loads(line[1], strict=False))
except ValueError:
pass
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore_dict_kv(a_dict, key, copy_func=copy.deepcopy):
"""Backup an object in a with context and restore it when leaving the scope. :param a_dict: associativ... |
exists = False
if key in a_dict:
backup = copy_func(a_dict[key])
exists = True
try:
yield
finally:
if exists:
a_dict[key] = backup
else:
a_dict.pop(key, 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 popen(*args, **kwargs):
"""Run a process in background in a `with` context. Parameters given to this function are passed to `subprocess.Popen`. Process is ki... |
process = subprocess.Popen(*args, **kwargs)
try:
yield process.pid
finally:
os.kill(process.pid, signal.SIGTERM)
os.waitpid(process.pid, 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 coerce(self, value):
""" Takes one or two values in the domain and returns a LinearOrderedCell with the same domain """ |
if isinstance(value, LinearOrderedCell) and (self.domain == value.domain or \
list_diff(self.domain, value.domain) == []):
# is LinearOrderedCell with same domain
return value
elif value in self.domain:
return LinearOrderedCell(self.domain, value, 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 coerce(value):
""" Turns a value into a list """ |
if isinstance(value, ListCell):
return value
elif isinstance(value, (list)):
return ListCell(value)
else:
return ListCell([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 append(self, el):
""" Idiosynractic method for adding an element to a list """ |
if self.value is None:
self.value = [el]
else:
self.value.append(el) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(self, other):
""" Merges two prefixes """ |
other = PrefixCell.coerce(other)
if self.is_equal(other):
# pick among dependencies
return self
elif other.is_entailed_by(self):
return self
elif self.is_entailed_by(other):
self.value = other.value
elif self.is_contradictory(other... |
<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_template(self, context, **kwargs):
""" Returns the template to be used for the current context and arguments. """ |
if 'template' in kwargs['params']:
self.template = kwargs['params']['template']
return super(GoscaleTemplateInclusionTag, self).get_template(context, **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 admin_keywords_submit(request):
""" Adds any new given keywords from the custom keywords field in the admin, and returns their IDs for use when saving a mode... |
keyword_ids, titles = [], []
remove = punctuation.replace("-", "") # Strip punctuation, allow dashes.
for title in request.POST.get("text_keywords", "").split(","):
title = "".join([c for c in title if c not in remove]).strip()
if title:
kw, created = Keyword.objects.get_or_cre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comment(request, template="generic/comments.html", extra_context=None):
""" Handle a ``ThreadedCommentForm`` submission and redirect back to its related obje... |
response = initial_validation(request, "comment")
if isinstance(response, HttpResponse):
return response
obj, post_data = response
form_class = import_dotted_path(settings.COMMENT_FORM_CLASS)
form = form_class(request, obj, post_data)
if form.is_valid():
url = obj.get_absolute_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 rating(request):
""" Handle a ``RatingForm`` submission and redirect back to its related object. """ |
response = initial_validation(request, "rating")
if isinstance(response, HttpResponse):
return response
obj, post_data = response
url = add_cache_bypass(obj.get_absolute_url().split("#")[0])
response = redirect(url + "#rating-%s" % obj.id)
rating_form = RatingForm(request, obj, post_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 add(self, obj, metadata=None, update=False):
""" Add an existing CDSTAR object to the catalog. :param obj: A pycdstar.resource.Object instance """ |
if (obj not in self) or update:
self[obj.id] = Object.fromdict(
obj.id,
dict(
metadata=obj.metadata.read() if metadata is None else metadata,
bitstreams=[bs._properties for bs in obj.bitstreams]))
time.sleep(0.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 delete(self, obj):
""" Delete an object in CDSTAR and remove it from the catalog. :param obj: An object ID or an Object instance. """ |
obj = self.api.get_object(getattr(obj, 'id', obj))
obj.delete()
self.remove(obj.id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, path, metadata, filter_=filter_hidden, object_class=None):
""" Create objects in CDSTAR and register them in the catalog. Note that we guess the... |
path = Path(path)
if path.is_file():
fnames = [path]
elif path.is_dir():
fnames = list(walk(path, mode='files'))
else:
raise ValueError('path must be a file or directory') # pragma: no cover
for fname in fnames:
if not filter_ 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 csep_close(ra, rb):
"""Return the closest separation vector between each point in one set, and every point in a second set. Parameters ra, rb: float array-li... |
seps = csep(ra, rb)
seps_sq = np.sum(np.square(seps), axis=-1)
i_close = np.argmin(seps_sq, axis=-1)
i_all = list(range(len(seps)))
sep = seps[i_all, i_close]
sep_sq = seps_sq[i_all, i_close]
return sep, sep_sq |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def csep_periodic(ra, rb, L):
"""Return separation vectors between each pair of the two sets of points. Parameters ra, rb: float array-like, shape (n, d) and (m,... |
seps = ra[:, np.newaxis, :] - rb[np.newaxis, :, :]
for i_dim in range(ra.shape[1]):
seps_dim = seps[:, :, i_dim]
seps_dim[seps_dim > L[i_dim] / 2.0] -= L[i_dim]
seps_dim[seps_dim < -L[i_dim] / 2.0] += L[i_dim]
return seps |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def csep_periodic_close(ra, rb, L):
"""Return the closest separation vector between each point in one set, and every point in a second set, in periodic space. Pa... |
seps = csep_periodic(ra, rb, L)
seps_sq = np.sum(np.square(seps), axis=-1)
i_close = np.argmin(seps_sq, axis=-1)
i_all = list(range(len(seps)))
sep = seps[i_all, i_close]
sep_sq = seps_sq[i_all, i_close]
return sep, sep_sq |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cdist_sq_periodic(ra, rb, L):
"""Return the squared distance between each point in on set, and every point in a second set, in periodic space. Parameters ra,... |
return np.sum(np.square(csep_periodic(ra, rb, L)), axis=-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 pdist_sq_periodic(r, L):
"""Return the squared distance between all combinations of a set of points, in periodic space. Parameters r: shape (n, d) for n poin... |
d = csep_periodic(r, r, L)
d[np.identity(len(r), dtype=np.bool)] = np.inf
d_sq = np.sum(np.square(d), axis=-1)
return d_sq |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def angular_distance(n1, n2):
"""Return the angular separation between two 3 dimensional vectors. Parameters n1, n2: array-like, shape (3,) Coordinates of two ve... |
return np.arctan2(vector.vector_mag(np.cross(n1, n2)), np.dot(n1, n2)) |
<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_namedtuple(cls, field_mappings, name="Record"):
"""Gets a namedtuple class that matches the destination_names in the list of field_mappings.""" |
return namedtuple(name, [fm.destination_name for fm in field_mappings]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transfer(cls, field_mappings, source, destination_factory):
"""Convert a record to a dictionary via field_mappings, and pass that to destination_factory.""" |
data = dict()
for index, field_mapping in enumerate(field_mappings):
try:
data[field_mapping.destination_name] = field_mapping.get_value(source)
except Exception as ex:
raise Exception(
"Error with mapping #{0} '{1}'->'{2}': {3}".format(
index,
fiel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transfer_all(cls, field_mappings, sources, destination_factory=None):
"""Calls cls.transfer on all records in sources.""" |
for index, source in enumerate(sources):
try:
yield cls.transfer(field_mappings, source, destination_factory or (lambda x: x))
except Exception as ex:
raise Exception("Error with source #{0}: {1}".format(index, ex)) from ex |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_dict(lhs, rhs):
""" Merge content of a dict in another :param: dict: lhs dict where is merged the second one :param: dict: rhs dict whose content is me... |
assert isinstance(lhs, dict)
assert isinstance(rhs, dict)
for k, v in rhs.iteritems():
if k not in lhs:
lhs[k] = v
else:
lhs[k] = merge_dict(lhs[k], v)
return lhs |
<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(*streams):
""" Build voluptuous.Schema function parameters from a streams of YAMLs """ |
return from_dict(merge_dicts(*map(
lambda f: yaml.load(f, Loader=Loader),
list(streams)
))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_config(raise_=True):
""" Verifies that all configuration values have a valid setting """ |
ELIBConfig.check()
known_paths = set()
duplicate_values = set()
missing_values = set()
for config_value in ConfigValue.config_values:
if config_value.path not in known_paths:
known_paths.add(config_value.path)
else:
duplicate_values.add(config_value.name)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groupby(iterable, key=None):
""" Group items from iterable by key and return a dictionary where values are the lists of items from the iterable having the sa... |
groups = {}
for item in iterable:
if key is None:
key_value = item
else:
key_value = key(item)
groups.setdefault(key_value, []).append(item)
return groups |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enter(clsQname):
""" Delegate a rule to another class which instantiates a Klein app This also memoizes the resource instance on the handler function itself ... |
def wrapper(routeHandler):
@functools.wraps(routeHandler)
def inner(self, request, *a, **kw):
if getattr(inner, '_subKlein', None) is None:
cls = namedAny(clsQname)
inner._subKlein = cls().app.resource()
return routeHandler(self, request, inne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def openAPIDoc(**kwargs):
""" Update a function's docstring to include the OpenAPI Yaml generated by running the openAPIGraph object """ |
s = yaml.dump(kwargs, default_flow_style=False)
def deco(routeHandler):
# Wrap routeHandler, retaining name and __doc__, then edit __doc__.
# The only reason we need to do this is so we can be certain
# that __doc__ will be modifiable. partial() objects have
# a modifiable __do... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_app(application):
""" Associates the error handler """ |
for code in werkzeug.exceptions.default_exceptions:
application.register_error_handler(code, handle_http_exception) |
<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_palettes(stream):
''' Need to configure palettes manually, since we are checking stderr. '''
chosen = choose_palette(stream=stream)
palettes = get_available_palettes(chosen)
fg = ForegroundPalette(palettes=palettes)
fx = EffectsPalette(palettes=palettes)
return fg, fx, chosen |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def configure(self, **kwargs):
''' Convenience function to set a number of parameters on this logger
and associated handlers and formatters.
'''
for kwarg in kwargs:
value = kwargs[kwarg]
if kwarg == 'level':
self.set_level(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 log_config(self):
''' Log the current logging configuration. '''
level = self.level
debug = self.debug
debug('Logging config:')
debug('/ name: {}, id: {}', self.name, id(self))
debug(' .level: %s (%s)', level_map_int[level], level)
debug(' .default_level: %s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_valid_timestamp(date, unit='millis'):
""" Checks that a number that represents a date as milliseconds is correct. """ |
assert isinstance(date, int), "Input is not instance of int"
if unit is 'millis':
return is_positive(date) and len(str(date)) == 13
elif unit is 'seconds':
return is_positive(date) and len(str(date)) == 10
else:
raise ValueError('Unknown unit "%s"' % unit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debug(self, msg=None, *args, **kwargs):
"""Write log at DEBUG level. Same arguments as Python's built-in Logger. """ |
return self._log(logging.DEBUG, msg, args, 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 info(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at INFO level.""" |
return self._log(logging.INFO, msg, args, 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 exception(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at ERROR level with exc_info set. https://github.com/python/cpython/blob/2.7/Lib/logging/... |
kwargs['exc_info'] = 1
return self._log(logging.ERROR, msg, args, 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 log(self, level, msg=None, *args, **kwargs):
"""Writes log out at any arbitray level.""" |
return self._log(level, msg, args, 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 _log(self, level, msg, args, kwargs):
"""Throttled log output.""" |
with self._tb_lock:
if self._tb is None:
throttled = 0
should_log = True
else:
throttled = self._tb.throttle_count
should_log = self._tb.check_and_consume()
if should_log:
if throttled > 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 timestamp_to_local_time(timestamp, timezone_name):
"""Convert epoch timestamp to a localized Delorean datetime object. Arguments --------- timestamp : int Th... |
# first convert timestamp to UTC
utc_time = datetime.utcfromtimestamp(float(timestamp))
delo = Delorean(utc_time, timezone='UTC')
# shift d according to input timezone
localized_d = delo.shift(timezone_name)
return localized_d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timestamp_to_local_time_str( timestamp, timezone_name, fmt="yyyy-MM-dd HH:mm:ss"):
"""Convert epoch timestamp to a localized datetime string. Arguments -----... |
localized_d = timestamp_to_local_time(timestamp, timezone_name)
localized_datetime_str = localized_d.format_datetime(fmt)
return localized_datetime_str |
<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_timestamp(timezone_name, year, month, day, hour=0, minute=0):
"""Epoch timestamp from timezone, year, month, day, hour and minute.""" |
tz = pytz.timezone(timezone_name)
tz_datetime = tz.localize(datetime(year, month, day, hour, minute))
timestamp = calendar.timegm(tz_datetime.utctimetuple())
return timestamp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.