code stringlengths 1 18.2k |
|---|
def install_reqs(venv, repo_dest): """Installs all compiled requirements that can't be shipped in vendor.""" with dir_path(repo_dest): args = ['-r', 'requirements/compiled.txt'] if not verbose: args.insert(0, '-q') subprocess.check_call([os.path.join(venv, 'bin', 'pip'), 'install'] + args) |
def find_executable(name): """ Finds the actual path to a named command. The first one on $PATH wins. """ for pt in os.environ.get('PATH', '').split(':'): candidate = os.path.join(pt, name) if os.path.exists(candidate): return candidate |
def dir_path(dir): """with dir_path(path) to change into a directory.""" old_dir = os.getcwd() os.chdir(dir) yield os.chdir(old_dir) |
def MWColorMapping(maptype='jet', reverse=True): """Maps amino-acid molecular weights to colors. Otherwise, this function is identical to *KyteDoolittleColorMapping* """ d = {'A':89,'R':174,'N':132,'D':133,'C':121,'Q':146,'E':147,\ 'G':75,'H':155,'I':131,'L':131,'K':146,'M':149,'F':165,\ 'P':115,'S':105,'T':119,'W':204... |
def ChargeColorMapping(maptype='jet', reverse=False): """Maps amino-acid charge at neutral pH to colors. Currently does not use the keyword arguments for *maptype* or *reverse* but accepts these arguments to be consistent with KyteDoolittleColorMapping and MWColorMapping for now.""" pos_color = '#FF0000' neg_color = '#... |
def FunctionalGroupColorMapping(maptype='jet', reverse=False): """Maps amino-acid functional groups to colors. Currently does not use the keyword arguments for *maptype* or *reverse* but accepts these arguments to be consistent with the other mapping functions, which all get called with these arguments.""" small_color ... |
def LogoPlot(sites, datatype, data, plotfile, nperline, numberevery=10, allowunsorted=False, ydatamax=1.01, overlay=None, fix_limits={}, fixlongname=False, overlay_cmap=None, ylimits=None, relativestackheight=1, custom_cmap='jet', map_metric='kd', noseparator=False, underlay=False, scalebar=False): """Create sequence l... |
be one of the following strings: * 'prefs' for preferences * 'diffprefs' for differential preferences * 'diffsel' for differential selection * *data* is a dictionary that has a key for every entry in *sites*. For every site *r* in *sites*, *sites[r][x]* is the value for character *x*. Preferences must sum to one; diffe... |
put labels for the sites on x-axis. * *allowunsorted* : if *True* then we allow the entries in *sites* to **not** be sorted. This means that the logo plot will **not** have sites in sorted order. * *ydatamax* : meaningful only if *datatype* is 'diffprefs'. In this case, it gives the maximum that the logo stacks extend ... |
the sites. If you set to something other than `None`, it should be a list giving one to three properties. Each property is a tuple: *(prop_d, shortname, longname)* where: - *prop_d* is a dictionary keyed by site numbers that are in *sites*. For each *r* in *sites*, *prop_d[r]* gives the value of the property, or if the... |
the property; will not format well if more than 4 or 5 characters. - *longname* : longer name for property used on axes label. Can be the same as *shortname* if you don't need a different long name. - In the special case where both *shortname* and *longname* are the string `wildtype`, then rather than an overlay bar we... |
corresponding tick label for that tick. * If *fixlongname* is *True*, then we use the *longname* in *overlay* exactly as written; otherwise we add a parenthesis indicating the *shortname* for which this *longname* stands. * *overlay_cmap* can be the name of a valid *matplotlib.colors.Colormap*, such as the string *jet*... |
letter stack. * *map_metric* specifies the amino-acid property metric used to map colors to amino-acid letters. Valid options are 'kd' (Kyte-Doolittle hydrophobicity scale, default), 'mw' (molecular weight), 'functionalgroup' (functional groups: small, nucleophilic, hydrophobic, aromatic, basic, acidic, and amide), and... |
be a 2-tuple of `(scalebarlen, scalebarlabel)`. Currently only works when data is `diffsel`. """ assert datatype in ['prefs', 'diffprefs', 'diffsel'], "Invalid datatype {0}".format(datatype) # check data, and get characters assert sites, "No sites specified" assert set(sites) == set(data.keys()), "Not a match between s... |
in characters, "firstblankchar in characters" lastblankchar = 'b' # character for last blank space for diffprefs / diffsel assert lastblankchar not in characters, "lastblankchar in characters" separatorchar = '-' # separates positive and negative for diffprefs / diffsel assert separatorchar not in characters, "lastblan... |
size of 10.8, but set to this in weblogo call below barheight = 5.5 # height of bars in points if using overlay barspacing = 2.0 # spacing between bars in points if using overlay stackaspectratio = 4.4 # ratio of stack height:width, doesn't count part going over maximum value of 1 assert relativestackheight > 0, "relat... |
between stacks in points, fixed by weblogo showscalebar = False try: # write data into transfacfile (a temporary file) (fd, transfacfile) = tempfile.mkstemp() f = os.fdopen(fd, 'w') ordered_alphabets = {} # keyed by site index (0, 1, ...) with values ordered lists for characters from bottom to top if datatype == 'prefs... |
% ' '.join(chars_for_string)) for (isite, r) in enumerate(sites): positivesum = sum([data[r][x] for x in characters if data[r][x] > 0]) + separatorheight / 2.0 negativesum = sum([data[r][x] for x in characters if data[r][x] < 0]) - separatorheight / 2.0 if abs(positivesum + negativesum) > 1.0e-3: raise ValueError("Diff... |
0: firstpositiveindex += 1 ordered_alphabets[isite] = [firstblankchar] + [tup[1] for tup in deltapi_r[ : firstpositiveindex]] + [separatorchar] + [tup[1] for tup in deltapi_r[firstpositiveindex : ]] + [lastblankchar] # order from most negative to most positive with blank characters and separators f.write(' %g %g %g\n' ... |
in characters if data[r][x] > 0]) + separatorheight / 2.0 negativesum = sum([data[r][x] for x in characters if data[r][x] < 0]) - separatorheight / 2.0 assert positivesum <= dataymax, "Data exceeds ylimits in positive direction" assert negativesum >= dataymin, "Data exceeds ylimits in negative direction" f.write('{0}'.... |
charactors and separators # height of one unit on y-axis in points heightofone = stackwidth * stackaspectratio / yextent assert heightofone > 0 if scalebar: showscalebar = (heightofone * scalebar[0], scalebar[1]) else: raise ValueError("Invalid datatype of %s" % datatype) f.close() # create web logo charstring = ''.joi... |
== 'nt': colormapping = {} colormapping['A'] = '#008000' colormapping['T'] = '#FF0000' colormapping['C'] = '#0000FF' colormapping['G'] = '#FFA500' else: raise ValueError("Invalid alphabet_type %s" % alphabet_type) colormapping[firstblankchar] = colormapping[lastblankchar] = '#000000' # black, but color doesn't matter a... |
"Failed to find expected plotfile %s" % plotfile finally: # close if still open try: f.close() except: pass # remove temporary file if os.path.isfile(transfacfile): os.remove(transfacfile) # now build the overlay if overlay or showscalebar: try: (fdoverlay, overlayfile) = tempfile.mkstemp(suffix='.pdf') (fdmerged, merg... |
try: plotfile_f.close() except: pass try: overlayfile_f.close() except: pass try: foverlay.close() except: pass try: fmerged.close() except: pass for fname in [overlayfile, mergedfile]: if os.path.isfile(fname): os.remove(fname) |
def _my_pdf_formatter(data, format, ordered_alphabets) : """ Generate a logo in PDF format. Modified from weblogo version 3.4 source code. """ eps = _my_eps_formatter(data, format, ordered_alphabets).decode() gs = weblogolib.GhostscriptAPI() return gs.convert('pdf', eps, format.logo_width, format.logo_height) |
def _my_eps_formatter(logodata, format, ordered_alphabets) : """ Generate a logo in Encapsulated Postscript (EPS) Modified from weblogo version 3.4 source code. *ordered_alphabets* is a dictionary keyed by zero-indexed consecutive sites, with values giving order of characters from bottom to top. """ substitutions = {} ... |
[] if hasattr(format.color_scheme, 'rules'): grouplist = format.color_scheme.rules else: # this line needed for weblogo 3.4 grouplist = format.color_scheme.groups for group in grouplist: cf = format_color(group.color) for s in group.symbols : colors.append( " ("+s+") " + cf ) substitutions["color_dict"] = "\n".join(col... |
if conv_factor: stack_height = logodata.entropy[seq_index] * std_units[format.unit_name] else : stack_height = 1.0 # Probability # The following code modified by JDB to use ordered_alphabets # and also to replace the "blank" characters 'b' and 'B' # by spaces. s_d = dict(zip(logodata.alphabet, logodata.counts[seq_index... |
# print(fraction_width, file=sys.stderr) for c in s: data.append(" %f %f (%s) ShowSymbol" % (fraction_width, c[0]*stack_height/C, c[1]) ) # Draw error bar on top of logo. Replaced by DrawErrorbarFirst above. if logodata.entropy_interval is not None and conv_factor and C>0.0: low, high = logodata.entropy_interval[seq_in... |
def LogoOverlay(sites, overlayfile, overlay, nperline, sitewidth, rmargin, logoheight, barheight, barspacing, fix_limits={}, fixlongname=False, overlay_cmap=None, underlay=False, scalebar=False): """Makes overlay for *LogoPlot*. This function creates colored bars overlay bars showing up to two properties. The trick of ... |
is the right margin in points. * *logoheight* is the total height of each logo row in points. * *barheight* is the total height of each bar in points. * *barspacing* is the vertical spacing between bars in points. * *fix_limits* has the same meaning of the variable of this name used by *LogoPlot*. * *fixlongname* has t... |
overlay_cmap: (cmap, mapping_d, mapper) = KyteDoolittleColorMapping() else: mapper = pylab.cm.ScalarMappable(cmap=overlay_cmap) cmap = mapper.get_cmap() pts_per_inch = 72.0 # to convert between points and inches # some general properties of the plot matplotlib.rc('text', usetex=True) matplotlib.rc('xtick', labelsize=8)... |
fig = pylab.figure(figsize=(figwidth / pts_per_inch, figheight / pts_per_inch)) # determine property types prop_types = {} for (prop_d, shortname, longname) in overlay: if shortname == longname == 'wildtype': assert all([(isinstance(prop, str) and len(prop) == 1) for prop in prop_d.values()]), 'prop_d does not give let... |
if vmin >= 0 and vmin / float(vmax - vmin) < 0.05: vmin = 0.0 # And if vmax is just a bit less than one, set it to that... if 0.9 <= vmax <= 1.0: vmax = 1.0 else: raise ValueError("Property %s is neither continuous or discrete. Values are:\n%s" % (shortname, str(prop_d.items()))) if shortname in fix_limits: (vmin, vmax... |
min(len(sites), (iline + 1) * nperline)] xlength = len(isites) * sitewidth logo_ax = pylab.axes([lmargin / figwidth, ((nlines - iline - 1) * (logoheight + len(overlay) * (barspacing + barheight))) / figheight, xlength / figwidth, logoheight / figheight], frameon=False) logo_ax.yaxis.set_ticks_position('none') logo_ax.x... |
horizontalalignment='center', family='monospace') continue pylab.yticks([0], [shortname], size=8) prop_ax.yaxis.set_ticks_position('left') propdata = pylab.zeros(shape=(1, len(isites))) propdata[ : ] = pylab.nan # set to nan for all entries for (isite, site) in enumerate(isites): if site in prop_d: if proptype == 'cont... |
+ colorbarspacingfrac)) # width of color bars in fraction of figure width colorbarspacingwidth = colorbarwidth * colorbarspacingfrac # width of color bar spacing in fraction of figure width # bottom of color bars ybottom = 1.0 - (colorbar_tmargin + barheight) / figheight propnames = {} icolorbar = -1 icolorbarshift = 0... |
/ 2.0, scalebarlabel, verticalalignment='center', horizontalalignment='left', transform=fullfigax.transAxes) continue (prop_d, shortname, longname) = overlay[icolorbar] icolorbar += 1 (proptype, vmin, vmax, propcategories) = prop_types[shortname] if proptype == 'wildtype': icolorbarshift += 1 continue if shortname == l... |
if it seems plausible, set integer ticks if 4 < (vmax - vmin) <= 11: fixedticks = [itick for itick in range(int(vmin), int(vmax) + 1)] cb.set_ticks(fixedticks) cb.set_ticklabels([str(itick) for itick in fixedticks]) elif proptype == 'discrete': cb = pylab.colorbar(prop_image[shortname], cax=colorbar_ax, orientation='ho... |
def read_transfac( fin, alphabet = None) : """ Parse a sequence matrix from a file. Returns a tuple of (alphabet, matrix) """ items = [] start=True for line in fin : if line.isspace() or line[0] =='#' : continue stuff = line.split() if start and stuff[0] != 'PO' and stuff[0] != 'P0': continue if stuff[0]=='XX' or stuff... |
in range(1, len(items)) : if cols != len(items[i]) : raise ValueError("Inconsistant length, row %d: " % i) # Vertical or horizontal arrangement? if header[0] == 'PO' or header[0] == 'P0': header.pop(0) position_header = True alphabet_header = True for h in header : if not corebio.utils.isint(h) : position_header = Fals... |
and r[0][0]!='P' : raise ValueError( "Expected position as first item on line %d" % i) a.append(r.pop(0)) defacto_alphabet = ''.join(a) # Check defacto_alphabet defacto_alphabet = corebio.seq.Alphabet(defacto_alphabet) if alphabet : if not defacto_alphabet.alphabetic(alphabet) : raise ValueError("Incompatible alphabets... |
matrix[r,c] = float( items[r][c]) if position_header : matrix.transpose() return _my_Motif(defacto_alphabet, matrix).reindex(alphabet) |
def pruneToAtoms(self, atoms): """Prune the molecule to the specified atoms bonds will be removed atomatically""" _atoms = self.atoms[:] for atom in _atoms: if atom not in atoms: self.remove_atom(atom) |
def poll(connection: connection, timeout: float=1.0) -> Iterable[Event]: """Poll the connection for notification events. This method operates as an iterable. It will keep returning events until all events have been read. Parameters ---------- connection: psycopg2.extensions.connection Active connection to a PostGreSQL ... |
logger_name=_LOGGER_NAME) connection.poll() while connection.notifies: event = connection.notifies.pop(0) log(str(event), logger_name=_LOGGER_NAME) yield Event.fromjson(event.payload) |
def fromjson(cls, json_string: str) -> 'Event': """Create a new Event from a from a psycopg2-pgevent event JSON. Parameters ---------- json_string: str Valid psycopg2-pgevent event JSON. Returns ------- Event Event created from JSON deserialization. """ obj = json.loads(json_string) return cls( UUID(obj['event_id']), o... |
def tojson(self) -> str: """Serialize an Event into JSON. Returns ------- str JSON-serialized Event. """ return json.dumps({ 'event_id': str(self.id), 'event_type': self.type, 'schema_name': self.schema_name, 'table_name': self.table_name, 'row_id': self.row_id }) |
def input_data(self): """Function to extract data from files according to pid. This function will read in the data with :class:`bowie.plotutils.readdata.ReadInData`. """ ordererd = np.sort(np.asarray(list(self.plot_info.keys())).astype(int)) trans_cont_dict = OrderedDict() for i in ordererd: trans_cont_dict[str(i)] = s... |
for index in self.plot_info[axis_string]['indices']: index = int(index) x[k].append(x[index][0]) y[k].append(y[index][0]) z[k].append(z[index][0]) # read or append control values for ratio plots for k, axis_string in enumerate(self.plot_info.keys()): if 'control' in self.plot_info[axis_string]: if ('name' in self.plot_... |
def setup_figure(self): """Sets up the initial figure on to which every plot is added. """ # declare figure and axes environments fig, ax = plt.subplots(nrows=int(self.num_rows), ncols=int(self.num_cols), sharex=self.sharex, sharey=self.sharey) fig.set_size_inches(self.figure_width, self.figure_height) # create list of... |
if 'Ratio' in self.plot_types or 'Waterfall': self.subplots_adjust_kwargs['right'] = 0.79 # adjust figure sizes fig.subplots_adjust(**self.subplots_adjust_kwargs) if 'fig_y_label' in self.__dict__.keys(): fig.text(self.fig_y_label_x, self.fig_y_label_y, r'{}'.format(self.fig_y_label), **self.fig_y_label_kwargs) if 'fig... |
def create_plots(self): """Creates plots according to each plotting class. """ for i, axis in enumerate(self.ax): # plot everything. First check general dict for parameters related to plots. trans_plot_class_call = globals()[self.plot_types[i]] trans_plot_class = trans_plot_class_call(self.fig, axis, self.value_classes... |
def create_ngram_table(self, cardinality): """ Creates a table for n-gram of a give cardinality. The table name is constructed from this parameter, for example for cardinality `2` there will be a table `_2_gram` created. Parameters ---------- cardinality : int The cardinality to create a table for. """ query = "CREATE ... |
def create_index(self, cardinality): """ Create an index for the table with the given cardinality. Parameters ---------- cardinality : int The cardinality to create a index for. """ for i in reversed(range(cardinality)): if i != 0: query = "CREATE INDEX idx_{0}_gram_{1} ON _{0}_gram(word_{1});".format(cardinality, i) s... |
def ngrams(self, with_counts=False): """ Returns all ngrams that are in the table. Parameters ---------- None Returns ------- ngrams : generator A generator for ngram tuples. """ query = "SELECT " for i in reversed(range(self.cardinality)): if i != 0: query += "word_{0}, ".format(i) elif i == 0: query += "word" if with... |
def ngram_count(self, ngram): """ Gets the count for a given ngram from the database. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. Returns ------- count : int The count of the ngram. """ query = "SELECT count FROM _{0}_gram".format(len(ngram)) query += self._build_where_clause(ngram) q... |
def insert_ngram(self, ngram, count): """ Inserts a given n-gram with count into the database. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. count : int The count for the given n-gram. """ query = "INSERT INTO _{0}_gram {1};".format(len(ngram), self._build_values_clause(ngram, count)) s... |
def update_ngram(self, ngram, count): """ Updates a given ngram in the database. The ngram has to be in the database, otherwise this method will stop with an error. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. count : int The count for the given n-gram. """ query = "UPDATE _{0}_gram SE... |
def remove_ngram(self, ngram): """ Removes a given ngram from the databae. The ngram has to be in the database, otherwise this method will stop with an error. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. """ query = "DELETE FROM _{0}_gram".format(len(ngram)) query += self._build_where_... |
def execute_sql(self, query): """ Executes a given query string on an open sqlite database. """ c = self.con.cursor() c.execute(query) result = c.fetchall() return result |
def create_database(self): """ Creates an empty database if not exists. """ if not self._database_exists(): con = psycopg2.connect(host=self.host, database="postgres", user=self.user, password=self.password, port=self.port) con.set_isolation_level( psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) query = "CREATE DATABAS... |
def reset_database(self): """ Re-create an empty database. """ if self._database_exists(): con = psycopg2.connect(host=self.host, database="postgres", user=self.user, password=self.password, port=self.port) con.set_isolation_level( psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) query = "DROP DATABASE {0};".format(self... |
def create_index(self, cardinality): """ Create an index for the table with the given cardinality. Parameters ---------- cardinality : int The cardinality to create a index for. """ DatabaseConnector.create_index(self, cardinality) query = "CREATE INDEX idx_{0}_gram_varchar ON _{0}_gram(word varchar_pattern_ops);".form... |
def delete_index(self, cardinality): """ Delete index for the table with the given cardinality. Parameters ---------- cardinality : int The cardinality of the index to delete. """ DatabaseConnector.delete_index(self, cardinality) query = "DROP INDEX IF EXISTS idx_{0}_gram_varchar;".format(cardinality) self.execute_sql(... |
def open_database(self): """ Opens the sqlite database. """ if not self.con: try: self.con = psycopg2.connect(host=self.host, database=self.dbname, user=self.user, password=self.password, port=self.port) except psycopg2.Error as e: print("Error while opening database:") print(e.pgerror) |
def execute_sql(self, query): """ Executes a given query string on an open postgres database. """ c = self.con.cursor() c.execute(query) result = [] if c.rowcount > 0: try: result = c.fetchall() except psycopg2.ProgrammingError: pass return result |
def _database_exists(self): """ Check if the database exists. """ con = psycopg2.connect(host=self.host, database="postgres", user=self.user, password=self.password, port=self.port) query_check = "select datname from pg_catalog.pg_database" query_check += " where datname = '{0}';".format(self.dbname) c = con.cursor() c... |
def getChirality(self, order): """(order)->what is the chirality of a given order of atoms?""" indices = tuple([self._initialOrder.index(atom.handle) for atom in order]) same = chiral_table[indices] if same: return self.chirality else: if self.chirality == "@": return "@@" else: return "@" |
def log_cef(name, severity=logging.INFO, env=None, username='none', signature=None, **kwargs): """ Wraps cef logging function so we don't need to pass in the config dictionary every time. See bug 707060. ``env`` can be either a request object or just the request.META dictionary. """ cef_logger = commonware.log.getLogge... |
the last part of this if() will never be hit except in the # test runner. Good luck with that. if isinstance(env, HttpRequest): r = env.META.copy() elif isinstance(env, dict): r = env else: r = {} # Drop kwargs into CEF config array, then log. c['environ'] = r c.update({ 'username': username, 'signature': signature, 'd... |
def get_changedir(env): "changedir = {envdir}" from ctox.subst import replace_braces changedir = _get_env_maybe(env, 'testenv', 'changedir') if changedir: return replace_braces(changedir, env) else: return env.toxinidir |
def remove_signals_listeners(instance): """ utility function that disconnects all listeners from all signals on an object """ if hasattr(instance, "__listeners__"): for listener in list(instance.__listeners__): for signal in instance.__listeners__[listener]: signal.disconnect(listener) |
def connect(self, listener, pass_signal=False): """ Connect a new listener to this signal :param listener: The listener (callable) to add :param pass_signal: An optional argument that controls if the signal object is explicitly passed to this listener when it is being fired. If enabled, a ``signal=`` keyword argument i... |
collections.defaultdict(list) # Append the signals a listener is connected to listener_object.__listeners__[listener].append(self) |
def disconnect(self, listener, pass_signal=False): """ Disconnect an existing listener from this signal :param listener: The listener (callable) to remove :param pass_signal: An optional argument that controls if the signal object is explicitly passed to this listener when it is being fired. If enabled, a ``signal=`` k... |
del listener_object.__listeners__[listener] |
def fire(self, args, kwargs): """ Fire this signal with the specified arguments and keyword arguments. Typically this is used by using :meth:`__call__()` on this object which is more natural as it does all the argument packing/unpacking transparently. """ for info in self._listeners[:]: if info.pass_signal: info.listen... |
def watchSignal(self, signal): """ Setup provisions to watch a specified signal :param signal: The :class:`Signal` to watch for. After calling this method you can use :meth:`assertSignalFired()` and :meth:`assertSignalNotFired()` with the same signal. """ self._extend_state() def signal_handler(*args, **kwargs): self._... |
def assertSignalFired(self, signal, *args, **kwargs): """ Assert that a signal was fired with appropriate arguments. :param signal: The :class:`Signal` that should have been fired. Typically this is ``SomeClass.on_some_signal`` reference :param args: List of positional arguments passed to the signal handler :param kwar... |
def assertSignalNotFired(self, signal, *args, **kwargs): """ Assert that a signal was fired with appropriate arguments. :param signal: The :class:`Signal` that should not have been fired. Typically this is ``SomeClass.on_some_signal`` reference :param args: List of positional arguments passed to the signal handler :par... |
def assertSignalOrdering(self, *expected_events): """ Assert that a signals were fired in a specific sequence. :param expected_events: A (varadic) list of events describing the signals that were fired Each element is a 3-tuple (signal, args, kwargs) that describes the event. .. note:: If you are using :meth:`assertSign... |
def url(viewname, *args, **kwargs): """Helper for Django's ``reverse`` in templates.""" return reverse(viewname, args=args, kwargs=kwargs) |
def urlparams(url_, hash=None, **query): """Add a fragment and/or query paramaters to a URL. New query params will be appended to exising parameters, except duplicate names, which will be replaced. """ url = urlparse.urlparse(url_) fragment = hash if hash is not None else url.fragment # Use dict(parse_qsl) so we don't ... |
def _urlencode(items): """A Unicode-safe URLencoder.""" try: return urllib.urlencode(items) except UnicodeEncodeError: return urllib.urlencode([(k, smart_str(v)) for k, v in items]) |
def urlencode(txt): """Url encode a path.""" if isinstance(txt, unicode): txt = txt.encode('utf-8') return urllib.quote_plus(txt) |
def token_handler_str_default( token, dispatcher, node, subnode, sourcepath_stack=(None,)): """ Standard token handler that will return the value, ignoring any tokens or strings that have been remapped. """ if isinstance(token.pos, int): _, lineno, colno = node.getpos(subnode, token.pos) else: lineno, colno = None, Non... |
def token_handler_unobfuscate( token, dispatcher, node, subnode, sourcepath_stack=(None,)): """ A token handler that will resolve and return the original identifier value. """ original = ( node.value if isinstance(node, Identifier) and node.value != subnode else None ) if isinstance(token.pos, int): _, lineno, colno = ... |
def read(parser, stream): """ Return an AST from the input ES5 stream. Arguments parser A parser instance. stream Either a stream object or a callable that produces one. The stream object to read from; its 'read' method will be invoked. If a callable was provided, the 'close' method on its return value will be called t... |
def write( unparser, nodes, output_stream, sourcemap_stream=None, sourcemap_normalize_mappings=True, sourcemap_normalize_paths=True, source_mapping_url=NotImplemented): """ Write out the node using the unparser into an output stream, and optionally the sourcemap using the sourcemap stream. Ideally, file objects should ... |
should have its sourcepath set to path that this node originated from. Arguments unparser An unparser instance. nodes The Node or list of Nodes to stream to the output stream with the unparser. output_stream Either a stream object or a callable that produces one. The stream object to write to; its 'write' method will b... |
as the output_stream will be used for writing out the source map, and the source map will instead be encoded as a 'data:application/json;base64,' URL. sourcemap_normalize_mappings Flag for the normalization of the sourcemap mappings; Defaults to True to enable a reduction in output size. sourcemap_normalize_paths If se... |
closer.append(result.close) else: result = stream return result def cleanup(): for close in reversed(closer): close() chunks = None if isinstance(nodes, Node): chunks = unparser(nodes) elif isinstance(nodes, Iterable): raw = [unparser(node) for node in nodes if isinstance(node, Node)] if raw: chunks = chain(*raw) if no... |
def dof(self, index=None): """The number of degrees of freedom""" if index is None: dof = 0 for i in range(self.len): dof += self.A[i].shape[0] * self.F[i].shape[1] return dof else: return self.A[index].shape[0] * self.F[index].shape[1] |
def clearFixedEffect(self): """ erase all fixed effects """ self.A = [] self.F = [] self.F_any = np.zeros((self.N,0)) self.clear_cache() |
def addFixedEffect(self,F=None,A=None,index=None): """ set sample and trait designs F: NxK sample design A: LxP sample design fast_computations: False deactivates the fast computations for any and common effects (for debugging) """ if F is None: F = np.ones((self.N,1)) else: assert F.shape[0]==self.N, "F dimension mism... |
def Lr(self,value): """ set row rotation """ assert value.shape==(self.N, self.N), 'dimension mismatch' self._Lr = value self.clear_cache() |
def Lc(self,value): """ set col rotation """ assert value.shape==(self.P, self.P), 'dimension mismatch' self._Lc = value self.clear_cache() |
def d(self,value): """ set anisotropic scaling """ assert value.shape[0]==self.P*self.N, 'd dimension mismatch' self._d = value self.clear_cache() |
def beta_hat(self): """compute ML beta""" XKY = self.XKY() XanyKY = self.XanyKY() beta_hat, beta_hat_any = self.Areml_solver.solve(b_any=XanyKY,b=XKY,check_finite=True) return beta_hat, beta_hat_any |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.