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 _getconf(self, rscpath, logger=None, conf=None): """Get specific conf from one driver path. :param str rscpath: resource path. :param Logger logger: logger t...
result = None resource = self.pathresource(rscpath=rscpath, logger=logger) if resource is not None: for cname in self._cnames(resource=resource): category = Category(name=cname) if result is None: result = Configuration() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, delete_zip_import=True, *args, **kwargs): """ If a zip file is uploaded, extract any images from it and add them to the gallery, before removing t...
super(BaseGallery, self).save(*args, **kwargs) if self.zip_import: zip_file = ZipFile(self.zip_import) for name in zip_file.namelist(): data = zip_file.read(name) try: from PIL import Image image = Image.ope...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def seconds_to_DHMS(seconds, as_str=True): """converts seconds to Days, Hours, Minutes, Seconds :param int seconds: number of seconds :param bool as_string: to r...
d = DotDot() d.days = int(seconds // (3600 * 24)) d.hours = int((seconds // 3600) % 24) d.minutes = int((seconds // 60) % 60) d.seconds = int(seconds % 60) return FMT_DHMS_DICT.format(**d) if as_str else d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def relations_dict(rel_lst): """constructs a relation's dictionary from a list that describes amphidromus relations between objects :param list rel_lst: a relati...
dc = {} for c in rel_lst: for i in c: for k in c: dc.setdefault(i, []) dc[i].append(k) do = {} for k in list(dc.keys()): if dc[k]: vl = list(set(dc[k])) # remove duplicates vl.remove(k) do[k] = vl retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunks(sliceable, n): """ returns a list of lists of any slice-able object each of max lentgh n :Parameters: -sliceable: (string|list|tuple) any sliceable ob...
return [sliceable[i:i+n] for i in range(0, len(sliceable), n)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunks_str(str, n, separator="\n", fill_blanks_last=True): """returns lines with max n characters :Example: 123 456 X """
return separator.join(chunks(str, n))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def class_name_str(obj, skip_parent=False): """ return's object's class name as string """
rt = str(type(obj)).split(" ")[1][1:-2] if skip_parent: rt = rt.split(".")[-1] return rt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_name(cls, value): """ Returns the label from a value if label exists otherwise returns the value since method does a reverse look up it is slow """
for k, v in list(cls.__dict__.items()): if v == value: return k 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 _is_visible(cls, property_name): """ private method to check visible object property to be visible """
if isinstance(property_name, list): return [cls._is_visible(p) for p in property_name] if property_name.startswith('__') and property_name.endswith('__'): return False return property_name.startswith(cls.STARTS_WITH) and property_name.endswith(cls.ENDS_WITH)
<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_class(cls, class_name, module_name=None, *args, **kwargs): """ class method to create object of a given class """
def _get_module(module_name): names = module_name.split(".") module = __import__(names[0]) for i in xrange(1, len(names)): module = getattr(module, names[i]) return module if module_name: # module = globals()[module_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 from_serializable(cls, object_dict): """ core class method to create visible objects from a dictionary """
key_class = cls._from_visible(cls.STARTS_WITH + 'class' + cls.ENDS_WITH) key_module = cls._from_visible(cls.STARTS_WITH + 'module' + cls.ENDS_WITH) obj_class = object_dict.pop(key_class) obj_module = object_dict.pop(key_module) if key_module in object_dict else None obj = cls...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify_object(self, property_name, property_value_variant=None): """ api visible method for modifying visible object properties :param property_name: propert...
if type(property_name) is dict: property_value_variant = property_name.values() property_name = property_name.keys() if isinstance(property_name, str): property_name, property_value_variant = [property_name], [property_value_variant] assert len(property_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 arg_types(**kwargs): """ Mark the expected types of certain arguments. Arguments for which no types are provided default to strings. To specify an argument t...
def decorator(func): if not hasattr(func, '_bark_types'): func._bark_types = {} func._bark_types.update(kwargs) return func return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def boolean(text): """ An alternative to the "bool" argument type which interprets string values. """
tmp = text.lower() if tmp.isdigit(): return bool(int(tmp)) elif tmp in ('t', 'true', 'on', 'yes'): return True elif tmp in ('f', 'false', 'off', 'no'): return False raise ValueError("invalid Boolean value %r" % text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_handler(name, logname, filename, mode='a', encoding=None, delay=False): """ A Bark logging handler logging output to a named file. Similar to logging.Fi...
return wrap_log_handler(logging.FileHandler( filename, mode=mode, encoding=encoding, delay=delay))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watched_file_handler(name, logname, filename, mode='a', encoding=None, delay=False): """ A Bark logging handler logging output to a named file. If the file h...
return wrap_log_handler(logging.handlers.WatchedFileHandler( filename, mode=mode, encoding=encoding, delay=delay))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotating_file_handler(name, logname, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False): """ A Bark logging handler logging output to...
return wrap_log_handler(logging.handlers.RotatingFileHandler( filename, mode=mode, maxBytes=maxBytes, backupCount=backupCount, encoding=encoding, delay=delay))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timed_rotating_file_handler(name, logname, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False): """ A Bark logging handler ...
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler( filename, when=when, interval=interval, backupCount=backupCount, encoding=encoding, delay=delay, utc=utc))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nt_event_log_handler(name, logname, appname, dllname=None, logtype="Application"): """ A Bark logging handler logging output to the NT Event Log. Similar to ...
return wrap_log_handler(logging.handlers.NTEventLogHandler( appname, dllname=dllname, logtype=logtype))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def http_handler(name, logname, host, url, method="GET"): """ A Bark logging handler logging output to an HTTP server, using either GET or POST semantics. Simila...
return wrap_log_handler(logging.handlers.HTTPHandler( host, url, method=method))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lookup_handler(name): """ Look up the implementation of a named handler. Broken out for testing purposes. :param name: The name of the handler to look up. :...
# Look up and load the handler factory for ep in pkg_resources.iter_entry_points('bark.handler', name): try: # Load and return the handler factory return ep.load() except (ImportError, pkg_resources.UnknownExtra): # Couldn't load it... continue ...
<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_keys_safe(dct): """Modify the keys in |dct| to be valid attribute names."""
result = {} for key, val in dct.items(): key = key.replace('-', '_') if key in keyword.kwlist: key = key + '_' result[key] = val 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 _apply_args_to_func(global_args, func): """ Unpacks the argparse Namespace object and applies its contents as normal arguments to the function func """
global_args = vars(global_args) local_args = dict() for argument in inspect.getargspec(func).args: local_args[argument] = global_args[argument] return func(**local_args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, path, mode='r', *args, **kwargs): """Proxy to function `open` with path to the current file."""
return open(os.path.join(os.path.dirname(self.path), path), mode=mode, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def abspath(self, path): """Return absolute path for a path relative to the current file."""
return os.path.abspath(os.path.join(os.path.dirname(self.path), path))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lot(self, id, user=True, dependencies=True, comments=True, votes=True, no_strip=False): """ Retrieve the lot with given identifier :param id: Identifier of t...
args = {} if user: args['user'] = 'true' if dependencies: args['dependencies'] = 'true' if comments: args['comments'] = 'true' if votes: args['votes'] = 'true' if no_strip: args['nostrip'] = 'true' retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def head(self, wg_uuid, uuid): """ Get one workgroup node."""
url = "%(base)s/%(wg_uuid)s/nodes/%(uuid)s" % { 'base': self.local_base_url, 'wg_uuid': wg_uuid, 'uuid': uuid } # return self.core.head(url) try: # workaround return self.core.get(url) except LinShareException: ...
<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(self, wg_uuid, parent=None, flat=False, node_types=None): """ Get a list of workgroup nodes."""
url = "%(base)s/%(wg_uuid)s/nodes" % { 'base': self.local_base_url, 'wg_uuid': wg_uuid } param = [] if parent: # I use only the last folder uuid, the first ones are not really useful if isinstance(parent, (list,)): if len(p...
<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(self, data): """ Update meta of one document."""
self.debug(data) self._check(data) wg_uuid = data.get('workGroup') self.log.debug("wg_uuid : %s ", wg_uuid) uuid = data.get('uuid') url = "%(base)s/%(wg_uuid)s/nodes/%(uuid)s" % { 'base': self.local_base_url, 'wg_uuid': wg_uuid, 'uuid'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def arquire_attributes(self, attributes, active=True): """ Claims a list of attributes for the current client. Can also disable attributes. Returns update respon...
attribute_update = self._post_object(self.update_api.attributes.acquire, attributes) return ExistAttributeResponse(attribute_update)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def owned_attributes(self): """ Returns a list of attributes owned by this service. """
attributes = self._get_object(self.update_api.attributes.owned) return [ExistOwnedAttributeResponse(attribute) for attribute in attributes]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_sequence(cycles, program_or_profile='program', unit_converter=None): """ Makes the command list for a move sequence. Constructs the list of commands ...
# If needed, cycles needs to be converted to motor units. if unit_converter is None: cv_cycles = cycles else: cv_cycles = convert_sequence_to_motor_units(cycles, \ unit_converter=unit_converter) # Initially, we have no commands in our command list. commands = [] # ...
<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_sequence_time(cycles, unit_converter=None, eres=None): """ Calculates the time the move sequence will take to complete. Calculates the amount of time it ...
# If we are doing unit conversion, then that is equivalent to motor # units but with eres equal to one. if unit_converter is not None: eres = 1 # Starting with 0 time, steadily add the time of each movement. tme = 0.0 # Go through each cycle and collect times. for cycle in cycles: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_time(move, eres): """ Calculates the time it takes to do a move. Calculates how long it will take to complete a move of the motor. It is assumed that th...
# Grab the move parameters. If the deceleration is given as zero, # that means it has the same value as the acceleration. Distance is # converted to the same units as the others by dividing by the # encoder resolution. The absolute value of everything is taken for # simplicity. A = abs(move['A'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_sequence_to_motor_units(cycles, unit_converter): """ Converts a move sequence to motor units. Converts a move sequence to motor units using the provi...
# Make a deep copy of cycles so that the conversions don't damage # the original one. cv_cycles = copy.deepcopy(cycles) # Go through each cycle and do the conversions. for cycle in cv_cycles: # Go through each of the moves and do the conversions. for move in cycle['moves']: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile(self): """Return Hip string if already compiled else compile it."""
if self.buffer is None: self.buffer = self._compile_value(self.data, 0) return self.buffer.strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compile_value(self, data, indent_level): """Dispatch to correct compilation method."""
if isinstance(data, dict): return self._compile_key_val(data, indent_level) elif isinstance(data, list): return self._compile_list(data, indent_level) else: return self._compile_literal(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compile_literal(self, data): """Write correct representation of literal."""
if data is None: return 'nil' elif data is True: return 'yes' elif data is False: return 'no' else: return repr(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compile_list(self, data, indent_level): """Correctly write possibly nested list."""
if len(data) == 0: return '--' elif not any(isinstance(i, (dict, list)) for i in data): return ', '.join(self._compile_literal(value) for value in data) else: # 'ere be dragons, # granted there are fewer dragons than the parser, # but ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compile_key_val(self, data, indent_level): """Compile a dictionary."""
buffer = '' for (key, val) in data.items(): buffer += self._indent * indent_level # TODO: assumes key is a string buffer += key + ':' if isinstance(val, dict): buffer += '\n' buffer += self._compile_key_val(val, indent_lev...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def word(cap=False): """ This function generates a fake word by creating between two and three random syllables and then joining them together. """
syllables = [] for x in range(random.randint(2,3)): syllables.append(_syllable()) word = "".join(syllables) if cap: word = word[0].upper() + word[1:] return word
<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(data_access): """Wrap statements in a transaction. If the statements succeed, commit, otherwise rollback. :param data_access: a DataAccess instan...
old_autocommit = data_access.autocommit data_access.autocommit = False try: yield data_access except RollbackTransaction as ex: data_access.rollback() except Exception as ex: data_access.rollback() raise ex else: data_access.commit() finally: data_access.autocommit = old_autocommi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autocommit(data_access): """Make statements autocommit. :param data_access: a DataAccess instance """
if not data_access.autocommit: data_access.commit() old_autocommit = data_access.autocommit data_access.autocommit = True try: yield data_access finally: data_access.autocommit = old_autocommit
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autocommit(self, value): """Set the autocommit value. :param value: the new autocommit value """
logger.debug("Setting autocommit from %s to %s", self.autocommit, value) self.core.set_autocommit(self.connection, 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 _configure_connection(self, name, value): """Sets a Postgres run-time connection configuration parameter. :param name: the name of the parameter :param value...
self.update("pg_settings", dict(setting=value), dict(name=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 open(self, *, autocommit=False): """Sets the connection with the core's open method. :param autocommit: the default autocommit state :type autocommit: boolea...
if self.connection is not None: raise Exception("Connection already set") self.connection = self.core.open() self.autocommit = autocommit if self._search_path: self._configure_connection( "search_path", self._search_path) 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 close(self, *, commit=True): """Closes the connection via the core's close method. :param commit: if true the current transaction is commited, otherwise it i...
self.core.close(self.connection, commit=commit) self.connection = None 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 execute(self, query_string, params=None): """Executes a query. Returns the resulting cursor. :query_string: the parameterized query string :params: can be ei...
cr = self.connection.cursor() logger.info("SQL: %s (%s)", query_string, params) self.last_query = (query_string, params) t0 = time.time() cr.execute(query_string, params or self.core.empty_params) ms = (time.time() - t0) * 1000 logger.info("RUNTIME: %.2f ms", ms) self._update_cursor_sta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def callproc(self, name, params, param_types=None): """Calls a procedure. :param name: the name of the procedure :param params: a list or tuple of parameters to ...
if param_types: placeholders = [self.sql_writer.typecast(self.sql_writer.to_placeholder(), t) for t in param_types] else: placeholders = [self.sql_writer.to_placeholder() for p in params] # TODO: This may be Postgres specific... qs = "select * from {0}({1});".format(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_callproc_signature(self, name, param_types): """Returns a procedure's signature from the name and list of types. :name: the name of the procedure :params...
if isinstance(param_types[0], (list, tuple)): params = [self.sql_writer.to_placeholder(*pt) for pt in param_types] else: params = [self.sql_writer.to_placeholder(None, pt) for pt in param_types] return name + self.sql_writer.to_tuple(params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(self, table_name, constraints=None, *, columns=None, order_by=None): """Returns the first record that matches the given criteria. :table_name: the name ...
query_string, params = self.sql_writer.get_find_all_query( table_name, constraints, columns=columns, order_by=order_by) query_string += " limit 1;" return self.execute(query_string, params).fetchone()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_all(self, table_name, constraints=None, *, columns=None, order_by=None, limiting=None): """Returns all records that match a given criteria. :table_name:...
query_string, params = self.sql_writer.get_find_all_query( table_name, constraints, columns=columns, order_by=order_by, limiting=limiting) query_string += ";" return self.execute(query_string, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def page(self, table_name, paging, constraints=None, *, columns=None, order_by=None, get_count=True): """Performs a find_all method with paging. :param table_nam...
if get_count: count = self.count(table_name, constraints) else: count = None page, page_size = paging limiting = None if page_size > 0: limiting = (page_size, page * page_size) records = list(self.find_all( table_name, constraints, columns=columns, order_by=order_by, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, table_name, values, constraints=None, *, returning=None): """Builds and executes and update statement. :param table_name: the name of the table ...
if constraints is None: constraints = "1=1" assignments, assignment_params = self.sql_writer.parse_constraints( values, ", ", is_assignment=True) where, where_params = self.sql_writer.parse_constraints(constraints, " and ") returns = "" if returning and self.core.supports_returning_synt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, table_name, constraints=None): """Builds and executes an delete statement. :param table_name: the name of the table to delete from :param constr...
if constraints is None: constraints = "1=1" where, params = self.sql_writer.parse_constraints(constraints) sql = "delete from {0} where {1};".format(table_name, where) self.execute(sql, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count(self, table_name, constraints=None, *, extract="index"): """Returns the count of records in a table. If the default cursor is a tuple or named tuple, t...
where, params = self.sql_writer.parse_constraints(constraints) sql = "select count(*) as count from {0} where {1};".format(table_name, where or "1 = 1") # NOTE: Won't work right with dict cursor return self.get_scalar(self.execute(sql, params), 0 if extract == "index" else "count")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_scalar(self, cursor, index=0): """Returns a single value from the first returned record from a cursor. By default it will get cursor.fecthone()[0] which ...
if isinstance(index, int): return cursor.fetchone()[index] else: return get_value(cursor.fetchone(), index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def target_str(self): """Returns the string representation of the target property."""
if isinstance(self.target, tuple): return "({})".format(", ".join(self.target)) else: return self.target
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli_certify_core_number( config, min_value, max_value, value, ): """Console script for certify_number"""
verbose = config['verbose'] if verbose: click.echo(Back.GREEN + Fore.BLACK + "ACTION: certify-int") def parser(v): # Attempt a json/pickle decode: try: v = load_json_pickle(v, config) except Exception: pass # Attempt a straight conversion to...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_url(url, desktop_user_agent=None, mobile_user_agent=None): """ Url Resolver Given a url a list of resolved urls is returned for desktop and mobile us...
if not desktop_user_agent: desktop_user_agent = DESKTOP_USER_AGENT if not mobile_user_agent: mobile_user_agent = MOBILE_USER_AGENT input_urls = set() parsed = urlparse(url_with_protocol(url)) netloc = parsed.netloc if netloc.startswith('www.'): netloc = netloc[4:] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def token(self): " Get token when needed." if hasattr(self, '_token'): return getattr(self, '_token') # Json formatted auth. data = json.dumps({'customer_name': self.customer, 'user_name': self.username, 'password': 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 parse_error(self, response): " Parse authentication errors." # Check invalid credentials. if self.check_error(response, 'failure', 'INVALID_DATA'): raise self.CredentialsError( self.response_message(response, 'ERROR'))
<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_error(self, response, status, err_cd): " Check an error in the response." if 'status' not in response: return False if response['status'] != status: return False if 'msgs' not in response: return False if not isinstance(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 hook_response(self, response): " Detect any failure." # Decode content with json. response._content = json.loads(response.content) 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 check_errors(self, response): " Check some common errors." # Read content. content = response.content if 'status' not in content: raise self.GeneralError('We expect a status field.') # Return the decoded content if status is success. if content['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 add_address(self, fqdn, address, ttl=0): " Add a new address to a domain." data = {'rdata': {'address': address}, 'ttl': str(ttl)} # Make request. response = self.post('/REST/ARecord/%s/%s' % ( self.zone, fqdn), data=data) return Address(self, data=response.con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def publish(self): " Publish last changes." # Publish changes. response = self.put('/REST/Zone/%s' % ( self.zone, ), data={'publish': True}) return response.content['data']['serial']
<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_address(self, domain): " Get the list of addresses of a single domain." try: response = self.get('/REST/ARecord/%s/%s' % ( self.zone, domain)) except self.NotFoundError: return [] # Return a generator with the addresses. addresse...
<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_address(self, fqdn, address): " Remove an address of a domain." # Get a list of addresses. for record in self.list_address(fqdn): if record.address == address: record.delete() break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete(self): " Delete the address." response = self.dyn.delete(self.delete_url) return response.content['job_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 delete(self): " Delete the record." response = self.dyn.delete(self.url) return response.content['job_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 make_tstore_conn(params, **kwargs): """ Returns a triplestore connection args: attr_name: The name the connection will be assigned in the config manager para...
log.setLevel(params.get('log_level', __LOG_LEVEL__)) log.debug("\n%s", params) params.update(kwargs) try: vendor = RdfwConnections['triplestore'][params.get('vendor')] except KeyError: vendor = RdfwConnections['triplestore']['blazegraph'] conn = vendor(**params) return conn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_conn(self, **kwargs): """ takes a connection and creates the connection """
# log = logging.getLogger("%s.%s" % (self.log, inspect.stack()[0][3])) log.setLevel(kwargs.get('log_level',self.log_level)) conn_name = kwargs.get("name") if not conn_name: raise NameError("a connection requires a 'name': %s" % kwargs) elif self.conns.get(conn_name...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, conn_name, default=None, **kwargs): """ returns the specified connection args: conn_name: the name of the connection """
if isinstance(conn_name, RdfwConnections): return conn_name try: return self.conns[conn_name] except KeyError: if default: return self.get(default, **kwargs) raise LookupError("'%s' connection has not been set" % conn_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 load(self, conn_list, **kwargs): """ Takes a list of connections and sets them in the manager args: conn_list: list of connection defitions """
for conn in conn_list: conn['delay_check'] = kwargs.get('delay_check', False) self.set_conn(**conn) if kwargs.get('delay_check'): test = self.wait_for_conns(**kwargs) if not test: log.critical("\n\nEXITING:Unable to establish connections \...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def failing(self): """ Tests to see if all connections are working returns: dictionary of all failing connections """
log_levels = {key: conn.log_level for key, conn in self.conns.items() if hasattr(conn, 'log_level')} for key in log_levels: self.conns[key].log_level = logging.CRITICAL failing_conns = {key: conn for key, conn in self.active.items() if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wait_for_conns(self, timeout=60, start_delay=0, interval=5, **kwargs): ''' delays unitil all connections are working args: timeout: number of seconds to try to connecting. Error out when timeout is reached start_delay: number of seconds to...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def active(self): """ returns a dictionary of connections set as active. """
return {key: value for key, value in self.conns.items() if value.active}
<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(): """Host a file."""
description = """Host a file on the LAN.""" argParser = _argparse.ArgumentParser(description=description) argParser.add_argument('file', help='File to host') argParser.add_argument('-p', '--port', help='Port to use. (default: 80/8000)', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def small_register_machine(rom_size = 50, ram_size = 200, flash_size = 500): """ An unprogrammend Register Machine with * one OutputRegister to ``sys.stdout``...
rom = memory.ROM(rom_size) ram = memory.RAM(ram_size) flash = device.Flash(flash_size) proc = processor.Processor() proc.register_memory_device(rom) proc.register_memory_device(ram) proc.register_device(flash) registers = [register.OutputRegister("out0", sys.stdout), register.Register("r0"), register.Re...
<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_edge(self, u, v, **attr): """ Add an edge from u to v and update edge attributes """
if u not in self.vertices: self.vertices[u] = [] self.pred[u] = [] self.succ[u] = [] if v not in self.vertices: self.vertices[v] = [] self.pred[v] = [] self.succ[v] = [] vertex = (u, v) self.edges[vertex] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_successor(self, u, v): """ Check if vertex u has successor v """
if u not in self.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (u,)) return (u in self.succ and v in self.succ[u])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_predecessor(self, u, v): """ Check if vertex u has predecessor v """
if u not in self.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (u,)) return(u in self.pred and v in self.pred[u])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_header(frmt, return_len=False): """creates a header string from a new style format string useful when printing dictionaries :param str frmt: a new sty...
names = re.sub("{(.*?):.*?}", r"\1", frmt) names = [i for i in names.split("|") if i] frmt_clean = re.sub("\.\df", r"", frmt) # get read of floats i.e {:8.2f} sizes = re.findall(r':(\d+)', frmt_clean) frmt_header = "|{{:^{}}}" * len(sizes) + "|" header_frmt = frmt_header.format(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_form(self, request, form, change): """Here we pluck out the data to create a new cloned repo. Form is an instance of NewRepoForm. """
name = form.cleaned_data['name'] origin_url = form.cleaned_data['origin_url'] res = ClonedRepo(name=name, origin=origin_url) LOG.info("New repo form produced %s" % str(res)) form.save(commit=False) return res
<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_view(self, request, **kwargs): """A custom add_view, to catch exceptions from 'save_model'. Just to be clear, this is very filthy. """
try: return super(ClonedRepoAdmin, self).add_view(request, **kwargs) except ValidationError: # Rerender the form, having messaged the user. return redirect(request.path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def git_pull_view(self, request, repo_name): """Perform a git pull and redirect back to the repo."""
LOG.info("Pull requested for %s." % repo_name) repo = get_object_or_404(self.model, name=repo_name) repo.pull() self.message_user(request, "Repo %s successfully updated." % repo_name, level=messages.SUCCESS) return redirect('admin:registry_clonedrepo_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 update_all_view(self, request): """Update all repositories and redirect back to the repo list."""
LOG.info("Total update requested.") total_count = errors = 0 for repo in self.model.objects.all(): total_count += 1 try: repo.pull() except: LOG.exception('While updating %s.' % repo) errors += 1 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 clean(self): """Validate the new repo form. Might perform a request to upstream Bower."""
cleaned_data = super(NewRepoForm, self).clean() origin_url = cleaned_data['origin_url'] origin_source = cleaned_data['origin_source'] if origin_source == 'origin_url' and not origin_url: msg = 'Please provide an origin URL.' self._errors['origin_url'] = self.erro...
<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(lang=None): """Activate a translation for lang. If lang is None, then the language of locale.getdefaultlocale() is used. If the translation file doe...
if lang is None: lang = locale.getlocale()[0] tr = gettext.translation("argparse", os.path.join(locpath, "locale"), [lang], fallback=True) argparse._ = tr.gettext argparse.ngettext = tr.ngettext
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Run until there are no more events. This only looks at events scheduled through the event loop. """
self._stop = False while not self._stop: have_sources = self._timers or self._readers or self._writers if not self._processor.pending and not have_sources: break events = QEventLoop.AllEvents if not self._processor.pending: ...
<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_namedtuple(self): """ Convert class to namedtuple. Note: This method is neccessary for AMQP communication. Returns: namedtuple: Representation of the clas...
keys = filter(lambda x: not x.startswith("_"), self.__dict__) opt_nt = namedtuple(self.__class__.__name__, keys) filtered_dict = dict(map(lambda x: (x, self.__dict__[x]), keys)) return opt_nt(**filtered_dict)
<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_hash(self): """ Create hash of the class. Hash should be unique for given ebook, so ISBN is main component of the hash if provided. Returns: str: Hash. ...
if self.optionals and self.optionals.ISBN: isbn = self.optionals.ISBN.replace("-", "") if len(isbn) <= 10: return "97880" + isbn return isbn if self.optionals and self.optionals.EAN: return self.optionals.EAN return self.title ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def luriegold(R): """Lurie-Goldberg Algorithm to adjust a correlation matrix to be semipositive definite Philip M. Lurie and Matthew S. Goldberg (1998), An Appro...
# subfunctions def xtotril(x, idx, mat): """Create 'L' lower triangular matrix.""" mat[idx] = x return mat def xtocorr(x, idx, mat): L = xtotril(x, idx, mat) C = np.dot(L, L.T) return C, L def objectivefunc(x, R, idx, mat): C, _ = xtocorr(x, 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 generate_datasets_list(settings, argv): """ generate datasets list to activate args: settings: dictionary from settings file argv: list from sys.argv """
datasets_string_list = settings["DATASETS_LIST"] datasets_list = [] if len(argv) == 2: try: datasets_items = datasets_string_list.iteritems() except AttributeError: datasets_items = datasets_string_list.items() for key, val in datasets_items: 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 manage(settingspath, root_dir, argv): """ Manage all processes """
# add settings.json to environment variables os.environ[ENV_VAR_SETTINGS] = settingspath # add root_dir os.environ[ENV_VAR_ROOT_DIR] = root_dir # get datasets list with open(settingspath) as settings_file: settings = json.load(settings_file) # manage args datasets_list = generat...
<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_pathname_valid(pathname: str) -> bool: """Checks if the given path name is valid. Returns ------- `True` if the passed pathname is a valid pathname for the...
# If this pathname is either not a string or is but is empty, this pathname # is invalid. try: if not isinstance(pathname, str) or not pathname: return False # Strip this pathname's Windows-specific drive specifier (e.g., `C:\`) # if any. Since Windows prohibits path co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_path_creatable(pathname: str) -> bool: """Checks whether the given path is creatable. Returns ------- `True` if the current user has sufficient permissions...
# Parent directory of the passed path. If empty, we substitute the current # working directory (CWD) instead. dirname = os.path.dirname(pathname) or os.getcwd() return os.access(dirname, os.W_OK)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path_exists_or_creatable(pathname: str) -> bool: """Checks whether the given path exists or is creatable. This function is guaranteed to _never_ raise excepti...
try: # To prevent "os" module calls from raising undesirable exceptions on # invalid pathnames, is_pathname_valid() is explicitly called first. return is_pathname_valid(pathname) and ( os.path.exists(pathname) or is_path_creatable(pathname)) # Report failure on non-fatal fil...
<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_path_sibling_creatable(pathname: str) -> bool: """Checks whether current user can create siblings of the given path. Returns ------- `True` if the current ...
# Parent directory of the passed path. If empty, we substitute the current # working directory (CWD) instead. dirname = os.path.dirname(pathname) or os.getcwd() try: # For safety, explicitly close and hence delete this temporary file # immediately after creating it in the passed path's...