code
stringlengths
1
18.2k
try: r = requests.get(url) except Exception as ex: print('Error accessing url {}'.format(url)) print(ex.message) return # Check status and display results if r.status_code == 200: ind = r.content.find(b'@') print(r.content[ind:].strip().decode('utf-8')) if fetch: return r.content[ind:].strip() else: print('Error gettin...
def info(self): """ Prints out information for the loaded database, namely the available tables and the number of entries for each. """ t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() print('\nDatabase path: {} \nSQL path: {}\n'.format(self.dbpath, self.sqlp...
def inventory(self, source_id, fetch=False, fmt='table'): """ Prints a summary of all objects in the database. Input string or list of strings in **ID** or **unum** for specific objects. Parameters ---------- source_id: int The id from the SOURCES table whose data across all tables is to be printed. fetch: bool Return ...
the table for this source's data t = self.query("PRAGMA table_info({})".format(table), fmt='table') columns = np.array(t['name']) types = np.array(t['type']) if table == 'sources' or 'source_id' in columns: # If printing, only get simple data types and exclude redundant 'source_id' for nicer printing if not fetch: colu...
data_tables[table] = self.query( "SELECT {} FROM {} WHERE {}={}".format(','.join(columns), table, id, source_id), \ fetch=True, fmt=fmt) else: data = data[[c.lower() for c in columns]] pprint(data, title=table.upper()) else: pass except: print('Could not retrieve data from {} table.'.format(table.upper())) if fetch: re...
def lookup(self, criteria, table, columns=''): """ Returns a table of records from *table* the same length as *criteria* with the best match for each element. Parameters ---------- criteria: sequence The search criteria table: str The table to search columns: sequence The column name in the sources table to search Retu...
else '')) # If no matches, make an empty row if len(records)==0: records.add_row(np.asarray(np.zeros(len(records.colnames))).T) colmasks.append([True]*len(records.colnames)) else: colmasks.append([False]*len(records.colnames)) # Grab the first row results.append(records[0]) # Add all the rows to the results table table...
def _lowest_rowids(self, table, limit): """ Gets the lowest available row ids for table insertion. Keeps things tidy! Parameters ---------- table: str The name of the table being modified limit: int The number of row ids needed Returns ------- available: sequence An array of all available row ids """ try: t = self.quer...
def merge(self, conflicted, tables=[], diff_only=True): """ Merges specific **tables** or all tables of **conflicted** database into the master database. Parameters ---------- conflicted: str The path of the SQL database to be merged into the master. tables: list (optional) The list of tables to merge. If None, all tab...
Gather user data to add to CHANGELOG table import socket, datetime if not diff_only: user = get_input('Please enter your name : ') machine_name = socket.gethostname() date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") modified_tables = [] # Merge table by table, starting with SOURCES if not isinstance(tables, ty...
= self.query("PRAGMA table_info({})".format(table), unpack=True)[1:4] conflicted_cols = con.query("PRAGMA table_info({})".format(table), unpack=True)[1] if any([i not in columns for i in conflicted_cols]): # Abort table merge if conflicted has new columns not present in master. New columns must be added to the master d...
'.join( \ ['{} {} {}{}'.format(c, t, r, ' UNIQUE PRIMARY KEY' if c == 'id' else '') \ for c, t, r in zip(columns, types, constraints * ['NOT NULL'])]))) con.modify("INSERT INTO {0} ({1}) SELECT {1} FROM Conflicted_{0}".format(table, ','.join( conflicted_cols))) con.modify("DROP TABLE Conflicted_{0}".format(table)) # Pu...
verbose=False) self.modify("ALTER TABLE {0} RENAME TO Backup_{0}".format(table), verbose=False) self.modify("CREATE TABLE {0} ({1})".format(table, ', '.join( \ ['{} {} {}{}'.format(c, t, r, ' UNIQUE PRIMARY KEY' if c == 'id' else '') \ for c, t, r in zip(columns, types, constraints * ['NOT NULL'])])), verbose=False) se...
1 # Insert unique records into master for d in data: self.modify( "INSERT INTO {} VALUES({})".format(table, ','.join(['?' for c in columns])), d, verbose=False) pprint(zip(*data), names=columns, title="{} records added to {} table at '{}':".format(len(data), table, master)) # Run clean_up on the table to check for conf...
up and detach if diff_only: print("\nDiff complete. No changes made to either database. Set `diff_only=False' to apply merge.") else: print("\nMerge complete!") con.modify("DETACH DATABASE c", verbose=False) self.modify("DETACH DATABASE c", verbose=False) con.modify("DETACH DATABASE m", verbose=False) self.modify("DETA...
def modify(self, SQL, params='', verbose=True): """ Wrapper for CRUD operations to make them distinct from queries and automatically pass commit() method to cursor. Parameters ---------- SQL: str The SQL query to execute params: sequence Mimics the native parameter substitution of sqlite3 verbose: bool Prints the numbe...
def output_spectrum(self, spectrum, filepath, header={}): """ Prints a file of the given spectrum to an ascii file with specified filepath. Parameters ---------- spectrum: int, sequence The id from the SPECTRA table or a [w,f,e] sequence filepath: str The path of the file to print the data to. header: dict A dictionary...
'wavelength_units': '', 'flux_units': ''} try: data['header'] = list(map(list, data['spectrum'].header.cards)) except: data['header'] = '' if data: fn = filepath if filepath.endswith('.txt') else filepath + 'spectrum.txt' # Write the header if data['header']: for n, line in enumerate(data['header']): data['header'][n] ...
def show_image(self, image_id, table='images', column='image', overplot=False, cmap='hot', log=False): """ Plots a spectrum from the given column and table Parameters ---------- image_id: int The id from the table of the images to plot. overplot: bool Overplot the image table: str The table from which the plot is being...
i.items() if k != column]), \ verticalalignment='top') ax.legend(loc=8, frameon=False) else: ax = plt.gca() # Plot the data cmap = plt.get_cmap(cmap) cmap.set_under(color='white') vmin = 0.0000001 vmax = np.nanmax(img) if log: from matplotlib.colors import LogNorm ax.imshow(img, cmap=cmap, norm=LogNorm(vmin=vmin,vmax=v...
def plot_spectrum(self, spectrum_id, table='spectra', column='spectrum', overplot=False, color='b', norm=False): """ Plots a spectrum from the given column and table Parameters ---------- spectrum_id: int The id from the table of the spectrum to plot. overplot: bool Overplot the spectrum table: str The table from which...
'' # Draw the axes and add the metadata if not overplot: fig, ax = plt.subplots() plt.rc('text', usetex=False) ax.set_yscale('log', nonposy='clip') plt.figtext(0.15, 0.88, '\n'.join(['{}: {}'.format(k, v) for k, v in i.items() if k != column]), \ verticalalignment='top') try: ax.set_xlabel(r'$\lambda$ [{}]'.format(i.ge...
{}'.format(spectrum_id)) plt.ion() except IOError: print("Could not plot spectrum {}".format(spectrum_id)) plt.close() else: print("No spectrum {} in the {} table.".format(spectrum_id, table.upper()))
def query(self, SQL, params='', fmt='array', fetch='all', unpack=False, export='', \ verbose=False, use_converters=True): """ Returns data satisfying the provided **SQL** script. Only SELECT or PRAGMA statements are allowed. Results can be returned in a variety of formats. For example, to extract the ra and dec of all ...
str The file path of the ascii file to which the data should be exported verbose: bool print the data as well use_converters: bool Apply converters to columns with custom data types Returns ------- result: (array,dict,table) The result of the database query """ try: # Restrict queries to SELECT and PRAGMA statements if...
except: pass # Make an array array = np.asarray(table) # Unpack the results if necessary (data types are not preserved) if unpack: array = np.array(zip(*array)) # print on screen if verbose: pprint(table) # print the results to file if export: # If .vot or .xml, assume VOTable export with votools if export.lower().ends...
print('Could not execute: ' + SQL)
def references(self, criteria, publications='publications', column_name='publication_shortname', fetch=False): """ Do a reverse lookup on the **publications** table. Will return every entry that matches that reference. Parameters ---------- criteria: int or str The id from the PUBLICATIONS table whose data across all t...
print('No match found for {}'.format(criteria)) return t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() for table in ['sources'] + [t for t in all_tables if t not in ['publications', 'sqlite_sequence', 'sources']]: # Get the columns, pull out redundant ones, ...
= self.query( "SELECT {} FROM {} WHERE {}='{}'".format( ','.join(columns), table, column_name, criteria), fmt='table', fetch=True) else: data = data[[c.lower() for c in columns]] # force lowercase since astropy.Tables have all lowercase pprint(data, title=table.upper()) if fetch: return data_tables
def save(self, directory=None): """ Dump the entire contents of the database into the tabledata directory as ascii files """ from subprocess import call # If user did not supply a new directory, use the one loaded (default: tabledata) if isinstance(directory, type(None)): directory = self.directory # Create the .sql fi...
type='table'")['tbl_name'] tablepaths = [self.sqlpath] for table in tables: print('Generating {}...'.format(table)) tablepath = '{0}/{1}.sql'.format(directory, table) tablepaths.append(tablepath) with open(tablepath, 'w') as f: for line in self.conn.iterdump(): line = line.strip() if line.startswith('INSERT INTO "{}"'....
def schema(self, table): """ Print the table schema Parameters ---------- table: str The table name """ try: pprint(self.query("PRAGMA table_info({})".format(table), fmt='table')) except ValueError: print('Table {} not found'.format(table))
def search(self, criterion, table, columns='', fetch=False, radius=1/60., use_converters=False, sql_search=False): """ General search method for tables. For (ra,dec) input in decimal degrees, i.e. (12.3456,-65.4321), returns all sources within 1 arcminute, or the specified radius. For string input, i.e. 'vb10', returns...
for objects if using (ra,dec). Default: 1/60 degree use_converters: bool Apply converters to columns with custom data types sql_search: bool Perform the search by coordinates in a box defined within the SQL commands, rather than with true angular separations. Faster, but not a true radial search. """ # Get list of colu...
print("'{}' is not a column in the {} table.".format(col, table.upper())) # Coordinate search if sys.version_info[0] == 2: str_check = (str, unicode) else: str_check = str results = '' if isinstance(criterion, (tuple, list, np.ndarray)): try: if sql_search: q = "SELECT * FROM {} WHERE ra BETWEEN ".format(table) \ + str...
", ".join(['{}'.format(s) for s in df[good]['id'].tolist()]) try: results = self.query('SELECT * FROM {} WHERE source_id IN ({})'.format(table, params), fmt='table') except: results = self.query('SELECT * FROM {} WHERE id IN ({})'.format(table, params), fmt='table') except: print("Could not search {} table by coordinat...
int): try: q = "SELECT * FROM {} WHERE {}".format(table, ' OR '.join(['{}={}'.format(c, criterion) \ for c, t in zip(columns, types[np.in1d(columns, all_columns)]) if t == 'INTEGER'])) results = self.query(q, fmt='table', use_converters=use_converters) except: print("Could not search {} table by id {}. Try again.".form...
def snapshot(self, name_db='export.db', version=1.0): """ Function to generate a snapshot of the database by version number. Parameters ---------- name_db: string Name of the new database (Default: export.db) version: float Version number to export (Default: 1.0) """ # Check if file exists if os.path.isfile(name_db): i...
they match version number t = db.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() for table in [t for t in all_tables if t not in ['sqlite_sequence', 'changelog']]: # Check if this is table with version column metadata = db.query("PRAGMA table_info({})".format(table),...
def table(self, table, columns, types, constraints='', pk='', new_table=False): """ Rearrange, add or delete columns from database **table** with desired ordered list of **columns** and corresponding data **types**. Parameters ---------- table: sequence The name of the table to modify columns: list A sequence of the co...
# and the appropriate number of elements in each sequence if columns[0] != 'id': print("Column 1 must be called 'id'") goodtogo = False if constraints: if 'UNIQUE' not in constraints[0].upper() and 'NOT NULL' not in constraints[0].upper(): print("'id' column constraints must be 'UNIQUE NOT NULL'") goodtogo = False else...
\ .format(len(columns), len(types), len(constraints))) goodtogo = False if goodtogo: t = self.query("SELECT name FROM sqlite_master", unpack=True, fmt='table') tables = t['name'].tolist() # If the table exists, modify the columns if table in tables and not new_table: # Rename the old table and create a new one self.lis...
any foreign key constraints t = self.query('PRAGMA foreign_key_list(TempOldTable)', fmt='table') if not isinstance(t, type(None)): self.list("DROP TABLE TempOldTable") self.add_foreign_key(table, t['table'].tolist(), t['from'].tolist(), t['to'].tolist()) else: self.list("DROP TABLE TempOldTable") # If the table does no...
else: print('The {} table has not been {}. Please make sure your table columns, \ types, and constraints are formatted properly.'.format(table.upper(), \ 'created' if new_table else 'modified'))
def read(path): """Read a secret from Vault REST endpoint""" url = '{}/{}/{}'.format(settings.VAULT_BASE_URL.rstrip('/'), settings.VAULT_BASE_SECRET_PATH.strip('/'), path.lstrip('/')) headers = {'X-Vault-Token': settings.VAULT_ACCESS_TOKEN} resp = requests.get(url, headers=headers) if resp.ok: return resp.json()['data'...
def getIndexes(self, rabaOnly = True) : "returns a list of all indexes in the sql database. rabaOnly returns only the indexes created by raba" sql = "SELECT * FROM sqlite_master WHERE type='index'" cur = self.execute(sql) l = [] for n in cur : if rabaOnly : if n[1].lower().find('raba') == 0 : l.append(n) else : l.appen...
def flushIndexes(self) : "drops all indexes created by Raba" for n in self.getIndexes(rabaOnly = True) : self.dropIndexByName(n[1])
def createIndex(self, table, fields, where = '', whereValues = []) : """Creates indexes for Raba Class a fields resulting in significantly faster SELECTs but potentially slower UPADTES/INSERTS and a bigger DBs Fields can be a list of fields for Multi-Column Indices, or siply the name of one single field. With the where...
CLAUSE in INDEX. Partial indexes where only implemented in sqlite 3.8.0+, your version is: %s. Sorry about that.\n" % sq.sqlite_version) indexTable = self.makeIndexTableName(table, fields) else : indexTable = self.makeIndexTableName(table, fields, where, whereValues) if type(fields) is types.ListType : sql = "CREATE IN...
def dropIndex(self, table, fields, where = '') : "DROPs an index created by RabaDb see createIndexes()" indexTable = self.makeIndexTableName(table, fields, where) self.dropIndexByName(indexTable)
def enableStats(self, bol, logQueries = False) : "If bol == True, Raba will keep a count of every query time performed, logQueries == True it will also keep a record of all the queries " self._enableStats = bol self._logQueries = logQueries if bol : self._enableStats = True self.eraseStats() self.startTime = time.time(...
def execute(self, sql, values = ()) : "executes an sql command for you or appends it to the current transacations. returns a cursor" sql = sql.strip() self._debugActions(sql, values) cur = self.connection.cursor() cur.execute(sql, values) return cur
def initateSave(self, obj) : """Tries to initiates a save sessions. Each object can only be saved once during a session. The session begins when a raba object initates it and ends when this object and all it's dependencies have been saved""" if self.saveIniator != None : return False self.saveIniator = obj return True
def freeSave(self, obj) : """THIS IS WHERE COMMITS TAKE PLACE! Ends a saving session, only the initiator can end a session. The commit is performed at the end of the session""" if self.saveIniator is obj and not self.inTransaction : self.saveIniator = None self.savedObject = set() self.connection.commit() return True r...
def registerSave(self, obj) : """Each object can only be save donce during a session, returns False if the object has already been saved. True otherwise""" if obj._runtimeId in self.savedObject : return False self.savedObject.add(obj._runtimeId) return True
def delete(self, table, where, values = ()) : """where is a string of condictions without the sql 'WHERE'. ex: deleteRabaObject('Gene', where = raba_id = ?, values = (33,))""" sql = 'DELETE FROM %s WHERE %s' % (table, where) return self.execute(sql, values)
def getLastRabaId(self, cls) : """keep track all loaded raba classes""" self.loadedRabaClasses[cls.__name__] = cls sql = 'SELECT MAX(raba_id) from %s LIMIT 1' % (cls.__name__) cur = self.execute(sql) res = cur.fetchone() try : return int(res[0])+1 except TypeError: return 0
def createTable(self, tableName, strFields) : 'creates a table and resturns the ursor, if the table already exists returns None' if not self.tableExits(tableName) : sql = 'CREATE TABLE %s ( %s)' % (tableName, strFields) self.execute(sql) self.tables.add(tableName) return True return False
def dropColumnsFromRabaObjTable(self, name, lstFieldsToKeep) : "Removes columns from a RabaObj table. lstFieldsToKeep should not contain raba_id or json fileds" if len(lstFieldsToKeep) == 0 : raise ValueError("There are no fields to keep") cpy = name+'_copy' sqlFiledsStr = ', '.join(lstFieldsToKeep) self.createTable(cp...
def get_likes(self, offset=0, limit=50): """ Get user's likes. """ response = self.client.get( self.client.USER_LIKES % (self.name, offset, limit)) return self._parse_response(response, strack)
def get_tracks(self, offset=0, limit=50): """ Get user's tracks. """ response = self.client.get( self.client.USER_TRACKS % (self.name, offset, limit)) return self._parse_response(response, strack)
def get_playlists(self, offset=0, limit=50): """ Get user's playlists. """ response = self.client.get( self.client.USER_PLAYLISTS % (self.name, offset, limit)) return self._parse_response(response, splaylist) return playlists
def _parse_response(self, response, target_object=strack): """ Generic response parser method """ objects = json.loads(response.read().decode("utf-8")) list = [] for obj in objects: list.append(target_object(obj, client=self.client)) return list
def create_external_feed_courses(self, url, course_id, header_match=None, verbosity=None): """ Create an external feed. Create a new external feed for the course or group. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - url """The url to the external...
def create_external_feed_groups(self, url, group_id, header_match=None, verbosity=None): """ Create an external feed. Create a new external feed for the course or group. """ path = {} data = {} params = {} # REQUIRED - PATH - group_id """ID""" path["group_id"] = group_id # REQUIRED - url """The url to the external rss ...
def delete_external_feed_courses(self, course_id, external_feed_id): """ Delete an external feed. Deletes the external feed. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - external_feed_id """ID""" path["external_feed_id"] = external_feed_id ...
def delete_external_feed_groups(self, group_id, external_feed_id): """ Delete an external feed. Deletes the external feed. """ path = {} data = {} params = {} # REQUIRED - PATH - group_id """ID""" path["group_id"] = group_id # REQUIRED - PATH - external_feed_id """ID""" path["external_feed_id"] = external_feed_id self....
def count_token_occurrences(cls, words): """ Creates a key/value set of word/count for a given sample of text :param words: full list of all tokens, non-unique :type words: list :return: key/value pairs of words and their counts in the list :rtype: dict """ counts = {} for word in words: if word in counts: counts[word]...
def calculate_category_probability(self): """ Caches the individual probabilities for each category """ total_tally = 0.0 probs = {} for category, bayes_category in \ self.categories.get_categories().items(): count = bayes_category.get_tally() total_tally += count probs[category] = count # Calculating the probability f...
def train(self, category, text): """ Trains a category with a sample of text :param category: the name of the category we want to train :type category: str :param text: the text we want to train the category with :type text: str """ try: bayes_category = self.categories.get_category(category) except KeyError: bayes_cat...
def untrain(self, category, text): """ Untrains a category with a sample of text :param category: the name of the category we want to train :type category: str :param text: the text we want to untrain the category with :type text: str """ try: bayes_category = self.categories.get_category(category) except KeyError: ret...
def classify(self, text): """ Chooses the highest scoring category for a sample of text :param text: sample text to classify :type text: str :return: the "winning" category :rtype: str """ score = self.score(text) if not score: return None return sorted(score.items(), key=lambda v: v[1])[-1][0]
def score(self, text): """ Scores a sample of text :param text: sample text to score :type text: str :return: dict of scores per category :rtype: dict """ occurs = self.count_token_occurrences(self.tokenizer(text)) scores = {} for category in self.categories.get_categories().keys(): scores[category] = 0 categories = se...
# Removing empty categories from the results final_scores = {} for category, score in scores.items(): if score > 0: final_scores[category] = score return final_scores
def calculate_bayesian_probability(self, cat, token_score, token_tally): """ Calculates the bayesian probability for a given token/category :param cat: The category we're scoring for this token :type cat: str :param token_score: The tally of this token for this category :type token_score: float :param token_tally: The ...
* prc) denominator = (numerator + (prtnc * prnc)) # Returning the calculated bayes probability unless the denom. is 0 return numerator / denominator if denominator != 0.0 else 0.0
def tally(self, category): """ Gets the tally for a requested category :param category: The category we want a tally for :type category: str :return: tally for a given category :rtype: int """ try: bayes_category = self.categories.get_category(category) except KeyError: return 0 return bayes_category.get_tally()
def get_cache_location(self): """ Gets the location of the cache file :return: the location of the cache file :rtype: string """ filename = self.cache_path if \ self.cache_path[-1:] == '/' else \ self.cache_path + '/' filename += self.cache_file return filename
def cache_persist(self): """ Saves the current trained data to the cache. This is initiated by the program using this module """ filename = self.get_cache_location() pickle.dump(self.categories, open(filename, 'wb'))
def cache_train(self): """ Loads the data for this classifier from a cache file :return: whether or not we were successful :rtype: bool """ filename = self.get_cache_location() if not os.path.exists(filename): return False categories = pickle.load(open(filename, 'rb')) assert isinstance(categories, BayesCategories), \ ...
def create_feature_type_rates(self, created=False): """ If the role is being created we want to populate a rate for all existing feature_types. """ if created: for feature_type in FeatureType.objects.all(): FeatureTypeRate.objects.create(role=self, feature_type=feature_type, rate=0)
def addToService(self, service, namespace=None, seperator='.'): """ Add this Handler's exported methods to an RPC Service instance. """ if namespace is None: namespace = [] if isinstance(namespace, basestring): namespace = [namespace] for n, m in inspect.getmembers(self, inspect.ismethod): if hasattr(m, 'export_rpc'): ...
def print_progress_bar(text, done, total, width): """ Print progress bar. """ if total > 0: n = int(float(width) * float(done) / float(total)) sys.stdout.write("\r{0} [{1}{2}] ({3}/{4})".format(text, '#' * n, ' ' * (width - n), done, total)) sys.stdout.flush()
def fetch_modules(config, relative_path, download_directory): """ Assemble modules which will be included in CMakeLists.txt. """ from collections import Iterable, namedtuple, defaultdict from autocmake.extract import extract_list, to_d, to_l from autocmake.parse_rst import parse_cmake_module cleaned_config = defaultdic...
if os.path.exists(src): path = os.path.dirname(src) name = module_name file_name = src fetch_dst_directory = path else: sys.stderr.write("ERROR: {0} does not exist\n".format(src)) sys.exit(-1) # we infer config from the module documentation # dictionary d overrides the configuration in the module documentation # this a...
def main(argv): """ Main function. """ if len(argv) != 2: sys.stderr.write("\nYou can update a project in two steps.\n\n") sys.stderr.write("Step 1: Update or create infrastructure files\n") sys.stderr.write(" which will be needed to configure and build the project:\n") sys.stderr.write(" $ {0} --self\n\n".format(argv[...
dst='autocmake.yml' ) if not os.path.isfile('.gitignore'): print('- creating .gitignore') with open('.gitignore', 'w') as f: f.write('*.pyc\n') for f in ['autocmake/configure.py', 'autocmake/__init__.py', 'autocmake/external/docopt.py', 'autocmake/external/__init__.py', 'autocmake/generate.py', 'autocmake/extract.py', ...
def fetch_url(src, dst): """ Fetch file from URL src and save it to dst. """ # we do not use the nicer sys.version_info.major # for compatibility with Python < 2.7 if sys.version_info[0] > 2: import urllib.request class URLopener(urllib.request.FancyURLopener): def http_error_default(self, url, fp, errcode, errmsg, hea...
def get_single_poll_submission(self, id, poll_id, poll_session_id): """ Get a single poll submission. Returns the poll submission with the given id """ path = {} data = {} params = {} # REQUIRED - PATH - poll_id """ID""" path["poll_id"] = poll_id # REQUIRED - PATH - poll_session_id """ID""" path["poll_session_id"] = po...
def create_single_poll_submission(self, poll_id, poll_session_id, poll_submissions_poll_choice_id): """ Create a single poll submission. Create a new poll submission for this poll session """ path = {} data = {} params = {} # REQUIRED - PATH - poll_id """ID""" path["poll_id"] = poll_id # REQUIRED - PATH - poll_session_...
def list(self, request, *args, **kwargs): """Modified list view to driving listing from ES""" search_kwargs = {"published": False} query_params = get_query_params(self.request) for field_name in ("status"): if field_name in query_params: search_kwargs[field_name] = query_params.get(field_name) if "search" in query_para...
def recode_wgsim_reads( rnf_fastq_fo, fai_fo, genome_id, wgsim_fastq_1_fn, wgsim_fastq_2_fn=None, number_of_read_tuples=10**9, ): """Convert WgSim FASTQ files to RNF FASTQ files. Args: rnf_fastq_fo (file): File object of the target RNF file. fai_fo (file): File object of FAI index of the reference genome. genome_id (in...
2 7) number of indels end 2 10) id 11) pair """ fai_index = rnftools.utils.FaIdx(fai_fo) read_tuple_id_width = len(format(number_of_read_tuples, 'x')) last_read_tuple_name = None fq_creator = rnftools.rnfformat.FqCreator( fastq_fo=rnf_fastq_fo, read_tuple_id_width=read_tuple_id_width, genome_id_width=2, chr_id_width=fa...
substitutions_2 = int(m.group(8)) indels_2 = int(m.group(9)) read_tuple_id_w = int(m.group(10), 16) pair = int(m.group(11)) chr_id = fai_index.dict_chr_ids[contig_name] if fai_index.dict_chr_ids != {} else "0" if start_1 < end_2: direction_1 = "F" direction_2 = "R" else: direction_1 = "R" direction_2 = "F" segment1 = r...
bases=bases2, qualities=qualities2, segments=[segment2], ) i += 1 fq_creator.flush_read_tuple()
def has_object_permission(self, request, view, obj): """determines if requesting user has permissions for the object :param request: WSGI request object - where we get the user from :param view: the view calling for permission :param obj: the object in question :return: `bool` """ # Give permission if we're not protect...
def has_permission(self, request, view): """If method is GET, user can access, if method is PUT or POST user must be a superuser. """ has_permission = False if request.method == "GET" \ or request.method in ["PUT", "POST", "DELETE"] \ and request.user and request.user.is_superuser: has_permission = True return has_perm...
def bind(self, app): """Bind API to Muffin.""" self.parent = app app.add_subapp(self.prefix, self.app)
def register(self, *paths, methods=None, name=None): """Register handler to the API.""" if isinstance(methods, str): methods = [methods] def wrapper(handler): if isinstance(handler, (FunctionType, MethodType)): handler = RESTHandler.from_view(handler, *(methods or ['GET'])) if handler.name in self.handlers: raise muffi...