code stringlengths 1 18.2k |
|---|
def get_token(self): """Performs Neurio API token authentication using provided key and secret. Note: This method is generally not called by hand; rather it is usually called as-needed by a Neurio Client object. Returns: string: the access token """ if self.__token is not None: return self.__token url = "https://api.ne... |
def __append_url_params(self, url, params): """Utility method formatting url request parameters.""" url_parts = list(urlparse(url)) query = dict(parse_qsl(url_parts[4])) query.update(params) url_parts[4] = urlencode(query) return urlunparse(url_parts) |
def get_appliance(self, appliance_id): """Get the information for a specified appliance Args: appliance_id (string): identifiying string of appliance Returns: list: dictionary object containing information about the specified appliance """ url = "https://api.neur.io/v1/appliances/%s"%(appliance_id) headers = self.__gen... |
def get_appliances(self, location_id): """Get the appliances added for a specified location. Args: location_id (string): identifiying string of appliance Returns: list: dictionary objects containing appliances data """ url = "https://api.neur.io/v1/appliances" headers = self.__gen_headers() headers["Content-Type"] = "a... |
def get_appliance_event_after_time(self, location_id, since, per_page=None, page=None, min_power=None): """Get appliance events by location Id after defined time. Args: location_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` since (string): ISO 8601 start time for getting the events tha... |
"application/json" params = { "locationId": location_id, "since": since } if min_power: params["minPower"] = min_power if per_page: params["perPage"] = per_page if page: params["page"] = page url = self.__append_url_params(url, params) r = requests.get(url, headers=headers) return r.json() |
def get_appliance_stats_by_location(self, location_id, start, end, granularity=None, per_page=None, page=None, min_power=None): """Get appliance usage data for a given location within a given time range. Stats are generated by fetching appliance events that match the supplied criteria and then aggregating them together... |
(string): granularity of stats. If the granularity is 'unknown', the stats for the appliances between the start and end time is returned.; must be one of "minutes", "hours", "days", "weeks", "months", or "unknown" (default: days) min_power (string): The minimum average power (in watts) for filtering. Only events with a... |
min_power if per_page: params["perPage"] = per_page if page: params["page"] = page url = self.__append_url_params(url, params) r = requests.get(url, headers=headers) return r.json() |
def get_local_current_sample(ip): """Gets current sample from *local* Neurio device IP address. This is a static method. It doesn't require a token to authenticate. Note, call get_user_information to determine local Neurio IP addresses. Args: ip (string): address of local Neurio device Returns: dictionary object contai... |
def get_samples_live(self, sensor_id, last=None): """Get recent samples, one sample per second for up to the last 2 minutes. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` last (string): starting range, as ISO8601 timestamp Returns: list: dictionary objects containing sampl... |
def get_samples_live_last(self, sensor_id): """Get the last sample recorded by the sensor. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` Returns: list: dictionary objects containing sample data """ url = "https://api.neur.io/v1/samples/live/last" headers = self.__gen_heade... |
def get_samples(self, sensor_id, start, granularity, end=None, frequency=None, per_page=None, page=None, full=False): """Get a sensor's samples for a specified time interval. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` start (string): ISO 8601 start time of sampling; dep... |
a value of 3 will result in a sample for every third day, should be a multiple of 5 when using minutes granularity) (default: 1) (example: "1, 5") per_page (string, optional): the number of returned results per page (min 1, max 500) (default: 10) page (string, optional): the page number to return (min 1, max 100000) (d... |
return r.json() |
def get_user_information(self): """Gets the current user information, including sensor ID Args: None Returns: dictionary object containing information about the current user """ url = "https://api.neur.io/v1/users/current" headers = self.__gen_headers() headers["Content-Type"] = "application/json" r = requests.get(url,... |
def get_figure( self, emin=None, emax=None, width=800, height=400, margin_left=100, margin_bottom=60, margin_top=30, margin_right=0, colorbar_size=0.4, xaxis_label=None, yaxis_label=None, xaxis_nticks=None, yaxis_nticks=None, xtick_angle=30, font='"Droid Serif", "Open Serif", serif', font_size=12, title_font_size=None,... |
bottom margin (in px). [60] colorbar_size : int or float, optional The sze of the colorbar, relative to the figure size. [0.4] xaxis_label : str or None, optional X-axis label. If None, use `ExpMatrix` default. [None] yaxis_label : str or None, optional y-axis label. If None, use `ExpMatrix` default. [None] xtick_angle... |
[None] show_sample_labels : bool, optional Whether to show the sample labels. [True] Returns ------- `plotly.graph_objs.Figure` The plotly figure. """ # emin and/or emax are unspecified, set to data min/max values if emax is None: emax = self.matrix.X.max() if emin is None: emin = self.matrix.X.min() title = self.title... |
number. """ assert isinstance(labels, Iterable) fixed_labels = [] for l in labels: try: float(l) except (ValueError, TypeError): fixed_labels.append(str(l)) else: fixed_labels.append(str(l) + '_') return fixed_labels x = fix_plotly_label_bug(self.matrix.samples) gene_labels = self.matrix.genes.tolist() if self.gene_ali... |
% self.matrix.p layout = go.Layout( width=width, height=height, title=title, titlefont=go.Font( size=title_font_size ), font=go.Font( size=font_size, family=font ), xaxis=go.XAxis( title=xaxis_label, titlefont=dict(size=title_font_size), showticklabels=show_sample_labels, ticks=xticks, nticks=xaxis_nticks, tickangle=xt... |
#opacity=0.5, opacity=1-ann.transparency, ) ) if ann.label is not None: layout.annotations.append( go.Annotation( text=ann.label, x=0.01, y=i-0.5, #y=i+0.5, xref='paper', yref='y2', xanchor='left', yanchor='bottom', showarrow=False, bgcolor='white', #opacity=1-ann.transparency, opacity=0.8, borderpad=0, #textangle=30, ... |
def api2_formula(req): """ A simple `GET`-, URL-based API to OpenFisca, making the assumption of computing formulas for a single person. Combination ----------- You can compute several formulas at once by combining the paths and joining them with `+`. Example: ``` /salaire_super_brut+salaire_net_a_payer?salaire_de_base... |
combined requests. On a server, just test what your library handles. """ API_VERSION = '2.1.0' wsgihelpers.track(req.url.decode('utf-8')) params = dict(req.GET) data = dict() try: extensions_header = req.headers.get('X-Openfisca-Extensions') tax_benefit_system = model.get_cached_composed_reform( reform_keys = extension... |
def arithmetic_mean4(rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat): ''' Calculates the arithmetic mean of every 4 consecutive input numbers Input handshake & data rx_rdy - (o) Ready rx_vld - (i) Valid rx_dat - (i) Data Output handshake & data tx_rdy - (i) Ready tx_vld - (o) Valid tx_dat - (o) Data Implement... |
pipe_ctrl = pipeline_control( rst = rst, clk = clk, rx_vld = rx_vld, rx_rdy = rx_rdy, tx_vld = tx_vld, tx_rdy = tx_rdy, stage_enable = stage_en, stop_tx = stop_tx) s0_dat = Signal(intbv(0)[DATA_WIDTH:]) @always_seq(clk.posedge, reset=rst) def stage_0(): ''' Register input data''' if (stage_en[0]): s0_dat.next = rx_dat ... |
1 - it determines whether the data will be sent to the next pipeline stage (stop_tx==0) or will be dropped (stop_tx==1 ). The signals stop_rx and stop_tx must be registered ''' s2_dat = Signal(intbv(0)[DATA_WIDTH:]) @always_seq(clk.posedge, reset=rst) def stage_2(): ''' Divide by 4''' if (stage_en[2]): s2_dat.next = s1... |
def pipeline_control_stop_tx(): ''' Instantiates the arithmetic_mean4 pipeline, feeds it with data and drains its output ''' clk = sim.Clock(val=0, period=10, units="ns") rst = sim.ResetSync(clk=clk, val=0, active=1) rx_rdy, rx_vld, tx_rdy, tx_vld = [Signal(bool(0)) for _ in range(4)] rx_dat = Signal(intbv(0)[8:]) tx_d... |
Drains the pipeline output ''' @instance def _drain(): yield clk.posedge while True: yield cap.read() data_out.append(cap.d) for _ in range(GAP): yield clk.posedge return _drain # You can play with the gap size at the input and at the output to see how the pipeline responds (see time diagrams) Simulation(clkgen, dut, s... |
def clean(self, value): """Clean the provided dict of values and then return an EmbeddedDocument instantiated with them. """ value = super(MongoEmbedded, self).clean(value) return self.document_class(**value) |
def fetch_object(self, doc_id): """Fetch the document by its PK.""" try: return self.object_class.objects.get(pk=doc_id) except self.object_class.DoesNotExist: raise ReferenceNotFoundError |
def get_argument_parser(): """Create the argument parser for the script. Parameters ---------- Returns ------- `argparse.ArgumentParser` The arguemnt parser. """ desc = 'Generate a sample sheet based on a GEO series matrix.' parser = cli.get_argument_parser(desc=desc) g = parser.add_argument_group('Input and output fil... |
def read_series_matrix(path, encoding): """Read the series matrix.""" assert isinstance(path, str) accessions = None titles = None celfile_urls = None with misc.smart_open_read(path, mode='rb', try_gzip=True) as fh: reader = csv.reader(fh, dialect='excel-tab', encoding=encoding) for l in reader: if not l: continue if l... |
def write_sample_sheet(path, accessions, names, celfile_urls, sel=None): """Write the sample sheet.""" with open(path, 'wb') as ofh: writer = csv.writer(ofh, dialect='excel-tab', lineterminator=os.linesep, quoting=csv.QUOTE_NONE) # write header writer.writerow(['Accession', 'Name', 'CEL file', 'CEL file URL']) n = len(... |
def main(args=None): """Script entry point.""" if args is None: parser = get_argument_parser() args = parser.parse_args() #series_matrix_file = newstr(args.series_matrix_file, 'utf-8') #output_file = newstr(args.output_file, 'utf-8') #encoding = newstr(args.encoding, 'utf-8') series_matrix_file = args.series_matrix_fil... |
def create_blueprint(state): """Create blueprint serving JSON schemas. :param state: :class:`invenio_jsonschemas.ext.InvenioJSONSchemasState` instance used to retrieve the schemas. """ blueprint = Blueprint( 'invenio_jsonschemas', __name__, ) @blueprint.route('/<path:schema_path>') def get_schema(schema_path): """Retri... |
def download_files(manifest, download_dir, auth_token=None, chunk_size=1048576, avoid_redownload=True): """Individually download files from GDC. Params ------ manifest : `pandas.DataFrame` GDC manifest that contains a list of files. The data frame should have five columns: id, filename, md5, size, and state. download_d... |
= auth_token #payload = {'ids': file_ids} #logger.info('Downloading data to "%s"...', download_dir) num_files = manifest.shape[0] logger.info('Downloading %d files to "%s"...', num_files, download_dir) for i, row in manifest.iterrows(): #(uuid, (file_name, file_hash)) success = False download_file = os.path.join(downlo... |
if not success: logger.warning('Hash value mismatch (should be: %s; is: %s). ' 'Attempting to re-download file...', row['md5'], h) |
def printBlastRecord(record): """ Print a BLAST record. @param record: A BioPython C{Bio.Blast.Record.Blast} instance. """ for key in sorted(record.__dict__.keys()): if key not in ['alignments', 'descriptions', 'reference']: print('%s: %r' % (key, record.__dict__[key])) print('alignments: (%d in total):' % len(record.a... |
def normalizeHSP(hsp, readLen, blastApplication): """ Examine an HSP and return information about where the query and subject match begins and ends. Return a dict with keys that allow the query to be displayed against the subject. The returned readStartInSubject and readEndInSubject indices are offsets into the subject... |
match offset modulo 3, plus one (i.e., it tells us which of the 3 possible reading frames is used in the match). The value is redundant because that information could also be obtained from the mod 3 value of the match offset. NOTE: the returned readStartInSubject value may be negative. We consider the hit sequence to s... |
command line program that was run (e.g., 'blastn', 'blastx'). """ def debugPrint(locals, msg=None): """ Print debugging information showing the local variables from a call to normalizeHSP and then raise an C{AssertionError}. @param locals: A C{dict} of local variables. @param msg: A C{str} message to raise C{AssertionE... |
sbjct_end = hsp['sbjct_end'] # When the read is positive, BLASTN and TBLASTX give read offsets # ascending. # # TBLASTX reports negative read sense with indices ascending. # BLASTN does not report negative read sense. # # In all cases the read offsets should be ascending. if read_start > read_end: debugPrint(locals(), ... |
about the original HSP values # and gotten them into ascending order, make some sane 0-based offsets. readStartInSubject = read_start - 1 readEndInSubject = read_end subjectStart = sbjct_start - 1 subjectEnd = sbjct_end if blastApplication == 'blastx': # In Blastx output, hit offsets are based on protein sequence # len... |
# should appear beyond this point. subjectLength = subjectEnd - subjectStart readLength = readEndInSubject - readStartInSubject # NOTE: readLength (above) is a really bad name. It's actually going to # hold the length of the match in the query. I don't know why # readEndInSubject - readStartInSubject is used (I mean wh... |
of the matches in the hit and read # are identical, taking into account gaps in either (indicated by '-' # characters in the match sequences, as returned by BLAST). subjectLengthWithGaps = subjectLength + hitGaps readLengthWithGaps = readLength + readGaps if subjectLengthWithGaps != readLengthWithGaps: debugPrint(local... |
the match with the # hit takes. if hitPositive: readStartInSubject = subjectStart - unmatchedReadLeft readEndInSubject = readStartInSubject + readLen + readGaps else: readEndInSubject = subjectEnd + unmatchedReadLeft readStartInSubject = readEndInSubject - readLen - readGaps # Final sanity checks. if readStartInSubject... |
def parse_gaf(path_or_buffer, gene_ontology, valid_genes=None, db=None, ev_codes=None): """Parse a GAF 2.1 file containing GO annotations. Parameters ---------- path_or_buffer : str or buffer The GAF file. gene_ontology : `GeneOntology` The Gene Ontology. valid_genes : Iterable of str, optional A list of valid gene nam... |
and ev_codes: ev_codes = set(ev_codes) else: ev_codes = None # open file, if necessary if isinstance(path_or_buffer, (str, _oldstr)): buffer = misc.gzip_open_text(path_or_buffer, encoding='ascii') else: buffer = path_or_buffer if valid_genes is not None: valid_genes = set(valid_genes) # use pandas to parse the file qui... |
value if db is not None: sel = (df.iloc[:, 0] == db) logger.info( 'Excluding %d / %d annotations (%.1f %%) with wrong DB values.', (~sel).sum(), sel.size, 100*((~sel).sum()/float(sel.size))) df = df.loc[sel] # filter rows for evidence value if ev_codes is not None: sel = (df.iloc[:, 6].isin(ev_codes)) logger.info( 'Exc... |
def get_goa_gene_sets(go_annotations): """Generate a list of gene sets from a collection of GO annotations. Each gene set corresponds to all genes annotated with a certain GO term. """ go_term_genes = OrderedDict() term_ids = {} for ann in go_annotations: term_ids[ann.go_term.id] = ann.go_term try: go_term_genes[ann.go... |
def pipeline_control(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_enable, stop_rx=None, stop_tx=None): """ Synchronizes data flow in a processing pipeline. rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline) tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline)... |
producing data; allows for multicycle execution in a stage (consume multiple data to produce single data ) stop_rx and stop_tx - If you do not need them, then do not connect them """ NUM_STAGES = len(stage_enable) if (stop_rx == None): stop_rx = Signal(intbv(0)[NUM_STAGES:]) if (stop_tx == None): stop_tx = Signal(intbv... |
def comb_assign(): tx_vld.next = vld_reg[NUM_STAGES-1] and not stop_tx[NUM_STAGES-1] rx_rdy.next = rdy[0] and not stop_rx[0] stage_enable.next = vld[NUM_STAGES:] & rdy[NUM_STAGES:] rdy_s.next = rdy return instances() |
def pipeline_control_new(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_enable, stop_rx=None, stop_tx=None): """ Pipeline control unit rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline) tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline) stage_enable - (o) vec... |
multicycle execution in a stage (consume multiple data to produce single data ) stop_rx and stop_tx - If you do not need them, then do not connect them """ NUM_STAGES = len(stage_enable) if (stop_rx == None): stop_rx = Signal(intbv(0)[NUM_STAGES:]) if (stop_tx == None): stop_tx = Signal(intbv(0)[NUM_STAGES:]) assert (l... |
_stage_ctrl(rst = rst, clk = clk, rx_rdy = rdy[i], rx_vld = vld[i], tx_rdy = rdy[i+1], tx_vld = vld[i+1], stage_en = en[i], stop_rx = stop_rx_s[i], stop_tx = stop_tx_s[i], BC = BC[i]) x = en[0] if NUM_STAGES==1 else ConcatSignal(*reversed(en)) @always_comb def _comb(): stage_enable.next = x for i in range(NUM_STAGES): ... |
def _stage_ctrl(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_en, stop_rx=None, stop_tx=None, BC=False): ''' Single stage control BC - enable bubble compression ''' if stop_rx==None: stop_rx = False if stop_tx==None: stop_tx = False state = Signal(bool(0)) a = Signal(bool(0)) b = Signal(bool(0)) bc_link = state if BC... |
def _debugPrint(hsp, queryLen, localDict, msg=''): """ Print debugging information showing the local variables used during a call to normalizeHSP and the hsp and then raise an C{AssertionError}. @param hsp: The HSP C{dict} passed to normalizeHSP. @param queryLen: the length of the query sequence. @param localDict: A C{... |
def _sanityCheck(subjectStart, subjectEnd, queryStart, queryEnd, queryStartInSubject, queryEndInSubject, hsp, queryLen, subjectGaps, queryGaps, localDict): """ Perform some sanity checks on an HSP. Call _debugPrint on any error. @param subjectStart: The 0-based C{int} start offset of the match in the subject. @param su... |
gaps in the subject. @param queryGaps: the C{int} number of gaps in the query. @param localDict: A C{dict} of local variables from our caller (as produced by locals()). """ # Subject indices must always be ascending. if subjectStart >= subjectEnd: _debugPrint(hsp, queryLen, localDict, 'subjectStart >= subjectEnd') subj... |
< subjectEnd: _debugPrint(hsp, queryLen, localDict, 'queryEndInSubject (%d) < subjectEnd (%d)' % (queryEndInSubject, subjectEnd)) |
def normalizeHSP(hsp, queryLen, diamondTask): """ Examine an HSP and return information about where the query and subject match begins and ends. Return a dict with keys that allow the query to be displayed against the subject. The returned readStartInSubject and readEndInSubject indices are offsets into the subject. I.... |
it tells us which of the 3 possible query reading frames was used in the match). NOTE: the returned readStartInSubject value may be negative. We consider the subject sequence to start at offset 0. So if the query string has sufficient additional nucleotides before the start of the alignment match, it may protrude to th... |
subjectEnd The returned offset values are all zero-based. """ queryGaps, subjectGaps = countGaps(hsp['btop']) # Make some variables using Python's standard string indexing (start # offset included, end offset not). No calculations in this function # are done with the original 1-based HSP variables. queryStart = hsp['qu... |
undo # that (because the start is actually the end). We didn't take # one off the end index, and need to do that now (because the # end is actually the start). queryStart = queryLen - (queryStart + 1) queryEnd = queryLen - (queryEnd - 1) else: _debugPrint(hsp, queryLen, locals(), 'queryStart >= queryEnd') if diamondTas... |
the start # and/or the end of the original DNA query. At the start this is # due to the frame in use, and at the end it is due to always using # three nucleotides at a time to form codons. # # So, for example, a query of 6 nucleotides that is translated in # frame 2 (i.e., the translation starts from the second nucleot... |
- 1 queryLen = (queryLen - initiallyIgnored) // 3 queryStart = (queryStart - initiallyIgnored) // 3 queryEnd = (queryEnd - initiallyIgnored) // 3 # unmatchedQueryLeft is the number of query bases that will extend # to the left of the start of the subject in our plots. unmatchedQueryLeft = queryStart # Set the query off... |
def get_storage_credentials(key, read_only=False): """Authenticates a service account for reading and/or writing on a bucket. This uses the `google.oauth2.service_account` module to obtain "scoped credentials". These can be used with the `google.storage` module. TODO: docstring""" if read_only: scopes = ['https://www.g... |
def get_compute_credentials(key): """Authenticates a service account for the compute engine. This uses the `oauth2client.service_account` module. Since the `google` Python package does not support the compute engine (yet?), we need to make direct HTTP requests. For that we need authentication tokens. Obtaining these ba... |
def hash(self): """Generate a hash value.""" h = hash_pandas_object(self, index=True) return hashlib.md5(h.values.tobytes()).hexdigest() |
def genes(self): """Return a list of all genes.""" return [ExpGene.from_series(g) for i, g in self.reset_index().iterrows()] |
def read_tsv(cls, file_or_buffer: str): """Read genes from tab-delimited text file.""" df = pd.read_csv(file_or_buffer, sep='\t', index_col=0) df = df.where(pd.notnull(df), None) # Note: df.where(..., None) changes all column types to `object`. return cls(df) |
def from_genes(cls, genes: List[ExpGene]): """Initialize instance using a list of `ExpGene` objects.""" data = [g.to_dict() for g in genes] index = [d.pop('ensembl_id') for d in data] table = cls(data, index=index) return table |
def from_gene_ids(cls, gene_ids: List[str]): """Initialize instance from gene IDs.""" genes = [ExpGene(id_) for id_ in gene_ids] return cls.from_genes(genes) |
def from_gene_ids_and_names(cls, gene_names: Dict[str, str]): """Initialize instance from gene IDs and names.""" genes = [ExpGene(id_, name=name) for id_, name in gene_names.items()] return cls.from_genes(genes) |
def find_gene(self, name: str): """Find gene(s) by name.""" result = [ExpGene.from_series(s) for i, s in self.loc[self['name'] == name].iterrows()] return result |
def get_figure(self, **kwargs): """Get a plotly figure of the heatmap.""" emin = kwargs.pop('emin', -1.0) emax = kwargs.pop('emax', 1.0) width = kwargs.pop('width', 800) height = kwargs.pop('height', 600) margin_left = kwargs.pop('margin_left', 100) margin_bottom = kwargs.pop('margin_bottom', 60) margin_top = kwargs.po... |
annotation_font_size is None: annotation_font_size = font_size colorbar_label = self.colorbar_label or 'Pearson Correlation' ### set up heatmap colorbar = go.ColorBar( lenmode='fraction', len=colorbar_size, title=colorbar_label, titlefont = dict( size=title_font_size, ), titleside='right', xpad=0, ypad=0, outlinewidth=... |
**kwargs ), ] xshowticklabels = False yshowticklabels = False ### set up layout if show_sample_labels == 'x': xshowticklabels = True elif show_sample_labels == 'y': yshowticklabels = True elif show_sample_labels == 'both': xshowticklabels = True yshowticklabels = True xticks = 'outside' yticks = 'outside' if xaxis_labe... |
but overlaying, axes to place the annotations layout['xaxis2'] = go.XAxis( overlaying='x', showline=False, tickfont=dict(size=0), autorange=False, #range=[-0.5, self.corr_matrix.n-0.5], range=[-0.5, self.corr_matrix.n-0.5], ticks='', showticklabels=False, zeroline=False, showgrid=False, ) layout['yaxis2'] = go.YAxis( o... |
the labels are not limited # by the plotting area for i in range(k): mn = block_coords[i, 0] mx = block_coords[i, 1] layout.annotations.append( dict( x=mx, y=(mn+mx)/2.0, text=block_labels[i], xref='x2', yref='y2', showarrow=False, #ax=20, #ay=-20, xanchor='left', yanchor='middle', font=dict( color='black', size=annota... |
def copy(src, trg, transform=None): ''' copy items with optional fields transformation ''' source = open(src[0], src[1]) target = open(trg[0], trg[1], autocommit=1000) for item in source.get(): item = dict(item) if '_id' in item: del item['_id'] if transform: item = transform(item) target.put(trg[0](item)) source.close... |
def _regexp(expr, item): ''' REGEXP function for Sqlite ''' reg = re.compile(expr) return reg.search(item) is not None |
def _dict_factory(cursor, row): ''' factory for sqlite3 to return results as dict ''' d = {} for idx, col in enumerate(cursor.description): if col[0] == 'rowid': d['_id'] = row[idx] else: d[col[0]] = row[idx] return d |
def parse_uri(uri): ''' parse URI ''' if not uri or uri.find('://') <= 0: raise RuntimeError('Incorrect URI definition: {}'.format(uri)) backend, rest_uri = uri.split('://') if backend not in SUPPORTED_BACKENDS: raise RuntimeError('Unknown backend: {}'.format(backend)) database, table = rest_uri.rsplit(':',1) return da... |
def fieldnames(self): ''' return fieldnames ''' if not self._fields: if self._item_class is not None: for m in inspect.getmembers(self._item_class): if m[0] == 'fields' and isinstance(m[1], dict): self._fields = m[1] if not self._fields: raise RuntimeError('Unknown item type, no fields: %s' % self._item_class) else: ra... |
def _create_table(self, table_name): ''' create sqlite's table for storing simple dictionaries ''' if self.fieldnames: sql_fields = [] for field in self._fields: if field != '_id': if 'dblite' in self._fields[field]: sql_fields.append(' '.join([field, self._fields[field]['dblite']])) else: sql_fields.append(field) sql_... |
def _make_item(self, item): ''' make Item class ''' for field in self._item_class.fields: if (field in item) and ('dblite_serializer' in self._item_class.fields[field]): serializer = self._item_class.fields[field]['dblite_serializer'] item[field] = serializer.loads(item[field]) return self._item_class(item) |
def get(self, criteria=None, offset=None, limit=None): ''' returns items selected by criteria If the criteria is not defined, get() returns all items. ''' if criteria is None and limit is None: return self._get_all() elif limit is not None and limit == 1: return self.get_one(criteria) else: return self._get_with_criter... |
def _get_all(self): ''' return all items ''' rowid = 0 while True: SQL_SELECT_MANY = 'SELECT rowid, * FROM %s WHERE rowid > ? LIMIT ?;' % self._table self._cursor.execute(SQL_SELECT_MANY, (rowid, ITEMS_PER_REQUEST)) items = self._cursor.fetchall() if len(items) == 0: break for item in items: rowid = item['_id'] yield s... |
def _get_with_criteria(self, criteria, offset=None, limit=None): ''' returns items selected by criteria ''' SQL = SQLBuilder(self._table, criteria).select(offset=offset, limit=limit) self._cursor.execute(SQL) for item in self._cursor.fetchall(): yield self._make_item(item) |
def get_one(self, criteria): ''' return one item ''' try: items = [item for item in self._get_with_criteria(criteria, limit=1)] return items[0] except: return None |
def _do_autocommit(self): ''' perform autocommit ''' # commit() self._commit_counter += 1 # autocommit as boolean if isinstance(self._autocommit, bool) and self._autocommit: self.commit() self._commit_counter = 0 # autocommit as counter elif isinstance(self._autocommit, int) and self._autocommit > 0: if (self._commit_c... |
def put(self, item): ''' store item in sqlite database ''' if isinstance(item, self._item_class): self._put_one(item) elif isinstance(item, (list, tuple)): self._put_many(item) else: raise RuntimeError('Unknown item(s) type, %s' % type(item)) |
def _put_one(self, item): ''' store one item in database ''' # prepare values values = [] for k, v in item.items(): if k == '_id': continue if 'dblite_serializer' in item.fields[k]: serializer = item.fields[k]['dblite_serializer'] v = serializer.dumps(v) if v is not None: v = sqlite3.Binary(buffer(v)) values.append(v) ... |
RuntimeError('Item put() error, %s, SQL: %s, values: %s' % (err, SQL, values) ) except sqlite3.IntegrityError: raise DuplicateItem('Duplicate item, %s' % item) self._do_autocommit() |
def _put_many(self, items): ''' store items in sqlite database ''' for item in items: if not isinstance(item, self._item_class): raise RuntimeError('Items mismatch for %s and %s' % (self._item_class, type(item))) self._put_one(item) |
def sql(self, sql, params=()): ''' execute sql request and return items ''' def _items(items): for item in items: yield self._item_class(item) sql = sql.strip() try: self._cursor.execute(sql, params) except sqlite3.OperationalError, err: raise SQLError('%s, SQL: %s, params: %s' % (err, sql, params) ) except sqlite3.Int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.