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 from_string(self, value):
"""Convert string to enum value.""" |
if not isinstance(value, basestring):
raise ValueError('expected string value: ' + str(type(value)))
self.test_value(value)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self):
"""Convert enum data type definition into a dictionary. Overrides the super class method to add list of enumeration values. Returns ------- dict Json-like dictionary representation of the attribute data type """ |
obj = super(EnumType, self).to_dict()
obj['values'] = self.values
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_string(self, value):
"""Convert string to list.""" |
# Remove optional []
if value.startswith('[') and value.endswith(']'):
text = value[1:-1].strip()
else:
text = value.strip()
# Result is a list
result = []
# If value starts with '(' assume a list of pairs
if text.startswith('('):
tokens = text.split(',')
if len(tokens) % 2 != 0:
raise ValueError('not a valid list of pairs')
pos = 0
while (pos < len(tokens)):
val1 = float(tokens[pos].strip()[1:].strip())
val2 = float(tokens[pos + 1].strip()[:-1])
result.append((val1, val2))
pos += 2
else:
for val in text.split(','):
result.append(float(val))
# Ensure that the result contains at least two elements
if len(result) < 2:
raise ValueError('invalid number of elements in list: ' + str(len(result)))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_or_create_iexact(self, **kwargs):
""" Case insensitive title version of ``get_or_create``. Also allows for multiple existing results. """ |
lookup = dict(**kwargs)
try:
lookup["title__iexact"] = lookup.pop("title")
except KeyError:
pass
try:
return self.filter(**lookup)[0], False
except IndexError:
return self.create(**kwargs), 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 delete_unused(self, keyword_ids=None):
""" Removes all instances that are not assigned to any object. Limits processing to ``keyword_ids`` if given. """ |
if keyword_ids is None:
keywords = self.all()
else:
keywords = self.filter(id__in=keyword_ids)
keywords.filter(assignments__isnull=True).delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_lookup(apps, lookup_class=TemplateLookup):
""" Registering template directories of apps to Lookup. Lookups will be set up as dictionary, app name as key and lookup for this app will be it's value. Each lookups is correspond to each template directories of apps._lookups. The directory should be named 'templates', and put under app directory. """ |
global _lookups
_lookups = {}
for app in apps:
app_template_dir = os.path.join(os.path.dirname(app.__file__),
'templates')
app_lookup = lookup_class(directories=[app_template_dir],
output_encoding='utf-8',
encoding_errors='replace')
_lookups[app.__name__] = app_lookup |
<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_app_template(name):
""" Getter function of templates for each applications. Argument `name` will be interpreted as colon separated, the left value means application name, right value means a template name. get_app_template('blog:dashboarb.mako') It will return a template for dashboard page of `blog` application. """ |
app_name, template_name = name.split(':')
return get_lookups()[app_name].get_template(template_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 setup(db_class, simple_object_cls, primary_keys):
"""A simple API to configure the metadata""" |
table_name = simple_object_cls.__name__
column_names = simple_object_cls.FIELDS
metadata = MetaData()
table = Table(table_name, metadata,
*[Column(cname, _get_best_column_type(cname),
primary_key=cname in primary_keys)
for cname in column_names])
db_class.metadata = metadata
db_class.mapper_class = simple_object_cls
db_class.table = table
mapper(simple_object_cls, table) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sqlalchemy_escape(val, escape_char, special_chars):
"""Escape a string according for use in LIKE operator 'text\_table' """ |
if sys.version_info[:2] >= (3, 0):
assert isinstance(val, str)
else:
assert isinstance(val, basestring)
result = []
for c in val:
if c in special_chars + escape_char:
result.extend(escape_char + c)
else:
result.extend(c)
return ''.join(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _remove_unicode_keys(dictobj):
"""Convert keys from 'unicode' to 'str' type. workaround for <http://bugs.python.org/issue2646> """ |
if sys.version_info[:2] >= (3, 0): return dictobj
assert isinstance(dictobj, dict)
newdict = {}
for key, value in dictobj.items():
if type(key) is unicode:
key = key.encode('utf-8')
newdict[key] = value
return newdict |
<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(self):
"""Reset the database Drop all tables and recreate them """ |
self.metadata.drop_all(self.engine)
self.metadata.create_all(self.engine) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transaction(self, session=None):
"""Start a new transaction based on the passed session object. If session is not passed, then create one and make sure of closing it finally. """ |
local_session = None
if session is None:
local_session = session = self.create_scoped_session()
try:
yield session
finally:
# Since ``local_session`` was created locally, close it here itself
if local_session is not None:
# but wait!
# http://groups.google.com/group/sqlalchemy/browse_thread/thread/7c1eb642435adde7
# To workaround this issue with sqlalchemy, we can either:
# 1) pass the session object explicitly
# 2) do not close the session at all (bad idea - could lead to memory leaks)
#
# Till pypm implements atomic transations in client.installer,
# we retain this hack (i.e., we choose (2) for now)
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 create_from(cls, another, **kwargs):
"""Create from another object of different type. Another object must be from a derived class of SimpleObject (which contains FIELDS) """ |
reused_fields = {}
for field, value in another.get_fields():
if field in cls.FIELDS:
reused_fields[field] = value
reused_fields.update(kwargs)
return cls(**reused_fields) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def brightness(sequence_number, brightness):
"""Create a brightness message""" |
return MessageWriter().string("brightness").uint64(sequence_number).uint8(int(brightness*255)).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 mainswitch_state(sequence_number, state):
"""Create a mainswitch.state message""" |
return MessageWriter().string("mainswitch.state").uint64(sequence_number).bool(state).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 animation_add(sequence_number, animation_id, name):
"""Create a animation.add message""" |
return MessageWriter().string("animation.add").uint64(sequence_number).uint32(animation_id).string(name).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 scene_active(sequence_number, scene_id):
"""Create a scene.setactive message""" |
return MessageWriter().string("scene.setactive").uint64(sequence_number).uint32(scene_id).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 scene_add(sequence_number, scene_id, animation_id, name, color, velocity, config):
"""Create a scene.add message""" |
(red, green, blue) = (int(color[0]*255), int(color[1]*255), int(color[2]*255))
return MessageWriter().string("scene.add").uint64(sequence_number).uint32(scene_id).uint32(animation_id).string(name) \
.uint8_3(red, green, blue).uint32(int(velocity * 1000)).string(config).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 scene_remove(sequence_number, scene_id):
"""Create a scene.rm message""" |
return MessageWriter().string("scene.rm").uint64(sequence_number).uint32(scene_id).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 scene_name(sequence_number, scene_id, name):
"""Create a scene.name message""" |
return MessageWriter().string("scene.name").uint64(sequence_number).uint32(scene_id).string(name).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 scene_config(sequence_number, scene_id, config):
"""Create a scene.config message""" |
return MessageWriter().string("scene.config").uint64(sequence_number).uint32(scene_id).string(config).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 scene_color(sequence_number, scene_id, color):
"""Create a scene.color message""" |
return MessageWriter().string("scene.color").uint64(sequence_number).uint32(scene_id) \
.uint8_3(int(color[0]*255), int(color[1]*255), int(color[2]*255)).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 scene_velocity(sequence_number, scene_id, velocity):
"""Create a scene.velocity message""" |
return MessageWriter().string("scene.velocity").uint64(sequence_number).uint32(scene_id).uint32(int(velocity*1000)).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 uint8(self, val):
"""append a frame containing a uint8""" |
try:
self.msg += [pack("B", val)]
except struct.error:
raise ValueError("Expected uint32")
return 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 uint8_3(self, val1, val2, val3):
"""append a frame containing 3 uint8""" |
try:
self.msg += [pack("BBB", val1, val2, val3)]
except struct.error:
raise ValueError("Expected uint8")
return 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 uint32(self, val):
"""append a frame containing a uint32""" |
try:
self.msg += [pack("!I", val)]
except struct.error:
raise ValueError("Expected uint32")
return 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 uint64(self, val):
"""append a frame containing a uint64""" |
try:
self.msg += [pack("!Q", val)]
except struct.error:
raise ValueError("Expected uint64")
return 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 brightness(frames):
"""parse a brightness message""" |
reader = MessageReader(frames)
res = reader.string("command").uint32("brightness").assert_end().get()
if res.command != "brightness":
raise MessageParserError("Command is not 'brightness'")
return (res.brightness/1000,) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mainswitch_state(frames):
"""parse a mainswitch.state message""" |
reader = MessageReader(frames)
res = reader.string("command").bool("state").assert_end().get()
if res.command != "mainswitch.state":
raise MessageParserError("Command is not 'mainswitch.state'")
return (res.state,) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scene_add(frames):
"""parse a scene.add message""" |
reader = MessageReader(frames)
results = reader.string("command").uint32("animation_id").string("name").uint8_3("color").uint32("velocity").string("config").get()
if results.command != "scene.add":
raise MessageParserError("Command is not 'scene.add'")
return (results.animation_id, results.name, np.array([results.color[0]/255, results.color[1]/255, results.color[2]/255]),
results.velocity/1000, results.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 scene_color(frames):
"""parse a scene.color message""" |
# "scene.color" <scene_id> <color>
reader = MessageReader(frames)
results = reader.string("command").uint32("scene_id").uint8_3("color").assert_end().get()
if results.command != "scene.color":
raise MessageParserError("Command is not 'scene.color'")
return (results.scene_id, np.array([results.color[0]/255, results.color[1]/255, results.color[2]/255])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scene_config(frames):
"""parse a scene.config message""" |
# "scene.config" <scene_id> <config>
reader = MessageReader(frames)
results = reader.string("command").uint32("scene_id").string("config").assert_end().get()
if results.command != "scene.config":
raise MessageParserError("Command is not 'scene.config'")
return (results.scene_id, results.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 scene_name(frames):
"""parse a scene.name message""" |
# "scene.name" <scene_id> <config>
reader = MessageReader(frames)
results = reader.string("command").uint32("scene_id").string("name").assert_end().get()
if results.command != "scene.name":
raise MessageParserError("Command is not 'scene.name'")
return (results.scene_id, results.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 scene_remove(frames):
"""parse a scene.rm message""" |
# "scene.rm" <scene_id>
reader = MessageReader(frames)
results = reader.string("command").uint32("scene_id").assert_end().get()
if results.command != "scene.rm":
raise MessageParserError("Command is not 'scene.rm'")
return (results.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 scene_velocity(frames):
"""parse a scene.velocity message""" |
# "scene.velocity" <scene_id> <velocity>
reader = MessageReader(frames)
results = reader.string("command").uint32("scene_id").uint32("velocity").assert_end().get()
if results.command != "scene.velocity":
raise MessageParserError("Command is not 'scene.velocity'")
return (results.scene_id, results.velocity/1000) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def string(self, name):
"""parse a string frame""" |
self._assert_is_string(name)
frame = self._next_frame()
try:
val = frame.decode('utf-8')
self.results.__dict__[name] = val
except UnicodeError as err:
raise MessageParserError("Message contained invalid Unicode characters") \
from err
return 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 bool(self, name):
"""parse a boolean frame""" |
self._assert_is_string(name)
frame = self._next_frame()
if len(frame) != 1:
raise MessageParserError("Expected exacty 1 byte for boolean value")
val = frame != b"\x00"
self.results.__dict__[name] = val
return 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 uint8_3(self, name):
"""parse a tuple of 3 uint8 values""" |
self._assert_is_string(name)
frame = self._next_frame()
if len(frame) != 3:
raise MessageParserError("Expected exacty 3 byte for 3 unit8 values")
vals = unpack("BBB", frame)
self.results.__dict__[name] = vals
return 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 uint32(self, name):
"""parse a uint32 value""" |
self._assert_is_string(name)
frame = self._next_frame()
if len(frame) != 4:
raise MessageParserError("Expected exacty 4 byte for uint32 value")
(val,) = unpack("!I", frame)
self.results.__dict__[name] = val
return 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 activate(self, event):
"""Change the value.""" |
self._index += 1
if self._index >= len(self._values):
self._index = 0
self._selection = self._values[self._index]
self.ao2.speak(self._selection) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cached_read(self, kind):
"""Cache stats calls to prevent hammering the API""" |
if not kind in self.cache:
self.pull_stats(kind)
if self.epochnow() - self.cache[kind]['lastcall'] > self.cache_timeout:
self.pull_stats(kind)
return self.cache[kind]['lastvalue'] |
<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(self, key, name=None):
"""Return value for specific key""" |
if name is None:
self.nodename = self.local_name
self.nodeid = self.local_id
else:
self.logger.debug('Replacing nodename "{0}" with "{1}"'.format(self.nodename, name))
self.nodename = name
self.find_name()
return get_value(self.stats(), fix_key(key)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_circle(nodes):
""" Wrapper for recursive _detect_circle function """ |
# Verify nodes and traveled types
if not isinstance(nodes, dict):
raise TypeError('"nodes" must be a dictionary')
dependencies = set(nodes.keys())
traveled = []
heads = _detect_circle(nodes, dependencies, traveled)
return DependencyTree(heads) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _detect_circle(nodes=None, dependencies=None, traveled=None, path=None):
""" Recursively iterate over nodes checking if we've traveled to that node before. """ |
# Verify nodes and traveled types
if nodes is None:
nodes = {}
elif not isinstance(nodes, dict):
raise TypeError('"nodes" must be a dictionary')
if dependencies is None:
return
elif not isinstance(dependencies, set):
raise TypeError('"dependencies" must be a set')
if traveled is None:
traveled = []
elif not isinstance(traveled, list):
raise TypeError('"traveled" must be a list')
if path is None:
path = []
if not dependencies:
# We're at the end of a dependency path.
return []
# Recursively iterate over nodes,
# and gather dependency children nodes.
children = []
for name in dependencies:
# Path is used for circular dependency exceptions
# to display to the user the circular path.
new_path = list(path)
new_path.append(name)
# Check if we've traveled to this node before.
if name in traveled:
raise CircularDependencyException(new_path)
# Make recursive call
node_children = _detect_circle(nodes=nodes,
dependencies=nodes[name],
traveled=traveled + list(name),
path=new_path)
# Create node for this dependency with children.
node = DependencyNode(name)
for child in node_children:
child.parent = node
node.add_child(child)
children.append(node)
return children |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do(self, nodes):
""" Recursive method to instantiate services """ |
if not isinstance(nodes, dict):
raise TypeError('"nodes" must be a dictionary')
if not nodes:
# we're done!
return
starting_num_nodes = len(nodes)
newly_instantiated = set()
# Instantiate services with an empty dependency set
for (name, dependency_set) in six.iteritems(nodes):
if dependency_set:
# Skip non-empty dependency sets
continue
# Instantiate
config = self._config[name]
service = self._factory.create_from_dict(config)
self._factory.add_instantiated_service(name, service)
newly_instantiated.add(name)
# We ALWAYS should have instantiated a new service
# or we'll end up in an infinite loop.
if not newly_instantiated:
raise Exception('No newly instantiated services')
# Remove from Nodes
for name in newly_instantiated:
del nodes[name]
# Check if the number of nodes have changed
# to prevent infinite loops.
# We should ALWAYS have removed a node.
if starting_num_nodes == len(nodes):
raise Exception('No nodes removed!')
# Remove newly instantiated services from dependency sets
for (name, dependency_set) in six.iteritems(nodes):
nodes[name] = dependency_set.difference(newly_instantiated)
# Recursion is recursion is ...
self._do(nodes) |
<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_nodes(self, config):
""" Gathers dependency sets onto _nodes """ |
if not isinstance(config, dict):
raise TypeError('"config" must be a dictionary')
for (name, conf) in six.iteritems(config):
args = [] if 'args' not in conf else conf['args']
kwargs = {} if 'kwargs' not in conf else conf['kwargs']
dependencies = set()
arg_deps = self._get_dependencies_from_args(args)
kwarg_deps = self._get_dependencies_from_kwargs(kwargs)
dependencies.update(arg_deps)
dependencies.update(kwarg_deps)
self._nodes[name] = dependencies |
<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_dependencies_from_kwargs(self, args):
""" Parse keyed arguments """ |
if not isinstance(args, dict):
raise TypeError('"kwargs" must be a dictionary')
dependency_names = set()
for arg in args.values():
new_names = self._check_arg(arg)
dependency_names.update(new_names)
return dependency_names |
<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_regions(db_connection):
""" Gets a list of all regions. :return: A list of all regions. Results have regionID and regionName. :rtype: list """ |
if not hasattr(get_all_regions, '_results'):
sql = 'CALL get_all_regions();'
results = execute_sql(sql, db_connection)
get_all_regions._results = results
return get_all_regions._results |
<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_not_wh_regions(db_connection):
""" Gets a list of all regions that are not WH regions. :return: A list of all regions not including wormhole regions. Results have regionID and regionName. :rtype: list """ |
if not hasattr(get_all_not_wh_regions, '_results'):
sql = 'CALL get_all_not_wh_regions();'
results = execute_sql(sql, db_connection)
get_all_not_wh_regions._results = results
return get_all_not_wh_regions._results |
<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_regions_connected_to_region(db_connection, region_id):
""" Gets a list of all regions connected to the region ID passed in. :param region_id: Region ID to find all regions connected to. :type region_id: int :return: A list of all regions connected to the specified region ID. Results have regionID and regionName. :rtype: list """ |
sql = 'CALL get_all_regions_connected_to_region({});'.format(region_id)
results = execute_sql(sql, db_connection)
return results |
<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(cnf_file, uid, overwrite):
""" Creates configuration file and the directory where it should be stored and set correct permissions. Args: cnf_file (str):
Path to the configuration file. uid (int):
User ID - will be used for chown. overwrite (bool):
Overwrite the configuration with :attr:`CLEAN_CONFIG`. """ |
conf = None
# needed also on suse, because pyClamd module
if not os.path.exists(settings.DEB_CONF_PATH):
os.makedirs(settings.DEB_CONF_PATH, 0755)
os.chown(settings.DEB_CONF_PATH, uid, -1)
if not os.path.exists(cnf_file): # create new conf file
conf = CLEAN_CONFIG
elif overwrite: # ovewrite old conf file
backup_name = cnf_file + "_"
if not os.path.exists(backup_name):
shutil.copyfile(cnf_file, backup_name)
os.chown(backup_name, uid, -1)
conf = CLEAN_CONFIG
else: # switch variables in existing file
with open(cnf_file) as f:
conf = f.read()
# write the conf file
with open(cnf_file, "w") as f:
f.write(update_configuration(conf))
# permission check (uid)
os.chown(cnf_file, uid, -1)
os.chmod(cnf_file, 0644)
symlink = settings.DEB_CONF_PATH + settings.CONF_FILE
if not settings.is_deb_system() and not os.path.exists(symlink):
os.symlink(cnf_file, symlink)
os.chown(symlink, uid, -1)
os.chmod(symlink, 0644) |
<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_log(log_file, uid):
""" Create log file and set necessary permissions. Args: log_file (str):
Path to the log file. uid (int):
User ID - will be used for chown. """ |
if not os.path.exists(log_file): # create new log file
dir_name = os.path.dirname(log_file)
if not os.path.exists(dir_name):
os.makedirs(dir_name, 0755)
os.chown(dir_name, uid, -1)
with open(log_file, "w") as f:
f.write("")
os.chown(log_file, uid, -1)
os.chmod(log_file, 0640) |
<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(conf_file, overwrite, logger):
""" Create configuration and log file. Restart the daemon when configuration is done. Args: conf_file (str):
Path to the configuration file. overwrite (bool):
Overwrite the configuration file with `clean` config? """ |
uid = pwd.getpwnam(get_username()).pw_uid
# stop the daemon
logger.info("Stopping the daemon.")
sh.service(get_service_name(), "stop")
# create files
logger.info("Creating config file.")
create_config(
cnf_file=conf_file,
uid=uid,
overwrite=overwrite
)
logger.info("Creating log file.")
create_log(
log_file=REQUIRED_SETTINGS["LogFile"],
uid=uid
)
# start the daemon
logger.info("Starting the daemon..")
sh.service(get_service_name(), "start") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_debug_logging():
""" set up debug logging """ |
logger = logging.getLogger("xbahn")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter("%(name)s: %(message)s"))
logger.addHandler(ch) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shell(ctx):
""" open an engineer shell """ |
shell = code.InteractiveConsole({"engineer": getattr(ctx.parent, "widget", None)})
shell.interact("\n".join([
"Engineer connected to %s" % ctx.parent.params["host"],
"Dispatch available through the 'engineer' object"
])) |
<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, ctx):
""" establish xbahn connection and store on click context """ |
if hasattr(ctx,"conn") or "host" not in ctx.params:
return
ctx.conn = conn = connect(ctx.params["host"])
lnk = link.Link()
lnk.wire("main", receive=conn, send=conn)
ctx.client = api.Client(link=lnk)
ctx.widget = ClientWidget(ctx.client, "engineer") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_commands(self, ctx):
""" list all commands exposed to engineer """ |
self.connect(ctx)
if not hasattr(ctx, "widget"):
return super(Engineer, self).list_commands(ctx)
return ctx.widget.engineer_list_commands() + super(Engineer, self).list_commands(ctx) |
<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_command(self, ctx, name):
""" get click command from engineer exposed xbahn command specs """ |
# connect to xbahn
self.connect(ctx)
if not hasattr(ctx, "widget") or name in ["shell"]:
return super(Engineer, self).get_command(ctx, name)
if name == "--help":
return None
# get the command specs (description, arguments and options)
info = ctx.widget.engineer_info(name)
# make command from specs
return self.make_command(ctx, name, info) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_command(self, ctx, name, info):
""" make click sub-command from command info gotten from xbahn engineer """ |
@self.command()
@click.option("--debug/--no-debug", default=False, help="Show debug information")
@doc(info.get("description"))
def func(*args, **kwargs):
if "debug" in kwargs:
del kwargs["debug"]
fn = getattr(ctx.widget, name)
result = fn(*args, **kwargs)
click.echo("%s: %s> %s" % (ctx.params["host"],name,result))
ctx.conn.close()
ctx.info_name = "%s %s" % (ctx.info_name , ctx.params["host"])
for a in info.get("arguments",[]):
deco = click.argument(*a["args"], **a["kwargs"])
func = deco(func)
for o in info.get("options",[]):
deco = click.option(*o["args"], **o["kwargs"])
func = deco(func)
return func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getMe(self):
''' returns User Object '''
response_str = self._command('getMe')
if(not response_str):
return False
response = json.loads(response_str)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sendMessage(self,chat_id,text,parse_mode=None,disable_web=None,reply_msg_id=None,markup=None):
''' On failure returns False
On success returns Message Object '''
payload={'chat_id' : chat_id, 'text' : text, 'parse_mode': parse_mode , 'disable_web_page_preview' : disable_web , 'reply_to_message_id' : reply_msg_id}
if(markup):
payload['reply_markup']=json.dumps(markup)
response_str = self._command('sendMessage',payload,method='post')
return _validate_response_msg(response_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 if_callable_call_with_formatted_string(callback, formattable_string, *args):
"""If the callback is callable, format the string with the args and make a call. Otherwise, do nothing. Args: callback (function):
May or may not be callable. formattable_string (str):
A string with '{}'s inserted. *args: A variable amount of arguments for the string formatting. Must correspond to the amount of '{}'s in 'formattable_string'. Raises: ValueError """ |
try:
formatted_string = formattable_string.format(*args)
except IndexError:
raise ValueError("Mismatch metween amount of insertion points in the formattable string\n"
"and the amount of args given.")
if callable(callback):
callback(formatted_string) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def feeling_lucky(cls, obj):
"""Tries to convert given object to an UTC timestamp is ms, based on its type. """ |
if isinstance(obj, six.string_types):
return cls.from_str(obj)
elif isinstance(obj, six.integer_types) and obj <= MAX_POSIX_TIMESTAMP:
return cls.from_posix_timestamp(obj)
elif isinstance(obj, datetime):
return cls.from_datetime(obj)
else:
raise ValueError(
u"Don't know how to get timestamp from '{}'".format(obj)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fix_mispelled_day(cls, timestr):
"""fix mispelled day when written in english :return: `None` if the day was not modified, the new date otherwise """ |
day_extraction = cls.START_WITH_DAY_OF_WEEK.match(timestr)
if day_extraction is not None:
day = day_extraction.group(1).lower()
if len(day) == 3:
dataset = DAYS_ABBR
else:
dataset = DAYS
if day not in dataset:
days = list(dataset)
days.sort(key=lambda e: levenshtein(day, e))
return days[0] + day_extraction.group(2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_timezone(cls, timestr):
"""Completely remove timezone information, if any. :return: the new string if timezone was found, `None` otherwise """ |
if re.match(r".*[\-+]?\d{2}:\d{2}$", timestr):
return re.sub(
r"(.*)(\s[\+-]?\d\d:\d\d)$",
r"\1",
timestr
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fix_timezone_separator(cls, timestr):
"""Replace invalid timezone separator to prevent `dateutil.parser.parse` to raise. :return: the new string if invalid separators were found, `None` otherwise """ |
tz_sep = cls.TIMEZONE_SEPARATOR.match(timestr)
if tz_sep is not None:
return tz_sep.group(1) + tz_sep.group(2) + ':' + tz_sep.group(3)
return timestr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_str(cls, timestr, shaked=False):
"""Use `dateutil` module to parse the give string :param basestring timestr: string representing a date to parse :param bool shaked: whether the input parameter been already cleaned or not. """ |
orig = timestr
if not shaked:
timestr = cls.fix_timezone_separator(timestr)
try:
date = parser.parse(timestr)
except ValueError:
if not shaked:
shaked = False
for shaker in [
cls.fix_mispelled_day,
cls.remove_parenthesis_around_tz,
cls.remove_quotes_around_tz]:
new_timestr = shaker(timestr)
if new_timestr is not None:
timestr = new_timestr
shaked = True
if shaked:
try:
return cls.from_str(timestr, shaked=True)
except ValueError:
# raise ValueError below with proper message
pass
msg = u"Unknown string format: {!r}".format(orig)
raise ValueError(msg), None, sys.exc_info()[2]
else:
try:
return cls.from_datetime(date)
except ValueError:
new_str = cls.remove_timezone(orig)
if new_str is not None:
return cls.from_str(new_str)
else:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next_redirect(request, fallback, **get_kwargs):
""" Handle the "where should I go next?" part of comment views. The next value could be a the view modules for examples. Returns an ``HttpResponseRedirect``. """ |
next = request.POST.get('next')
if not is_safe_url(url=next, allowed_hosts=request.get_host()):
next = resolve_url(fallback)
if get_kwargs:
if '#' in next:
tmp = next.rsplit('#', 1)
next = tmp[0]
anchor = '#' + tmp[1]
else:
anchor = ''
joiner = ('?' in next) and '&' or '?'
next += joiner + urlencode(get_kwargs) + anchor
return HttpResponseRedirect(next) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self, password: str) -> bool: """ Checks the given password with the one stored in the database """ |
return (
pbkdf2_sha512.verify(password, self.password) or
pbkdf2_sha512.verify(password,
pbkdf2_sha512.encrypt(self.api_key))
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ |
try:
self.check_complex(complex)
except exceptions.RumetrComplexNotFound:
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 house_exists(self, complex: str, house: str) -> bool: """ Shortcut to check if house exists in our database. """ |
try:
self.check_house(complex, house)
except exceptions.RumetrHouseNotFound:
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 appt_exists(self, complex: str, house: str, appt: str) -> bool: """ Shortcut to check if appt exists in our database. """ |
try:
self.check_appt(complex, house, appt)
except exceptions.RumetrApptNotFound:
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 post(self, url: str, data: str, expected_status_code=201):
""" Do a POST request """ |
r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT)
self._check_response(r, expected_status_code)
return r.json() |
<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(self, url):
""" Do a GET request """ |
r = requests.get(self._format_url(url), headers=self.headers, timeout=TIMEOUT)
self._check_response(r, 200)
return r.json() |
<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_complex(self, **kwargs):
""" Add a new complex to the rumetr db """ |
self.check_developer()
self.post('developers/%s/complexes/' % self.developer, data=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 add_house(self, complex: str, **kwargs):
""" Add a new house to the rumetr db """ |
self.check_complex(complex)
self.post('developers/{developer}/complexes/{complex}/houses/'.format(developer=self.developer, complex=complex), data=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 add_appt(self, complex: str, house: str, price: str, square: str, **kwargs):
""" Add a new appartment to the rumetr db """ |
self.check_house(complex, house)
kwargs['price'] = self._format_decimal(price)
kwargs['square'] = self._format_decimal(square)
self.post('developers/{developer}/complexes/{complex}/houses/{house}/appts/'.format(
developer=self.developer,
complex=complex,
house=house,
), data=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 update_house(self, complex: str, id: str, **kwargs):
""" Update the existing house """ |
self.check_house(complex, id)
self.put('developers/{developer}/complexes/{complex}/houses/{id}'.format(
developer=self.developer,
complex=complex,
id=id,
), data=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 update_appt(self, complex: str, house: str, price: str, square: str, id: str, **kwargs):
""" Update existing appartment """ |
self.check_house(complex, house)
kwargs['price'] = self._format_decimal(price)
kwargs['square'] = self._format_decimal(square)
self.put('developers/{developer}/complexes/{complex}/houses/{house}/appts/{id}'.format(
developer=self.developer,
complex=complex,
house=house,
id=id,
price=self._format_decimal(price),
), data=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 inject(self, func, **kwargs):
"""Inject arguments from context into a callable. :param func: The callable to inject arguments into. :param \*\*kwargs: Specify values to override context items. """ |
args, varargs, keywords, defaults = self._get_argspec(func)
if defaults:
required_args = args[:-len(defaults)]
optional_args = args[len(required_args):]
else:
required_args = args
optional_args = []
values = [
kwargs[arg] if arg in kwargs else self[arg]
for arg in required_args
]
if defaults:
values.extend(
kwargs[arg] if arg in kwargs else self.get(arg, default)
for arg, default in zip(optional_args, defaults)
)
return func(*values) |
<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_date(val, zone='default'):
val = parse_isodate(val, None)
''' date has no ISO zone information '''
if not val.tzinfo:
val = timezone[zone].localize(val)
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_sanitizer(sanitizer):
""" Imports the sanitizer python module. :param sanitizer: Sanitizer python module file. :type sanitizer: unicode :return: Module. :rtype: object """ |
directory = os.path.dirname(sanitizer)
not directory in sys.path and sys.path.append(directory)
namespace = __import__(foundations.strings.get_splitext_basename(sanitizer))
if hasattr(namespace, "bleach"):
return namespace
else:
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' is not a valid sanitizer module file!".format(sanitizer)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pixels_from_coordinates(lat, lon, max_y, max_x):
""" Return the 2 matrix with lat and lon of each pixel. Keyword arguments: lat -- A latitude matrix lon -- A longitude matrix max_y -- The max vertical pixels amount of an orthorectified image. max_x -- The max horizontal pixels amount of an orthorectified image. """ |
# The degrees by pixel of the orthorectified image.
x_ratio, y_ratio = max_x/360., max_y/180.
x, y = np.zeros(lon.shape), np.zeros(lat.shape)
x = (lon + 180.) * x_ratio
y = (lat + 90.) * y_ratio
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 obtain_to(filename, compressed=True):
""" Return the linke turbidity projected to the lat lon matrix coordenates. Keyword arguments: filename -- the name of a netcdf file. """ |
files = glob.glob(filename)
root, _ = nc.open(filename)
lat, lon = nc.getvar(root, 'lat')[0,:], nc.getvar(root, 'lon')[0,:]
date_str = lambda f: ".".join((f.split('/')[-1]).split('.')[1:-2])
date = lambda f: datetime.strptime(date_str(f), "%Y.%j.%H%M%S")
linke = lambda f: transform_data(obtain(date(f), compressed), lat, lon)
linkes_projected = map(lambda f: (f, linke(f)), files)
nc.close(root)
return dict(linkes_projected) |
<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_targets(conn=None):
""" get_brain_targets function from Brain.Targets table. :return: <generator> yields dict objects """ |
targets = RBT
results = targets.run(conn)
for item in results:
yield item |
<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_targets_by_plugin(plugin_name, conn=None):
""" get_targets_by_plugin function from Brain.Targets table :return: <generator> yields dict objects """ |
targets = RBT
results = targets.filter({PLUGIN_NAME_KEY: plugin_name}).run(conn)
for item in results:
yield item |
<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_plugin_command(plugin_name, command_name, conn=None):
""" get_specific_command function queries a specific CommandName :param plugin_name: <str> PluginName :param command_name: <str> CommandName :return: <dict> """ |
commands = RPX.table(plugin_name).filter(
{COMMAND_NAME_KEY: command_name}).run(conn)
command = None
for command in commands:
continue # exhausting the cursor
return command |
<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_job_done(job_id, conn=None):
""" is_job_done function checks to if Brain.Jobs Status is 'Done' :param job_id: <str> id for the job :param conn: (optional)<connection> to run on :return: <dict> if job is done <false> if """ |
result = False
get_done = RBJ.get_all(DONE, index=STATUS_FIELD)
for item in get_done.filter({ID_FIELD: job_id}).run(conn):
result = item
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_job_complete(job_id, conn=None):
""" is_job_done function checks to if Brain.Jobs Status is Completed Completed is defined in statics as Done|Stopped|Error :param job_id: <str> id for the job :param conn: (optional)<connection> to run on :return: <dict> if job is done <false> if """ |
result = False
job = RBJ.get(job_id).run(conn)
if job and job.get(STATUS_FIELD) in COMPLETED:
result = job
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_output_content(job_id, max_size=1024, conn=None):
""" returns the content buffer for a job_id if that job output exists :param job_id: <str> id for the job :param max_size: <int> truncate after [max_size] bytes :param conn: (optional)<connection> to run on :return: <str> or <bytes> """ |
content = None
if RBO.index_list().contains(IDX_OUTPUT_JOB_ID).run(conn):
# NEW
check_status = RBO.get_all(job_id, index=IDX_OUTPUT_JOB_ID).run(conn)
else:
# OLD
check_status = RBO.filter({OUTPUTJOB_FIELD: {ID_FIELD: job_id}}).run(conn)
for status_item in check_status:
content = _truncate_output_content_if_required(status_item, max_size)
return content |
<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_job_by_id(job_id, conn=None):
"""returns the job with the given id :param job_id: <str> id of the job :param conn: <rethinkdb.DefaultConnection> :return: <dict> job with the given id """ |
job = RBJ.get(job_id).run(conn)
return job |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup(self):
""" Run setup tasks after initialization """ |
self._populate_local()
try:
self._populate_latest()
except Exception as e:
self.log.exception('Unable to retrieve latest %s version information', self.meta_name)
self._sort() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sort(self):
""" Sort versions by their version number """ |
self.versions = OrderedDict(sorted(self.versions.items(), key=lambda v: v[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 _populate_local(self):
""" Populate version data for local archives """ |
archives = glob(os.path.join(self.path, '*.zip'))
for archive in archives:
try:
version = self._read_zip(archive)
self.versions[version.vtuple] = self.meta_class(self, version, filepath=archive)
except BadZipfile as e:
self.log.warn('Unreadable zip archive in versions directory (%s): %s', e.message, archive)
if self.dev_path:
dev_archives = glob(os.path.join(self.dev_path, '*.zip'))
dev_versions = []
for dev_archive in dev_archives:
try:
dev_versions.append((self._read_zip(dev_archive), dev_archive))
except BadZipfile as e:
self.log.warn('Unreadable zip archive in versions directory (%s): %s', e.message, dev_archive)
if not dev_versions:
self.log.debug('No development releases found')
return
dev_version = sorted(dev_versions, key=lambda v: v[0].vtuple).pop()
self.dev_version = self.meta_class(self, dev_version[0], filepath=dev_version[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 download(self):
""" Download the latest IPS release @return: Download file path @rtype: str """ |
# Submit a download request and test the response
self.log.debug('Submitting request: %s', self.request)
response = self.session.request(*self.request, stream=True)
if response.status_code != 200:
self.log.error('Download request failed: %d', response.status_code)
raise HtmlParserError
# If we're re-downloading this version, delete the old file
if self.filepath and os.path.isfile(self.filepath):
self.log.info('Removing old version download')
os.remove(self.filepath)
# Make sure our versions data directory exists
if not os.path.isdir(self.basedir):
self.log.debug('Creating versions data directory')
os.makedirs(self.basedir, 0o755)
# Process our file download
vslug = self.version.vstring.replace(' ', '-')
self.filepath = self.filepath or os.path.join(self.basedir, '{v}.zip'.format(v=vslug))
with open(self.filepath, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
self.log.info('Version {v} successfully downloaded to {fn}'.format(v=self.version, fn=self.filepath)) |
<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_handlers_bound_to_instance(self, obj):
""" Remove all handlers bound to given object instance. This is useful to remove all handler methods that are part of an instance. :param object obj: Remove handlers that are methods of this instance """ |
for handler in self.handlers:
if handler.im_self == obj:
self -= handler |
<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, handler, priority=10):
""" Add handler. :param callable handler: callable handler :return callable: The handler you added is given back so this can be used as a decorator. """ |
self.container.add_handler(handler, priority=priority)
return handler |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def usage(self):
"""Print usage description for this program. Output is to standard out.""" |
print self.programName + " [options]",
if self.maxArgs == -1 or self.maxArgs - self.minArgs > 1:
print "[files..]"
elif self.maxArgs - self.minArgs == 1:
print "[file]"
print
print self.shortDescription
print "Options:"
for o in self.options:
print "\t", ("-" + o.short + ", --" + o.long).ljust(15), ":",
print o.description.replace("\t", "\\t").ljust(80) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parseCommandLine(self, line):
""" Parse the given command line and populate self with the values found. If the command line doesn't conform to the specification defined by this CLI object, this function prints a message to stdout indicating what was wrong, prints the program usage instructions and then exists the program :param line: list of tokens from the command line. Should have had program name removed - generally one would do this: sys.argv[1:] """ |
# separate arguments and options
try:
optlist, args = getopt.getopt(line, self._optlist(), self._longoptl())
except getopt.GetoptError, err:
print str(err)
self.usage()
sys.exit(2)
# parse options
for opt, arg in optlist:
opt = opt.lstrip("-")
found = False
for option in self.options:
if option.short == opt or option.long == opt:
option.value = option.type(arg)
option.set = True
found = True
if not found:
sys.stderr.write("unknown option: " + opt)
self.usage()
sys.exit(2)
# check for special options
specialOptions = False
for opt in self.options:
if opt.special and opt.isSet():
specialOptions = True
# parse arguments
if len(args) < self.minArgs and not specialOptions:
err = (str(len(args)) + " input arguments found, but required at " +
"least " + str(self.minArgs) + " arguments")
sys.stderr.write(err)
sys.stderr.write("\n\n")
self.usage()
sys.exit(2)
else:
self.args = args
# check for required options
for option in self.options:
if option.isRequired() and not option.isSet() and not specialOptions:
err = "required option \'" + str(option) + "\' is missing"
sys.stderr.write(err)
print "\n"
self.usage()
sys.exit(2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getOption(self, name):
""" Get the the Option object associated with the given name. :param name: the name of the option to retrieve; can be short or long name. :raise InterfaceException: if the named option doesn't exist. """ |
name = name.strip()
for o in self.options:
if o.short == name or o.long == name:
return o
raise InterfaceException("No such option: " + name) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.