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 ready(self): """Auto load Trionyx"""
models_config.auto_load_configs() self.auto_load_app_modules(['layouts', 'signals']) app_menu.auto_load_model_menu() auto_register_search_models() tabs.auto_generate_missing_tabs()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auto_load_app_modules(self, modules): """Auto load app modules"""
for app in apps.get_app_configs(): for module in modules: try: import_module('{}.{}'.format(app.module.__package__, module)) except ImportError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bump(match): """Bumps the version"""
before, old_version, after = match.groups() major, minor, patch = map(int, old_version.split('.')) patch += 1 if patch == 10: patch = 0 minor += 1 if minor == 10: minor = 0 major += 1 new_version = '{0}.{1}.{2}'.format(major, minor, patch) print('{0} => {1}'.format(old_version, new_version)) return before + new_version + after
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_raw(self, suffix): """ writes a the suffix prefixed by the CSI to the handle """
if not self.enabled: return self.buffer.write(CSI) self.buffer.write(suffix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_db_tables(db): """Build Seshet's basic database schema. Requires one parameter, `db` as `pydal.DAL` instance. """
if not isinstance(db, DAL) or not db._uri: raise Exception("Need valid DAL object to define tables") # event log - self-explanatory, logs all events db.define_table('event_log', Field('event_type'), Field('event_time', 'datetime'), Field('source'), Field('target'), Field('message', 'text'), Field('host'), Field('params', 'list:string'), ) db.define_table('modules', Field('name', notnull=True, unique=True, length=256), Field('enabled', 'boolean'), Field('event_types', 'list:string'), Field('description', 'text'), Field('echannels', 'list:string'), Field('dchannels', 'list:string'), Field('enicks', 'list:string'), Field('dnicks', 'list:string'), Field('whitelist', 'list:string'), Field('blacklist', 'list:string'), Field('cmd_prefix', length=1, default='!', notnull=True), Field('acl', 'json'), Field('rate_limit', '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 generate_values(self, *args, **kwargs): """ Generate a sample of values by sampling from a distribution. The size of the sample can be overriden with the 'size' kwarg. If `self.sample_mean_value == True` the sample will contain "size" times the mean value. :param args: :param kwargs: :return: sample as vector of given size """
sample_size = kwargs.get('size', self.size) f = self.instantiate_distribution_function(self.module_name, self.distribution_name) distribution_function = partial(f, *self.random_function_params, size=sample_size) if self.sample_mean_value: sample = np.full(sample_size, self.get_mean(distribution_function)) else: sample = distribution_function() return sample
<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_scenario(self, parameter: 'Parameter', scenario_name: str = default_scenario): """ Add a scenario for this parameter. :param scenario_name: :param parameter: :return: """
self.scenarios[scenario_name] = parameter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill_missing_attributes_from_default_parameter(self, param): """ Empty fields in Parameter definitions in scenarios are populated with default values. E.g. in the example below, the source for the Power_TV variable in the 8K scenario would also be EnergyStar. | name | scenario | val | tags | source | | Power_TV | | 60 | UD, TV | EnergyStar | | Power_TV | 8K | 85 | new_tag| | **Note** tags must not differ. In the example above, the 8K scenario variable the tags value would be overwritten with the default value. :param param: :return: """
if not self.exists(param.name) or not ParameterScenarioSet.default_scenario in self.parameter_sets[ param.name].scenarios.keys(): logger.warning( f'No default value for param {param.name} found.') return default = self.parameter_sets[param.name][ParameterScenarioSet.default_scenario] for att_name, att_value in default.__dict__.items(): if att_name in ['unit', 'label', 'comment', 'source', 'tags']: if att_name == 'tags' and default.tags != param.tags: logger.warning( f'For param {param.name} for scenarios {param.source_scenarios_string}, tags is different from default parameter tags. Overwriting with default values.') setattr(param, att_name, att_value) if not getattr(param, att_name): logger.debug( f'For param {param.name} for scenarios {param.source_scenarios_string}, populating attribute {att_name} with value {att_value} from default parameter.') setattr(param, att_name, att_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 find_by_tag(self, tag) -> Dict[str, Set[Parameter]]: """ Get all registered dicts that are registered for a tag :param tag: str - single tag :return: a dict of {param name: set[Parameter]} that contains all ParameterScenarioSets for all parameter names with a given tag """
return self.tags[tag]
<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_parameter_definitions(self, sheet_name: str = None): """ Load variable text from rows in excel file. If no spreadsheet arg is given, all spreadsheets are loaded. The first cell in the first row in a spreadsheet must contain the keyword 'variable' or the sheet is ignored. Any cells used as titles (with no associated value) are also added to the returned dictionary. However, the values associated with each header will be None. For example, given the speadsheet: | variable | A | B | | Title | | | | Entry | 1 | 2 | The following list of definitions would be returned: [ { variable: 'Title', A: None, B: None } , { variable: 'Entry', A: 1 , B: 2 } ] :param sheet_name: :return: list of dicts with {header col name : cell value} pairs """
definitions = self.excel_handler.load_definitions(sheet_name, filename=self.filename) self.definition_version = self.excel_handler.version return definitions
<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: str) -> str: """A small wrapper method which makes a quick GET request. Parameters url : str The URL to get. Returns ------- str The raw html of the requested page. Raises ------ RuneConnectionError If the GET response status is not 200. """
resp = self.session.get(url, headers=self.HEADERS) if resp.status_code is 200: return resp.text else: raise RuneConnectionError(resp.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 sys_call(cmd): """Execute cmd and capture stdout and stderr :param cmd: command to be executed :return: (stdout, stderr) """
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) return p.stdout.readlines(), p.stderr.readlines()
<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_alphanumeric_index(query_string): """ Given an input string of either int or char, returns what index in the alphabet and case it is :param query_string: str, query string :return: (int, str), list of the index and type """
# TODO: could probably rework this. it works, but it's ugly as hell. try: return [int(query_string), 'int'] except ValueError: if len(query_string) == 1: if query_string.isupper(): return [string.ascii_uppercase.index(query_string), 'char_hi'] elif query_string.islower(): return [string.ascii_lowercase.index(query_string), 'char_lo'] else: raise IOError('The input is a string longer than one character')
<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_numeric(val): """ Helper function for conversion of various data types into numeric representation. """
if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)): return val return float(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 evaluate_binop_logical(self, operation, left, right, **kwargs): """ Evaluate given logical binary operation with given operands. """
if not operation in self.binops_logical: raise ValueError("Invalid logical binary operation '{}'".format(operation)) result = self.binops_logical[operation](left, right) return bool(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 evaluate_binop_comparison(self, operation, left, right, **kwargs): """ Evaluate given comparison binary operation with given operands. """
if not operation in self.binops_comparison: raise ValueError("Invalid comparison binary operation '{}'".format(operation)) if left is None or right is None: return None if not isinstance(left, (list, ListIP)): left = [left] if not isinstance(right, (list, ListIP)): right = [right] if not left or not right: return None if operation in ['OP_IS']: res = self.binops_comparison[operation](left, right) if res: return True elif operation in ['OP_IN']: for iteml in left: res = self.binops_comparison[operation](iteml, right) if res: return True else: for iteml in left: if iteml is None: continue for itemr in right: if itemr is None: continue res = self.binops_comparison[operation](iteml, itemr) if res: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calculate_vector(self, operation, left, right): """ Calculate vector result from two list operands with given mathematical operation. """
result = [] if len(right) == 1: right = _to_numeric(right[0]) for iteml in left: iteml = _to_numeric(iteml) result.append(self.binops_math[operation](iteml, right)) elif len(left) == 1: left = _to_numeric(left[0]) for itemr in right: itemr = _to_numeric(itemr) result.append(self.binops_math[operation](left, itemr)) elif len(left) == len(right): for iteml, itemr in zip(left, right): iteml = _to_numeric(iteml) itemr = _to_numeric(itemr) result.append(self.binops_math[operation](iteml, itemr)) else: raise FilteringRuleException("Uneven length of math operation '{}' operands".format(operation)) 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 evaluate_binop_math(self, operation, left, right, **kwargs): """ Evaluate given mathematical binary operation with given operands. """
if not operation in self.binops_math: raise ValueError("Invalid math binary operation '{}'".format(operation)) if left is None or right is None: return None if not isinstance(left, (list, ListIP)): left = [left] if not isinstance(right, (list, ListIP)): right = [right] if not left or not right: return None try: vect = self._calculate_vector(operation, left, right) if len(vect) > 1: return vect return vect[0] except: return 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 evaluate_unop(self, operation, right, **kwargs): """ Evaluate given unary operation with given operand. """
if not operation in self.unops: raise ValueError("Invalid unary operation '{}'".format(operation)) if right is None: return None return self.unops[operation](right)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decorate_function(self, name, decorator): """ Decorate function with given name with given decorator. :param str name: Name of the function. :param callable decorator: Decorator callback. """
self.functions[name] = decorator(self.functions[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 render(self, template=None, additional=None): """ Render single model to its html representation. You may set template path in render function argument, or model's variable named 'template_path', or get default name: $app_label$/models/$model_name$.html Settings: * MODEL_RENDER_DEFAULT_EXTENSION set default template extension. Usable if you use jinja or others. :param template: custom template_path :return: rendered model html string """
template_path = template or self.get_template_path() template_vars = {'model': self} if additional: template_vars.update(additional) rendered = render_to_string(template_path, template_vars) return mark_safe(rendered)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self): """Execute a system command."""
if self._decode_output: # Capture and decode system output with Popen(self.command, shell=True, stdout=PIPE) as process: self._output = [i.decode("utf-8").strip() for i in process.stdout] self._success = True else: # Execute without capturing output os.system(self.command) self._success = True 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 accepts(exception=TypeError, **types): """ A wrapper of function for checking function parameters type Example 1: @accepts(a=int, b='__iter__', c=str) def test(a, b=None, c=None): print('accepts OK') test(13, b=[], c='abc') -- OK test('aaa', b=(), c='abc') --Failed Example 2: @accepts(a=int, b=('__iter__', None), c=str) def test(a, b=None, c=None): print('accepts OK') test(13, b=[], c='abc') -- OK test(13, b=None, c='abc') -- OK """
def check_param(v, type_or_funcname): if isinstance(type_or_funcname, tuple): results1 = [check_param(v, t) for t in type_or_funcname if t is not None] results2 = [v == t for t in type_or_funcname if t is None] return any(results1) or any(results2) is_type_instance, is_func_like = False, False try: is_type_instance = isinstance(v, type_or_funcname) except TypeError: pass if isinstance(type_or_funcname, str): if type_or_funcname == '__iter__' and isinstance(v, str) and version_info < (3,): # at py 2.x, str object has non `__iter__` attribute, # str object can use like `for c in s`, bcz `iter(s)` returns an iterable object. is_func_like = True else: is_func_like = hasattr(v, type_or_funcname) return is_type_instance or is_func_like def check_accepts(f): assert len(types) <= f.__code__.co_argcount,\ 'accept number of arguments not equal with function number of arguments in "{}"'.format(f.__name__) @functools.wraps(f) def new_f(*args, **kwargs): for i, v in enumerate(args): if f.__code__.co_varnames[i] in types and \ not check_param(v, types[f.__code__.co_varnames[i]]): raise exception("function '%s' arg '%s'=%r does not match %s" % (f.__name__, f.__code__.co_varnames[i], v, types[f.__code__.co_varnames[i]])) del types[f.__code__.co_varnames[i]] for k, v in kwargs.items(): if k in types and \ not check_param(v, types[k]): raise exception("function '%s' arg '%s'=%r does not match %s" % (f.__name__, k, v, types[k])) return f(*args, **kwargs) return new_f return check_accepts
<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_vimball(fd): """Test for vimball archive format compliance. Simple check to see if the first line of the file starts with standard vimball archive header. """
fd.seek(0) try: header = fd.readline() except UnicodeDecodeError: # binary files will raise exceptions when trying to decode raw bytes to # str objects in our readline() wrapper return False if re.match('^" Vimball Archiver', header) is not None: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def files(self): """Yields archive file information."""
# try new file header format first, then fallback on old for header in (r"(.*)\t\[\[\[1\n", r"^(\d+)\n$"): header = re.compile(header) filename = None self.fd.seek(0) line = self.readline() while line: m = header.match(line) if m is not None: filename = m.group(1) try: filelines = int(self.readline().rstrip()) except ValueError: raise ArchiveError('invalid archive format') filestart = self.fd.tell() yield (filename, filelines, filestart) line = self.readline() if filename is not None: 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 extract(self, extractdir=None, verbose=False): """Extract archive files to a directory."""
if extractdir is None: filebase, ext = os.path.splitext(self.path) if ext in ('.gz', '.bz2', '.xz'): filebase, _ext = os.path.splitext(filebase) extractdir = os.path.basename(filebase) if os.path.exists(extractdir): tempdir = tempfile.mkdtemp(prefix='vimball-', dir=os.getcwd()) extractdir = os.path.join(tempdir.split('/')[-1], extractdir) self.fd.seek(0) for filename, lines, offset in self.files: filepath = os.path.join(extractdir, filename) try: directory = os.path.dirname(filepath) mkdir_p(directory) except OSError as e: raise ArchiveError(f"failed creating directory {directory!r}: {e.strerror}") with open(filepath, 'w') as f: if verbose: print(filepath) self.fd.seek(offset) for i in range(lines): f.write(self.readline())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ini_dump_hook(cfg, text: bool=False): """ Dumps all the data into a INI file. This will automatically kill anything with a '_' in the keyname, replacing it with a dot. You have been warned. """
data = cfg.config.dump() # Load data back into the goddamned ini file. ndict = {} for key, item in data.items(): key = key.replace('_', '.') ndict[key] = item cfg.tmpini = configparser.ConfigParser() cfg.tmpini.read_dict(data) if not text: cfg.tmpini.write(cfg.fd) else: return cfg.reload()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exception_message(): """Create a message with details on the exception."""
exc_type, exc_value, exc_tb = exc_info = sys.exc_info() return {'exception': {'type': exc_type, 'value': exc_value, 'traceback': exc_tb}, 'traceback': traceback.format_exception(*exc_info)}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def behavior(f): """Decorator for declaring a function as behavior. Use as:: @behavior def fun(x, y, self, msg): And create or become this behavior by passing the two arguments `x` and `y`. """
@wraps(f) def wrapper(*args): message = args[-1] if isinstance(message, MutableMapping): message = Message(message) f(*(args[:-1] + (message,))) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromtimestamp(timestamp): """Because python doesn't support negative timestamp to datetime so we have to implement my own method """
if timestamp >= 0: return datetime.fromtimestamp(timestamp) else: return datetime(1969, 12, 31, 20, 0) + timedelta(seconds=timestamp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rigid_linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis): """A datetime-version that takes datetime object list as x_axis. """
numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in datetime_axis ] numeric_datetime_new_axis = [ totimestamp(a_datetime) for a_datetime in datetime_new_axis ] return rigid_linear_interpolate( numeric_datetime_axis, y_axis, numeric_datetime_new_axis)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exam_reliability_by_datetime( datetime_axis, datetime_new_axis, reliable_distance): """A datetime-version that takes datetime object list as x_axis reliable_distance equals to the time difference in seconds. """
numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in datetime_axis ] numeric_datetime_new_axis = [ totimestamp(a_datetime) for a_datetime in datetime_new_axis ] return exam_reliability(numeric_datetime_axis, numeric_datetime_new_axis, reliable_distance, precision=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 import_object_by_string(namespace): """Import object by complete namespace"""
segments = namespace.split('.') module = importlib.import_module('.'.join(segments[:-1])) return getattr(module, segments[-1])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_celerybeat_schedule(apps): """Create Celery beat schedule by get schedule from every installed app"""
beat_schedule = {} for app in apps: try: config = import_object_by_string(app) module = importlib.import_module('{}.cron'.format(config.name)) except Exception: try: module = importlib.import_module('{}.cron'.format(app)) except Exception: continue if not (hasattr(module, 'schedule') and isinstance(module.schedule, dict)): logger.warning('{} has no schedule or schedule is not a dict'.format(module.__name__)) continue # Add cron queue option for name, schedule in module.schedule.items(): options = schedule.get('options', {}) if 'queue' not in options: options['queue'] = 'cron' schedule['options'] = options beat_schedule[name] = schedule return beat_schedule
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_client( cls, address: Union[str, Tuple[str, int], Path] = 'localhost', port: int = 6379, db: int = 0, password: str = None, ssl: Union[bool, str, SSLContext] = False, **client_args) -> Dict[str, Any]: """ Configure a Redis client. :param address: IP address, host name or path to a UNIX socket :param port: port number to connect to (ignored for UNIX sockets) :param db: database number to connect to :param password: password used if the server requires authentication :param ssl: one of the following: * ``False`` to disable SSL * ``True`` to enable SSL using the default context * an :class:`~ssl.SSLContext` instance * a ``module:varname`` reference to an :class:`~ssl.SSLContext` instance * name of an :class:`~ssl.SSLContext` resource :param client_args: extra keyword arguments passed to :func:`~aioredis.create_redis_pool` """
assert check_argument_types() if isinstance(address, str) and not address.startswith('/'): address = (address, port) elif isinstance(address, Path): address = str(address) client_args.update({ 'address': address, 'db': db, 'password': password, 'ssl': resolve_reference(ssl) }) return client_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 format_word_list_mixedcase(word_list): """ Given a list of words, this function returns a new list where the words follow mixed case convention. As a reminder this is mixedCase. :param word_list: list, a list of words :return: list, a list of words where the words are mixed case """
to_return, first_word = list(), True for word in word_list: if first_word: to_return.append(word.lower()) first_word = False else: to_return.append(word.capitalize()) return to_return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_string(string_to_format, wordstyle="lowercase", separator=" "): """ Takes an un-formatted string and returns it in the desired format Acceptable formats are defined in the function_map dictionary. """
# first split the string up into its constituent words words = string_to_format.split(" ") # format the individual words function_map = { "lowercase": format_word_list_lowercase, "uppercase": format_word_list_uppercase, "capitalize": format_word_list_capitalize, "mixedcase": format_word_list_mixedcase } try: words = function_map[wordstyle](words) except KeyError: msg = "Passed in an invalid wordstyle, allowed styles are {}" raise InvalidWordStyleError(msg.format(function_map.keys())) # now add in the separator and return return str(separator).join(words)
<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_random_word(dictionary, starting_letter=None): """ Takes the dictionary to read from and returns a random word optionally accepts a starting letter """
if starting_letter is None: starting_letter = random.choice(list(dictionary.keys())) try: to_return = random.choice(dictionary[starting_letter]) except KeyError: msg = "Dictionary does not contain a word starting with '{}'" raise NoWordForLetter(msg.format(starting_letter)) return to_return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_dictionary(dictionary): """ Function used to import the dictionary file into memory opened_file should be an already opened dictionary file :raises DictionaryNotFoundError if dictionary can't be loaded """
def load_into_dictionary(dictionary_file): """create the dictionary to hold the words""" to_return = dict() for line in dictionary_file: try: to_return[line[0].lower()].append(line.strip().lower()) except KeyError: to_return[line[0].lower()] = [line.strip().lower()] return to_return try: with open(dictionary) as dictionary_file: to_return = load_into_dictionary(dictionary_file) except TypeError: to_return = load_into_dictionary(dictionary) except IOError: message = "Could not find the dictionary at {}".format(dictionary) raise DictionaryNotFoundError(message) return to_return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def string_for_count(dictionary, count): """Create a random string of N=`count` words"""
string_to_print = "" if count is not None: if count == 0: return "" ranger = count else: ranger = 2 for index in range(ranger): string_to_print += "{} ".format(get_random_word(dictionary)) return string_to_print.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 generate_seed(seed): """Generate seed for random number generator"""
if seed is None: random.seed() seed = random.randint(0, sys.maxsize) random.seed(a=seed) return seed
<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(dictionary='dictionaries/all_en_US.dict', count=None, initials=None, seed=None, wordstyle='lowercase', separator=' '): """Main processing function for namealizer"""
generate_seed(seed) # attempt to read in the given dictionary dictionary = import_dictionary(dictionary) # if count and initials are both set, let the user know what's up if count and initials: msg = "--count and --initials are mutually exclusive, using initials" logging.info(msg) if initials is not None: string_to_print = string_for_initials(dictionary, initials) else: string_to_print = string_for_count(dictionary, count) return format_string(string_to_print, wordstyle, separator)
<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_parser(): """Creates the Namespace object to be used by the rest of the tool"""
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-d', '--dictionary', nargs='?', default='dictionaries/all_en_US.dict', help='Specify a non-default word dictionary to use.') parser.add_argument('-c', '--count', help='Specify the number of words to return.', type=int) parser.add_argument('-i', '--initials', type=str, help='String of letters used to form the word list') parser.add_argument('-s', '--seed', help='Specify the seed to use for the random number ' 'generator. Using the same seed without changing ' 'other settings will give repeatable results.', type=int) parser.add_argument('-ws', '--wordstyle', nargs='?', default='lowercase', type=str, help='Specify how to style the individual words. ' 'Default is lowercase.') parser.add_argument('-sep', '--separator', nargs='?', default=' ', type=str, help='How to separate words. Default is space.') return parser.parse_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 save_to_db(model_text_id, parsed_values): """save to db and return saved object"""
Model = apps.get_model(model_text_id) # normalise values and separate to m2m, simple simple_fields = {} many2many_fields = {} for field, value in parsed_values.items(): if (Model._meta.get_field( field).get_internal_type() == 'ManyToManyField'): many2many_fields[field] = value elif (Model._meta.get_field( field).get_internal_type() == 'DateTimeField'): simple_fields[field] = time_parser.parse(value) else: simple_fields[field] = value # ToDo: add unique identify parameter to field # ToDo: allow unique identify m2m field model, created = Model.objects.get_or_create(**simple_fields) for field, value in many2many_fields.items(): setattr(model, field, value) model.save() return model
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grouper(iterable, n): """ Slice up `iterable` into iterables of `n` items. :param iterable: Iterable to splice. :param n: Number of items per slice. :returns: iterable of iterables """
it = iter(iterable) while True: chunk = itertools.islice(it, n) try: first = next(chunk) except StopIteration: return yield itertools.chain([first], chunk)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self, dataframe): """ Takes the already cleaned dataframe, splits it into train and test and returns the train and test as numpy arrays. If the problem is supervised, the target column will be that last one of the returned arrays. """
mapping = DataFrameMapCreator().get_mapping_from_config(self.__config) self.__mapper = DataFrameMapper(mapping) train, test = split_dataframe_train_test(dataframe, self.__config.get_option_parameter("split", "train_percentage")) return self.__get_correct_return_parameters(train, test)
<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_target_data(self, transformed_data, original_data): """ Picks up the target data from the original_data and appends it as a column to the transformed_data. Both arguments are expected to be np.array's. """
model = self.__config.get_data_model() target_feature = model.find_target_feature() name = target_feature.get_name() if target_feature.is_categorical(): target_row = original_data[name] target = self.__label_encoder_adapter.transform(target_row) else: target = original_data[name].values.astype(type_name_to_data_type("float")) target = target[..., None] return np.hstack((transformed_data, 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 set_params(method, params): """Set params to query limesurvey"""
data = {'method': method, 'params': params, 'id': str(uuid4())} return json.dumps(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 list_surveys(session): """retrieve a list of surveys from current user"""
params = {'sUser': session['user'], 'sSessionKey': session['token']} data = set_params('list_surveys', params) req = requests.post(session['url'], data=data, headers=headers) return req.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 stop(self): """Send signal to stop the current stream playback"""
self._response['shouldEndSession'] = True self._response['action']['audio']['interface'] = 'stop' self._response['action']['audio']['sources'] = [] 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 sub_path(self, path): """ If this redirect is a regular expression, it will return a rewritten version of `path`; otherwise returns the `new_path`. """
if not self.regular_expression: return self.new_path return re.sub(self.old_path, self.new_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 _set_formatter(self): """ Inspects config and sets the name of the formatter to either "json" or "text" as instance attr. If not present in config, default is "text" """
if hasattr(self._config, "formatter") and self._config.formatter == "json": self._formatter = "json" else: self._formatter = "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 _set_log_level(self): """ Inspects config and sets the log level as instance attr. If not present in config, default is "INFO". """
# set log level on logger log_level = "INFO" if hasattr(self._config, "level") and self._config.level.upper() in ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]: log_level = self._config.level.upper() self._log_level = log_level
<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_framework_logger(self): """ Creates a logger with default formatting for internal use by the CloeePy framework and its plugins. User may configure customer fields on their logger, but the framework would not know how to incorporate those custom fields, and by design of the logging pkg authors, the program would error out. """
formatter = None if self._formatter == "json": formatter = CustomJsonFormatter(self.default_json_fmt) else: formatter = logging.Formatter(self.default_text_fmt) self._logger = logging.getLogger("CloeePyFramework") logHandler = logging.StreamHandler() logHandler.setFormatter(formatter) self._logger.addHandler(logHandler) self._logger.setLevel(self._log_level)
<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_application_logger(self): """ Creates a logger intended for use by applications using CloeePy. This logger is fully configurable by the user and can include custom fields """
formatter = None if self._formatter == "json": if hasattr(self._config, "formatString"): formatter = CustomJsonFormatter(self._config.formatString) else: formatter = CustomJsonFormatter(self.default_json_fmt) else: if hasattr(self._config, "formatString"): formatter = logging.Formatter(self._config.formatString) else: formatter = logging.Formatter(self.default_txt_fmt) # get logging.Logger instance and set formatter self.logger = logging.getLogger('CloeePyApplication') logHandler = logging.StreamHandler() logHandler.setFormatter(formatter) self.logger.addHandler(logHandler) self.logger.setLevel(self._log_level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lisFichierLexique(self, filepath): """ Lecture des lemmes, et enregistrement de leurs radicaux :param filepath: Chemin du fichier à charger :type filepath: str """
orig = int(filepath.endswith("ext.la")) lignes = lignesFichier(filepath) for ligne in lignes: self.parse_lemme(ligne, orig)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_modele(self, modele: Modele): """ Register a modele onto the lemmatizer :param modele: Modele to register """
self.lemmatiseur._modeles[modele.gr()] = modele
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _register_lemme(self, lemma): """ Register a lemma into the Lemmatiseur :param lemma: Lemma to register :return: """
if lemma.cle() not in self.lemmatiseur._lemmes: self.ajRadicaux(lemma) self.lemmatiseur._lemmes[lemma.cle()] = lemma
<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_irreg(self, l): """ Constructeur de la classe Irreg. :param l: Ligne de chargement des irréguliers :type l: str """
ecl = l.split(':') grq = ecl[0] exclusif = False if grq.endswith("*"): grq = grq[:-1] exclusif = True return Irreg( graphie_accentuee=grq, graphie=atone(grq), exclusif=exclusif, morphos=listeI(ecl[2]), lemme=self.lemmatiseur.lemme(ecl[1]), parent=self.lemmatiseur )
<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_listener(self, event, callback, single=False, priority=1): """ Add a callback to an event list so it will be run at this event's firing. If single is True, the event is auto-removed after the first invocation. Priority can be used to jump ahead or behind other callback invocations."""
event_stack = self._events[event] event_stack.append({ "callback": callback, "single": single, "priority": priority }) event_stack.sort(key=lambda x: x['priority'])
<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_listener(self, event, callback, single=None, priority=None): """ Remove the event listener matching the same signature used for adding it. This will remove AT MOST one entry meeting the signature requirements. """
event_stack = self._events[event] for x in event_stack: if x['callback'] == callback and \ (single is None or x['single'] == single) and \ (priority is None or x['priority'] == priority): event_stack.remove(x) break else: raise KeyError('Listener not found for "%s": %s' % (event, callback))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fire_event(self, event, *args, **kwargs): """ Execute the listeners for this event passing any arguments along. """
remove = [] event_stack = self._events[event] for x in event_stack: x['callback'](*args, **kwargs) if x['single']: remove.append(x) for x in remove: event_stack.remove(x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Save last elapse time to self.records. """
self.elapse = time.clock() - self.st self.records.append(self.elapse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def display_all(self): """Print detailed information. """
print( ("total elapse %0.6f seconds, last elapse %0.6f seconds, " "took %s times measurement") % ( self.total_elapse, self.elapse, len(self.records)))
<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_cached(html_dump): """Parse html string from cached html files. Parameters html_dump : string HTML content Returns ------- translations : list Translations list. """
soup = BeautifulSoup(html_dump, "html.parser") translations = [] for trans in soup.find_all("div", class_="translation"): word = tuple(t.get_text() for t in trans.select("div.word > h2")) trans_list = [] for part in trans.find_all("div", class_="part-of-speech"): pn = part.find("p", class_="part-name") if pn: pn = pn.get_text().strip("[]") meanings = [] for meaning in part.find_all("div", class_="meaning"): m = [mn.get_text() for mn in meaning.select("li > span")] examples = [] for e in meaning.find_all("p"): examples.append([ex.get_text() for ex in e.find_all("span")]) meanings.append(Meaning(m, examples)) trans_list.append(PartOfSpeech(pn, meanings)) translations.append(Translation(word, trans_list)) return translations
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cache_lookup(word, data_dir, native=False): """Checks if word is in cache. Parameters word : str Word to check in cache. data_dir : pathlib.Path Cache directory location. Returns ------- translation : str or None Translation of given word. """
trans_dir = "translations" if native: trans_dir += "_native" logger.debug("Cache lookup: %s", word) filename = data_dir.joinpath(trans_dir, "{}.html".format(word)) if filename.is_file(): with open(filename, mode="r") as f: logger.debug("Cache found: %s", word) # TODO: not sure if we should parse data here translation = _parse_cached(f.read()) return translation logger.debug("Cache miss: %s", word) return 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 _get_words(data_dir): """Get list of words from history file. Parameters data_dir : pathlib.Path Directory where data is saved. Returns ------- word_list : list of str List of words. """
words_file = data_dir.joinpath("words.txt") word_list = [] if not words_file.is_file(): return word_list with open(words_file, mode="r") as f: for l in f: line = l.rstrip() word_list.append(line) return word_list
<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_to_history(word, data_dir): """Write word to history file. Parameters word : str Word to save to history. data_dir : pathlib.Path Directory where history file should be saved. data_dir and it's parent directories will be created if needed. """
if not data_dir.exists(): logger.debug("Creating DATA DIR: %s", data_dir.as_posix()) data_dir.mkdir(parents=True) if word not in _get_words(data_dir): with open(data_dir.joinpath("words.txt"), mode="a+") as f: logger.debug("Adding to history: %s", word) f.write(word + "\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 _create_html_file_content(translations): """Create html string out of translation dict. Parameters tralnslations : dict Dictionary of word translations. Returns ------- str: html string of translation """
content = [] for i1, t in enumerate(translations): if i1 > 0: content.append("<br>") content.append('<div class="translation">') content.append('<div class="word">') for w in t.word: content.append("<h2>{word}</h2>".format(word=w)) content.append("</div>") # end `word` for i2, t2 in enumerate(t.parts_of_speech): if i2 > 0: content.append("<br>") content.append('<div class="part-of-speech">') if t2.part is not None: content.append('<p class="part-name">[{part}]</p>'.format(part=t2.part)) content.append("<ol>") for m in t2.meanings: content.append('<div class="meaning">') mng = ["<strong><li>"] for i3, mn in enumerate(m.meaning): if i3 > 0: mng.append(", ") mng.append("<span>{meaning}</span>".format(meaning=mn)) mng.append("</li></strong>") content.append("".join(mng)) content.append('<div class="examples">') for e in m.examples: exmpl = "<p><span>{ex}</span>".format(ex=e[0]) if e[1]: exmpl += "<br><span>{tr}</span>".format(tr=e[1]) exmpl += "</p>" content.append(exmpl) content.append("</div>") # end `examples` content.append("</div>") # end `meaning` content.append("</ol>") content.append("</div>") # end `part-of-speech` content.append("</div>") # end `translation` return "\n".join(content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_html_file(word, translations, data_dir, native=False): """Create html file of word translations. Parameters word : str Word that was translated. tralnslations : dict Dictionary of word translations. data_dir : pathlib.Path Location where html files are saved. """
content_str = _create_html_file_content(translations) html_string = HTML_TEMPLATE.replace("{% word %}", word) html_string = html_string.replace("{% content %}", content_str) trans_dir = "translations" if native: trans_dir += "_native" translations_dir = data_dir.joinpath(trans_dir) fname = translations_dir.joinpath("{word}.html".format(word=word)) save_file(fname, html_string, mk_parents=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 _create_index_content(words): """Create html string of index file. Parameters words : list of str List of cached words. Returns ------- str html string. """
content = ["<h1>Index</h1>", "<ul>"] for word in words: content.append( '<li><a href="translations/{word}.html">{word}</a></li>'.format(word=word) ) content.append("</ul>") if not words: content.append("<i>Nothing to see here ...yet!</i>") return "\n".join(content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_index_file(data_dir): """Create index file of cached translations. Parameters data_dir : pathlib.Path Cache directory location. """
cached_words = [ w for w in _get_words(data_dir) if data_dir.joinpath("translations/{}.html".format(w)).is_file() ] content_str = _create_index_content(cached_words) html_string = HTML_TEMPLATE.replace("{% word %}", "Index") html_string = html_string.replace("{% content %}", content_str) filename = data_dir.joinpath("index.html") save_file(filename, html_string, mk_parents=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 save_file(filename, data, mk_parents=True): """Save file to disk. Paramaters filename : pathlib.Path Path to the file. data : str File contents. mk_parents : bool, optional If to create parent directories. """
parent = filename.parent if not parent.exists() and mk_parents: logger.debug("Creating directory: %s", parent.as_posix()) parent.mkdir(parents=True) with open(filename, mode="w") as f: logger.debug("Saving file: %s", filename.as_posix()) f.write(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 _lookup_online(word): """Look up word on diki.pl. Parameters word : str Word too look up. Returns ------- str website HTML content. """
URL = "https://www.diki.pl/{word}" HEADERS = { "User-Agent": ( "Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; " "Trident/7.0; rv:11.0) like Gecko" ) } logger.debug("Looking up online: %s", word) quoted_word = urllib.parse.quote(word) req = urllib.request.Request(URL.format(word=quoted_word), headers=HEADERS) with urllib.request.urlopen(req) as response: html_string = response.read().decode() return html.unescape(html_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 translate(word, config, use_cache=True, to_eng=False): """Translate a word. Parameters word : str Word to translate. config : Config Configuration settings. use_cache : bool, optional Wheter to use cache. to_eng : bool, optional Translate from Polish to English. Returns ------- translation Translation of a word. Raises ------ WordNotFound If word can't be found. """
translation = None data_dir = Path(config["data dir"]) if use_cache: logger.debug("Checking cache: %s", word) translation = _cache_lookup(word, data_dir, native=to_eng) if translation: return translation html_dump = _lookup_online(word) try: translation = _parse_html(html_dump, native=to_eng) except WordNotFound as exn: logger.error(str(exn)) raise exn _write_html_file(word, translation, data_dir, native=to_eng) if not to_eng: _save_to_history(word, data_dir) _write_index_file(data_dir) return translation
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def display_index(config): """Open index in web browser. Parameters config : Config Configuration settings. Raises ------ FileNotFoundError If index file doesn't exist. """
browser = config["web browser"].lower() data_dir = Path(config["data dir"]) if browser in webbrowser._browsers: b = webbrowser.get(browser) else: if browser != "default": logger.warning( "Couldn't find '%s' browser. Falling back to default.", browser ) b = webbrowser.get() index_file = data_dir.joinpath("index.html") if not index_file.exists(): logger.error("File doesn't exist: %s", index_file.as_posix()) raise FileNotFoundError("Index file doesn't exist") else: logger.info("Opening %s in '%s'", index_file.as_posix(), b.name) b.open(index_file.as_uri())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_text(translations, linewrap=0): """Pretty print translations. If linewrap is set to 0 disble line wrapping. Parameters translations : list List of word translations. linewrap : int Maximum line length before wrapping. """
# pylint: disable=too-many-locals def wrap(text, width=linewrap, findent=0, sindent=0, bold=False): if width == 0: text = " " * findent + text else: text = textwrap.fill( text, width=width, initial_indent=" " * findent, subsequent_indent=" " * sindent, ) # don't use bold when stdout is pipe or redirect if bold and sys.stdout.isatty(): text = "\033[0;1m" + text + "\033[0m" return text indent = 5 result = [] for i1, trans in enumerate(translations): if i1 > 0: result.append("\n") for w in trans.word: result.append(wrap(w, bold=True)) for i2, t in enumerate(trans.parts_of_speech): if i2 > 0: result.append("") if t.part: result.append("[{part}]".format(part=t.part)) for i3, m in enumerate(t.meanings, 1): if i3 > 1: result.append("") meaning = "{index:>3}. {meanings}".format( index=i3, meanings=", ".join(m.meaning) ) result.append(wrap(meaning, sindent=indent, bold=True)) eindent = indent + 1 for e in m.examples: result.append("") result.append(wrap(e[0], findent=eindent, sindent=eindent)) if len(e) == 2 and e[1]: result.append(wrap(e[1], findent=eindent, sindent=eindent + 1)) return "\n".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 read_config(self): """ Read config from a file. Invalid config values will be discarded and defaults used in their place. """
_config = self.config["dikicli"] # TODO: what if file doesn't exist? if self.config_file.is_file(): logger.debug("Reading config file: %s", self.config_file.as_posix()) with open(self.config_file, mode="r") as f: self.config.read_file(f) # DIKI_DATA_DIR should always take precedence if it's set if "DIKI_DATA_DIR" in os.environ: _config["data dir"] = DATA_DIR.as_posix() w = _config.get("linewrap") try: w = int(w) if w < 0: raise ValueError() except ValueError: logger.warning("Config: Invalid linewrap value. Using default.") _config["linewrap"] = self.default_config["linewrap"] c = _config.get("colors") if c.lower() not in ["yes", "no", "true", "false"]: logger.warning("Config: Invalid colors value. Using default.") _config["colors"] = self.default_config["colors"]
<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_default_config(self): """Write default config file to disk. Backs up existing configuration file. Returns ------- filename : string Path to config file. """
filename = self.config_file.as_posix() logger.info("Creating default config file: %s", filename) config_dir = self.config_file.parent if not config_dir.exists(): config_dir.mkdir(parents=True) if self.config_file.is_file(): backup = filename + ".old" logger.info("Saving config file backup at: %s", backup) shutil.copy(filename, backup) with open(self.config_file, mode="w") as f: config_string = CONFIG_TEMPLATE.format( data_dir=self.default_config["data dir"], linewrap=self.default_config["linewrap"], colors=self.default_config["colors"], browser=self.default_config["web browser"], ) f.write(config_string) return filename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def arc_length(start_a=[0.0], end_a=[0.0], radius=0.0): '''Return Euclidean length of arc. ''' assert isinstance(start_a, list) assert isinstance(end_a, list) l_angle = len(start_a) assert l_angle > 0 assert l_angle == len(end_a) for i in start_a: assert isinstance(i, float) assert abs(i) <= 2*pi for i in end_a: assert isinstance(i, float) assert abs(i) <= 2*pi assert isinstance(radius, float) # Allow negative radius full = pi * radius*2 diff = angle_diff(start_a, end_a, True) vec = [full * abs(d)/(2*pi) for d in diff] return sqrt(sum([v**2 for v in vec]))
<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_autopaginate(parser, token): """ Splits the arguments to the autopaginate tag and formats them correctly. """
split = token.split_contents() as_index = None context_var = None for i, bit in enumerate(split): if bit == 'as': as_index = i break if as_index is not None: try: context_var = split[as_index + 1] except IndexError: raise template.TemplateSyntaxError("Context variable assignment " + "must take the form of {%% %r object.example_set.all ... as " + "context_var_name %%}" % split[0]) del split[as_index:as_index + 2] if len(split) == 2: return AutoPaginateNode(split[1]) elif len(split) == 3: return AutoPaginateNode(split[1], paginate_by=split[2], context_var=context_var) elif len(split) == 4: try: orphans = int(split[3]) except ValueError: raise template.TemplateSyntaxError(u'Got %s, but expected integer.' % split[3]) return AutoPaginateNode(split[1], paginate_by=split[2], orphans=orphans, context_var=context_var) else: raise template.TemplateSyntaxError('%r tag takes one required ' + 'argument and one optional argument' % split[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 linebuffered_stdout(): """ Always line buffer stdout so pipes and redirects are CLI friendly. """
if sys.stdout.line_buffering: return sys.stdout orig = sys.stdout new = type(orig)(orig.buffer, encoding=orig.encoding, errors=orig.errors, line_buffering=True) new.mode = orig.mode return new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ignore_broken_pipe(): """ If a shellish program has redirected stdio it is subject to erroneous "ignored" exceptions during the interpretor shutdown. This essentially beats the interpretor to the punch by closing them early and ignoring any broken pipe exceptions. """
for f in sys.stdin, sys.stdout, sys.stderr: try: f.close() except BrokenPipeError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_last_nonce(app, key, nonce): """ This method is only an example! Replace it with a real nonce database. :param str key: the public key the nonce belongs to :param int nonce: the latest nonce """
if not hasattr(app, 'example_nonce_db'): # store nonces as a pair {key: lastnonce} app.example_nonce_db = {} if not key in app.example_nonce_db: app.example_nonce_db[key] = nonce return 0 else: oldnonce = copy.copy(app.example_nonce_db[key]) app.example_nonce_db[key] = nonce return oldnonce
<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_user_by_key(app, key): """ This method is only an example! Replace it with a real user database. :param str key: the public key the user belongs to """
if not hasattr(app, 'example_user_db'): app.example_user_db = {} if key in app.example_user_db: return app.example_user_db[key] return 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 load_jws_from_request(req): """ This function performs almost entirely bitjws authentication tasks. If valid bitjws message and signature headers are found, then the request will be assigned 'jws_header' and 'jws_payload' attributes. :param req: The flask request to load the jwt claim set from. """
current_app.logger.info("loading request with headers: %s" % req.headers) if (("content-type" in req.headers and "application/jose" in req.headers['content-type']) or ("Content-Type" in req.headers and "application/jose" in req.headers['Content-Type'])): path = urlparse.urlsplit(req.url).path for rule in current_app.url_map.iter_rules(): if path == rule.rule and req.method in rule.methods: dedata = req.get_data().decode('utf8') bp = current_app.bitjws.basepath req.jws_header, req.jws_payload = \ bitjws.validate_deserialize(dedata, requrl=bp + rule.rule) 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 load_user_from_request(req): """ Just like the Flask.login load_user_from_request If you need to customize the user loading from your database, the FlaskBitjws.get_user_by_key method is the one to modify. :param req: The flask request to load a user based on. """
load_jws_from_request(req) if not hasattr(req, 'jws_header') or req.jws_header is None or not \ 'iat' in req.jws_payload: current_app.logger.info("invalid jws request.") return None ln = current_app.bitjws.get_last_nonce(current_app, req.jws_header['kid'], req.jws_payload['iat']) if (ln is None or 'iat' not in req.jws_payload or req.jws_payload['iat'] * 1000 <= ln): current_app.logger.info("invalid nonce. lastnonce: %s" % ln) return None rawu = current_app.bitjws.get_user_by_key(current_app, req.jws_header['kid']) if rawu is None: return None current_app.logger.info("logging in user: %s" % rawu) return FlaskUser(rawu)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dumplist(args): """Dumps lists of files based on your criteria"""
from .query import Database db = Database() r = db.objects( protocol=args.protocol, purposes=args.purpose, model_ids=(args.client,), groups=args.group, classes=args.sclass ) output = sys.stdout if args.selftest: from bob.db.utils import null output = null() for f in r: output.write('%s\n' % (f.make_path(args.directory, args.extension),)) return 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 checkfiles(args): """Checks existence of files based on your criteria"""
from .query import Database db = Database() r = db.objects() # go through all files, check if they are available on the filesystem good = [] bad = [] for f in r: if os.path.exists(f.make_path(args.directory, args.extension)): good.append(f) else: bad.append(f) # report output = sys.stdout if args.selftest: from bob.db.utils import null output = null() if bad: for f in bad: output.write('Cannot find file "%s"\n' % (f.make_path(args.directory, args.extension),)) output.write('%d files (out of %d) were not found at "%s"\n' % \ (len(bad), len(r), args.directory)) return 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 reverse(args): """Returns a list of file database identifiers given the path stems"""
from .query import Database db = Database() output = sys.stdout if args.selftest: from bob.db.utils import null output = null() r = db.reverse(args.path) for f in r: output.write('%d\n' % f.id) if not r: return 1 return 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 path(args): """Returns a list of fully formed paths or stems given some file id"""
from .query import Database db = Database() output = sys.stdout if args.selftest: from bob.db.utils import null output = null() r = db.paths(args.id, prefix=args.directory, suffix=args.extension) for path in r: output.write('%s\n' % path) if not r: return 1 return 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 app_restart(cls): ''' Restart a frozen esky app Can also restart if the program is being run as a script passes restarted as an argument to the restarted app ''' logging.debug('In restarter') executable = sys.executable.split(os.sep)[-1] if os.name == 'nt': logging.info('executable is is %s' % executable) # restart works here when testing compiled version only if executable != 'python.exe': boot_strap_path = cls.esky_bootstrap_path() bootstrap_file = os.path.join(boot_strap_path, executable) logging.info('Bootstrap file for restart: %s' % bootstrap_file) subprocess.Popen( [os.path.join(bootstrap_file, bootstrap_file), 'restarted'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_client(self, host, port=5001, protocol='TCP', timeout=5, parallel=None, bandwidth=None): """iperf -D -c host -t 60 """
cmd = ['iperf', '-c', host, '-p', str(port), '-t', str(timeout)] if not (protocol, 'UDP'): cmd.append('-u') if parallel: cmd.extend(['-P', str(parallel)]) if bandwidth: cmd.extend(['-b', '%sM' % bandwidth]) stdcode, stdout, stderr = utils.execute_wait(cmd) if (not stdcode) or (not stderr): out_dict = stdout.split('\n') if not out_dict[-1]: out_dict.pop() out_data = out_dict[-1].split() data = dict() data['Bandwidth'] = out_data[-2] + ' ' + out_data[-1] data['Transfer'] = out_data[-4] + ' ' + out_data[-3] data['Interval'] = out_data[-6] return data raise Exception('Start iperf failed, please check on the node.')
<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_language_database(): ''' Return the language to be used to search the database contents ''' lang = None language = get_language() if language: for x in settings.LANGUAGES_DATABASES: if x.upper() == language.upper(): lang = language break if lang is None: lang = settings.LANGUAGES_DATABASES[0] return lang.lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def df_string(df, percentage_columns=(), format_map=None, **kwargs): """Return a nicely formatted string for the given dataframe. Arguments --------- df : pandas.DataFrame A dataframe object. percentage_columns : iterable A list of cloumn names to be displayed with a percentage sign. Returns ------- str A nicely formatted string for the given dataframe. Example ------- num char 1 8 a 2 5 b """
formatters_map = {} for col, dtype in df.dtypes.iteritems(): if col in percentage_columns: formatters_map[col] = '{:,.2f} %'.format elif dtype == 'float64': formatters_map[col] = '{:,.2f}'.format if format_map: for key in format_map: formatters_map[key] = format_map[key] return df.to_string(formatters=formatters_map, **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 big_dataframe_setup(): # pragma: no cover """Sets pandas to display really big data frames."""
pd.set_option('display.max_colwidth', sys.maxsize) pd.set_option('max_colwidth', sys.maxsize) # height has been deprecated. # pd.set_option('display.height', sys.maxsize) pd.set_option('display.max_rows', sys.maxsize) pd.set_option('display.width', sys.maxsize) pd.set_option('display.colheader_justify', 'center') pd.set_option('display.column_space', sys.maxsize) pd.set_option('display.max_seq_items', sys.maxsize) pd.set_option('display.expand_frame_repr', 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 df_to_html(df, percentage_columns=None): # pragma: no cover """Return a nicely formatted HTML code string for the given dataframe. Arguments --------- df : pandas.DataFrame A dataframe object. percentage_columns : iterable A list of cloumn names to be displayed with a percentage sign. Returns ------- str A nicely formatted string for the given dataframe. """
big_dataframe_setup() try: res = '<br><h2> {} </h2>'.format(df.name) except AttributeError: res = '' df.style.set_properties(**{'text-align': 'center'}) res += df.to_html(formatters=_formatters_dict( input_df=df, percentage_columns=percentage_columns )) res += '<br>' 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 All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """
@wraps(All) def built(value): for validator in validators: value = validator(value) return value return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Any(*validators): """ Combines all the given validator callables into one, running the given value through them in sequence until a valid result is given. """
@wraps(Any) def built(value): error = None for validator in validators: try: return validator(value) except Error as e: error = e raise error return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Maybe(validator): """ Wraps the given validator callable, only using it for the given value if it is not ``None``. """
@wraps(Maybe) def built(value): if value != None: return validator(value) return built