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 status(self, status_id, raise_exception_on_failure=False): """Return the status of the generation job."""
query = {"output": "json", "user_credentials": self.api_key} resp = requests.get( "%sstatus/%s" % (self._url, status_id), params=query, timeout=self._timeout ) if raise_exception_on_failure and resp.status_code != 200: raise DocumentStatusFailure(resp.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 download(self, download_key, raise_exception_on_failure=False): """Download the file represented by the download_key."""
query = {"output": "json", "user_credentials": self.api_key} resp = requests.get( "%sdownload/%s" % (self._url, download_key), params=query, timeout=self._timeout, ) if raise_exception_on_failure and resp.status_code != 200: raise Documen...
<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_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[Any], logger: Logger) -> Dict[str, Any]: """ Simply inspects the...
# nb of file children n_children = len(obj_on_fs.get_multifile_children()) # first extract base collection type subtypes, key_type = _extract_collection_base_type(desired_type) if isinstance(subtypes, tuple): # -- check the tuple length if n_children !=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_stat_summary(df, fig=None): ''' Plot stats grouped by test capacitor load _and_ frequency. In other words, we calculate the mean of all samples in the data frame for each test capacitance and frequency pairing, plotting the following stats: - Root mean squared error - Coefficien...
<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_manifest(raw_manifest, namespace=None, **kwargs): """ wrapper method which generates the manifest from various sources """
if isinstance(raw_manifest, configparser.RawConfigParser): return Manifest(raw_manifest) manifest = create_configparser() if not manifest.has_section('config'): manifest.add_section('config') _load_manifest_interpret_source(manifest, raw_manifest, ...
<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_manifest_from_url(manifest, url, verify_certificate=True, username=None, password=None): """ load a url body into a manifest """
try: if username and password: manifest_file_handler = StringIO(lib.authenticated_get(username, password, url, verify=verify_certificate).decode("utf-8")) else: manifest_file_handler = StringIO(lib.cleaned_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 _load_manifest_from_file(manifest, path): """ load manifest from file """
path = os.path.abspath(os.path.expanduser(path)) if not os.path.exists(path): raise ManifestException("Manifest does not exist at {0}!".format(path)) manifest.read(path) if not manifest.has_option('config', 'source'): manifest.set('config', 'source', str(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 formula_sections(self): """ Return all sections related to a formula, re-ordered according to the "depends" section. """
if self.dtree is not None: return self.dtree.order else: return [s for s in self.manifest.sections() if s != "config"]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_affirmative(self, section, option): """ Return true if the section option combo exists and it is set to a truthy value. """
return self.has_option(section, option) and \ lib.is_affirmative(self.get(section, option))
<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(self, file_handle): """ write the current state to a file manifest """
for k, v in self.inputs.write_values().items(): self.set('config', k, v) self.set('config', 'namespace', self.namespace) self.manifest.write(file_handle)
<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_context_dict(self): """ return a context dict of the desired state """
context_dict = {} for s in self.sections(): for k, v in self.manifest.items(s): context_dict["%s:%s" % (s, k)] = v for k, v in self.inputs.values().items(): context_dict["config:{0}".format(k)] = v context_dict.update(self.additional_context_varia...
<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, section, key, default=MANIFEST_NULL_KEY): """ Returns the value if it exist, or default if default is set """
if not self.manifest.has_option(section, key) and default is not MANIFEST_NULL_KEY: return default return self.manifest.get(section, 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 __parse_namespace(self): """ Parse the namespace from various sources """
if self.manifest.has_option('config', 'namespace'): return self.manifest.get('config', 'namespace') elif self.manifest.has_option('config', 'source'): return NAMESPACE_REGEX.search(self.manifest.get('config', 'source')).groups()[0] else: logger.warn('Could no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __generate_dependency_tree(self): """ Generate the dependency tree object """
dependency_dict = {} for s in self.manifest.sections(): if s != "config": if self.manifest.has_option(s, 'depends'): dependency_list = [d.strip() for d in re.split('\n|,', self.manifest.get(s, 'depends'))] dependency_dict[s] = dependen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __substitute_objects(self, value, context_dict): """ recursively substitute value with the context_dict """
if type(value) == dict: return dict([(k, self.__substitute_objects(v, context_dict)) for k, v in value.items()]) elif type(value) == str: try: return value % context_dict except KeyError: e = sys.exc_info()[1] logger.wa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __setup_inputs(self): """ Setup the inputs object """
input_object = Inputs() # populate input schemas for s in self.manifest.sections(): if self.has_option(s, 'inputs'): input_object.add_inputs_from_inputstring(self.get(s, 'inputs')) # add in values for k, v in self.items('config'): if input...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def should_run(self): """ Returns true if the feature should run """
should_run = True config = self.target or self.source if config.has('systems'): should_run = False valid_systems = [s.lower() for s in config.get('systems').split(",")] for system_type, param in [('is_osx', 'osx'), ('is_...
<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(self): """ Resolve differences between the target and the source configuration """
if self.source and self.target: for key in self.source.keys(): if (key not in self.dont_carry_over_options and not self.target.has(key)): self.target.set(key, self.source.get(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 _log_error(self, message): """ Log an error for the feature """
key = (self.feature_name, self.target.get('formula')) self.environment.log_feature_error(key, "ERROR: " + message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jinja_fragment_extension(tag, endtag=None, name=None, tag_only=False, allow_args=True, callblock_args=None): """Decorator to easily create a jinja extension ...
if endtag is None: endtag = "end" + tag def decorator(f): def parse(self, parser): lineno = parser.stream.next().lineno args = [] kwargs = [] if allow_args: args, kwargs = parse_block_signature(parser) call = self.cal...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jinja_block_as_fragment_extension(name, tagname=None, classname=None): """Creates a fragment extension which will just act as a replacement of the block stat...
if tagname is None: tagname = name if classname is None: classname = "%sBlockFragmentExtension" % name.capitalize() return type(classname, (BaseJinjaBlockAsFragmentExtension,), { "tags": set([tagname]), "end_tag": "end" + tagname, "block_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 find_copies(input_dir, exclude_list): """ find files that are not templates and not in the exclude_list for copying from template to image """
copies = [] def copy_finder(copies, dirname): for obj in os.listdir(dirname): pathname = os.path.join(dirname, obj) if os.path.isdir(pathname): continue if obj in exclude_list: continue if obj.endswith('.mustache'): ...
<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_devices(self, refresh=False, generic_type=None): """Get all devices from Lupusec."""
_LOGGER.info("Updating all devices...") if refresh or self._devices is None: if self._devices is None: self._devices = {} responseObject = self.get_sensors() if (responseObject and not isinstance(responseObject, (tuple, 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 parse_from_dict(json_dict): """ Given a Unified Uploader message, parse the contents and return a MarketHistoryList instance. :param dict json_dict: A Unifie...
history_columns = json_dict['columns'] history_list = MarketHistoryList( upload_keys=json_dict['uploadKeys'], history_generator=json_dict['generator'], ) for rowset in json_dict['rowsets']: generated_at = parse_datetime(rowset['generatedAt']) region_id = rowset['region...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_to_json(history_list): """ Encodes this MarketHistoryList instance to a JSON string. :param MarketHistoryList history_list: The history instance to se...
rowsets = [] for items_in_region_list in history_list._history.values(): region_id = items_in_region_list.region_id type_id = items_in_region_list.type_id generated_at = gen_iso_datetime_str(items_in_region_list.generated_at) rows = [] for entry in items_in_region_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 load(self, configuration): """ Load a YAML configuration file. :param configuration: Configuration filename or YAML string """
try: self.config = yaml.load(open(configuration, "rb")) except IOError: try: self.config = yaml.load(configuration) except ParserError, e: raise ParserError('Error parsing config: %s' % e) # put customer data into self.custome...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def instances(self, test_type=".*"): """ Returns a dict of all instances defined using a regex :param test_type: Regular expression to match for self.instance['t...
import re data = {} for k, v in self.instances_dict.iteritems(): if re.match(test_type, v.get('test_type'), re.IGNORECASE): if 'filter_type' in v: hostfilter = { 'filtertype': v['filter_type'], 'cont...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def none_to_blank(s, exchange=''): """Replaces NoneType with '' '' '' u'something' [u'1', ''] :param s: String to replace :para exchange: Character to return for...
if isinstance(s, list): return [none_to_blank(z) for y, z in enumerate(s)] return exchange if s is None else unicode(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_good_url(url=None, addition="/"): """Appends addition to url, ensuring the right number of slashes exist and the path doesn't get clobbered. 'http://www...
if url is None: return None if isinstance(url, str) and isinstance(addition, str): return "%s/%s" % (url.rstrip('/'), addition.lstrip('/')) else: 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 build_kvasir_url( proto="https", server="localhost", port="8443", base="Kvasir", user="test", password="test", path=KVASIR_JSONRPC_PATH): """ Creates a full ...
uri = proto + '://' + user + '@' + password + '/' + server + ':' + port + '/' + base return make_good_url(uri, 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 get_default(parser, section, option, default): """helper to get config settings with a default if not present"""
try: result = parser.get(section, option) except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): result = default 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 set_db_application_prefix(prefix, sep=None): """Set the global app prefix and separator."""
global _APPLICATION_PREFIX, _APPLICATION_SEP _APPLICATION_PREFIX = prefix if (sep is not None): _APPLICATION_SEP = sep
<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_index(self, cls, index_name, value): """Find records matching index query - defer to backend."""
return self.backend.find_by_index(cls, index_name, 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 humanTime(seconds): ''' Convert seconds to something more human-friendly ''' intervals = ['days', 'hours', 'minutes', 'seconds'] x = deltaTime(seconds=seconds) return ' '.join('{} {}'.format(getattr(x, k), k) for k in intervals if getattr(x, k))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def humanTimeConverter(): ''' Cope whether we're passed a time in seconds on the command line or via stdin ''' if len(sys.argv) == 2: print humanFriendlyTime(seconds=int(sys.argv[1])) else: for line in sys.stdin: print humanFriendlyTime(int(line)) sys.exit(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 train(self, data, **kwargs): """ Calculate the standard deviations and means in the training data """
self.data = data for i in xrange(0,data.shape[1]): column_mean = np.mean(data.icol(i)) column_stdev = np.std(data.icol(i)) #Have to do += or "list" type will fail (ie with append) self.column_means += [column_mean] self.column_stdevs += [colu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict(self, test_data, **kwargs): """ Adjust new input by the values in the training data """
if test_data.shape[1]!=self.data.shape[1]: raise Exception("Test data has different number of columns than training data.") for i in xrange(0,test_data.shape[1]): test_data.loc[:,i] = test_data.icol(i) - self.column_means[i] if int(self.column_stdevs[i])!=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 action_decorator(name): """Decorator to register an action decorator """
def decorator(cls): action_decorators.append((name, cls)) return cls 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 load_global_config(config_path): """ Load a global configuration object, and query for any required variables along the way """
config = configparser.RawConfigParser() if os.path.exists(config_path): logger.debug("Checking and setting global parameters...") config.read(config_path) else: _initial_run() logger.info("Unable to find a global sprinter configuration!") logger.info("Creating one no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_global_config(global_config): """ print the global configuration """
if global_config.has_section('shell'): print("\nShell configurations:") for shell_type, set_value in global_config.items('shell'): print("{0}: {1}".format(shell_type, set_value)) if global_config.has_option('global', 'env_source_rc'): print("\nHave sprinter env source rc: {...
<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(): """ Create a default configuration object, with all parameters filled """
config = configparser.RawConfigParser() config.add_section('global') config.set('global', 'env_source_rc', False) config.add_section('shell') config.set('shell', 'bash', "true") config.set('shell', 'zsh', "true") config.set('shell', 'gui', "true") return config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _initial_run(): """ Check things during the initial setting of sprinter's global config """
if not system.is_officially_supported(): logger.warn(warning_template + "===========================================================\n" + "Sprinter is not officially supported on {0}! Please use at your own risk.\n\n".format(system.operating_system()) ...
<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_shell(config): """ Checks and queries values for the shell """
config.has_section('shell') or config.add_section('shell') logger.info( "What shells or environments would you like sprinter to work with?\n" "(Sprinter will not try to inject into environments not specified here.)\n" "If you specify 'gui', sprinter will attempt to inject it's state int...
<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_env_source_rc(config): """ Configures wether to have .env source .rc """
config.set('global', 'env_source_rc', False) if system.is_osx(): logger.info("On OSX, login shells are default, which only source sprinter's 'env' configuration.") logger.info("I.E. environment variables would be sourced, but not shell functions " + "or terminal status lines...
<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_members(self): """Return all members in the group as CSHMember objects"""
res = self.__con__.search_s( self.__ldap_base_dn__, ldap.SCOPE_SUBTREE, "(memberof=%s)" % self.__dn__, ['uid']) ret = [] for val in res: val = val[1]['uid'][0] try: ret.append(val.decode('ut...
<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_member(self, member, dn=False): """Check if a Member is in the bound group. Arguments: member -- the CSHMember object (or distinguished name) of the me...
if dn: res = self.__con__.search_s( self.__dn__, ldap.SCOPE_BASE, "(member=%s)" % dn, ['ipaUniqueID']) else: res = self.__con__.search_s( self.__dn__, ldap.SC...
<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_member(self, member, dn=False): """Add a member to the bound group Arguments: member -- the CSHMember object (or distinguished name) of the member Keywor...
if dn: if self.check_member(member, dn=True): return mod = (ldap.MOD_ADD, 'member', member.encode('ascii')) else: if self.check_member(member): return mod = (ldap.MOD_ADD, 'member', member.get_dn().encode('ascii')) ...
<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_object_from_yaml(desired_type: Type[Any], file_object: TextIOBase, logger: Logger, fix_imports: bool = True, errors: str = 'strict', *args, **kwargs) -> ...
return yaml.load(file_object)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_collection_from_yaml(desired_type: Type[Any], file_object: TextIOBase, logger: Logger, conversion_finder: ConversionFinder, fix_imports: bool = True, err...
res = yaml.load(file_object) # convert if required return ConversionFinder.convert_collection_values_according_to_pep(res, desired_type, conversion_finder, logger, **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 pass_feature(*feature_names): """Injects a feature instance into the kwargs """
def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): for name in feature_names: kwargs[name] = feature_proxy(name) return f(*args, **kwargs) return wrapper 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 extract_tar(url, target_dir, additional_compression="", remove_common_prefix=False, overwrite=False): """ extract a targz and install to the target directory...
try: if not os.path.exists(target_dir): os.makedirs(target_dir) tf = tarfile.TarFile.open(fileobj=download_to_bytesio(url)) if not os.path.exists(target_dir): os.makedirs(target_dir) common_prefix = os.path.commonprefix(tf.getnames()) if not common_pr...
<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_path(target_path): """ Delete the target path """
if os.path.isdir(target_path): shutil.rmtree(target_path) else: os.unlink(target_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, obj, id_code): """ Save an object, and use id_code in the filename obj - any object id_code - unique identifier """
filestream = open('{0}/{1}'.format(self.data_path, id_code), 'w+') pickle.dump(obj, filestream) filestream.close()
<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, id_code): """ Loads a workflow identified by id_code id_code - unique identifier, previously must have called save with same id_code """
filestream = open('{0}/{1}'.format(self.data_path, id_code), 'rb') workflow = pickle.load(filestream) return workflow
<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_object_from_pickle(desired_type: Type[T], file_path: str, encoding: str, fix_imports: bool = True, errors: str = 'strict', *args, **kwargs) -> Any: """ P...
import pickle file_object = open(file_path, mode='rb') try: return pickle.load(file_object, fix_imports=fix_imports, encoding=encoding, errors=errors) finally: file_object.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def should_display_warnings_for(to_type): """ Central method where we control whether warnings should be displayed """
if not hasattr(to_type, '__module__'): return True elif to_type.__module__ in {'builtins'} or to_type.__module__.startswith('parsyfiles') \ or to_type.__name__ in {'DataFrame'}: return False elif issubclass(to_type, int) or issubclass(to_type, str) \ or issubclass(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 print_dict(dict_name, dict_value, logger: Logger = None): """ Utility method to print a named dictionary :param dict_name: :param dict_value: :return: """
if logger is None: print(dict_name + ' = ') try: from pprint import pprint pprint(dict_value) except: print(dict_value) else: logger.info(dict_name + ' = ') try: from pprint import pformat logger.info(pformat(di...
<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_able_to_parse_detailed(self, desired_type: Type[Any], desired_ext: str, strict: bool): """ Explicitly declare that we are not able to parse collections :p...
if not _is_valid_for_dict_to_object_conversion(strict, None, None if desired_type is JOKER else desired_type): return False, None else: return super(MultifileObjectParser, self).is_able_to_parse_detailed(desired_type, desired_ext, strict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parsyfiles_global_config(multiple_errors_tb_limit: int = None, full_paths_in_logs: bool = None, dict_to_object_subclass_limit: int = None): """ This is the m...
if multiple_errors_tb_limit is not None: GLOBAL_CONFIG.multiple_errors_tb_limit = multiple_errors_tb_limit if full_paths_in_logs is not None: GLOBAL_CONFIG.full_paths_in_logs = full_paths_in_logs if dict_to_object_subclass_limit is not None: GLOBAL_CONFIG.dict_to_object_subclass_lim...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid(self, context): """Checks through the previous_actions iterable if required actions have been executed """
if self.requires: for r in self.requires: if not r in context.executed_actions: raise RequirementMissingError("Action '%s' requires '%s'" % (self.name, r)) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_file_contents(file_path): """Get the context of the file using full path name"""
full_path = os.path.join(package_dir, file_path) return open(full_path, 'r').read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(self): """Refresh a device"""
# new_device = {} if self.type in CONST.BINARY_SENSOR_TYPES: response = self._lupusec.get_sensors() for device in response: if device['device_id'] == self._device_id: self.update(device) return device elif self.type == 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 desc(self): """Get a short description of the device."""
return '{0} (ID: {1}) - {2} - {3}'.format( self.name, self.device_id, self.type, self.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 list(declared, undeclared): """List configured queues."""
queues = current_queues.queues.values() if declared: queues = filter(lambda queue: queue.exists, queues) elif undeclared: queues = filter(lambda queue: not queue.exists, queues) queue_names = [queue.routing_key for queue in queues] queue_names.sort() for queue in queue_names: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def declare(queues): """Initialize the given queues."""
current_queues.declare(queues=queues) click.secho( 'Queues {} have been declared.'.format( queues or current_queues.queues.keys()), fg='green' )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def purge_queues(queues=None): """Purge the given queues."""
current_queues.purge(queues=queues) click.secho( 'Queues {} have been purged.'.format( queues or current_queues.queues.keys()), fg='green' )
<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_queue(queues): """Delete the given queues."""
current_queues.delete(queues=queues) click.secho( 'Queues {} have been deleted.'.format( queues or current_queues.queues.keys()), fg='green' )
<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_needed_formatter(input_format, output_format): """ Find a data formatter given an input and output format input_format - needed input format. see utils....
#Only take the formatters in the registry selected_registry = [re.cls for re in registry if re.category==RegistryCategories.formatters] needed_formatters = [] for formatter in selected_registry: #Initialize the formatter (needed so it can discover its formats) formatter_inst = formatter...
<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_needed_input(input_format): """ Find a needed input class input_format - needed input format, see utils.input.dataformats """
needed_inputs = [re.cls for re in registry if re.category==RegistryCategories.inputs and re.cls.input_format == input_format] if len(needed_inputs)>0: return needed_inputs[0] 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 exists_in_registry(category, namespace, name): """ See if a given category, namespace, name combination exists in the registry category - See registrycategor...
selected_registry = [re for re in registry if re.category==category and re.namespace==namespace and re.name == name] if len(selected_registry)>0: 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 register(cls): """ Register a given model in the registry """
registry_entry = RegistryEntry(category = cls.category, namespace = cls.namespace, name = cls.name, cls=cls) if registry_entry not in registry and not exists_in_registry(cls.category, cls.namespace, cls.name): registry.append(registry_entry) else: log.warn("Class {0} already in registry".fo...
<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_fields(self): """ Initialize the fields for data caching. """
self.fields = [] self.required_input = [] for member_name, member_object in inspect.getmembers(self.__class__): if inspect.isdatadescriptor(member_object) and not member_name.startswith("__"): self.fields.append(member_name) if member_object.required_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subscriber(address,topics,callback,message_type): """ Creates a subscriber binding to the given address and subscribe the given topics. The callback is invok...
return Subscriber(address,topics,callback,message_type)
<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(self): """ Start a thread that consumes the messages and invokes the callback """
t=threading.Thread(target=self._consume) t.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_forecast_api(self, longitude: str, latitude: str) -> {}: """gets data from API"""
api_url = APIURL_TEMPLATE.format(longitude, latitude) response = urlopen(api_url) data = response.read().decode('utf-8') json_data = json.loads(data) return json_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def async_get_forecast_api(self, longitude: str, latitude: str) -> {}: """gets data from API asyncronious"""
api_url = APIURL_TEMPLATE.format(longitude, latitude) if self.session is None: self.session = aiohttp.ClientSession() async with self.session.get(api_url) as response: if response.status != 200: raise SmhiForecastException( ...
<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(iterable = None, *, name = None, metric = call_default): """Measure total time and item count for consuming an iterable :arg iterable: any iterable :arg ...
if iterable is None: return _iter_decorator(name, metric) else: return _do_all(iterable, name, metric)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def each(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce each item of an iterable :arg iterable: any iterable :arg fu...
if iterable is None: return _each_decorator(name, metric) else: return _do_each(iterable, name, metric)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def first(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg ...
if iterable is None: return _first_decorator(name, metric) else: return _do_first(iterable, name, metric)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reducer(*, name = None, metric = call_default): """Decorator to measure a function that consumes many items. The wrapped ``func`` should take either a single...
class instrument_reducer_decorator(object): def __init__(self, func): self.orig_func = func self.wrapping = wraps(func) self.metric_name = name if name is not None else func.__module__ + '.' +func.__name__ self.varargs = inspect.getargspec(func).varargs is no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def producer(*, name = None, metric = call_default): """Decorator to measure a function that produces many items. The function should return an object that suppo...
def wrapper(func): def instrumenter(name_, *args, **kwargs): t = time.time() try: ret = func(*args, **kwargs) except Exception: # record a metric for other exceptions, than raise metric(name_, 0, time.time() - t) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block(*, name = None, metric = call_default, count = 1): """Context manager to measure execution time of a block :arg function metric: f(name, 1, time) :arg ...
t = time.time() try: yield finally: metric(name, count, time.time() - t)
<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_package_manager(self): """ Installs and verifies package manager """
package_manager = "" args = "" sudo_required = True if system.is_osx(): package_manager = "brew" sudo_required = False args = " install" elif system.is_debian(): package_manager = "apt-get" args = " -y install" ...
<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(self, data, doctype): ''' Parse an input string, and return an AST doctype must have WCADocument as a baseclass ''' self.doctype = doctype self.lexer.lineno = 0 del self.errors[:] del self.warnings[:] self.lexer.lexerror = False 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 p_error(self, elem): '''Handle syntax error''' self.errors.append("Syntax error on line " + str(self.lexer.lineno) + ". Got unexpected token " + elem.type)
<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_progress_brackets(self, start, end): """Set brackets to set around a progress bar."""
self.sep_start = start self.sep_end = end
<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_progress(self, width): """Create the formatted string that displays the progress."""
chunk_widths = self._get_chunk_sizes(width) progress_chunks = [chunk.format_chunk(chunk_width) for (chunk, chunk_width) in zip(self._progress_chunks, chunk_widths)] return "{sep_start}{progress}{sep_end}".format( sep_start=self.s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def summary_width(self): """Calculate how long a string is needed to show a summary string. This is not simply the length of the formatted summary string since t...
chunk_counts = [chunk.count for chunk in self._progress_chunks] numbers_width = sum(max(1, ceil(log10(count + 1))) for count in chunk_counts) separators_with = len(chunk_counts) - 1 return numbers_width + separators_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 format_summary(self): """Generate a summary string for the progress bar."""
chunks = [chunk.format_chunk_summary() for chunk in self._progress_chunks] return "/".join(chunks)
<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_status(self, width=None, label_width=None, progress_width=None, summary_width=None): """Generate the formatted status bar string."""
if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] if label_width is None: label_width = len(self.label) if summary_width is None: summary_width = self.summary_width() if progress_width is None: progress_width = w...
<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_status_line(self, label): """Add a status bar line to the table. This function returns the status bar and it can be modified from this return value. """
status_line = StatusBar(label, self._sep_start, self._sep_end, self._fill_char) self._lines.append(status_line) return status_line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_field_widths(self, width=None, min_label_width=10, min_progress_width=10): """Calculate how wide each field should be so we can align them. We alwa...
if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] summary_width = self.summary_width() label_width = self.label_width() remaining = width - summary_width - label_width - 2 if remaining >= min_progress_width: progress_width = 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 format_table(self, width=None, min_label_width=10, min_progress_width=10): """Format the entire table of progress bars. The function first computes the width...
# handle the special case of an empty table. if len(self._lines) == 0: return [] if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] labelw, progw, summaryw = self.calculate_field_widths( width=width, min_label_wi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_log_dict(request, response): """ Create a dictionary with logging data. """
remote_addr = request.META.get('REMOTE_ADDR') if remote_addr in getattr(settings, 'INTERNAL_IPS', []): remote_addr = request.META.get( 'HTTP_X_FORWARDED_FOR') or remote_addr user_email = "-" if hasattr(request, 'user'): user_email = getattr(request.user, 'email', '-') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_log_message(log_dict, use_sql_info=False, fmt=True): """ Create the logging message string. """
log_msg = ( "%(remote_address)s %(user_email)s %(method)s %(url)s %(status)d " "%(content_length)d (%(request_time).2f seconds)" ) if use_sql_info: sql_time = sum( float(q['time']) for q in connection.queries) * 1000 extra_log = { 'nr_queries': len(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 process_response(self, request, response): """ Create the logging message.. """
try: log_dict = create_log_dict(request, response) # add the request time to the log_dict; if no start time is # available, use -1 as NA value request_time = ( time.time() - self.start_time if hasattr(self, 'start_time') and 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 as_completed(jobs): ''' Generator function that yields the jobs in order of their completion. Attaches a new listener to each job. ''' jobs = tuple(jobs) event = threading.Event() callback = lambda f, ev: event.set() [job.add_listener(Job.SUCCESS, callback, once=True) for job in jobs] [job.add_listen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reraise(tpe, value, tb=None): " Reraise an exception from an exception info tuple. " Py3 = (sys.version_info[0] == 3) if value is None: value = tpe() if Py3: if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: exec('raise tpe, value, tb')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finished(self): """ True if the job run and finished. There is no difference if the job finished successfully or errored. """
return self.__state in (Job.ERROR, Job.SUCCESS, Job.CANCELLED)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _trigger_event(self, event): """ Private. Triggers and event and removes all one-off listeners for that event. """
if event is None or event not in self.__listeners: raise ValueError('invalid event type: {0!r}'.format(event)) # Check the event has not already been triggered, then mark # the event as triggered. if event in self.__event_set: raise RuntimeError('event already triggered: {0!r}'.format(eve...