code stringlengths 1 18.2k |
|---|
def dequeue(self): """ Returns a :class:`~retask.task.Task` object from the queue. Returns ``None`` if the queue is empty. :return: :class:`~retask.task.Task` object from the queue If the queue is not connected then it will raise :class:`retask.ConnectionError` .. doctest:: >>> from retask import Queue >>> q = Queue('t... |
def enqueue(self, task): """ Enqueues the given :class:`~retask.task.Task` object to the queue and returns a :class:`~retask.queue.Job` object. :arg task: ::class:`~retask.task.Task` object :return: :class:`~retask.queue.Job` object If the queue is not connected then it will raise :class:`retask.ConnectionError`. .. do... |
def send(self, task, result, expire=60): """ Sends the result back to the producer. This should be called if only you want to return the result in async manner. :arg task: ::class:`~retask.task.Task` object :arg result: Result data to be send back. Should be in JSON serializable. :arg expire: Time in seconds after the ... |
def find(self, obj): """Returns the index of the given object in the queue, it might be string which will be searched inside each task. :arg obj: object we are looking :return: -1 if the object is not found or else the location of the task """ if not self.connected: raise ConnectionError('Queue is not connected') data ... |
def result(self): """ Returns the result from the worker for this job. This is used to pass result in async way. """ if self.__result: return self.__result data = self.rdb.rpop(self.urn) if data: self.rdb.delete(self.urn) data = json.loads(data) self.__result = data return data else: return None |
def wait(self, wait_time=0): """ Blocking call to check if the worker returns the result. One can use job.result after this call returns ``True``. :arg wait_time: Time in seconds to wait, default is infinite. :return: `True` or `False`. .. note:: This is a blocking call, you can specity wait_time argument for timeout. ... |
def messages_in_flight(self): """ Returns True if there are messages waiting to be sent or that we're still waiting to see if errors occur for. """ self.prune_sent() if not self.send_queue.empty() or len(self.sent) > 0: return True return False |
def _reallysend(self, payload, token, expiration=None, priority=None, identifier=None): """ Args: payload (dict): The payload dictionary of the push to send descriptor (any): Opaque variable that is passed back to the pushbaby on failure """ if not self.alive: raise ConnectionDeadException() if not self.useable: raise ... |
written < len(apnsFrame): written += self.sock.send(apnsFrame[written:]) except: logger.exception("Caught exception sending push") raise self.sent[seq] = PushConnection.SentMessage( time.time(), token, payload, expiration, priority, identifier ) self.last_push_sent = time.time() |
def db(self, connection_string=None): """Gets the SQLALchemy session for this request""" connection_string = connection_string or self.settings["db"] if not hasattr(self, "_db_conns"): self._db_conns = {} if not connection_string in self._db_conns: self._db_conns[connection_string] = oz.sqlalchemy.session(connection_st... |
def _sqlalchemy_on_finish(self): """ Closes the sqlalchemy transaction. Rolls back if an error occurred. """ if hasattr(self, "_db_conns"): try: if self.get_status() >= 200 and self.get_status() <= 399: for db_conn in self._db_conns.values(): db_conn.commit() else: for db_conn in self._db_conns.values(): db_conn.rollba... |
def _sqlalchemy_on_connection_close(self): """ Rollsback and closes the active session, since the client disconnected before the request could be completed. """ if hasattr(self, "_db_conns"): try: for db_conn in self._db_conns.values(): db_conn.rollback() except: tornado.log.app_log.warning("Error occurred during datab... |
def use_settings(**kwargs): ''' Context manager to temporarily override settings ''' from omnic import singletons singletons.settings.use_settings_dict(kwargs) yield singletons.settings.use_previous_settings() |
def add_key(self): "Add ssh key to gitlab if necessary" try: with open(self.args.ssh_public_key) as f: public_key = f.read().strip() except: log.debug("No key found in {}".format(self.args.ssh_public_key)) return None g = self.gitlab url = g['url'] + "/user/keys" query = {'private_token': g['token']} keys = requests.ge... |
def add_project(self): "Create project in gitlab if it does not exist" g = self.gitlab url = g['url'] + "/projects/" + g['repo'] query = {'private_token': g['token']} if (requests.get(url, params=query).status_code == requests.codes.ok): log.debug("project " + url + " already exists") return None else: log.info("add pr... |
def unprotect_branches(self): "Unprotect branches of the GitLab project" g = self.gitlab url = g['url'] + "/projects/" + g['repo'] + "/repository/branches" query = {'private_token': g['token']} unprotected = 0 r = requests.get(url, params=query) r.raise_for_status() for branch in r.json(): if branch['protected']: r = r... |
def json_loads(payload): "Log the payload that cannot be parsed" try: return json.loads(payload) except ValueError as e: log.error("unable to json.loads(" + payload + ")") raise e |
def get_pull_requests(self): "https://developer.github.com/v3/pulls/#list-pull-requests" g = self.github query = {'state': 'all'} if self.args.github_token: query['access_token'] = g['token'] def f(pull): if self.args.ignore_closed: return (pull['state'] == 'opened' or (pull['state'] == 'closed' and pull['merged_at']))... |
def get_merge_requests(self): "http://doc.gitlab.com/ce/api/merge_requests.html" g = self.gitlab merges = self.get(g['url'] + "/projects/" + g['repo'] + "/merge_requests", {'private_token': g['token'], 'state': 'all'}, cache=False) return dict([(str(merge['id']), merge) for merge in merges]) |
def cropIndices(dims, lat, lon, depth=None, doy=None): """ Return the indices to crop dataset Assuming that the dataset have the dimensions given by dims, this function return the indices to conform with the given coordinates (lat, lon, ...) """ dims_out = {} idx = {} yn = slice( np.nonzero(dims['lat'] <= lat.min())[0]... |
more than one data # point in the edge, I should extend this selection one point on # each side, without go beyond 0 # if zn.start < 0: # zn = slice(0, zn.stop, zn.step) dims_out['depth'] = np.atleast_1d(dims['depth'][zn]) idx['zn'] = zn if doy is not None: # Source has only one time, like total mean field, or annual m... |
def join_paired_end_reads_seqprep( reads1_infile_path, reads2_infile_path, outfile_label='seqprep', max_overlap_ascii_q_score='J', min_overlap=None, # typical default vs 15 max_mismatch_good_frac=None, # typical default is 0.02, min_frac_matching=None, # typical default is 0.9, phred_64=False, params={}, working_dir=te... |
[abs_r1_path, abs_r2_path] # check / make absolute infile paths for p in infile_paths: if not os.path.exists(p): raise IOError('Infile not found at: %s' % p) # set up controller seqprep_app = SeqPrep(params=params, WorkingDir=working_dir, SuppressStderr=SuppressStderr, SuppressStdout=SuppressStdout, HALT_EXEC=HALT_EXEC... |
if isinstance(min_frac_matching, float) and 0.0 < min_frac_matching <= 1.0: seqprep_app.Parameters['-n'].on(min_frac_matching) else: raise ValueError( "min_frac_matching must be a float between 0.0-1.0!") if max_overlap_ascii_q_score is not None: if isinstance(max_overlap_ascii_q_score, str) \ and len(max_overlap_ascii... |
def _unassembled_reads1_out_file_name(self): """Checks file name is set for reads1 output. Returns absolute path.""" if self.Parameters['-1'].isOn(): unassembled_reads1 = self._absolute( str(self.Parameters['-1'].Value)) else: raise ValueError("No reads1 (flag: -1) output path specified") return unassembled_reads1 |
def _unassembled_reads2_out_file_name(self): """Checks if file name is set for reads2 output. Returns absolute path.""" if self.Parameters['-2'].isOn(): unassembled_reads2 = self._absolute( str(self.Parameters['-2'].Value)) else: raise ValueError("No reads2 (flag -2) output path specified") return unassembled_reads2 |
def _discarded_reads1_out_file_name(self): """Checks if file name is set for discarded reads1 output. Returns absolute path.""" if self.Parameters['-3'].isOn(): discarded_reads1 = self._absolute(str(self.Parameters['-3'].Value)) else: raise ValueError( "No discarded-reads1 (flag -3) output path specified") return disca... |
def _discarded_reads2_out_file_name(self): """Checks if file name is set for discarded reads2 output. Returns absolute path.""" if self.Parameters['-4'].isOn(): discarded_reads2 = self._absolute(str(self.Parameters['-4'].Value)) else: raise ValueError( "No discarded-reads2 (flag -4) output path specified") return disca... |
def _assembled_out_file_name(self): """Checks file name is set for assembled output. Returns absolute path.""" if self.Parameters['-s'].isOn(): assembled_reads = self._absolute(str(self.Parameters['-s'].Value)) else: raise ValueError( "No assembled-reads (flag -s) output path specified") return assembled_reads |
def _pretty_alignment_out_file_name(self): """Checks file name is set for pretty alignment output. Returns absolute path.""" if self.Parameters['-E'].isOn(): pretty_alignment = self._absolute(str(self.Parameters['-E'].Value)) else: raise ValueError( "No pretty-=alignment (flag -E) output path specified") return pretty_... |
def _get_result_paths(self, data): """Captures SeqPrep output. """ result = {} # Always output: result['UnassembledReads1'] = ResultPath(Path= self._unassembled_reads1_out_file_name( ), IsWritten=True) result['UnassembledReads2'] = ResultPath(Path= self._unassembled_reads2_out_file_name( ), IsWritten=True) # optional o... |
def get_files_for_document(document): """ Returns the available files for all languages. In case the file is already present in another language, it does not re-add it again. """ files = [] for doc_trans in document.translations.all(): if doc_trans.filer_file is not None and \ doc_trans.filer_file not in files: doc_tra... |
def get_frontpage_documents(context): """Returns the library favs that should be shown on the front page.""" req = context.get('request') qs = Document.objects.published(req).filter(is_on_front_page=True) return qs |
def append_comps(comps, char): """ Append a character to `comps` following this rule: a vowel is added to the vowel part if there is no last consonant, else to the last consonant part; a consonant is added to the first consonant part if there is no vowel, and to the last consonant part if the vowel part is not empty. >... |
def separate(string): """ Separate a string into smaller parts: first consonant (or head), vowel, last consonant (if any). >>> separate('tuong') ['t','uo','ng'] >>> separate('ohmyfkinggod') ['ohmyfkingg','o','d'] """ def atomic_separate(string, last_chars, last_is_vowel): if string == "" or (last_is_vowel != is_vowel(s... |
and comps[1][0] in 'iI' and len(comps[1]) > 1) or (comps[0] in 'qQ' and comps[1][0] in 'uU')): comps[0] += comps[1][:1] comps[1] = comps[1][1:] return comps |
def swarm_denovo_cluster(seq_path, d=1, threads=1, HALT_EXEC=False): """ Function : launch the Swarm de novo OTU picker Parameters: seq_path, filepath to reads d, resolution threads, number of threads to use Return : clusters, list of lists """ # Check sequence file exists if not exists(seq_path): raise ValueError("%s ... |
list of lists (clusters) swarm.files_to_remove.append(tmp_swarm_otumap) # Launch Swarm # set the data string to include the read filepath # (to be passed as final arguments in the swarm command) clusters = swarm(seq_path) remove_files(swarm.files_to_remove, error_on_missing=False) # Return clusters return clusters |
def _swarm_breaker(self, seq_path): """ Input : seq_path, a filepath to de-replicated input FASTA reads Method: using swarm_breaker.py, break chains of amplicons based on abundance information. Abundance is stored after the final underscore '_' in each sequence label (recommended procedure for Swarm) Return: clusters, ... |
information from the labels for i in range(len(seq_ids)): seq_ids[i] = seq_ids[i].rsplit("_", 1)[0] clusters.append(seq_ids) except OSError: raise ApplicationNotFoundError("Cannot find swarm_breaker.py " "in the $PATH directories.") return clusters |
def _apply_identical_sequences_prefilter(self, seq_path): """ Input : seq_path, a filepath to input FASTA reads Method: prepares and writes de-replicated reads to a temporary FASTA file, calls parent method to do the actual de-replication Return: exact_match_id_map, a dictionary storing de-replicated amplicon ID as key... |
def _map_filtered_clusters_to_full_clusters(self, clusters, filter_map): """ Input: clusters, a list of cluster lists filter_map, the seq_id in each clusters is the key to the filter_map containing all seq_ids with duplicate FASTA sequences Output: an extended list of cluster lists """ results = [] for cluster in clust... |
def _get_result_paths(self, data): """ Set the result paths """ # Swarm OTU map (mandatory output) return {'OtuMap': ResultPath(Path=self.Parameters['-o'].Value, IsWritten=True)} |
def connect_to_database(host=None, port=None, connect=False, **kwargs): """ Explicitly begins a database connection for the application (if this function is not called, a connection is created when it is first needed). Takes arguments identical to pymongo.MongoClient.__init__ @param host: the hostname to connect to @pa... |
def authenticate_connection(username, password, db=None): """ Authenticates the current database connection with the passed username and password. If the database connection uses all default parameters, this can be called without connect_to_database. Otherwise, it should be preceded by a connect_to_database call. @para... |
def add_user(name, password=None, read_only=None, db=None, **kwargs): """ Adds a user that can be used for authentication. @param name: the name of the user to create @param passowrd: the password of the user to create. Can not be used with the userSource argument. @param read_only: if True the user will be read only @... |
already authenticated with another user with appropriate privileges to add a user to the specified database. """ return CONNECTION.add_user(name, password=password, read_only=read_only, db=db, **kwargs) |
def add_superuser(name, password, **kwargs): """ Adds a user with userAdminAnyDatabase role to mongo. @param name: the name of the user to create @param passowrd: the password of the user to create. Can not be used with the userSource argument. @param **kwargs: forwarded to pymongo.database.add_user """ return CONNECTI... |
def list_database(db=None): """ Lists the names of either the databases on the machine or the collections of a particular database @param db: the database for which to list the collection names; if db is None, then it lists all databases instead the contents of the database with the name passed in db """ if db is None:... |
def connect(self, host=None, port=None, connect=False, **kwargs): """ Explicitly creates the MongoClient; this method must be used in order to specify a non-default host or port to the MongoClient. Takes arguments identical to MongoClient.__init__""" try: self.__connection = MongoClient(host=host, port=port, connect=co... |
def authenticate(self, username, password, db=None): """ Authenticates the MongoClient with the passed username and password """ if db is None: return self.get_connection().admin.authenticate(username, password) return self.get_connection()[db].authenticate(username, password) |
def add_user(self, name, password=None, read_only=None, db=None, **kwargs): """ Adds a user that can be used for authentication """ if db is None: return self.get_connection().admin.add_user( name, password=password, read_only=read_only, **kwargs) return self.get_connection()[db].add_user( name, password=password, read... |
def metrique_object(_oid, _id=None, _hash=None, _start=None, _end=None, _e=None, _v=None, id=None, __v__=None, **kwargs): ''' Function which takes a dictionary (Mapping) object as input and returns return back a metrique object. Special meta property are added to each object:: _oid: ... _start: ... ... FIXME ''' # NOTE... |
= dt2ts(_end) if _end else None _err_msg = "_end(%s) must be >= _start(%s) or None!" % (_end, _start) assert _end is None or bool(_end >= _start), _err_msg # these meta fields are used to generate unique object _hash kwargs['_oid'] = _oid kwargs['_v'] = _v kwargs['_id'] = gen_id(_oid, _start, _end) # ignore passed in _... |
def _add_variants(self, key, value, schema): ''' also possible to define some function that takes current value and creates a new value from it ''' variants = schema.get('variants') obj = {} if variants: for _key, func in variants.iteritems(): _value = func(value, self.store) obj.update({_key: _value}) return obj |
def _type_container(self, value, _type): ' apply type to all values in the list ' if value is None: # normalize null containers to empty list return [] elif not isinstance(value, list): raise ValueError("expected list type, got: %s" % type(value)) else: return sorted(self._type_single(item, _type) for item in value) |
def _type_single(self, value, _type): ' apply type to the single value ' if value is None or _type in (None, NoneType): # don't convert null values # default type is the original type if none set pass elif isinstance(value, _type): # or values already of correct type # normalize all dates to epochs value = dt2ts(value)... |
def flush(self, objects=None, batch_size=None, **kwargs): ''' flush objects stored in self.container or those passed in''' batch_size = batch_size or self.config.get('batch_size') # if we're flushing these from self.store, we'll want to # pop them later. if objects: from_store = False else: from_store = True objects = ... |
since still will be < batch_size batch.extend(_grouped) else: if batch: # get the last batch too logger.debug("Upserting last batch of %s objects" % len(batch)) _ = self.upsert(objects=batch, **kwargs) _ids.extend(_) logger.debug("... Finished upserting all objects!") if from_store: for _id in _ids: # try to pop the _i... |
def count(self, query=None, date=None): ''' Run a query on the given cube and return only the count of resulting matches. :param query: The query in pql :param date: date (metrique date range) that should be queried If date==None then the most recent versions of the objects will be queried. :param collection: cube name... |
def index(self, fields, name=None, **kwargs): ''' Build a new index on a cube. Examples: + index('field_name') :param fields: A single field or a list of (key, direction) pairs :param name: (optional) Custom name to use for this index :param collection: cube name :param owner: username of cube owner ''' return self.pro... |
def share(self, with_user, roles=None): ''' Give cube access rights to another user ''' return self.proxy.share(table=self.name, with_user=with_user, roles=roles) |
def build_database_sortmerna(fasta_path, max_pos=None, output_dir=None, temp_dir=tempfile.gettempdir(), HALT_EXEC=False): """ Build sortmerna db from fasta_path; return db name and list of files created Parameters ---------- fasta_path : string path to fasta file of sequences to build database. max_pos : integer, optio... |
Will cd to this directory, so just pass the filename # so the app is not confused by relative paths fasta_path = fasta_filename index_basename = splitext(fasta_filename)[0] db_name = join(output_dir, index_basename) # Instantiate the object sdb = IndexDB(WorkingDir=output_dir, HALT_EXEC=HALT_EXEC) # The parameter --ref... |
'StdOut'} and hasattr(v, 'name')] return db_name, db_filepaths |
def sortmerna_ref_cluster(seq_path=None, sortmerna_db=None, refseqs_fp=None, result_path=None, tabular=False, max_e_value=1, similarity=0.97, coverage=0.97, threads=1, best=1, HALT_EXEC=False ): """Launch sortmerna OTU picker Parameters ---------- seq_path : str filepath to query sequences. sortmerna_db : str indexed r... |
which did not align """ # Instantiate the object smr = Sortmerna(HALT_EXEC=HALT_EXEC) # Set input query sequences path if seq_path is not None: smr.Parameters['--reads'].on(seq_path) else: raise ValueError("Error: a read file is mandatory input.") # Set the input reference sequence + indexed database path if sortmerna_... |
None: smr.Parameters['--id'].on(similarity) # Set query coverage threshold if coverage is not None: smr.Parameters['--coverage'].on(coverage) # Set number of best alignments to output if best is not None: smr.Parameters['--best'].on(best) # Set Blast tabular output # The option --blast 3 represents an # m8 blast tabula... |
file and failures FASTA file # (currently these are re-constructed using pick_rep_set.py # further in the OTU-picking pipeline) smr_files_to_remove = [app_result['FastaForDenovo'].name, app_result['FastaMatches'].name, app_result['OtuMap'].name] return clusters, failures, smr_files_to_remove |
def sortmerna_map(seq_path, output_dir, refseqs_fp, sortmerna_db, e_value=1, threads=1, best=None, num_alignments=None, HALT_EXEC=False, output_sam=False, sam_SQ_tags=False, blast_format=3, print_all_reads=True, ): """Launch sortmerna mapper Parameters ---------- seq_path : str filepath to reads. output_dir : str dirpa... |
output_sam : bool, optional flag to set SAM output format [default: False]. sam_SQ_tags : bool, optional add SQ field to SAM output (if output_SAM is True) [default: False]. blast_format : int, optional Output Blast m8 tabular + 2 extra columns for CIGAR string and query coverge [default: 3]. print_all_reads : bool, op... |
sequences path smr.Parameters['--reads'].on(seq_path) # Set Blast tabular output # The option --blast 3 represents an # m8 blast tabular output + two extra # columns containing the CIGAR string # and the query coverage if blast_format: smr.Parameters['--blast'].on(blast_format) # Output alignments in SAM format if outp... |
is not None: smr.Parameters['-a'].on(threads) # Turn off parameters related to OTU-picking smr.Parameters['--fastx'].off() smr.Parameters['--otu_map'].off() smr.Parameters['--de_novo_otu'].off() smr.Parameters['--id'].off() smr.Parameters['--coverage'].off() # Run sortmerna app_result = smr() return app_result |
def _get_result_paths(self, data): """ Build the dict of result filepaths """ # get the filepath of the indexed database (after comma) # /path/to/refseqs.fasta,/path/to/refseqs.idx # ^------------------^ db_name = (self.Parameters['--ref'].Value).split(',')[1] result = {} extensions = ['bursttrie', 'kmer', 'pos', 'stat... |
def _get_result_paths(self, data): """ Set the result paths """ result = {} # get the file extension of the reads file (sortmerna # internally outputs all results with this extension) fileExtension = splitext(self.Parameters['--reads'].Value)[1] # at this point the parameter --aligned should be set as # sortmerna will ... |
output) result['FastaForDenovo'] =\ ResultPath(Path=output_base + '_denovo' + fileExtension, IsWritten=self.Parameters['--de_novo_otu'].isOn()) # Log file result['LogFile'] =\ ResultPath(Path=output_base + '.log', IsWritten=self.Parameters['--log'].isOn()) return result |
def get_color(self, color): ''' Returns a color to use. :param integer/string color: Color for the plot. Can be an index for the color from COLORS or a key(string) from CNAMES. ''' if color is None: color = self.counter if isinstance(color, str): color = CNAMES[color] self.counter = color + 1 color %= len(COLORS) retur... |
def plot(self, series, label='', color=None, style=None): ''' Wrapper around plot. :param pandas.Series series: The series to be plotted, all values must be positive if stacked is True. :param string label: The label for the series. :param integer/string color: Color for the plot. Can be an index for the color from COL... |
def plots(self, series_list, label_list, colors=None): ''' Plots all the series from the list. The assumption is that all of the series share the same index. :param list series_list: A list of series which should be plotted :param list label_list: A list of labels corresponding to the series :params list list_of_colors... |
def line(self, x, label=None, y='bottom', color='grey', ax=None, **kwargs): ''' Creates a vertical line in the plot. :param x: The x coordinate of the line. Should be in the same units as the x-axis. :param string label: The label to be displayed. :param y: May be 'top', 'bottom' or int. The y coordinate of the text-la... |
verticalalignment=verticalalignment) |
def lines(self, lines_dict, y='bottom', color='grey', **kwargs): ''' Creates vertical lines in the plot. :param lines_dict: A dictionary of label, x-coordinate pairs. :param y: May be 'top', 'bottom' or int. The y coordinate of the text-labels. :param color color: The color of the lines. ''' for l, x in lines_dict.item... |
def plot(self, series, series_diff=None, label='', color=None, style=None): ''' :param pandas.Series series: The series to be plotted, all values must be positive if stacked is True. :param pandas.Series series_diff: The series representing the diff that will be plotted in the bottom part. :param string label: The labe... |
def line(self, x, label=None, y='bottom', color='grey', **kwargs): ''' Creates a vertical line in the plot. :param x: The x coordinate of the line. Should be in the same units as the x-axis. :param string label: The label to be displayed. :param y: May be 'top', 'bottom' or int. The y coordinate of the text-label. :par... |
def published(self, request=None): """ Returns the published documents in the current language. :param request: A Request instance. """ language = getattr(request, 'LANGUAGE_CODE', get_language()) if not language: return self.model.objects.none() qs = self.get_queryset() qs = qs.filter( translations__is_published=True,... |
def _format(self): """Format search queries to perform in bulk. Build up the URLs to call for the search engine. These will be ran through a bulk processor and returned to a detailer. """ self.log.debug("Formatting URLs to request") items = list() for i in range(0, self.limit, 10): query = '"%s" %s' % (self.domain, sel... |
def _process(self, responses): """Process search engine results for detailed analysis. Search engine result pages (SERPs) come back with each request and will need to be extracted in order to crawl the actual hits. """ self.log.debug("Processing search results") items = list() for response in responses: try: soup = Bea... |
def _fetch(self, urls): """Perform bulk collection of data and return the content. Gathering responses is handled by the base class and uses futures to speed up the processing. Response data is saved inside a local variable to be used later in extraction. """ responses = self._request_bulk(urls) for response in respons... |
def _extract(self): """Extract email addresses from results. Text content from all crawled pages are ran through a simple email extractor. Data is cleaned prior to running pattern expressions. """ self.log.debug("Extracting emails from text content") for item in self.data: emails = extract_emails(item, self.domain, sel... |
def search(self): """Run the full search process. Simple public method to abstract the steps needed to produce a full search using the engine. """ requests = self._format() serps = self._fetch(requests) urls = self._process(serps) details = self._fetch(urls) emails = self._extract() return {'emails': emails, 'processed... |
def which(executable_name, env_var='PATH'): """Equivalent to ``which executable_name`` in a *nix environment. Will return ``None`` if ``executable_name`` cannot be found in ``env_var`` or if ``env_var`` is not set. Otherwise will return the first match in ``env_var``. Note: this function will likely not work on Windows... |
def cmdline_generator(param_iter, PathToBin=None, PathToCmd=None, PathsToInputs=None, PathToOutput=None, PathToStderr='/dev/null', PathToStdout='/dev/null', UniqueOutputs=False, InputParam=None, OutputParam=None): """Generates command lines that can be used in a cluster environment param_iter : ParameterIterBase subcla... |
not isinstance(PathsToInputs, list): PathsToInputs = [PathsToInputs] # PathToBin and PathToCmd can be blank if PathToBin is None: PathToBin = '' if PathToCmd is None: PathToCmd = '' # stdout_ and stderr_ do not have to be redirected if PathToStdout is None: stdout_ = '' else: stdout_ = '> "%s"' % PathToStdout if PathTo... |
# Input can come from stdin or specified input argument if InputParam is None: input = '< "%s"' % inputfile else: input_param = params[InputParam] input_param.on('"%s"' % inputfile) input = str(input_param) input_param.off() cmdline.append(input) if UniqueOutputs: cmdline.append(''.join([output, str(output_count)])) ou... |
def get_tmp_filename(tmp_dir=gettempdir(), prefix="tmp", suffix=".txt", result_constructor=FilePath): """ Generate a temporary filename and return as a FilePath object tmp_dir: the directory to house the tmp_filename prefix: string to append to beginning of filename Note: It is very useful to have prefix be descriptive... |
= "" # if not current directory, append "/" if not already on path elif not tmp_dir.endswith("/"): tmp_dir += "/" chars = "abcdefghigklmnopqrstuvwxyz" picks = chars + chars.upper() + "0123456790" return result_constructor(tmp_dir) + result_constructor(prefix) +\ result_constructor("%s%s" % (''.join([choice(picks) for i... |
def guess_input_handler(seqs, add_seq_names=False): """Returns the name of the input handler for seqs.""" if isinstance(seqs, str): if '\n' in seqs: # can't be a filename... return '_input_as_multiline_string' else: # assume it was a filename return '_input_as_string' if isinstance(seqs, list) and len(seqs) and isinsta... |
def cleanUp(self): """ Delete files that are written by CommandLineApplication from disk WARNING: after cleanUp() you may still have access to part of your result data, but you should be aware that if the file size exceeds the size of the buffer you will only have part of the file. To be safe, you should not use cleanU... |
def _input_as_multiline_string(self, data): """Write a multiline string to a temp file and return the filename. data: a multiline string to be written to a file. * Note: the result will be the filename as a FilePath object (which is a string subclass). """ filename = self._input_filename = \ FilePath(self.getTmpFilenam... |
def _input_as_lines(self, data): """ Write a seq of lines to a temp file and return the filename string data: a sequence to be written to a file, each element of the sequence will compose a line in the file * Note: the result will be the filename as a FilePath object (which is a string subclass). * Note: '\n' will be s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.