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 prune_dupes(self): """Remove all but the last entry for a given resource URI. Returns the number of entries removed. Also removes all entries for a given URI...
n = 0 pruned1 = [] seen = set() deletes = {} for r in reversed(self.resources): if (r.uri in seen): n += 1 if (r.uri in deletes): deletes[r.uri] = r.change else: pruned1.append(r) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _str_datetime_now(self, x=None): """Return datetime string for use with time attributes. Handling depends on input: 'now' - returns datetime for now number -...
if (x == 'now'): # Now, this is wht datetime_to_str() with no arg gives return(datetime_to_str()) try: # Test for number junk = x + 0.0 return datetime_to_str(x) except TypeError: # Didn't look like a number, treat as strin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map(self, width, height): """ Creates and returns a new randomly generated map """
template = ti.load(os.path.join(script_dir, 'assets', 'template.tmx'))['map0'] #template.set_view(0, 0, template.px_width, template.px_height) template.set_view(0, 0, width*template.tw, height*template.th) # TODO: Save the generated map. #epoch = int(time.time()) #filen...
<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_node_dict(outer_list, sort="zone"): """Convert node data from nested-list to sorted dict."""
raw_dict = {} x = 1 for inner_list in outer_list: for node in inner_list: raw_dict[x] = node x += 1 if sort == "name": # sort by provider - name srt_dict = OrderedDict(sorted(raw_dict.items(), key=lambda k: (k[1].cloud, k[1].name.l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_read(): """Read config info from config file."""
config_file = (u"{0}config.ini".format(CONFIG_DIR)) if not os.path.isfile(config_file): config_make(config_file) config = configparser.ConfigParser(allow_no_value=True) try: config.read(config_file, encoding='utf-8') except IOError: print("Error reading config file: {}".form...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_prov(config): """Read providers from configfile and de-duplicate it."""
try: providers = [e.strip() for e in (config['info'] ['providers']).split(',')] except KeyError as e: print("Error reading config item: {}".format(e)) sys.exit() providers = list(OrderedDict.fromkeys(providers)) return providers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_cred(config, providers): """Read credentials from configfile."""
expected = ['aws', 'azure', 'gcp', 'alicloud'] cred = {} to_remove = [] for item in providers: if any(item.startswith(itemb) for itemb in expected): try: cred[item] = dict(list(config[item].items())) except KeyError as e: print("No credent...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_make(config_file): """Create config.ini on first use, make dir and copy sample."""
from pkg_resources import resource_filename import shutil if not os.path.exists(CONFIG_DIR): os.makedirs(CONFIG_DIR) filename = resource_filename("mcc", "config.ini") try: shutil.copyfile(filename, config_file) except IOError: print("Error copying sample config file: {}"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hash(self): """Provide access to the complete hash string. The hash string may have zero or more hash values with appropriate prefixes. All hash values are a...
hashvals = [] if (self.md5 is not None): hashvals.append('md5:' + self.md5) if (self.sha1 is not None): hashvals.append('sha-1:' + self.sha1) if (self.sha256 is not None): hashvals.append('sha-256:' + self.sha256) if (len(hashvals) > 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 hash(self, hash): """Parse space separated set of values. See specification at: http://tools.ietf.org/html/draft-snell-atompub-link-extensions-09 which defin...
self.md5 = None self.sha1 = None self.sha256 = None if (hash is None): return hash_seen = set() errors = [] for entry in hash.split(): (hash_type, value) = entry.split(':', 1) if (hash_type in hash_seen): errors...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def link_add(self, rel, href, **atts): """Create an link with specified rel. Will add a link even if one with that rel already exists. """
self.link_set(rel, href, allow_duplicates=True, **atts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equal(self, other, delta=0.0): """Equality or near equality test for resources. Equality means: 1. same uri, AND 2. same timestamp WITHIN delta if specified ...
if (other is None): return False if (self.uri != other.uri): return(False) if (self.timestamp is not None or other.timestamp is not None): # not equal if only one timestamp specified if (self.timestamp is None or other.timestam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ChiSquared(target_frequency): """Score a text by comparing its frequency distribution against another. Note: It is easy to be penalised without knowing it wh...
def inner(text): text = ''.join(text) return -chi_squared(frequency_analyze(text), target_frequency) return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def my_resource_list(): """Simulate the generator used by simulator"""
rl = ResourceList( resources=iter(my_resources), count=len(my_resources) ) rl.max_sitemap_entries = max_sitemap_entries return(rl)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, resource, replace=False): """Add a single resource, check for dupes."""
uri = resource.uri for r in self: if (uri == r.uri): if (replace): r = resource return else: raise ResourceListDupeError( "Attempt to add resource already in resource_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 add(self, resource, replace=False): """Add a resource or an iterable collection of resources. Will throw a ValueError if the resource (ie. same uri) already ...
if isinstance(resource, collections.Iterable): for r in resource: self.resources.add(r, replace) else: self.resources.add(resource, replace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(self, src): """Compare this ResourceList object with that specified as src. The parameter src must also be a ResourceList object, it is assumed to be...
dst_iter = iter(self.resources) src_iter = iter(src.resources) same = ResourceList() updated = ResourceList() deleted = ResourceList() created = ResourceList() dst_cur = next(dst_iter, None) src_cur = next(src_iter, None) while ((dst_cur is not 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 hashes(self): """Return set of hashes uses in this resource_list."""
hashes = set() if (self.resources is not None): for resource in self: if (resource.md5 is not None): hashes.add('md5') if (resource.sha1 is not None): hashes.add('sha-1') if (resource.sha256 is not None)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_sliced_filepath(filename, slice_count): """ append slice_count to the end of a filename """
root = os.path.splitext(filename)[0] ext = os.path.splitext(filename)[1] new_filepath = ''.join((root, str(slice_count), ext)) return _build_filepath_for_phantomcss(new_filepath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_filepath_for_phantomcss(filepath): """ Prepare screenshot filename for use with phantomcss. ie, append 'diff' to the end of the file if a baseline exi...
try: if os.path.exists(filepath): new_root = '.'.join((os.path.splitext(filepath)[0], 'diff')) ext = os.path.splitext(filepath)[1] diff_filepath = ''.join((new_root, ext)) if os.path.exists(diff_filepath): print 'removing stale diff: {0}'.form...
<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_filename_from_browserstack_json(j): """ Build a useful filename for an image from the screenshot json metadata """
filename = '' device = j['device'] if j['device'] else 'Desktop' if j['state'] == 'done' and j['image_url']: detail = [device, j['os'], j['os_version'], j['browser'], j['browser_version'], '.jpg'] filename = '_'.join(item.replace(" ", "_") for item in detail if item) e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _long_image_slice(in_filepath, out_filepath, slice_size): """ Slice an image into parts slice_size tall. """
print 'slicing image: {0}'.format(in_filepath) img = Image.open(in_filepath) width, height = img.size upper = 0 left = 0 slices = int(math.ceil(height / slice_size)) count = 1 for slice in range(slices): # if we are at the end, set the lower bound to be the bottom of the image ...
<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(dir, pattern, reason=''): """ delete files in dir that match pattern """
for f in os.listdir(dir): if re.search(pattern, f): print "Purging file {0}. {1}".format(f, reason) os.remove(os.path.join(dir, f))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crack(ciphertext, *fitness_functions, ntrials=30, nswaps=3000): """Break ``ciphertext`` using hill climbing. Note: Currently ntrails and nswaps default to ma...
if ntrials <= 0 or nswaps <= 0: raise ValueError("ntrials and nswaps must be positive integers") # Find a local maximum by swapping two letters and scoring the decryption def next_node_inner_climb(node): # Swap 2 characters in the key a, b = random.sample(range(len(node)), 2) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decrypt(key, ciphertext): """Decrypt Simple Substitution enciphered ``ciphertext`` using ``key``. Example: HELLO Args: key (iterable): The key to use cipher...
# TODO: Is it worth keeping this here I should I only accept strings? key = ''.join(key) alphabet = string.ascii_letters cipher_alphabet = key.lower() + key.upper() return ciphertext.translate(str.maketrans(cipher_alphabet, alphabet))
<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_heading(self, value): """value can be between 0 and 359"""
return self.write(request.SetHeading(self.seq, 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 set_back_led_output(self, value): """value can be between 0x00 and 0xFF"""
return self.write(request.SetBackLEDOutput(self.seq, 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 roll(self, speed, heading, state=1): """ speed can have value between 0x00 and 0xFF heading can have value between 0 and 359 """
return self.write(request.Roll(self.seq, speed, heading, state ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ISBNValidator(raw_isbn): """ Check string is a valid ISBN number"""
isbn_to_check = raw_isbn.replace('-', '').replace(' ', '') if not isinstance(isbn_to_check, string_types): raise ValidationError(_(u'Invalid ISBN: Not a string')) if len(isbn_to_check) != 10 and len(isbn_to_check) != 13: raise ValidationError(_(u'Invalid ISBN: Wrong length')) if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reward_battery(self): """ Add a battery level reward """
if not 'battery' in self.mode: return mode = self.mode['battery'] if mode and mode and self.__test_cond(mode): self.logger.debug('Battery out') self.player.stats['reward'] += mode['reward'] self.player.game_over = self.player.game_over or mode['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 reward_item(self, item_type): """ Add a food collision reward """
assert isinstance(item_type, str) if not 'items' in self.mode: return mode = self.mode['items'] if mode and mode[item_type] and self.__test_cond(mode[item_type]): self.logger.debug("{item_type} consumed".format(item_type=item_type)) self.player.stats...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reward_wall(self): """ Add a wall collision reward """
if not 'wall' in self.mode: return mode = self.mode['wall'] if mode and mode and self.__test_cond(mode): self.logger.debug("Wall {x}/{y}'".format(x=self.bumped_x, y=self.bumped_y)) self.player.stats['reward'] += mode['reward'] self.player.game_ov...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reward_explore(self): """ Add an exploration reward """
if not 'explore' in self.mode: return mode = self.mode['explore'] if mode and mode['reward'] and self.__test_cond(mode): self.player.stats['reward'] += mode['reward'] self.player.stats['score'] += mode['reward'] self.player.game_over = self.playe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reward_goal(self): """ Add an end goal reward """
if not 'goal' in self.mode: return mode = self.mode['goal'] if mode and mode['reward'] and self.__test_cond(mode): if mode['reward'] > 0: self.logger.info("Escaped!!") self.player.stats['reward'] += mode['reward'] self.player.stats...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reward_proximity(self): """ Add a wall proximity reward """
if not 'proximity' in self.mode: return mode = self.mode['proximity'] # Calculate proximity reward reward = 0 for sensor in self.player.sensors: if sensor.sensed_type == 'wall': reward += sensor.proximity_norm() else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sitemap(self): """Return the sitemap URI based on maps or explicit settings."""
if (self.sitemap_name is not None): return(self.sitemap_name) return(self.sitemap_uri(self.resource_list_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 read_resource_list(self, uri): """Read resource list from specified URI else raise exception."""
self.logger.info("Reading resource list %s" % (uri)) try: resource_list = ResourceList(allow_multifile=self.allow_multifile, mapper=self.mapper) resource_list.read(uri=uri) except Exception as e: raise ClientError("Can...
<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_resource_list_from_source_description(self, uri): """Read source description to find resource list. Raises a ClientError in cases where the client might...
self.logger.info("Reading source description %s" % (uri)) try: sd = SourceDescription() sd.read(uri=uri) except Exception as e: raise ClientError( "Can't read source description from %s (%s)" % (uri, str(e))) if (len(sd...
<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_resource_list_from_capability_list(self, uri): """Read capability list to find resource list. Raises a ClientError in cases where the client might look ...
self.logger.info("Reading capability list %s" % (uri)) try: cl = CapabilityList() cl.read(uri=uri) except Exception as e: raise ClientError( "Can't read capability list from %s (%s)" % (uri, str(e))) if (not cl.has_capa...
<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_resource_list(self): """Finf resource list by hueristics, returns ResourceList object. 1. Use explicitly specified self.sitemap_name (and fail if that d...
# 1 & 2 if (self.sitemap_name is not None): return(self.read_resource_list(self.sitemap_name)) if (self.capability_list_uri is not None): rluri = self.find_resource_list_from_capability_list(self.capability_list_uri) return(self.read_resource_list(rluri)) ...
<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_resource_list(self, paths=None, set_path=False): """Return a resource list for files on local disk. The set of files is taken by disk scan from the pat...
# 0. Sanity checks, parse paths is specified if (len(self.mapper) < 1): raise ClientFatalError( "No source to destination mapping specified") if (paths is not None): # Expect comma separated list of paths paths = paths.split(',') # 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 update_resource(self, resource, filename, change=None): """Update resource from uri to filename on local system. Update means three things: 1. GET resources ...
path = os.path.dirname(filename) distutils.dir_util.mkpath(path) num_updated = 0 if (self.dryrun): self.logger.info( "dryrun: would GET %s --> %s" % (resource.uri, filename)) else: # 1. GET for try_i in range(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 check_hashes(self, filename, resource): """Check all hashes present in self.hashes _and_ resource object. Simply shows warning for mismatch, does not raise e...
# which hashes to calculate? hashes = [] if ('md5' in self.hashes and resource.md5 is not None): hashes.append('md5') if ('sha-1' in self.hashes and resource.sha1 is not None): hashes.append('sha-1') if ('sha-256' in self.hashes and resource.sha256 is not...
<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_resource(self, resource, filename, allow_deletion=False): """Delete copy of resource in filename on local system. Will only actually do the deletion i...
num_deleted = 0 uri = resource.uri if (resource.timestamp is not None and resource.timestamp > self.last_timestamp): self.last_timestamp = resource.timestamp if (allow_deletion): if (self.dryrun): self.logger.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 parse_document(self): """Parse any ResourceSync document and show information. Will use sitemap URI taken either from explicit self.sitemap_name or derived f...
s = Sitemap() self.logger.info("Reading sitemap(s) from %s ..." % (self.sitemap)) try: list = s.parse_xml(url_or_file_open(self.sitemap)) except IOError as e: raise ClientFatalError("Cannot read document (%s)" % str(e)) num_entries = len(list.resources) ...
<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_resource_list( self, paths=None, outfile=None, links=None, dump=None): """Write a Resource List or a Resource Dump for files on local disk. Set of reso...
rl = self.build_resource_list(paths=paths, set_path=dump) if (links is not None): rl.ln = links if (dump): if (outfile is None): outfile = self.default_resource_dump self.logger.info("Writing resource dump to %s..." % (dump)) d = D...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_change_list(self, paths=None, outfile=None, ref_sitemap=None, newref_sitemap=None, empty=None, links=None, dump=None): """Write a change list. Unless t...
cl = ChangeList(ln=links) if (not empty): # 1. Get and parse reference sitemap old_rl = self.read_reference_resource_list(ref_sitemap) # 2. Depending on whether a newref_sitemap was specified, either read that # or build resource list from files on disk ...
<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_capability_list(self, capabilities=None, outfile=None, links=None): """Write a Capability List to outfile or STDOUT."""
capl = CapabilityList(ln=links) capl.pretty_xml = self.pretty_xml if (capabilities is not None): for name in capabilities.keys(): capl.add_capability(name=name, uri=capabilities[name]) if (outfile is None): print(capl.as_xml()) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_source_description( self, capability_lists=None, outfile=None, links=None): """Write a ResourceSync Description document to outfile or STDOUT."""
rsd = SourceDescription(ln=links) rsd.pretty_xml = self.pretty_xml if (capability_lists is not None): for uri in capability_lists: rsd.add_capability_list(uri) if (outfile is None): print(rsd.as_xml()) else: rsd.write(basename=...
<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_reference_resource_list(self, ref_sitemap, name='reference'): """Read reference resource list and return the ResourceList object. The name parameter is ...
rl = ResourceList() self.logger.info( "Reading %s resource list from %s ..." % (name, ref_sitemap)) rl.mapper = self.mapper rl.read(uri=ref_sitemap, index_only=(not self.allow_multifile)) num_entries = len(rl.resources) self.logger.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 prune_hashes(self, hashes, list_type): """Prune any hashes not in source resource or change list."""
discarded = [] for hash in hashes: if (hash in self.hashes): self.hashes.discard(hash) discarded.append(hash) self.logger.info("Not calculating %s hash(es) on destination as not present " "in source %s list" % (', '.join(sorte...
<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_status(self, in_sync=True, incremental=False, audit=False, same=None, created=0, updated=0, deleted=0, to_delete=0): """Write log message regarding statu...
if (audit): words = {'created': 'to create', 'updated': 'to update', 'deleted': 'to delete'} else: words = {'created': 'created', 'updated': 'updated', 'deleted': 'deleted'} if in_sync: ...
<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_latex_template(path_templates, template_filename, template_vars=None): '''Render a latex template, filling in its template variables :param path_templates: the path to the template directory :param template_filename: the name, rooted at the path_template_directory, of the desired...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _normalize_day(year, month, day): """ Coerce the day of the month to an internal value that may or may not match the "public" value. With the exception of th...
if year < MIN_YEAR or year > MAX_YEAR: raise ValueError("Year out of range (%d..%d)" % (MIN_YEAR, MAX_YEAR)) if month < 1 or month > 12: raise ValueError("Month out of range (1..12)") days_in_month = DAYS_IN_MONTH[(year, month)] if day in (days_in_month, -1): return year, month,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_clock_time(cls, clock_time, epoch): """ Convert from a ClockTime relative to a given epoch. """
try: clock_time = ClockTime(*clock_time) except (TypeError, ValueError): raise ValueError("Clock time must be a 2-tuple of (s, ns)") else: ordinal = clock_time.seconds // 86400 return Date.from_ordinal(ordinal + epoch.date().to_ordinal())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_native(cls, t): """ Convert from a native Python `datetime.time` value. """
second = (1000000 * t.second + t.microsecond) / 1000000 return Time(t.hour, t.minute, second, t.tzinfo)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_clock_time(cls, clock_time, epoch): """ Convert from a `.ClockTime` relative to a given epoch. """
clock_time = ClockTime(*clock_time) ts = clock_time.seconds % 86400 nanoseconds = int(1000000000 * ts + clock_time.nanoseconds) return Time.from_ticks(epoch.time().ticks + nanoseconds / 1000000000)
<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_native(self): """ Convert to a native Python `datetime.time` value. """
h, m, s = self.hour_minute_second s, ns = nano_divmod(s, 1) ms = int(nano_mul(ns, 1000000)) return time(h, m, s, ms)
<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_user(ctx, param, value): """Return a user if exists."""
if value: if value.isdigit(): user = User.query.get(str(value)) else: user = User.query.filter(User.email == value).one_or_none() return user
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokens_create(name, user, scopes, internal): """Create a personal OAuth token."""
token = Token.create_personal( name, user.id, scopes=scopes, is_internal=internal) db.session.commit() click.secho(token.access_token, fg='blue')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokens_delete(name=None, user=None, read_access_token=None, force=False): """Delete a personal OAuth token."""
if not (name or user) and not read_access_token: click.get_current_context().fail( 'You have to pass either a "name" and "user" or the "token"') if name and user: client = Client.query.filter( Client.user_id == user.id, Client.name == name, Client...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_residuals(self, points): """Normalize residuals by the level of the variable."""
residuals = self.evaluate_residual(points) solutions = self.evaluate_solution(points) return [resid / soln for resid, soln in zip(residuals, solutions)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, query, value, alias): """Convert UUID. :param query: SQLAlchemy query object. :param value: UUID value. :param alias: Alias of the column. :retur...
try: value = uuid.UUID(value) return query.filter(self.column == value) except ValueError: return query
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conv_uuid(self, column, name, **kwargs): """Convert UUID filter."""
return [f(column, name, **kwargs) for f in self.uuid_filters]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conv_variant(self, column, name, **kwargs): """Convert variants."""
return self.convert(str(column.type), column, name, **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 verify(self, otp, timestamp=False, sl=None, timeout=None, return_response=False): """ Verify a provided OTP. :param otp: OTP to verify. :type otp: ``str`` :p...
ca_bundle_path = self._get_ca_bundle_path() otp = OTP(otp, self.translate_otp) rand_str = b(os.urandom(30)) nonce = base64.b64encode(rand_str, b('xz'))[:25].decode('utf-8') query_string = self.generate_query_string(otp.otp, nonce, 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 verify_multi(self, otp_list, max_time_window=DEFAULT_MAX_TIME_WINDOW, sl=None, timeout=None): """ Verify a provided list of OTPs. :param max_time_window: Max...
# Create the OTP objects otps = [] for otp in otp_list: otps.append(OTP(otp, self.translate_otp)) if len(otp_list) < 2: raise ValueError('otp_list needs to contain at least two OTPs') device_ids = set() for otp in otps: device_ids.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 generate_query_string(self, otp, nonce, timestamp=False, sl=None, timeout=None): """ Returns a query string which is sent to the validation servers. """
data = [('id', self.client_id), ('otp', otp), ('nonce', nonce)] if timestamp: data.append(('timestamp', '1')) if sl is not None: if sl not in range(0, 101) and sl not in ['fast', 'secure']: raise Exception('sl parameter v...
<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_parameters_from_response(self, response): """ Returns a response signature and query string generated from the server response. 'h' aka signature argum...
lines = response.splitlines() pairs = [line.strip().split('=', 1) for line in lines if '=' in line] pairs = sorted(pairs) signature = ([unquote(v) for k, v in pairs if k == 'h'] or [None])[0] # already quoted query_string = '&' . join([k + '=' + v for k, v in pairs if 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 get_parameters_as_dictionary(self, query_string): """ Returns query string parameters as a dictionary. """
pairs = (x.split('=', 1) for x in query_string.split('&')) return dict((k, unquote(v)) for k, v in pairs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_request_urls(self, api_urls): """ Returns a list of the API URLs. """
if not isinstance(api_urls, (str, list, tuple)): raise TypeError('api_urls needs to be string or iterable!') if isinstance(api_urls, str): api_urls = (api_urls,) api_urls = list(api_urls) for url in api_urls: if not url.startswith('http://') and \ ...
<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_ca_bundle_path(self): """ Return a path to the CA bundle which is used for verifying the hosts SSL certificate. """
if self.ca_certs_bundle_path: # User provided a custom path return self.ca_certs_bundle_path # Return first bundle which is available for file_path in COMMON_CA_LOCATIONS: if self._is_valid_ca_bundle_file(file_path=file_path): return file_pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_str_uuid(string_length): """Returns a random string of length string_length"""
if not isinstance(string_length, int) or not 1 <= string_length <= 32: msg = "string_length must be type int where 1 <= string_length <= 32" raise ValueError(msg) random = str(uuid.uuid4()).upper().replace('-', '') return random[0:string_length]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def random_name_filepath(path_full, length_random=5): '''Take a filepath, add randome characters to its basename, and return the new filepath :param filename: either a filename or filepath :param length_random: length of random string to be generated ''' path_full_pre_extension, extension = os....
<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_filepathes_with_predicate(path_dir, predicate): '''List all filepathes in a directory that begin with predicate :param path_dir: the directory whose top-level contents you wish to list :param predicate: the predicate you want to test the directory's found files against ''' if not o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def recursive_apply(inval, func): '''Recursively apply a function to all levels of nested iterables :param inval: the object to run the function on :param func: the function that will be run on the inval ''' if isinstance(inval, dict): return {k: recursive_apply(v, func) for k, v in inval.i...
<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, basename=None, write_separate_manifests=True): """Write one or more dump files to complete this dump. Returns the number of dump/archive files wr...
self.check_files() n = 0 for manifest in self.partition_dumps(): dumpbase = "%s%05d" % (basename, n) dumpfile = "%s.%s" % (dumpbase, self.format) if (write_separate_manifests): manifest.write(basename=dumpbase + '.xml') if (self.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 write_zip(self, resources=None, dumpfile=None): """Write a ZIP format dump file. Writes a ZIP file containing the resources in the iterable resources along w...
compression = (ZIP_DEFLATED if self.compress else ZIP_STORED) zf = ZipFile( dumpfile, mode="w", compression=compression, allowZip64=True) # Write resources first rdm = ResourceDumpManifest(resources=resources) real_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 write_warc(self, resources=None, dumpfile=None): """Write a WARC dump file. WARC support is not part of ResourceSync v1.0 (Z39.99 2014) but is left in this l...
# Load library late as we want to be able to run rest of code # without this installed try: from warc import WARCFile, WARCHeader, WARCRecord except: raise DumpError("Failed to load WARC library") wf = WARCFile(dumpfile, mode="w", compress=self.compress) ...
<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_files(self, set_length=True, check_length=True): """Check all files in self.resources, find longest common prefix. Go though and check all files in sel...
total_size = 0 # total size of all files in bytes path_prefix = None for resource in self.resources: if (resource.path is None): # explicit test because exception raised by getsize otherwise # confusing raise DumpError( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partition_dumps(self): """Yeild a set of manifest object that parition the dumps. Simply adds resources/files to a manifest until their are either the the co...
manifest = self.manifest_class() manifest_size = 0 manifest_files = 0 for resource in self.resources: manifest.add(resource) manifest_size += resource.length manifest_files += 1 if (manifest_size >= self.max_size or man...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def archive_path(self, real_path): """Return the archive path for file with real_path. Mapping is based on removal of self.path_prefix which is determined by sel...
if (not self.path_prefix): return(real_path) else: return(os.path.relpath(real_path, self.path_prefix))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """ Attach a new engine to director """
self.scene = cocos.scene.Scene() self.z = 0 palette = config.settings['view']['palette'] #Player.palette = palette r, g, b = palette['bg'] self.scene.add(cocos.layer.ColorLayer(r, g, b, 255), z=self.z) self.z += 1 message_layer = MessageLayer() 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 act(self, action): """ Take one action for one step """
# FIXME: Hack to change in return type action = int(action) assert isinstance(action, int) assert action < self.actions_num, "%r (%s) invalid"%(action, type(action)) # Reset buttons for k in self.world_layer.buttons: self.world_layer.buttons[k] = 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 step(self): """ Step the engine one tick """
self.director.window.switch_to() self.director.window.dispatch_events() self.director.window.dispatch_event('on_draw') self.director.window.flip() # Ticking before events caused glitches. pyglet.clock.tick()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run_latex(self, cmd_wo_infile, path_outfile): '''Main runner for latex build Should compile the object's Latex template using a list of latex shell commands, along with an output file location. Runs the latex shell command until the process's .aux file remains unchanged. :r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_center(self, cshape_center): """cshape_center must be eu.Vector2"""
assert isinstance(cshape_center, eu.Vector2) self.position = world_to_view(cshape_center) self.cshape.center = cshape_center
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has(cls): """Class decorator that declares dependencies"""
deps = {} for i in dir(cls): if i.startswith('__') and i.endswith('__'): continue val = getattr(cls, i, None) if isinstance(val, Dependency): deps[i] = val if val.name is None: val.name = i cls.__injections__ = deps return cls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inject(self, inst, **renames): """Injects dependencies and propagates dependency injector"""
if renames: di = self.clone(**renames) else: di = self pro = di._provides inst.__injections_source__ = di deps = getattr(inst, '__injections__', None) if deps: for attr, dep in deps.items(): val = pro.get(dep.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 interconnect_all(self): """Propagate dependencies for provided instances"""
for dep in topologically_sorted(self._provides): if hasattr(dep, '__injections__') and not hasattr(dep, '__injections_source__'): self.inject(dep)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _basis_polynomial_factory(cls, kind): """Return a polynomial given some coefficients."""
valid_kind = cls._validate(kind) basis_polynomial = getattr(np.polynomial, valid_kind) return basis_polynomial
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate(cls, kind): """Validate the kind argument."""
if kind not in cls._valid_kinds: mesg = "'kind' must be one of {}, {}, {}, or {}." raise ValueError(mesg.format(*cls._valid_kinds)) else: return kind
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def derivatives_factory(cls, coef, domain, kind, **kwargs): """ Given some coefficients, return a the derivative of a certain kind of orthogonal polynomial defin...
basis_polynomial = cls._basis_polynomial_factory(kind) return basis_polynomial(coef, domain).deriv()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def functions_factory(cls, coef, domain, kind, **kwargs): """ Given some coefficients, return a certain kind of orthogonal polynomial defined over a specific dom...
basis_polynomial = cls._basis_polynomial_factory(kind) return basis_polynomial(coef, domain)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roots(cls, degree, domain, kind): """Return optimal collocation nodes for some orthogonal polynomial."""
basis_coefs = cls._basis_monomial_coefs(degree) basis_poly = cls.functions_factory(basis_coefs, domain, kind) return basis_poly.roots()
<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_capability_list(self, capability_list=None): """Add a capability list. Adds either a CapabiltyList object specified in capability_list or else creates a ...
if (hasattr(capability_list, 'uri')): r = Resource(uri=capability_list.uri, capability=capability_list.capability_name) if (capability_list.describedby is not None): r.link_set(rel='describedby', href=capability_list.describedby) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_oauth_token_and_set_current_user(): """Verify OAuth token and set current user on request stack. This function should be used **only** on REST applica...
for func in oauth2._before_request_funcs: func() if not hasattr(request, 'oauth') or not request.oauth: scopes = [] try: valid, req = oauth2.verify_request(scopes) except ValueError: abort(400, 'Error trying to decode a non urlencoded 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 scope_choices(self, exclude_internal=True): """Return list of scope choices. :param exclude_internal: Exclude internal scopes or not. (Default: ``True``) :re...
return [ (k, scope) for k, scope in sorted(self.scopes.items()) if not exclude_internal or not scope.is_internal ]
<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_scope(self, scope): """Register a scope. :param scope: A :class:`invenio_oauth2server.models.Scope` instance. """
if not isinstance(scope, Scope): raise TypeError("Invalid scope type.") assert scope.id not in self.scopes self.scopes[scope.id] = scope
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def monkeypatch_oauthlib_urlencode_chars(chars): """Monkeypatch OAuthlib set of "URL encoded"-safe characters. .. note:: OAuthlib keeps a set of characters that ...
modified_chars = set(chars) always_safe = set(oauthlib_commmon.always_safe) original_special_chars = oauthlib_commmon.urlencoded - always_safe if modified_chars != original_special_chars: warnings.warn( 'You are overriding the default OAuthlib "URL encoded" s...