code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
chars = 'abcdefghigklmnopqrstuvwxyz' all_chars = chars + chars.upper() + '01234567890' picks = list(all_chars) return ''.join([choice(picks) for i in range(num_chars)])
def make_unique_str(num_chars=20)
make a random string of characters for a temp filename
2.819572
2.835447
0.994401
result = checked_ids.keys() for i in checked_ids.values(): result.extend(i.keys()) return dict.fromkeys(result).keys()
def keep_everything_scorer(checked_ids)
Returns every query and every match in checked_ids, with best score.
4.280483
4.032063
1.061611
if isinstance(scorer, int): scorer = make_shotgun_scorer(scorer) seqs_to_check = list(seqs) checked_ids = {} curr_iteration = 0 while seqs_to_check: unchecked_ids = {} #pass seqs to command all_output = app(seqs_to_check) output = all_output.get('BlastOut...
def ids_from_seqs_iterative(seqs, app, query_parser, \ scorer=keep_everything_scorer, max_iterations=None, blast_db=None,\ max_seqs=None, )
Gets the ids from each seq, then does each additional id until all done. If scorer is passed in as an int, uses shotgun scorer with that # hits.
3.671952
3.457884
1.061907
# set up params to use with blastp params = { # matrix "-M":"BLOSUM62", # max procs "-a":"1", # expectation "-e":e_value, # max seqs to show "-b":max_hits, # max one line descriptions "-v":max_hits, # program ...
def blastp(seqs, blast_db="nr", e_value="1e-20", max_hits=200, working_dir=tempfile.gettempdir(), blast_mat_root=None, extra_params={})
Returns BlastResult from input seqs, using blastp. Need to add doc string
5.001742
5.179815
0.965622
global fh fh = open(fname, 'w') if os.name == 'nt': # Code for NT systems got from: http://code.activestate.com/recipes/65203/ import win32con import win32file import pywintypes LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK LOCK_SH = ...
def set_lock(fname)
Try to lock file and write PID. Return the status of operation.
2.799244
2.74013
1.021573
if not set_lock(fname): logger.error('File {} is already locked. Terminating.'.format(fname)) sys.exit()
def assert_lock(fname)
If file is locked then terminate program else lock file.
5.691476
4.54882
1.251198
fasta_dir, fasta_filename = split(fasta_path) if not output_dir: output_dir = fasta_dir or '.' # Will cd to this directory, so just pass the filename # so the app is not confused by relative paths fasta_path = fasta_filename if not output_dir.endswith('/'): db_n...
def build_blast_db_from_fasta_path(fasta_path, is_protein=False, output_dir=None, HALT_EXEC=False)
Build blast db from fasta_path; return db name and list of files created **If using to create temporary blast databases, you can call cogent.util.misc.remove_files(db_filepaths) to clean up all the files created by formatdb when you're done with the database. fasta_path: path to fasta ...
4.014791
3.695091
1.08652
output_dir = output_dir or '.' _, fasta_path = mkstemp(dir=output_dir, prefix="BLAST_temp_db_", suffix=".fasta") fasta_f = open(fasta_path, 'w') for line in fasta_file: fasta_f.write('%s\n' % line.strip()) fasta_f.close() blast_db, db_filepaths = build_...
def build_blast_db_from_fasta_file(fasta_file, is_protein=False, output_dir=None, HALT_EXEC=False)
Build blast db from fasta_path; return db name and list of files created **If using to create temporary blast databases, you can call cogent.util.misc.remove_files(db_filepaths) to clean up all the files created by formatdb when you're done with the database. fasta_path: path to fasta ...
2.359948
2.477844
0.95242
# Build a temp filepath _, tmp_fasta_filepath = mkstemp(prefix='Blast_tmp_db', suffix='.fasta') # open the temp file tmp_fasta_file = open(tmp_fasta_filepath, 'w') # write the sequence collection to file tmp_fasta_file.write(seqs.toFasta()) tmp_fasta_file.close() # build the bast ...
def build_blast_db_from_seqs(seqs, is_protein=False, output_dir='./', HALT_EXEC=False)
Build blast db from seqs; return db name and list of files created **If using to create temporary blast databases, you can call cogent.util.misc.remove_files(db_filepaths) to clean up all the files created by formatdb when you're done with the database. seqs: sequence collection or ali...
2.797125
2.791734
1.001931
usage = 'usage: %prog [options] fasta_filepath' version = 'Version: %prog 0.1' parser = OptionParser(usage=usage, version=version) # A binary 'verbose' flag parser.add_option('-p', '--is_protein', action='store_true', dest='is_protein', default=False, ...
def parse_command_line_parameters()
Parses command line arguments
3.590931
3.557359
1.009437
self.Parameters['-i'].on(data) # access data through self.Parameters so we know it's been cast # to a FilePath input_filepath = self.Parameters['-i'].Value input_file_dir, input_filename = split(input_filepath) input_file_base, input_file_ext = splitext(input_fil...
def _input_as_parameter(self, data)
Set the input path and log path based on data (a fasta filepath)
8.876953
7.85872
1.129567
# access data through self.Parameters so we know it's been cast # to a FilePath wd = self.WorkingDir db_name = self.Parameters['-n'].Value log_name = self.Parameters['-l'].Value result = {} result['log'] = ResultPath(Path=wd + log_name, IsWritten=True) ...
def _get_result_paths(self, data)
Build the dict of result filepaths
5.296118
5.036336
1.051582
if not hasattr(self, "_cached_session_key"): session_id_bytes = self.get_secure_cookie("session_id") session_id = None if session_id_bytes: try: session_id = session_id_bytes.decode('utf-8') except: ...
def _session_key(self)
Gets the redis key for a session
2.875697
2.745466
1.047435
session_time = oz.settings["session_time"] if session_time: self.redis().expire(self._session_key, session_time)
def _update_session_expiration(self)
Updates a redis item to expire later since it has been interacted with recently
9.233459
7.423958
1.243738
value = self.redis().hget(self._session_key, name) or default self._update_session_expiration() return value
def get_session_value(self, name, default=None)
Gets a session value
6.210351
5.65348
1.098501
self.redis().hset(self._session_key, name, value) self._update_session_expiration()
def set_session_value(self, name, value)
Sets a session value
7.095634
6.918643
1.025582
self.redis().hdel(self._session_key, name) self._update_session_expiration()
def clear_session_value(self, name)
Removes a session value
6.517989
6.888731
0.946181
''' Sanic middleware that utilizes a security class's "rewrite" method to check ''' if singletons.settings.SECURITY is not None: security_class = singletons.settings.load('SECURITY') else: security_class = DummySecurity security = security_class() try: new_path = ...
async def rewrite_middleware(server, request)
Sanic middleware that utilizes a security class's "rewrite" method to check
6.054685
3.942377
1.535796
if c in [Settings.SUCCESS, Settings.CREATED, Settings.ACCEPTED]: return details elif c == Settings.BAD_REQUEST: raise ErrAtlasBadRequest(c, details) elif c == Settings.UNAUTHORIZED: raise ErrAtlasUnauthorized(c, details) elif c == Settings.FOR...
def answer(self, c, details)
Answer will provide all necessary feedback for the caller Args: c (int): HTTP Code details (dict): Response payload Returns: dict: Response payload Raises: ErrAtlasBadRequest ErrAtlasUnauthorized ...
2.431517
1.703008
1.427778
r = None try: r = requests.get(uri, allow_redirects=True, timeout=Settings.requests_timeout, headers={}, auth=HTTPDigestAuth(self.user, self.password)) ...
def get(self, uri)
Get request Args: uri (str): URI Returns: Json: API response Raises: Exception: Network issue
3.943242
4.100462
0.961658
''' Walk through repo commits to generate a list of repo commit objects. Each object has the following properties: * repo uri * general commit info * files added, removed fnames * lines added, removed * acked_by * s...
def get_objects(self, uri, pull=True, **kwargs)
Walk through repo commits to generate a list of repo commit objects. Each object has the following properties: * repo uri * general commit info * files added, removed fnames * lines added, removed * acked_by * signed_off_by ...
4.021816
3.247871
1.238293
# This should be a yield from instead. for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)): yield value
def _dict_values_sorted_by_key(dictionary)
Internal helper to return the values of a dictionary, sorted by key.
8.241944
8.110795
1.01617
name = f.__name__ def func(self, *args, **kwargs): if not args and not kwargs: if hasattr(self, '_%s' % name): return getattr(self, '_%s' % name) a = f(self, *args, **kwargs) setattr(self, '_%s' % name, a) return a else: ...
def _ondemand(f)
Decorator to only request information if not in cache already.
2.025152
1.971935
1.026987
LOG.debug('get_memory: %d bytes from %x', size, start) return get_memory(self.ida.idaapi, start, size, default_byte=self.default_byte)
def get_memory(self, start, size)
Retrieve an area of memory from IDA. Returns a sparse dictionary of address -> value.
6.431928
5.879914
1.093881
''' Run `rpm -q` command on a {local, remote} system to get back details of installed RPMs. Default rpm details extracted are as follows: * name * version * release * arch * nvra * license * os ...
def get_objects(self, **kwargs)
Run `rpm -q` command on a {local, remote} system to get back details of installed RPMs. Default rpm details extracted are as follows: * name * version * release * arch * nvra * license * os * packager ...
4.673229
2.589181
1.804906
'''Handle 404 Not Found This handler should be used to handle error http 404 not found for all endpoints or if resource not available. ''' error = format_error(title='Resource not found', detail=str(exception)) return json(return_an_error(error), status=HTTPStatus.NOT_FOUND)
def handle_404(request, exception)
Handle 404 Not Found This handler should be used to handle error http 404 not found for all endpoints or if resource not available.
8.717679
3.721051
2.3428
if name in container: raise Exception("%s '%s' already exists" % (t, name)) else: container[name] = value
def _add_to_dict(t, container, name, value)
Adds an item to a dictionary, or raises an exception if an item with the specified key already exists in the dictionary.
4.120343
3.322416
1.240165
# Load the config file if config == None: config = {} config_source = None try: with open(os.environ.get("OZ_CONFIG", "config.py")) as f: config_source = f.read() except Exception: tornado.log.gen_log.info("Could not read config.py",...
def initialize(config=None)
Initializes oz
3.569142
3.482298
1.024939
# Relevant middleware is cached so we don't have to rediscover it # every time. Fetch the cached value if possible. listeners = self._triggers.get(name, []) # Execute each piece of middleware for listener in listeners: result = listener(*args, **kwargs) ...
def trigger(self, name, *args, **kwargs)
Triggers an event to run through middleware. This method will execute a chain of relevant trigger callbacks, until one of the callbacks returns the `break_trigger`.
9.086554
7.204062
1.26131
''' Make necessary directories to hold cache value ''' if subdir is not None: dirname = self.cache_path if subdir: dirname = os.path.join(dirname, subdir) else: dirname = os.path.dirname(self.cache_path) os.makedirs(dirn...
def cache_makedirs(self, subdir=None)
Make necessary directories to hold cache value
3.118423
2.265516
1.376474
global _session_makers connection_string = connection_string or oz.settings["db"] if not connection_string in _session_makers: _session_makers[connection_string] = sessionmaker(bind=engine(connection_string=connection_string)) return _session_makers[connection_string]()
def session(connection_string=None)
Gets a SQLAlchemy session
3.350206
3.103012
1.079663
if params is None: params = {} if '-out' not in params: params['-out'] = 'blast9' blat = Blat(params=params) result = blat([query_fasta_fp, database_fasta_fp, output_fp]) return result['output']
def assign_reads_to_database(query_fasta_fp, database_fasta_fp, output_fp, params=None)
Assign a set of query sequences to a reference database query_fasta_fp : absolute file path to query sequences database_fasta_fp : absolute file path to the reference database output_fp : absolute file path of the output file to write params : dict of BLAT specific parameters. This method returns ...
3.983345
3.634648
1.095937
if params is None: params = {} my_params = {'-t': 'dna', '-q': 'dna' } # if the user specified parameters other than default, then use them. # However, if they try to change the database or query types, raise an # applciation error. if '-t' in par...
def assign_dna_reads_to_dna_database(query_fasta_fp, database_fasta_fp, output_fp, params=None)
Assign DNA reads to a database fasta of DNA sequences. Wraps assign_reads_to_database, setting database and query types. All parameters are set to default unless params is passed. query_fasta_fp: absolute path to the query fasta file containing DNA sequences. database_fasta_fp: abso...
3.628279
3.428078
1.0584
if params is None: params = {} my_params = {'-t': 'prot', '-q': 'prot'} # make sure temp_dir specifies an absolute path if not isabs(temp_dir): raise ApplicationError("temp_dir must be an absolute path.") # if the user specified parameters other than default, then use them. ...
def assign_dna_reads_to_protein_database(query_fasta_fp, database_fasta_fp, output_fp, temp_dir="/tmp", params=None)
Assign DNA reads to a database fasta of protein sequences. Wraps assign_reads_to_database, setting database and query types. All parameters are set to default unless params is passed. A temporary file must be written containing the translated sequences from the input query fasta file because BLAT canno...
3.316493
3.162175
1.048801
command_parts = [] cd_command = ''.join(['cd ', str(self.WorkingDir), ';']) if self._command is None: raise ApplicationError('_command has not been set.') command = self._command parameters = sorted([str(x) for x in self.Parameters.values() ...
def _get_base_command(self)
Gets the command that will be run when the app controller is called.
4.668903
4.574389
1.020662
'''Takes the positional arguments as input in a list. The list input here should be [query_file_path, database_file_path, output_file_path]''' query, database, output = data if (not isabs(database)) \ or (not isabs(query)) \ or (not isabs(output))...
def _input_as_list(self, data)
Takes the positional arguments as input in a list. The list input here should be [query_file_path, database_file_path, output_file_path]
2.013665
1.837835
1.095672
if lon < 0: lon = lon+360 url = cfg['url'] doy = int(d.strftime('%j')) dataset = open_url(url) dn = (np.abs(doy-dataset['time'][:])).argmin() xn = (np.abs(lon-dataset['lon'][:])).argmin() yn = (np.abs(lat-dataset['lat'][:])).argmin() if re.match("temperature\d?$", var): ...
def woa_profile_from_dap(var, d, lat, lon, depth, cfg)
Monthly Climatologic Mean and Standard Deviation from WOA, used either for temperature or salinity. INPUTS time: [day of the year] lat: [-90<lat<90] lon: [-180<lon<180] depth: [meters] Reads the WOA Monthly Climatology NetCDF file and returns the corresponding WOA value...
2.243792
2.227589
1.007274
d = np.asanyarray(d) lat = np.asanyarray(lat) lon = np.asanyarray(lon) lon[lon < 0] += 360 doy = np.array([int(dd.strftime('%j')) for dd in d]) nc = netCDF4.Dataset(expanduser(filename), 'r') if varnames is None: varnames = {} for v in nc.variables.keys(): ...
def woa_track_from_file(d, lat, lon, filename, varnames=None)
Temporary solution: WOA for surface track
2.302442
2.284151
1.008008
dims, idx = cropIndices(self.dims, lat, lon, depth, doy) subset = {} for v in var: subset[v] = ma.asanyarray([ self.ncs[tnn][v][0, idx['zn'], idx['yn'], idx['xn']] \ for tnn in idx['tn']]) return subset, dims
def crop(self, doy, depth, lat, lon, var)
Crop a subset of the dataset for each var Given doy, depth, lat and lon, it returns the smallest subset that still contains the requested coordinates inside it. It handels special cases like a region around greenwich and the international date line. Accep...
8.336362
9.237135
0.902484
if not objtype: objtype = cls.OBJTYPE if not path: path = cls.PATH if not query: query = kwargs return objtype.db(path).find(query).count()
def count(cls, path=None, objtype=None, query=None, **kwargs)
Like __init__, but simply returns the number of objects that match the query rather than returning the objects NOTE: The path and objtype parameters to this function are to allow use of the DatabaseCollection class directly. However, this class is intended for subclassing and c...
3.332203
3.093752
1.077075
if not objtype: objtype = cls.OBJTYPE if not path: path = cls.PATH db = objtype.db(path) if not query: query = kwargs results = list(db.find(query).sort(ID_KEY, ASCENDING).limit(page_size)) while results: page = [ob...
def iterator(cls, path=None, objtype=None, query=None, page_size=1000, **kwargs)
Linear time, constant memory, iterator for a mongo collection. @param path: the path of the database to query, in the form "database.colletion"; pass None to use the value of the PATH property of the object or, if that is none, the PATH property of OBJTYPE @p...
2.809331
2.579574
1.089068
obj = self.OBJTYPE.create(data, path=self.PATH, **kwargs) self.append(obj) return obj
def insert(self, data, **kwargs)
Calls the create method of OBJTYPE NOTE: this function is only properly usable on children classes that have overridden either OBJTYPE or PATH. @param data: the data of the new object to be created @param **kwargs: forwarded to create @raise DatabaseCon...
8.486588
5.710621
1.486106
for elt in self: DatabaseObject.create(elt, path=new_path) for elt in self: elt._collection.remove({ID_KEY: elt[ID_KEY]})
def _move(self, new_path)
Moves the collection to a different database path NOTE: this function is intended for command prompt use only. WARNING: if execution is interrupted halfway through, the collection will be split into multiple pieces. Furthermore, there is a possible duplication of the d...
9.904782
9.913641
0.999106
seqs = LoadSeqs(data=seqs, moltype=moltype, aligned=False) try: s1, s2 = seqs.values() except ValueError: raise ValueError( "Pairwise aligning of seqs requires exactly two seqs.") try: gap_open = params['gap_open'] except KeyError: gap_open = 5 ...
def pair_hmm_align_unaligned_seqs(seqs, moltype=DNA_cogent, params={})
Checks parameters for pairwise alignment, returns alignment. Code from Greg Caporaso.
3.31312
3.413636
0.970555
''' Viewers determines the viewers installed based on settings, then uses the conversion infrastructure to convert all these JS files into a single JS bundle, that is then served. As with media, it will simply serve a cached version if necessary. ''' # Generates single bundle as such: # ...
async def viewers_js(request)
Viewers determines the viewers installed based on settings, then uses the conversion infrastructure to convert all these JS files into a single JS bundle, that is then served. As with media, it will simply serve a cached version if necessary.
10.161391
6.701115
1.516373
if params is None: params = {} if moltype == DNA or moltype == RNA: params['-nt'] = True elif moltype == PROTEIN: params['-nt'] = False else: raise ValueError, \ "FastTree does not support moltype: %s" % moltype.label if best_tree: param...
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None)
Returns a tree from alignment Will check MolType of aln object
5.001019
4.978793
1.004464
''' Load and transform csv data into a list of dictionaries. Each row in the csv will result in one dictionary in the list. :param uri: uri (file://, http(s)://) of csv file to load :param _oid: column or func to apply to map _oid in all resulting objects :p...
def get_objects(self, uri, _oid=None, _start=None, _end=None, load_kwargs=None, **kwargs)
Load and transform csv data into a list of dictionaries. Each row in the csv will result in one dictionary in the list. :param uri: uri (file://, http(s)://) of csv file to load :param _oid: column or func to apply to map _oid in all resulting objects :param _start: ...
3.994904
1.848671
2.16096
content = { "databaseName" : self.databaseName, "roles" : self.roles, "username" : self.username, "password" : self.password } return content
def getSpecs(self)
Get specs Returns: dict: Representation of the object
4.472044
4.698229
0.951857
for roleName in roleNames: self.add_role(databaseName, roleName, collectionName)
def add_roles(self, databaseName, roleNames, collectionName=None)
Add multiple roles Args: databaseName (str): Database Name roleNames (list of RoleSpecs): roles Keyword Args: collectionName (str): Collection Raises: ErrRoleException: role not compatible with the databaseName and/or...
2.621755
3.459487
0.757845
role = {"databaseName" : databaseName, "roleName" : roleName} if collectionName: role["collectionName"] = collectionName # Check atlas constraints if collectionName and roleName not in [RoleSpecs.read, RoleSpecs.readWrite]: ...
def add_role(self, databaseName, roleName, collectionName=None)
Add one role Args: databaseName (str): Database Name roleName (RoleSpecs): role Keyword Args: collectionName (str): Collection Raises: ErrRole: role not compatible with the databaseName and/or collectionName
3.833099
3.525955
1.08711
for roleName in roleNames: self.remove_role(databaseName, roleName, collectionName)
def remove_roles(self, databaseName, roleNames, collectionName=None)
Remove multiple roles Args: databaseName (str): Database Name roleNames (list of RoleSpecs): roles Keyword Args: collectionName (str): Collection
2.668605
4.254408
0.627256
role = {"databaseName" : databaseName, "roleName" : roleName} if collectionName: role["collectionName"] = collectionName if role in self.roles: self.roles.remove(role)
def remove_role(self, databaseName, roleName, collectionName=None)
Remove one role Args: databaseName (str): Database Name roleName (RoleSpecs): role Keyword Args: collectionName (str): Collection
2.556641
4.212738
0.606883
content = {} if len(self.roles) != 0: content["roles"] = self.roles if self.password: content["password"] = self.password return content
def getSpecs(self)
Get specs Returns: dict: Representation of the object
5.520106
5.38211
1.02564
# Sequence path is mandatory if (seq_path is None or not exists(seq_path)): raise ValueError("Error: FASTA query sequence filepath is " "mandatory input.") # Output directory is mandatory if (result_path is None or not isdir(dirname(realpat...
def sumaclust_denovo_cluster(seq_path=None, result_path=None, shortest_len=True, similarity=0.97, threads=1, exact=False, HALT_EXEC=False ...
Function : launch SumaClust de novo OTU picker Parameters: seq_path, filepath to reads; result_path, filepath to output OTU map; shortest_len, boolean; similarity, the similarity threshold (between (0,1]); threads, number of threa...
4.169467
3.96379
1.051889
result = {} # OTU map (mandatory output) result['OtuMap'] = ResultPath(Path=self.Parameters['-O'].Value, IsWritten=True) # SumaClust will not produce any output file if the # input file was empty, so we create an empty # o...
def _get_result_paths(self, data)
Set the result paths
8.218356
7.969716
1.031198
# write all vsearch output files to same directory # as output_filepath if working_dir is not specified if not working_dir: working_dir = dirname(abspath(output_filepath)) app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC) log_filepath = join(working_dir, log_name) uc_fil...
def vsearch_dereplicate_exact_seqs( fasta_filepath, output_filepath, output_uc=False, working_dir=None, strand="both", maxuniquesize=None, minuniquesize=None, sizein=False, sizeout=True, log_name="derep.log", HALT_EXEC=False)
Generates clusters and fasta file of dereplicated subsequences Parameters ---------- fasta_filepath : string input filepath of fasta file to be dereplicated output_filepath : string write the dereplicated sequences to output_filepath working_dir : ...
2.408309
2.303057
1.045701
# set working dir to same directory as the output # file (if not provided) if not working_dir: working_dir = dirname(output_filepath) app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC) log_filepath = join(working_dir, log_name) if minsize: app.Parameters['--minsi...
def vsearch_sort_by_abundance( fasta_filepath, output_filepath, working_dir=None, minsize=None, maxsize=None, log_name="abundance_sort.log", HALT_EXEC=False)
Fasta entries are sorted by decreasing abundance (Fasta entries are assumed to be dereplicated with the pattern "[>;]size=integer[;]" present in the read label, ex. use function vsearch_dereplicate_exact_seqs prior to calling this function) Parameters ---------- ...
2.784651
2.675972
1.040613
app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC) if not (output_chimeras or output_nonchimeras or output_alns or output_tabular): raise ValueError("At least one output format (output_chimeras," "output_nonchimeras, output_alns...
def vsearch_chimera_filter_de_novo( fasta_filepath, working_dir, output_chimeras=True, output_nonchimeras=True, output_alns=False, output_tabular=False, log_name="vsearch_uchime_de_novo_chimera_filtering.log", HALT_EXEC=False)
Detect chimeras present in the fasta-formatted filename, without external references (i.e. de novo). Automatically sort the sequences in filename by decreasing abundance beforehand. Output chimeras and non-chimeras to FASTA files and/or 3-way global alignments and/or tabular output. ...
1.766842
1.688916
1.04614
result = {} result['Output'] = ResultPath( Path=self.Parameters['--output'].Value, IsWritten=self.Parameters['--output'].isOn()) result['ClusterFile'] = ResultPath( Path=self.Parameters['--uc'].Value, IsWritten=self.Parameters['--uc'].i...
def _get_result_paths(self, data)
Set the result paths
2.471858
2.426101
1.01886
assert np.size(doy) == 1 assert np.size(latitude) == 1 assert np.size(longitude) == 1 assert np.size(depth) == 1 assert (longitude >= 0) & (longitude <= 360) assert depth >= 0 nc = netCDF4.Dataset(filename) t = 2 * np.pi * doy/366 Z = np.absolute(nc['depth'][:] - depth).argm...
def extract(filename, doy, latitude, longitude, depth)
For now only the nearest value For now only for one position, not an array of positions longitude 0-360
2.859875
2.885294
0.99119
assert np.size(doy) == 1 assert np.size(latitude) == 1 assert np.size(longitude) == 1 #assert np.size(depth) == 1 assert (longitude >= 0) & (longitude <= 360) assert depth >= 0 nc = netCDF4.Dataset(filename) t = 2 * np.pi * doy/366 # Improve this. Optimize to get only necess...
def cars_profile(filename, doy, latitude, longitude, depth)
For now only the nearest value For now only for one position, not an array of positions longitude 0-360
3.456266
3.472447
0.99534
dims, idx = cropIndices(self.dims, lat, lon, depth) dims['time'] = np.atleast_1d(doy) idx['tn'] = np.arange(dims['time'].size) # Temporary solution. Create an object for CARS dataset xn = idx['xn'] yn = idx['yn'] zn = idx['zn'] tn = idx['tn'] ...
def crop(self, doy, depth, lat, lon, var)
Crop a subset of the dataset for each var Given doy, depth, lat and lon, it returns the smallest subset that still contains the requested coordinates inside it. It handels special cases like a region around greenwich and the international date line. Accep...
3.831407
3.957294
0.968189
subset, dims = self.crop(doy, depth, lat, lon, var) if np.all([d in dims['time'] for d in doy]) & \ np.all([z in dims['depth'] for z in depth]) & \ np.all([y in dims['lat'] for y in lat]) & \ np.all([x in dims['lon'] for x in lon]): ...
def interpolate(self, doy, depth, lat, lon, var)
Interpolate each var on the coordinates requested
2.797361
2.777883
1.007012
api_meth = self.set_user_items_url(room_name) message_ids = self.unread_items(room_name).get('chat') if message_ids: return self.post(api_meth, data={'chat': message_ids}) else: raise GitterItemsError(room_name)
def mark_as_read(self, room_name)
message_ids return an array with unread message ids ['131313231', '323131']
7.174975
6.350935
1.129751
bash_header = "" for k,v in site.items(): bash_header += "%s=%s" % (k.upper(), v) bash_header += '\n' site['bash_header'] = bash_header # TODO: execute before_deploy # P.S. running init_before seems like impossible, because the file hasn't been r...
def init(cls, site)
put site settings in the header of the script
5.891067
5.701314
1.033282
provider = cls.name cls._render_config('wsgi.py', 'wsgi.py', site) # create yaml file yaml_template_name = os.path.join(provider, cls.provider_yml_name) cls._render_config(cls.provider_yml_name, yaml_template_name, site) # create requirements file # do...
def _create_configs(cls, site)
This is going to generate the following configuration: * wsgi.py * <provider>.yml * settings_<provider>.py
3.404468
3.114224
1.093199
template_args = template_args.copy() # Substitute values here pyversion = template_args['pyversion'] template_args['pyversion'] = cls.PYVERSIONS[pyversion] template = template_env.get_template(template_name) contents = template.render(**template_args) _...
def _render_config(cls, dest, template_name, template_args)
Renders and writes a template_name to a dest given some template_args. This is for platform-specific configurations
3.395782
3.696292
0.9187
''' Generates s ''' commands = sorted(self.subcommands.items(), key=lambda i: i[0]) return '\n'.join( '%s %s' % ( subcommand.ljust(15), textwrap.shorten(description, width=61), ) for subcommand, (description, act...
def gen_subcommand_help(self)
Generates s
5.519781
4.415984
1.249955
''' Parses args and returns an action and the args that were parsed ''' args = self.parse_args(argv) action = self.subcommands[args.subcommand][1] return action, args
def parse_args_to_action_args(self, argv=None)
Parses args and returns an action and the args that were parsed
5.640317
3.235562
1.743227
''' Registers a new subcommand with a given function action. If the function action is synchronous ''' action = coerce_to_synchronous(action) opts = [] for flags, kwargs in arguments.items(): if isinstance(flags, str): flags = tuple([f...
def register_subparser(self, action, name, description='', arguments={})
Registers a new subcommand with a given function action. If the function action is synchronous
5.474122
3.619071
1.512576
''' Decorator for quickly adding subcommands to the omnic CLI ''' def decorator(func): self.register_subparser( func, func.__name__.replace('_', '-'), description=description, arguments=arguments, ) ...
def subcommand(self, description='', arguments={})
Decorator for quickly adding subcommands to the omnic CLI
5.591978
3.341723
1.673382
''' Utility function that behaves identically to 'print' except it only prints if verbose ''' if self._last_args and self._last_args.verbose: print(*args, **kwargs)
def print(self, *args, **kwargs)
Utility function that behaves identically to 'print' except it only prints if verbose
9.186519
3.677631
2.497945
alignments = get_next_two_fasta_records(fasta_pairs_lines) for hit in get_next_record_type(uc_lines, 'H'): matching_strand = hit[4] if matching_strand == '-': strand_id = '-' target_rev_match = True elif matching_strand == '+': strand_id = '+' ...
def process_uclust_pw_alignment_results(fasta_pairs_lines, uc_lines)
Process results of uclust search and align
2.261316
2.251292
1.004453
clusters = {} failures = [] seeds = [] all_hits = set() # the types of hit lines we're interested in here # are hit (H), seed (S), library seed (L) and no hit (N) hit_types = {}.fromkeys(list('HSNL')) for record in get_next_record_type(uc_lines, hit_types): hit_type = record...
def clusters_from_uc_file(uc_lines, error_on_multiple_hits=True)
Given an open .uc file, return lists (clusters, failures, new_seeds) uc_lines: open .uc file, or similar object -- this is the output generated by uclust's -uc parameter error_on_multiple_hits: if True (default), when a single query hits to multiple seeds, as can happen when --allhits...
4.989883
4.456283
1.119741
if not output_filepath: _, output_filepath = mkstemp(dir=tmp_dir, prefix='uclust_fasta_sort', suffix='.fasta') app = Uclust(params={'--tmpdir': tmp_dir}, TmpDir=tmp_dir, HALT_EXEC=HALT_EXEC) app_result = app(data={'--mergesort': fasta_file...
def uclust_fasta_sort_from_filepath( fasta_filepath, output_filepath=None, tmp_dir=gettempdir(), HALT_EXEC=False)
Generates sorted fasta file via uclust --mergesort.
3.778834
3.398998
1.111749
# Explanation of parameter settings # id - min percent id to count a match # maxaccepts = 8 , searches for best match rather than first match # (0 => infinite accepts, or good matches before # quitting search) # maxaccepts = 32, # libonly = True...
def uclust_search_and_align_from_fasta_filepath( query_fasta_filepath, subject_fasta_filepath, percent_ID=0.75, enable_rev_strand_matching=True, max_accepts=8, max_rejects=32, tmp_dir=gettempdir(), HALT_EXEC=False)
query seqs against subject fasta using uclust, return global pw alignment of best match
5.422475
5.226027
1.03759
output_filepath = uc_save_filepath if not output_filepath: _, output_filepath = mkstemp(dir=tmp_dir, prefix='uclust_clusters', suffix='.uc') params = {'--id': percent_ID, '--maxaccepts': max_accepts, '--maxrejects': max_rejects, ...
def uclust_cluster_from_sorted_fasta_filepath( fasta_filepath, uc_save_filepath=None, percent_ID=0.97, max_accepts=1, max_rejects=8, stepwords=8, word_length=8, optimal=False, exact=False, suppress_sort=False, enable_rev_strand_matc...
Returns clustered uclust file from sorted fasta
2.44811
2.478928
0.987568
# Create readable intermediate filenames if they are to be kept fasta_output_filepath = None uc_output_filepath = None cd_hit_filepath = None if output_dir and not output_dir.endswith('/'): output_dir += '/' if save_uc_files: uc_save_filepath = get_output_filepaths( ...
def get_clusters_from_fasta_filepath( fasta_filepath, original_fasta_path, percent_ID=0.97, max_accepts=1, max_rejects=8, stepwords=8, word_length=8, optimal=False, exact=False, suppress_sort=False, output_dir=None, enable_r...
Main convenience wrapper for using uclust to generate cluster files A source fasta file is required for the fasta_filepath. This will be sorted to be in order of longest to shortest length sequences. Following this, the sorted fasta file is used to generate a cluster file in the uclust (.uc) format. ...
3.397305
3.272786
1.038047
# The list of values which can be passed on a per-run basis allowed_values = ['--input', '--uc', '--fastapairs', '--uc2clstr', '--output', '--mergesort'] unsupported_parameters = set(data.keys()) - set(allowed_values) if unsupported_parameters: ...
def _input_as_parameters(self, data)
Set the input path (a fasta filepath)
6.571132
6.394559
1.027613
result = {} result['Output'] = ResultPath( Path=self.Parameters['--output'].Value, IsWritten=self.Parameters['--output'].isOn()) result['ClusterFile'] = ResultPath( Path=self.Parameters['--uc'].Value, IsWritten=self.Parameters['--uc'].i...
def _get_result_paths(self, data)
Set the result paths
4.069964
3.834661
1.061362
'''Formatting JSON API Error Object Constructing an error object based on JSON API standard ref: http://jsonapi.org/format/#error-objects Args: status: Can be a http status codes title: A summary of error detail: A descriptive error message code: Application error codes (...
def format_error(status=None, title=None, detail=None, code=None)
Formatting JSON API Error Object Constructing an error object based on JSON API standard ref: http://jsonapi.org/format/#error-objects Args: status: Can be a http status codes title: A summary of error detail: A descriptive error message code: Application error codes (if any)...
3.94151
1.508426
2.612995
'''List of errors Put all errors into a list of errors ref: http://jsonapi.org/format/#errors Args: *args: A tuple contain errors Returns: A dictionary contains a list of errors ''' list_errors = [] list_errors.extend(list(args)) errors = { 'errors': list_errors } ...
def return_an_error(*args)
List of errors Put all errors into a list of errors ref: http://jsonapi.org/format/#errors Args: *args: A tuple contain errors Returns: A dictionary contains a list of errors
6.49168
2.281032
2.84594
"Write your forwards methods here." for doc in orm['document_library.Document'].objects.all(): for title in doc.documenttitle_set.all(): title.is_published = doc.is_published title.save()
def forwards(self, orm)
Write your forwards methods here.
6.761634
5.908554
1.144381
''' Import activities for a single document into timeline. ''' batch_updates = [time_doc] # We want to consider only activities that happend before time_doc # do not move this, because time_doc._start changes # time_doc['_start'] is a timestamp, whereas act[0] is ...
def _activity_import_doc(self, time_doc, activities)
Import activities for a single document into timeline.
5.670539
5.535484
1.024398
''' Returns a list of object ids of those objects that have changed since `mtime`. This method expects that the changed objects can be determined based on the `delta_mtime` property of the cube which specifies the field name that carries the time of the last change. This...
def get_changed_oids(self, last_update=None)
Returns a list of object ids of those objects that have changed since `mtime`. This method expects that the changed objects can be determined based on the `delta_mtime` property of the cube which specifies the field name that carries the time of the last change. This method is expected ...
7.210048
1.789486
4.029116
''' Dictionary of field_id: field_name, as defined in self.fields property ''' if hasattr(self, '_sql_fieldmap') and self._sql_fieldmap: fieldmap = self._sql_fieldmap else: fieldmap = defaultdict(str) fields = copy(self.fields) for ...
def fieldmap(self)
Dictionary of field_id: field_name, as defined in self.fields property
3.745706
2.596615
1.442534
''' Extract routine for SQL based cubes. :param force: for querying for all objects (True) or only those passed in as list :param last_update: manual override for 'changed since date' ''' return self._run_object_import(force=force, last_update=last_update, ...
def get_objects(self, force=None, last_update=None, flush=False)
Extract routine for SQL based cubes. :param force: for querying for all objects (True) or only those passed in as list :param last_update: manual override for 'changed since date'
14.505981
2.92346
4.961922
''' Returns a list of unique oids that have not been extracted yet. Essentially, a diff of distinct oids in the source database compared to cube. ''' table = self.lconfig.get('table') _oid = self.lconfig.get('_oid') if is_array(_oid): _oid = _...
def get_new_oids(self)
Returns a list of unique oids that have not been extracted yet. Essentially, a diff of distinct oids in the source database compared to cube.
5.877683
3.893138
1.509755
''' Fields change depending on when you run activity_import, such as "last_updated" type fields which don't have activity being tracked, which means we'll always end up with different hash values, so we need to always remove all existing object states and import fresh ...
def get_full_history(self, force=None, last_update=None, flush=False)
Fields change depending on when you run activity_import, such as "last_updated" type fields which don't have activity being tracked, which means we'll always end up with different hash values, so we need to always remove all existing object states and import fresh
16.156696
1.921287
8.409308
''' Query source database for a distinct list of oids. ''' table = self.lconfig.get('table') db = self.lconfig.get('db_schema_name') or self.lconfig.get('db') _oid = self.lconfig.get('_oid') if is_array(_oid): _oid = _oid[0] # get the db column, not t...
def sql_get_oids(self, where=None)
Query source database for a distinct list of oids.
4.143869
3.591504
1.153798
''' Main API method for sub-classed cubes to override for the generation of the objects which are to (potentially) be added to the cube (assuming no duplicates) ''' logger.debug('Running get_objects(flush=%s, autosnap=%s, %s)' % ( flush, autosnap, kwa...
def get_objects(self, flush=False, autosnap=True, **kwargs)
Main API method for sub-classed cubes to override for the generation of the objects which are to (potentially) be added to the cube (assuming no duplicates)
5.785534
2.632369
2.197844
'''wrapper for :func:`metrique.utils.get_cube` Locates and loads a metrique cube :param cube: name of cube to load :param init: (bool) initialize cube before returning? :param name: override the name of the cube :param copy_config: apply config of calling cube to new? ...
def get_cube(self, cube, init=True, name=None, copy_config=True, **kwargs)
wrapper for :func:`metrique.utils.get_cube` Locates and loads a metrique cube :param cube: name of cube to load :param init: (bool) initialize cube before returning? :param name: override the name of the cube :param copy_config: apply config of calling cube to new? ...
4.17592
1.935856
2.157144
# convert aln to phy since seq_names need fixed to run through pplacer new_aln=get_align_for_phylip(StringIO(aln)) # convert aln to fasta in case it is not already a fasta file aln2 = Alignment(new_aln) seqs = aln2.toFasta() ih = '_input_as_multiline_string' pplacer_app = Pplacer(p...
def insert_sequences_into_tree(aln, moltype, params={}, write_log=True)
Returns a tree from Alignment object aln. aln: an xxx.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object params: dict of parameters to pass in to the RAxML app controller. The result will be an xxx.Alignment object, or None if tree fails.
6.738168
6.64853
1.013482
return super(Pplacer,self).getTmpFilename(tmp_dir=tmp_dir, prefix=prefix, suffix=suffix, include_class_id=include_class_id, result_constructor=result_construc...
def getTmpFilename(self, tmp_dir="/tmp",prefix='tmp',suffix='.fasta',\ include_class_id=False,result_constructor=FilePath)
Define Tmp filename to contain .fasta suffix, since pplacer requires the suffix to be .fasta
2.451972
1.969668
1.244865
output_dir = self.Parameters['--out-dir'].Value result = {} result['json'] = ResultPath(Path=join(output_dir, splitext(split(self._input_filename)[-1])[0] + \ '.jplace')) return result
def _get_result_paths(self,data)
Define the output filepaths
11.499302
9.818868
1.171143
inst['iv_zon'] = {'data':inst['unit_zon_x'] * inst['iv_x'] + inst['unit_zon_y']*inst['iv_y'] + inst['unit_zon_z']*inst['iv_z'], 'units':'m/s', 'long_name':'Zonal ion velocity', 'notes':('Ion velocity relative to co-rotation along zonal ' ...
def add_mag_drifts(inst)
Adds ion drifts in magnetic coordinates using ion drifts in S/C coordinates along with pre-calculated unit vectors for magnetic coordinates. Note ---- Requires ion drifts under labels 'iv_*' where * = (x,y,z) along with unit vectors labels 'unit_zonal_*', 'unit_fa_*', and 'unit_mer_*', ...
2.361313
2.147183
1.099726
term = lambda expected, observed: float((expected - observed) ** 2) / max(expected, 1) mean_success_rate = float(sum([c.rewards for c in choices])) / max(sum([c.plays for c in choices]), 1) mean_failure_rate = 1 - mean_success_rate return sum([ term(mean_success_rate * c.plays, c.rewards)...
def chi_squared(*choices)
Calculates the chi squared
3.81273
3.723157
1.024058
def get_experiments_dict(active=True): return dict((experiment.name, experiment) for experiment in get_experiments(redis, active=active)) # Get the current experiments active_experiments = get_experiments_dict() archived_experiments = get_experiments_dict(active=False) # Get...
def sync_from_spec(redis, schema)
Takes an input experiment spec and creates/modifies/archives the existing experiments to match the spec. If there's an experiment in the spec that currently doesn't exist, it will be created along with the associated choices. If there's an experiment in the spec that currently exists, and the set of ...
2.345401
2.264297
1.035819
if not ALLOWED_NAMES.match(name): raise ExperimentException(name, "Illegal name") if redis.exists(EXPERIMENT_REDIS_KEY_TEMPLATE % name): raise ExperimentException(name, "Already exists") json = dict(creation_date=util.unicode_type(datetime.datetime.now())) pipe = redis.pipeline(tr...
def add_experiment(redis, name)
Adds a new experiment
3.618487
3.556171
1.017523
key = ACTIVE_EXPERIMENTS_REDIS_KEY if active else ARCHIVED_EXPERIMENTS_REDIS_KEY return [Experiment(redis, escape.to_unicode(name)) for name in redis.smembers(key)]
def get_experiments(redis, active=True)
Gets the full list of experiments
4.620219
4.352787
1.061439