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 ------- di...
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('('): ...
<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 ke...
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', ...
<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 ...
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 colum...
<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 cl...
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: #...
<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 cont...
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.animat...
<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.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 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 (resul...
<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...
<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'") ret...
<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 ...
<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()...
<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') ...
<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 (na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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() ...
<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....
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 ...
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_fi...
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 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 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...
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, ...
<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...
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 ) logg...
<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 = 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 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...
<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...
<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....
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: ...
<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: ...
<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 s...
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...
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_da...
<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 fo...
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 = '...
<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, ...
<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, ...
<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: Specif...
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 ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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: Modul...
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( ...
<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...
# 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 ...
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(...
<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> PluginNa...
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)...
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|Erro...
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 j...
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: ...
<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:...
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.war...
<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) ...
<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 p...
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...
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 +...
<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 specificat...
# 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 ...
<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 na...
name = name.strip() for o in self.options: if o.short == name or o.long == name: return o raise InterfaceException("No such option: " + name)