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 _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name."""
taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue name += c if name not in taken: break # If name is still taken, add a numb...
<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, name, desc, func=None, args=None, krgs=None): """Add a menu entry."""
self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number."""
name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, name): """Runs the function associated with the given entry `name`."""
for entry in self.entries: if entry.name == name: run_func(entry) break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partition_scripts(scripts, start_type1, start_type2): """Return two lists of scripts out of the original `scripts` list. Scripts that begin with a `start_typ...
match, other = [], [] for script in scripts: if (HairballPlugin.script_start_type(script) == start_type1 or HairballPlugin.script_start_type(script) == start_type2): match.append(script) else: other.append(script) return match, other
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attribute_result(cls, sprites): """Return mapping of attributes to if they were initialized or not."""
retval = dict((x, True) for x in cls.ATTRIBUTES) for properties in sprites.values(): for attribute, state in properties.items(): retval[attribute] &= state != cls.STATE_MODIFIED return retval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attribute_state(cls, scripts, attribute): """Return the state of the scripts for the given attribute. If there is more than one 'when green flag clicked' scr...
green_flag, other = partition_scripts(scripts, cls.HAT_GREEN_FLAG, cls.HAT_CLONE) block_set = cls.BLOCKMAPPING[attribute] state = cls.STATE_NOT_MODIFIED # TODO: Any regular broadcast blocks encountered in the initialization # zone should be added to this loop for conflict checki...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output_results(cls, sprites): """Output whether or not each attribute was correctly initialized. Attributes that were not modified at all are considered to b...
print(' '.join(cls.ATTRIBUTES)) format_strs = ['{{{}!s:^{}}}'.format(x, len(x)) for x in cls.ATTRIBUTES] print(' '.join(format_strs).format(**cls.attribute_result(sprites)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sprite_changes(cls, sprite): """Return a mapping of attributes to their initilization state."""
retval = dict((x, cls.attribute_state(sprite.scripts, x)) for x in (x for x in cls.ATTRIBUTES if x != 'background')) return retval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def analyze(self, scratch, **kwargs): """Run and return the results of the AttributeInitialization plugin."""
changes = dict((x.name, self.sprite_changes(x)) for x in scratch.sprites) changes['stage'] = { 'background': self.attribute_state(scratch.stage.scripts, 'costume')} # self.output_results(changes) return {'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def variable_state(cls, scripts, variables): """Return the initialization state for each variable in variables. The state is determined based on the scripts pass...
def conditionally_set_not_modified(): """Set the variable to modified if it hasn't been altered.""" state = variables.get(block.args[0], None) if state == cls.STATE_NOT_MODIFIED: variables[block.args[0]] = cls.STATE_MODIFIED green_flag, other = parti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def analyze(self, scratch, **kwargs): """Run and return the results of the VariableInitialization plugin."""
variables = dict((x, self.variable_state(x.scripts, x.variables)) for x in scratch.sprites) variables['global'] = self.variable_state(self.iter_scripts(scratch), scratch.stage.variables) # Output for now import p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self): """Output the default sprite names found in the project."""
print('{} default sprite names found:'.format(self.total_default)) for name in self.list_default: print(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 analyze(self, scratch, **kwargs): """Run and return the results from the SpriteNaming plugin."""
for sprite in self.iter_sprites(scratch): for default in self.default_names: if default in sprite.name: self.total_default += 1 self.list_default.append(sprite.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 prepare_request_params(self, _query_params, _json_params): """ Prepare query and update params. """
self._query_params = dictset( _query_params or self.request.params.mixed()) self._json_params = dictset(_json_params) ctype = self.request.content_type if self.request.method in ['POST', 'PUT', 'PATCH']: if ctype == 'application/json': try: ...
<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_override_rendered(self): """ Set self.request.override_renderer if needed. """
if '' in self.request.accept: self.request.override_renderer = self._default_renderer elif 'application/json' in self.request.accept: self.request.override_renderer = 'nefertari_json' elif 'text/plain' in self.request.accept: self.request.override_renderer = ...
<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_aggregation(self, aggregator=None): """ Wrap `self.index` method with ESAggregator. This makes `self.index` to first try to run aggregation and only o...
from nefertari.elasticsearch import ES if aggregator is None: aggregator = ESAggregator aggregations_enabled = ( ES.settings and ES.settings.asbool('enable_aggregations')) if not aggregations_enabled: log.debug('Elasticsearch aggregations are not enab...
<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_collection_es(self): """ Query ES collection and return results. This is default implementation of querying ES collection with `self._query_params`. It m...
from nefertari.elasticsearch import ES return ES(self.Model.__name__).get_collection(**self._query_params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_public_limits(self): """ Set public limits if auth is enabled and user is not authenticated. Also sets default limit for GET, HEAD requests. """
if self.request.method.upper() in ['GET', 'HEAD']: self._query_params.process_int_param('_limit', 20) if self._auth_enabled and not getattr(self.request, 'user', None): wrappers.set_public_limits(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 convert_ids2objects(self): """ Convert object IDs from `self._json_params` to objects if needed. Only IDs that belong to relationship field of `self.Model` a...
if not self.Model: log.info("%s has no model defined" % self.__class__.__name__) return for field in self._json_params.keys(): if not engine.is_relationship_field(field, self.Model): continue rel_model_cls = engine.get_relationship_cls(fi...
<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_default_wrappers(self): """ Setup defaulf wrappers. Wrappers are applied when view method does not return instance of Response. In this case nefertari ...
# Index self._after_calls['index'] = [ wrappers.wrap_in_dict(self.request), wrappers.add_meta(self.request), wrappers.add_object_url(self.request), ] # Show self._after_calls['show'] = [ wrappers.wrap_in_dict(self.request), ...
<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(self): """ Register new user by POSTing all required data. """
user, created = self.Model.create_account( self._json_params) if not created: raise JHTTPConflict('Looks like you already have an account.') self.request._user = user pk_field = user.pk_field() headers = remember(self.request, getattr(user, pk_field)) ...
<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(self): """ Register a new user by POSTing all required data. User's `Authorization` header value is returned in `WWW-Authenticate` header. """
user, created = self.Model.create_account(self._json_params) if user.api_key is None: raise JHTTPBadRequest('Failed to generate ApiKey for user') if not created: raise JHTTPConflict('Looks like you already have an account.') self.request._user = user he...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def claim_token(self, **params): """Claim current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` ...
self._json_params.update(params) success, self.user = self.Model.authenticate_by_password( self._json_params) if success: headers = remember(self.request, self.user.username) return JHTTPOk('Token claimed', headers=headers) if self.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 reset_token(self, **params): """ Reset current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate`...
response = self.claim_token(**params) if not self.user: return response self.user.api_key.reset_token() headers = remember(self.request, self.user.username) return JHTTPOk('Registered', headers=headers)
<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_nested_privacy(self, data): """ Apply privacy to nested documents. :param data: Dict of data to which privacy is already applied. """
kw = { 'is_admin': self.is_admin, 'drop_hidden': self.drop_hidden, } for key, val in data.items(): if is_document(val): data[key] = apply_privacy(self.request)(result=val, **kw) elif isinstance(val, list) and val and is_document(va...
<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_root_resource(config): """Returns the root resource."""
app_package_name = get_app_package_name(config) return config.registry._root_resources.setdefault( app_package_name, Resource(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 get_default_view_path(resource): "Returns the dotted path to the default view class." parts = [a.member_name for a in resource.ancestors] +\ [resource.collection_name or resource.member_name] if resource.prefix: parts.insert(-1, resource.prefix) view_file = '%s' % '_'.join(par...
<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_ancestors(self): "Returns the list of ancestor resources." if self._ancestors: return self._ancestors if not self.parent: return [] obj = self.resource_map.get(self.parent.uid) while obj and obj.member_name: self._ancestors.append(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 add_from_child(self, resource, **kwargs): """ Add a resource with its all children resources to the current resource. """
new_resource = self.add( resource.member_name, resource.collection_name, **kwargs) for child in resource.children: new_resource.add_from_child(child, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, path): """ Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFram...
name_with_ext = os.path.split(path)[1] # split directory and filename name = name_with_ext.split('.')[0] # remove extension self.list.update({name: 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 unpack(self, name): """ Unpacks a data set to a Pandas DataFrame Parameters name : str call `.list` to see all availble datasets Returns ------- pd.DataFrame...
path = self.list[name] df = pd.read_pickle(path, compression='gzip') return df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def six_frame(genome, table, minimum = 10): """ translate each sequence into six reading frames """
for seq in parse_fasta(genome): dna = Seq(seq[1].upper().replace('U', 'T'), IUPAC.ambiguous_dna) counter = 0 for sequence in ['f', dna], ['rc', dna.reverse_complement()]: direction, sequence = sequence for frame in range(0, 3): for prot in \ ...
<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_gaps(matches, gap_threshold = 0): """ check for large gaps between alignment windows """
gaps = [] prev = None for match in sorted(matches, key = itemgetter(0)): if prev is None: prev = match continue if match[0] - prev[1] >= gap_threshold: gaps.append([prev, match]) prev = match return [[i[0][1], i[1][0]] for i in gaps]
<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_overlap(current, hit, overlap = 200): """ determine if sequence has already hit the same part of the model, indicating that this hit is for another 16S...
for prev in current: p_coords = prev[2:4] coords = hit[2:4] if get_overlap(coords, p_coords) >= overlap: 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 find_coordinates(hmms, bit_thresh): """ find 16S rRNA gene sequence coordinates """
# get coordinates from cmsearch output seq2hmm = parse_hmm(hmms, bit_thresh) seq2hmm = best_model(seq2hmm) group2hmm = {} # group2hmm[seq][group] = [model, strand, coordinates, matches, gaps] for seq, info in list(seq2hmm.items()): group2hmm[seq] = {} # info = [model, [[hit1], [hit2...
<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_info(line, bit_thresh): """ get info from either ssu-cmsearch or cmsearch output """
if len(line) >= 18: # output is from cmsearch id, model, bit, inc = line[0].split()[0], line[2], float(line[14]), line[16] sstart, send, strand = int(line[7]), int(line[8]), line[9] mstart, mend = int(line[5]), int(line[6]) elif len(line) == 9: # output is from ssu-cmsearch if b...
<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_buffer(coords, length, buffer): """ check to see how much of the buffer is being used """
s = min(coords[0], buffer) e = min(length - coords[1], buffer) return [s, 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 _import_parsers(): """ Lazy imports to prevent circular dependencies between this module and utils """
global ARCGIS_NODES global ARCGIS_ROOTS global ArcGISParser global FGDC_ROOT global FgdcParser global ISO_ROOTS global IsoParser global VALID_ROOTS if ARCGIS_NODES is None or ARCGIS_ROOTS is None or ArcGISParser is None: from gis_metadata.arcgis_metadata_parser import 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 _init_metadata(self): """ Dynamically sets attributes from a Dictionary passed in by children. The Dictionary will contain the name of each attribute as keys...
if self._data_map is None: self._init_data_map() validate_properties(self._data_map, self._metadata_props) # Parse attribute values and assign them: key = parse(val) for prop in self._data_map: setattr(self, prop, parse_property(self._xml_tree, None, self._da...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_complex(self, prop): """ Default parsing operation for a complex struct """
xpath_root = None xpath_map = self._data_structures[prop] return parse_complex(self._xml_tree, xpath_root, xpath_map, prop)
<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_complex_list(self, prop): """ Default parsing operation for lists of complex structs """
xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop)
<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_dates(self, prop=DATES): """ Creates and returns a Date Types data structure parsed from the metadata """
return parse_dates(self._xml_tree, self._data_structures[prop])
<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_complex(self, **update_props): """ Default update operation for a complex struct """
prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex(xpath_root=xpath_root, xpath_map=xpath_map, **update_props)
<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_complex_list(self, **update_props): """ Default update operation for lists of complex structs """
prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex_list(xpath_root=xpath_root, xpath_map=xpath_map, **update_props)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spec(self, postf_un_ops: str) -> list: """Return prefix unary operators list"""
spec = [(l + op, {'pat': self.pat(pat), 'postf': self.postf(r, postf_un_ops), 'regex': None}) for op, pat in self.styles.items() for l, r in self.brackets] spec[0][1]['regex'] = self.regex_pat.format( _ops_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 one_symbol_ops_str(self) -> str: """Regex-escaped string with all one-symbol operators"""
return re.escape(''.join((key for key in self.ops.keys() if len(key) == 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 plot_gaps(plot, columns): """ plot % of gaps at each position """
from plot_window import window_plot_convolve as plot_window # plot_window([columns], len(columns)*.01, plot) plot_window([[100 - i for i in columns]], len(columns)*.01, plot)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample_group(sid, groups): """ Iterate through all categories in an OrderedDict and return category name if SampleID present in that category. :type sid: str...
for name in groups: if sid in groups[name].sids: return 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 combine_sets(*sets): """ Combine multiple sets to create a single larger set. """
combined = set() for s in sets: combined.update(s) return combined
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unique_otuids(groups): """ Get unique OTUIDs of each category. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :retu...
uniques = {key: set() for key in groups} for i, group in enumerate(groups): to_combine = groups.values()[:i]+groups.values()[i+1:] combined = combine_sets(*to_combine) uniques[group] = groups[group].difference(combined) return uniques
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shared_otuids(groups): """ Get shared OTUIDs between all unique combinations of groups. :type groups: Dict :param groups: {Category name: OTUIDs in category}...
for g in sorted(groups): print("Number of OTUs in {0}: {1}".format(g, len(groups[g].results["otuids"]))) number_of_categories = len(groups) shared = defaultdict() for i in range(2, number_of_categories+1): for j in combinations(sorted(groups), i): combo_name = " & ".join(lis...
<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_uniques(path, prefix, uniques): """ Given a path, the method writes out one file for each group name in the uniques dictionary with the file name in th...
for group in uniques: fp = osp.join(path, "{}_{}.txt".format(prefix, group)) with open(fp, "w") as outf: outf.write("\n".join(uniques[group]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def storeFASTA(fastaFNH): """ Parse the records in a FASTA-format file by first reading the entire file into memory. :type source: path to FAST file or open file...
fasta = file_handle(fastaFNH).read() return [FASTARecord(rec[0].split()[0], rec[0].split(None, 1)[1], "".join(rec[1:])) for rec in (x.strip().split("\n") for x in fasta.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 parseFASTA(fastaFNH): """ Parse the records in a FASTA-format file keeping the file open, and reading through one line at a time. :type source: path to FAST ...
recs = [] seq = [] seqID = "" descr = "" for line in file_handle(fastaFNH): line = line.strip() if line[0] == ";": continue if line[0] == ">": # conclude previous record if seq: recs.append(FASTARecord(seqID, descr, "".joi...
<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(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False): """ Trains a k-nearest neighbors classifier for face recogniti...
X = [] y = [] # Loop through each person in the training set for class_dir in os.listdir(train_dir): if not os.path.isdir(os.path.join(train_dir, class_dir)): continue # Loop through each training image for the current person for img_path in image_files_in_folder(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 predict(X_img_path, knn_clf=None, model_path=None, distance_threshold=0.6): """ Recognizes faces in given image using a trained KNN classifier :param X_img_p...
if not os.path.isfile(X_img_path) or os.path.splitext(X_img_path)[1][1:] not in ALLOWED_EXTENSIONS: raise Exception("Invalid image path: {}".format(X_img_path)) if knn_clf is None and model_path is None: raise Exception("Must supply knn classifier either thourgh knn_clf or model_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 show_prediction_labels_on_image(img_path, predictions): """ Shows the face recognition results visually. :param img_path: path to image to be recognized :par...
pil_image = Image.open(img_path).convert("RGB") draw = ImageDraw.Draw(pil_image) for name, (top, right, bottom, left) in predictions: # Draw a box around the face using the Pillow module draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 255)) # There's a bug in Pillow ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def face_distance(face_encodings, face_to_compare): """ Given a list of face encodings, compare them to a known face encoding and get a euclidean distance for ea...
if len(face_encodings) == 0: return np.empty((0)) return np.linalg.norm(face_encodings - face_to_compare, axis=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 batch_face_locations(images, number_of_times_to_upsample=1, batch_size=128): """ Returns an 2d array of bounding boxes of human faces in a image using the cn...
def convert_cnn_detections_to_css(detections): return [_trim_css_to_bounds(_rect_to_css(face.rect), images[0].shape) for face in detections] raw_detections_batched = _raw_face_locations_batched(images, number_of_times_to_upsample, batch_size) return list(map(convert_cnn_detections_to_css, raw_det...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def face_encodings(face_image, known_face_locations=None, num_jitters=1): """ Given an image, return the 128-dimension face encoding for each face in the image. ...
raw_landmarks = _raw_face_landmarks(face_image, known_face_locations, model="small") return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _int_size_to_type(size): """ Return the Catalyst datatype from the size of integers. """
if size <= 8: return ByteType if size <= 16: return ShortType if size <= 32: return IntegerType if size <= 64: return LongType
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _infer_type(obj): """Infer the DataType from obj """
if obj is None: return NullType() if hasattr(obj, '__UDT__'): return obj.__UDT__ dataType = _type_mappings.get(type(obj)) if dataType is DecimalType: # the precision and scale of `obj` may be different from row to row. return DecimalType(38, 18) elif dataType 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 _has_nulltype(dt): """ Return whether there is NullType in `dt` or not """
if isinstance(dt, StructType): return any(_has_nulltype(f.dataType) for f in dt.fields) elif isinstance(dt, ArrayType): return _has_nulltype((dt.elementType)) elif isinstance(dt, MapType): return _has_nulltype(dt.keyType) or _has_nulltype(dt.valueType) else: return isins...
<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_converter(dataType): """Create a converter to drop the names of fields in obj """
if not _need_converter(dataType): return lambda x: x if isinstance(dataType, ArrayType): conv = _create_converter(dataType.elementType) return lambda row: [conv(v) for v in row] elif isinstance(dataType, MapType): kconv = _create_converter(dataType.keyType) vconv =...
<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_arrow_type(dt): """ Convert Spark data type to pyarrow type """
import pyarrow as pa if type(dt) == BooleanType: arrow_type = pa.bool_() elif type(dt) == ByteType: arrow_type = pa.int8() elif type(dt) == ShortType: arrow_type = pa.int16() elif type(dt) == IntegerType: arrow_type = pa.int32() elif type(dt) == LongType: ...
<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_arrow_schema(schema): """ Convert a schema from Spark to Arrow """
import pyarrow as pa fields = [pa.field(field.name, to_arrow_type(field.dataType), nullable=field.nullable) for field in schema] return pa.schema(fields)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_arrow_type(at): """ Convert pyarrow type to Spark data type. """
import pyarrow.types as types if types.is_boolean(at): spark_type = BooleanType() elif types.is_int8(at): spark_type = ByteType() elif types.is_int16(at): spark_type = ShortType() elif types.is_int32(at): spark_type = IntegerType() elif types.is_int64(at): ...
<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_arrow_schema(arrow_schema): """ Convert schema from Arrow to Spark. """
return StructType( [StructField(field.name, from_arrow_type(field.type), nullable=field.nullable) for field in arrow_schema])
<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_series_localize_timestamps(s, timezone): """ Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone. If the i...
from pyspark.sql.utils import require_minimum_pandas_version require_minimum_pandas_version() from pandas.api.types import is_datetime64tz_dtype tz = timezone or _get_local_timezone() # TODO: handle nested timestamps, such as ArrayType(TimestampType())? if is_datetime64tz_dtype(s.dtype): ...
<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_dataframe_localize_timestamps(pdf, timezone): """ Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone :par...
from pyspark.sql.utils import require_minimum_pandas_version require_minimum_pandas_version() for column, series in pdf.iteritems(): pdf[column] = _check_series_localize_timestamps(series, timezone) return pdf
<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_series_convert_timestamps_internal(s, timezone): """ Convert a tz-naive timestamp in the specified timezone or local timezone to UTC normalized for Sp...
from pyspark.sql.utils import require_minimum_pandas_version require_minimum_pandas_version() from pandas.api.types import is_datetime64_dtype, is_datetime64tz_dtype # TODO: handle nested timestamps, such as ArrayType(TimestampType())? if is_datetime64_dtype(s.dtype): # When tz_localize 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 _check_series_convert_timestamps_localize(s, from_timezone, to_timezone): """ Convert timestamp to timezone-naive in the specified timezone or local timezone...
from pyspark.sql.utils import require_minimum_pandas_version require_minimum_pandas_version() import pandas as pd from pandas.api.types import is_datetime64tz_dtype, is_datetime64_dtype from_tz = from_timezone or _get_local_timezone() to_tz = to_timezone or _get_local_timezone() # TODO: ha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def asDict(self, recursive=False): """ Return as an dict :param recursive: turns the nested Row as dict (default: False). True True True """
if not hasattr(self, "__fields__"): raise TypeError("Cannot convert a Row class into dict") if recursive: def conv(obj): if isinstance(obj, Row): return obj.asDict(True) elif isinstance(obj, list): return [...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_local_dirs(sub): """ Get all the directories """
path = os.environ.get("SPARK_LOCAL_DIRS", "/tmp") dirs = path.split(",") if len(dirs) > 1: # different order in different processes and instances rnd = random.Random(os.getpid() + id(dirs)) random.shuffle(dirs, rnd.random) return [os.path.join(d, "python", str(os.getpid()), sub)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mergeValues(self, iterator): """ Combine the items by creator and combiner """
# speedup attribute lookup creator, comb = self.agg.createCombiner, self.agg.mergeValue c, data, pdata, hfun, batch = 0, self.data, self.pdata, self._partition, self.batch limit = self.memory_limit for k, v in iterator: d = pdata[hfun(k)] if pdata else data ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def items(self): """ Return all merged items as iterator """
if not self.pdata and not self.spills: return iter(self.data.items()) return self._external_items()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _external_items(self): """ Return all partitioned items as iterator """
assert not self.data if any(self.pdata): self._spill() # disable partitioning and spilling when merge combiners from disk self.pdata = [] try: for i in range(self.partitions): for v in self._merged_items(i): yield 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 _recursive_merged_items(self, index): """ merge the partitioned items and return the as iterator If one partition can not be fit in memory, then them will be...
subdirs = [os.path.join(d, "parts", str(index)) for d in self.localdirs] m = ExternalMerger(self.agg, self.memory_limit, self.serializer, subdirs, self.scale * self.partitions, self.partitions, self.batch) m.pdata = [{} for _ in range(self.partitions)] limit =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sorted(self, iterator, key=None, reverse=False): """ Sort the elements in iterator, do external sort when the memory goes above the limit. """
global MemoryBytesSpilled, DiskBytesSpilled batch, limit = 100, self._next_limit() chunks, current_chunk = [], [] iterator = iter(iterator) while True: # pick elements in batch chunk = list(itertools.islice(iterator, batch)) current_chunk.exte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _spill(self): """ dump the values into disk """
global MemoryBytesSpilled, DiskBytesSpilled if self._file is None: self._open_file() used_memory = get_used_memory() pos = self._file.tell() self._ser.dump_stream(self.values, self._file) self.values = [] gc.collect() DiskBytesSpilled += 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 _merge_sorted_items(self, index): """ load a partition from disk, then sort and group by key """
def load_partition(j): path = self._get_spill_dir(j) p = os.path.join(path, str(index)) with open(p, 'rb', 65536) as f: for v in self.serializer.load_stream(f): yield v disk_items = [load_partition(j) for j in range(self.spills)] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def portable_hash(x): """ This function returns consistent hash code for builtin types, especially for None and tuple with None. The algorithm is similar to that...
if sys.version_info >= (3, 2, 3) and 'PYTHONHASHSEED' not in os.environ: raise Exception("Randomness of hash of string should be disabled via PYTHONHASHSEED") if x is None: return 0 if isinstance(x, tuple): h = 0x345678 for i in x: h ^= portable_hash(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 ignore_unicode_prefix(f): """ Ignore the 'u' prefix of string in doc tests, to make it works in both python 2 and 3 """
if sys.version >= '3': # the representation of unicode string in Python 3 does not have prefix 'u', # so remove the prefix 'u' for doc tests literal_re = re.compile(r"(\W|^)[uU](['])", re.UNICODE) f.__doc__ = literal_re.sub(r'\1\2', f.__doc__) return 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 unpersist(self, blocking=False): """ Mark the RDD as non-persistent, and remove all blocks for it from memory and disk. .. versionchanged:: 3.0.0 Added optio...
self.is_cached = False self._jrdd.unpersist(blocking) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCheckpointFile(self): """ Gets the name of the file to which this RDD was checkpointed Not defined if RDD is checkpointed locally. """
checkpointFile = self._jrdd.rdd().getCheckpointFile() if checkpointFile.isDefined(): return checkpointFile.get()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map(self, f, preservesPartitioning=False): """ Return a new RDD by applying a function to each element of this RDD. [('a', 1), ('b', 1), ('c', 1)] """
def func(_, iterator): return map(fail_on_stopiteration(f), iterator) return self.mapPartitionsWithIndex(func, preservesPartitioning)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatMap(self, f, preservesPartitioning=False): """ Return a new RDD by first applying a function to all elements of this RDD, and then flattening the results...
def func(s, iterator): return chain.from_iterable(map(fail_on_stopiteration(f), iterator)) return self.mapPartitionsWithIndex(func, preservesPartitioning)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mapPartitions(self, f, preservesPartitioning=False): """ Return a new RDD by applying a function to each partition of this RDD. [3, 7] """
def func(s, iterator): return f(iterator) return self.mapPartitionsWithIndex(func, preservesPartitioning)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distinct(self, numPartitions=None): """ Return a new RDD containing the distinct elements in this RDD. [1, 2, 3] """
return self.map(lambda x: (x, None)) \ .reduceByKey(lambda x, _: x, numPartitions) \ .map(lambda x: x[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 sample(self, withReplacement, fraction, seed=None): """ Return a sampled subset of this RDD. :param withReplacement: can elements be sampled multiple times (...
assert fraction >= 0.0, "Negative fraction value: %s" % fraction return self.mapPartitionsWithIndex(RDDSampler(withReplacement, fraction, seed).func, 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 randomSplit(self, weights, seed=None): """ Randomly splits this RDD with the provided weights. :param weights: weights for splits, will be normalized if they...
s = float(sum(weights)) cweights = [0.0] for w in weights: cweights.append(cweights[-1] + w / s) if seed is None: seed = random.randint(0, 2 ** 32 - 1) return [self.mapPartitionsWithIndex(RDDRangeSampler(lb, ub, seed).func, True) for lb, u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def takeSample(self, withReplacement, num, seed=None): """ Return a fixed-size sampled subset of this RDD. .. note:: This method should only be used if the resul...
numStDev = 10.0 if num < 0: raise ValueError("Sample size cannot be negative.") elif num == 0: return [] initialCount = self.count() if initialCount == 0: return [] rand = random.Random(seed) if (not withReplacement) and nu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _computeFractionForSampleSize(sampleSizeLowerBound, total, withReplacement): """ Returns a sampling rate that guarantees a sample of size >= sampleSizeLowerB...
fraction = float(sampleSizeLowerBound) / total if withReplacement: numStDev = 5 if (sampleSizeLowerBound < 12): numStDev = 9 return fraction + numStDev * sqrt(fraction / total) else: delta = 0.00005 gamma = - log(delta)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def union(self, other): """ Return the union of this RDD and another one. [1, 1, 2, 3, 1, 1, 2, 3] """
if self._jrdd_deserializer == other._jrdd_deserializer: rdd = RDD(self._jrdd.union(other._jrdd), self.ctx, self._jrdd_deserializer) else: # These RDDs contain data in different serialized formats, so we # must normalize them to the default seria...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersection(self, other): """ Return the intersection of this RDD and another one. The output will not contain any duplicate elements, even if the input RDD...
return self.map(lambda v: (v, None)) \ .cogroup(other.map(lambda v: (v, None))) \ .filter(lambda k_vs: all(k_vs[1])) \ .keys()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repartitionAndSortWithinPartitions(self, numPartitions=None, partitionFunc=portable_hash, ascending=True, keyfunc=lambda x: x): """ Repartition the RDD accor...
if numPartitions is None: numPartitions = self._defaultReducePartitions() memory = _parse_memory(self.ctx._conf.get("spark.python.worker.memory", "512m")) serializer = self._jrdd_deserializer def sortPartition(iterator): sort = ExternalSorter(memory * 0.9, seri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sortBy(self, keyfunc, ascending=True, numPartitions=None): """ Sorts this RDD by the given keyfunc [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)] [('a', ...
return self.keyBy(keyfunc).sortByKey(ascending, numPartitions).values()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def groupBy(self, f, numPartitions=None, partitionFunc=portable_hash): """ Return an RDD of grouped items. [(0, [2, 8]), (1, [1, 1, 3, 5])] """
return self.map(lambda x: (f(x), x)).groupByKey(numPartitions, partitionFunc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pipe(self, command, env=None, checkCode=False): """ Return an RDD created by piping elements to a forked external process. [u'1', u'2', u'', u'3'] :param che...
if env is None: env = dict() def func(iterator): pipe = Popen( shlex.split(command), env=env, stdin=PIPE, stdout=PIPE) def pipe_objs(out): for obj in iterator: s = unicode(obj).rstrip('\n') + '\n' ...