code stringlengths 1 18.2k |
|---|
def setup_plot(self): """Set up limits and labels. For all plot types, this method is used to setup the basic features of each plot. """ if self.tick_label_fontsize is not None: self.x_tick_label_fontsize = self.tick_label_fontsize self.y_tick_label_fontsize = self.tick_label_fontsize # setup xticks and yticks and limi... |
= np.arange(1, len(yticks)-1) self.axis.set_xticks(xticks[x_inds]) self.axis.set_yticks(yticks[y_inds]) # set tick labels based on scale if self.xscale == 'log': self.axis.set_xticklabels([r'$10^{%i}$' % int(i) for i in xticks[x_inds]], fontsize=self.x_tick_label_fontsize) else: self.axis.set_xticklabels([r'$%.3g$' % (... |
def setup_colorbars(self, plot_call_sign): """Setup colorbars for each type of plot. Take all of the optional performed during ``__init__`` method and makes the colorbar. Args: plot_call_sign (obj): Plot instance of ax.contourf with colormapping to add as a colorbar. """ self.fig.colorbar(plot_call_sign, cax=self.cbar_... |
def _adapt_response(self, response): """Convert error responses to standardized ErrorDetails.""" if 'application/json' in response.headers['content-type']: body = response.json() status = response.status_code if body.get('error'): return self._simple_response_to_error_adapter(status, body) raise UnknownHttpError(respon... |
def _simple_response_to_error_adapter(self, status, original_body): """Convert a single error response.""" meta = original_body.get('error') e = [] if 'error_detail' in original_body: errors = original_body.get('error_detail') for error in errors: if type(error) == dict: for parameter, title in error.iteritems(): e.app... |
def setup_environ(manage_file, settings=None, more_pythonic=False): """Sets up a Django app within a manage.py file. Keyword Arguments **settings** An imported settings module. Without this, playdoh tries to import these modules (in order): DJANGO_SETTINGS_MODULE, settings **more_pythonic** When True, does not do any p... |
the Zen of Python. " "See http://playdoh.readthedocs.org/en/latest/" "getting-started/upgrading.html") # Give precedence to your app's parent dir, which contains __init__.py sys.path.append(os.path.abspath(os.path.join(ROOT, os.pardir))) site.addsitedir(path('apps')) site.addsitedir(path('lib')) # Local (project) vendo... |
def validate_settings(settings): """ Raise an error in prod if we see any insecure settings. This used to warn during development but that was changed in 71718bec324c2561da6cc3990c927ee87362f0f7 """ from django.core.exceptions import ImproperlyConfigured if settings.SECRET_KEY == '': msg = 'settings.SECRET_KEY cannot b... |
def cached(method): """ this function is used as a decorator for caching """ _cache_attr_name = '_cache_'+method.__name__ _bool_attr_name = '_cached_'+method.__name__ def method_wrapper(self,*args,**kwargs): is_cached = getattr(self,_bool_attr_name) if not is_cached: result = method(self, *args, **kwargs) setattr(self,... |
def cached_idxs(method): """ this function is used as a decorator for caching """ def method_wrapper(self,*args,**kwargs): tail = '_'.join(str(idx) for idx in args) _cache_attr_name = '_cache_'+method.__name__+'_'+tail _bool_attr_name = '_cached_'+method.__name__+'_'+tail is_cached = getattr(self,_bool_attr_name) if no... |
def incremental_neighbor_graph(X, precomputed=False, k=None, epsilon=None, weighting='none'): '''See neighbor_graph.''' assert ((k is not None) or (epsilon is not None) ), "Must provide `k` or `epsilon`" assert (_issequence(k) ^ _issequence(epsilon) ), "Exactly one of `k` or `epsilon` must be a sequence." assert weight... |
order[:, old_k:new_k] dist = D[I, idx.T] W[I, idx.T] = dist if is_weighted else 1 yield Graph.from_adj_matrix(W) old_k = new_k else: # varied epsilon, fixed k idx = order[:,:k] dist = D[I, idx.T].T old_i = np.zeros(D.shape[0], dtype=int) for eps in epsilon: for i, row in enumerate(dist): oi = old_i[i] ni = oi + np.sear... |
def Versions(): """Returns a string with version information. You would call this function if you want a string giving detailed information on the version of ``phydms`` and the associated packages that it uses. """ s = [\ 'Version information:', '\tTime and date: %s' % time.asctime(), '\tPlatform: %s' % platform.platfo... |
def ReadCodonAlignment(fastafile, checknewickvalid): """Reads codon alignment from file. *fastafile* is the name of an existing FASTA file. *checknewickvalid* : if *True*, we require that names are unique and do **not** contain spaces, commas, colons, semicolons, parentheses, square brackets, or single or double quotat... |
aligned sequences in this example: >>> seqs = [('seq1', 'ATGGAA'), ('seq2', 'ATGAAA')] >>> f = io.StringIO() >>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs])) >>> n = f.seek(0) >>> a = ReadCodonAlignment(f, True) >>> seqs == a True Trim stop codons from all sequences in this example: >>> seqs = ... |
== a True Premature stop codon gives error: >>> seqs = [('seq1', 'TGAATG'), ('seq2', 'ATGAGA')] >>> f = io.StringIO() >>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs])) >>> n = f.seek(0) >>> a = ReadCodonAlignment(f, True) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): Val... |
are not valid codon sequences" ).format(fastafile, seqlen)) terminalcodon = [] codons_by_position = dict([(icodon, []) for icodon in range(seqlen // 3)]) for (head, seq) in seqs: assert len(seq) % 3 == 0 for icodon in range(seqlen // 3): codon = seq[3 * icodon : 3 * icodon + 3] codons_by_position[icodon].append(codon) ... |
are gaps at position {1}" ).format(fastafile, icodon + 1)) if all([aa in ['*', '-'] for aa in terminalcodon]): if len(seq) == 3: raise ValueError(("The only codon is a terminal stop codon for " "the sequences in {0}").format(fastafile)) seqs = [(head, seq[ : -3]) for (head, seq) in seqs] elif any([aa == '*' for aa in t... |
in {0}:" "\n{2}").format(fastafile, head)) return seqs |
def readPrefs(prefsfile, minpref=0, avgprefs=False, randprefs=False, seed=1, sites_as_strings=False): """Read preferences from file with some error checking. Args: `prefsfile` (string or readable file-like object) File holding amino-acid preferences. Can be comma-, space-, or tab-separated file with column headers of `... |
(bool) By default, the site numers are coerced to integers. If this option is `True`, then they are kept as strings. Returns: `prefs` (dict) `prefs[r][a]` is the preference of site `r` for amino-acid `a`. `r` is an `int` unless `sites_as_strings=True`. """ assert minpref >= 0, 'minpref must be >= 0' aas = set(phydmslib... |
error check prefs if not sites_as_strings: try: sites = [int(r) for r in sites] except ValueError: raise ValueError("sites not int in prefsfile {0}".format(prefsfile)) assert (min(sites) == 1 and max(sites) - min(sites) == len(sites) - 1),\ "Sites not consecutive starting at 1" prefs = dict([(int(r), rprefs) for (r, rp... |
not include " "all amino acids at site {1}").format(prefsfile, r) rsum = float(sum(rprefs.values())) prefs[r] = dict([(aa, pi / rsum) for (aa, pi) in rprefs.items()]) assert set(sites) == set(prefs.keys()) # Iteratively adjust until all prefs exceed minpref after re-scaling. for r in list(prefs.keys()): rprefs = prefs[... |
avg_prefs = dict([(aa, 0.0) for aa in aas]) for rprefs in prefs.values(): for aa in aas: avg_prefs[aa] += rprefs[aa] for aa in aas: avg_prefs[aa] /= float(len(prefs)) for r in list(prefs.keys()): prefs[r] = avg_prefs return prefs |
def readPrefs_dms_tools_format(f): """Reads the amino-acid preferences written by `dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_. This is an exact copy of the same code from `dms_tools.file_io.ReadPreferences`. It is copied because `dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_ is currently only compa... |
= f.readlines() f.close() else: lines = f.readlines() characters = [] sites = [] wts = {} pi_means = {} pi_95credint = {} h = {} for line in lines: if line.isspace(): continue elif line[0] == '#' and not characters: entries = line[1 : ].strip().split() if len(entries) < 4: raise ValueError("Insufficient entries in head... |
all([entries[i + j] == 'PI_%s_95' % characters[j] for j in range(len(characters))]): raise ValueError("mean and credible interval character mismatch in header:\n%s" % line) linelength = 2 * len(characters) + 3 elif line[0] == '#': continue elif not characters: raise ValueError("Found data lines before encountering a va... |
= dict([(x, (float(entries[3 + len(characters) + i].split(',')[0]), float(entries[3 + len(characters) + i].split(',')[1]))) for (i, x) in enumerate(characters)]) return (sites, wts, pi_means, pi_95credint, h) |
def readDivPressure(fileName): """Reads in diversifying pressures from some file. Scale diversifying pressure values so absolute value of the max value is 1, unless all values are zero. Args: `fileName` (string or readable file-like object) File holding diversifying pressure values. Can be comma-, space-, or tab-separa... |
{0}".format(fileName) assert max(df["divPressureValue"].abs()) <= 1, "The scaling produced a diversifying pressure value with an absolute value greater than one." sites = df['site'].tolist() divPressure = {} for r in sites: divPressure[r] = df[df['site'] == r]["divPressureValue"].tolist()[0] return divPressure |
def load_configuration(conf_path): """Load and validate test configuration. :param conf_path: path to YAML configuration file. :return: configuration as dict. """ with open(conf_path) as f: conf_dict = yaml.load(f) validate_config(conf_dict) return conf_dict |
def validate_config(conf_dict): """Validate configuration. :param conf_dict: test configuration. :type conf_dict: {} :raise InvalidConfigurationError: """ # TASK improve validation if APPLICATIONS not in conf_dict.keys(): raise InvalidConfigurationError('Missing application configuration.') if SEED_FILES not in conf_di... |
def main(): """Read configuration and execute test runs.""" parser = argparse.ArgumentParser(description='Stress test applications.') parser.add_argument('config_path', help='Path to configuration file.') args = parser.parse_args() try: configuration = load_configuration(args.config_path) except InvalidConfigurationErr... |
def main(arguments, toxinidir=None): "ctox: tox with conda." try: # pragma: no cover # Exit on broken pipe. import signal signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # pragma: no cover # SIGPIPE is not available on Windows. pass try: import sys sys.exit(ctox(arguments, toxinidir)) except Called... |
def ctox(arguments, toxinidir): """Sets up conda environments, and sets up and runs each environment based on the project's tox.ini configuration file. Returns 1 if either the build or running the commands failed or 0 if all commmands ran successfully. """ if arguments is None: arguments = [] if toxinidir is None: toxi... |
= args.e.split(',') # TODO configure with option toxdir = os.path.join(toxinidir, ".tox") # create a zip file for the project from ctox.pkg import make_dist, package_name cprint("GLOB sdist-make: %s" % os.path.join(toxinidir, "setup.py")) package = package_name(toxinidir) if not make_dist(toxinidir, toxdir, package): c... |
def positional_args(arguments): """"Generator for position arguments. Example ------- >>> list(positional_args(["arg1", "arg2", "--kwarg"])) ["arg1", "arg2"] >>> list(positional_args(["--", "arg1", "--kwarg"])) ["arg1", "kwarg"] """ # TODO this behaviour probably isn't quite right. if arguments and arguments[0] == '--'... |
def _main(): "ctox: tox with conda" from sys import argv arguments = argv[1:] toxinidir = os.getcwd() return main(arguments, toxinidir) |
def ctox(self): """Main method for the environment. Parse the tox.ini config, install the dependancies and run the commands. The output of the commands is printed. Returns 0 if they ran successfully, 1 if there was an error (either in setup or whilst running the commands), 2 if the build was skipped. """ # TODO make th... |
need to be rebuilt) # TODO extract this as a method (for readability) if not self.env_exists() or self.reusableable(): cprint("%s create: %s" % (self.name, self.envdir)) self.create_env(force_remove=True) cprint("%s installdeps: %s" % (self.name, ', '.join(self.deps))) if not self.install_deps(): cprint(" deps installa... |
rebuilding cython files if they are unchanged cprint("%s inst: %s" % (self.name, self.envdistdir)) if not self.install_dist(): cprint(" install failed.\n", 'err') return 1 cprint("%s runtests" % self.name) # return False if all commands were successfully run # otherwise returns True if at least one command exited badly... |
def parse_tokens(tokens): '''Read tokens strings into (is_flag, value) tuples: For this value of `tokens`: ['-f', 'pets.txt', '-v', 'cut', '-cz', '--lost', '--delete=sam', '--', 'lester', 'jack'] `flatten(tokens)` yields an iterable: [ (True, 'f'), (False, 'pets.txt'), (True, 'v'), (False, 'cut'), (True, 'c'), (True, '... |
token, sep, value = token.partition('=') for flag in split_flag_token(token): yield True, flag if sep: # we don't re-flatten the 'value' from '--token=value' yield False, value else: yield False, token |
def is_blankspace(self, char): """ Test if a character is a blankspace. Parameters ---------- char : str The character to test. Returns ------- ret : bool True if character is a blankspace, False otherwise. """ if len(char) > 1: raise TypeError("Expected a char.") if char in self.blankspaces: return True return False |
def is_separator(self, char): """ Test if a character is a separator. Parameters ---------- char : str The character to test. Returns ------- ret : bool True if character is a separator, False otherwise. """ if len(char) > 1: raise TypeError("Expected a char.") if char in self.separators: return True return False |
def solve_chol(A,B): """ Solve cholesky decomposition:: return A\(A'\B) """ # X = linalg.solve(A,linalg.solve(A.transpose(),B)) # much faster version X = linalg.cho_solve((A, True), B) return X |
def jitChol(A, maxTries=10, warning=True): """Do a Cholesky decomposition with jitter. Description: U, jitter = jitChol(A, maxTries, warning) attempts a Cholesky decomposition on the given matrix, if matrix isn't positive definite the function adds 'jitter' and tries again. Thereafter the amount of jitter is multiplied... |
is True) See also CHOL, PDINV, LOGDET Copyright (c) 2005, 2006 Neil D. Lawrence """ jitter = 0 i = 0 while(True): try: # Try --- need to check A is positive definite if jitter == 0: jitter = abs(SP.trace(A))/A.shape[0]*1e-6 LC = linalg.cholesky(A, lower=True) return LC.T, 0.0 else: if warning: # pdb.set_trace() # plt.f... |
def jitEigh(A,maxTries=10,warning=True): """ Do a Eigenvalue Decomposition with Jitter, works as jitChol """ warning = True jitter = 0 i = 0 while(True): if jitter == 0: jitter = abs(SP.trace(A))/A.shape[0]*1e-6 S,U = linalg.eigh(A) else: if warning: # pdb.set_trace() # plt.figure() # plt.imshow(A, interpolation="neare... |
def init_app(self, app): """Initialize Flask application.""" if self.entry_point_group: eps = sorted(pkg_resources.iter_entry_points( self.entry_point_group), key=attrgetter('name')) for ep in eps: app.logger.debug("Loading config for entry point {}".format( ep)) app.config.from_object(ep.load()) |
def modelComparisonDataFrame(modelcomparisonfile, splitparams): """Converts ``modelcomparison.md`` file to `pandas` DataFrame. Running ``phydms_comprehensive`` creates a file with the suffix ``modelcomparison.md``. This function converts that file into a DataFrame that is easy to handle for downstream analysis. Args: `... |
7 | x=1.3, z=0.1 |', ... ])) ... f.flush() ... df_split = modelComparisonDataFrame(f.name, splitparams=True) ... df_nosplit = modelComparisonDataFrame(f.name, splitparams=False) >>> df_nosplit.equals(pandas.DataFrame.from_records( ... [['ExpCM', 0, -1000, 7, 'x=1.0, y=2.0'], ... ['YNGKP', 10.2, -1005.1, 7, 'x=1.3, z=0.... |
df = (df.join(params_df) .drop('ParamValues', axis=1) ) return df |
def BenjaminiHochbergCorrection(pvals, fdr): """Benjamini-Hochberg procedure to control false discovery rate. Calling arguments: *pvals* : a list of tuples of *(label, p)* where *label* is some label assigned to each data point, and *p* is the corresponding *P-value*. *fdr* : the desired false discovery rate The return... |
p)) in enumerate(sorted_tests): rank = rank + 1 # rank beginning with 1 for smallest p-value (there is no rank 0) bh_threshold = fdr * float(rank) / num_tests if p <= bh_threshold: assert rank > max_rank max_rank = rank pcutoff = bh_threshold # pcutoff to have one significant site if there are none if pcutoff == None: ... |
def param_dict_to_list(dict,skeys=None): """convert from param dictionary to list""" #sort keys RV = SP.concatenate([dict[key].flatten() for key in skeys]) return RV pass |
def param_list_to_dict(list,param_struct,skeys): """convert from param dictionary to list param_struct: structure of parameter array """ RV = [] i0= 0 for key in skeys: val = param_struct[key] shape = SP.array(val) np = shape.prod() i1 = i0+np params = list[i0:i1].reshape(shape) RV.append((key,params)) i0 = i1 return d... |
def checkgrad(f, fprime, x, *args,**kw_args): """ Analytical gradient calculation using a 3-point method """ LG.debug("Checking gradient ...") import numpy as np # using machine precision to choose h eps = np.finfo(float).eps step = np.sqrt(eps)*(x.min()) # shake things up a bit by taking random steps for each x dimens... |
def opt_hyper(gpr,Ifilter=None,bounds=None,opts={},*args,**kw_args): """ optimize params Input: gpr: GP regression class params0: dictionary filled with starting hyperparameters opts: options for optimizer """ if 'gradcheck' in opts: gradcheck = opts['gradcheck'] else: gradcheck = False if 'max_iter_opt' in opts: max_i... |
bounds is not None: _b = [] for key in skeys: if key in list(bounds.keys()): _b.extend(bounds[key]) else: _b.extend([[-SP.inf,+SP.inf]]*params0[key].size) bounds = SP.array(_b) bounds = bounds[Ifilter_x] LG.info('Starting optimization ...') t = time.time() x = X0.copy()[Ifilter_x] RV = optimize(f,x,maxfun=int(max_iter)... |
def chival(self, bonds): """compute the chiral value around an atom given a list of bonds""" # XXX I'm not sure how this works? order = [bond.xatom(self) for bond in bonds] return self._chirality(order) |
def setchival(self, bondorder, rotation): """compute chiral ordering of surrounding atoms""" rotation = [None, "@", "@@"][(rotation % 2)] # check to see if the bonds are attached if not bondorder: # use the default xatoms if len(self.oatoms) < 3 and self.explicit_hcount != 1: raise PinkyError("Need to have an explicit ... |
def disambiguate(self, symclasses): """Use the connection to the atoms around a given vertex as a multiplication function to disambiguate a vertex""" offsets = self.offsets result = symclasses[:] for index in self.range: try: val = 1 for offset, bondtype in offsets[index]: val *= symclasses[offset] * bondtype except Ov... |
def rank(self): """convert a list of integers so that the lowest integer is 0, the next lowest is 1 ... note: modifies list in place""" # XXX FIX ME, should the lowest value be 1 or 0? symclasses = self.symclasses stableSort = map(None, symclasses, range(len(symclasses))) stableSort.sort() last = None x = -1 for order,... |
def breakRankTies(self, oldsym, newsym): """break Ties to form a new list with the same integer ordering from high to low Example old = [ 4, 2, 4, 7, 8] (Two ties, 4 and 4) new = [60, 2 61,90,99] res = [ 4, 0, 3, 1, 2] * * This tie is broken in this case """ stableSort = map(None, oldsym, newsym, range(len(oldsym))) st... |
def findLowest(self, symorders): """Find the position of the first lowest tie in a symorder or -1 if there are no ties""" _range = range(len(symorders)) stableSymorders = map(None, symorders, _range) # XXX FIX ME # Do I need to sort? stableSymorders.sort() lowest = None for index in _range: if stableSymorders[index][0]... |
def findInvariant(self, symclasses): """(symclasses) -> converge the disambiguity function until we have an invariant""" get = primes.primes.get disambiguate = self.disambiguate breakRankTies = self.breakRankTies while 1: newSyms = map(get, symclasses) newSyms = disambiguate(newSyms) breakRankTies(symclasses, newSyms) ... |
def findInvariantPartitioning(self): """Keep the initial ordering of the symmetry orders but make all values unique. For example, if there are two symmetry orders equal to 0, convert them to 0 and 1 and add 1 to the remaining orders [0, 1, 0, 1] should become [0, 2, 1, 3]""" symorders = self.symorders[:] _range = range... |
def _api_call(self, method, target, args=None): """Create a Request object and execute the call to the API Server. Parameters method (str) HTTP request (e.g. 'POST'). target (str) The target URL with leading slash (e.g. '/v1/products'). args (dict) Optional dictionary of arguments to attach to the request. Returns (Res... |
def get_ride_types(self, latitude, longitude, ride_type=None): """Get information about the Ride Types offered by Lyft at a given location. Parameters latitude (float) The latitude component of a location. longitude (float) The longitude component of a location. ride_type (str) Optional specific ride type information o... |
def get_pickup_time_estimates(self, latitude, longitude, ride_type=None): """Get pickup time estimates (ETA) for products at a given location. Parameters latitude (float) The latitude component of a location. longitude (float) The longitude component of a location. ride_type (str) Optional specific ride type pickup est... |
def get_cost_estimates( self, start_latitude, start_longitude, end_latitude=None, end_longitude=None, ride_type=None, ): """Get cost estimates (in cents) for rides at a given location. Parameters start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a star... |
('ride_type', ride_type), ]) return self._api_call('GET', 'v1/cost', args=args) |
def get_drivers(self, latitude, longitude): """Get information about the location of drivers available near a location. A list of 5 locations for a sample of drivers for each ride type will be provided. Parameters latitude (float) The latitude component of a location. longitude (float) The longitude component of a loca... |
def request_ride( self, ride_type=None, start_latitude=None, start_longitude=None, start_address=None, end_latitude=None, end_longitude=None, end_address=None, primetime_confirmation_token=None, ): """Request a ride on behalf of an Lyft user. Parameters ride_type (str) Name of the type of ride you're requesting. E.g., ... |
args = { 'ride_type': ride_type, 'origin': { 'lat': start_latitude, 'lng': start_longitude, 'address': start_address, }, 'destination': { 'lat': end_latitude, 'lng': end_longitude, 'address': end_address, }, 'primetime_confirmation_token': primetime_confirmation_token, } return self._api_call('POST', 'v1/rides', args=a... |
def cancel_ride(self, ride_id, cancel_confirmation_token=None): """Cancel an ongoing ride on behalf of a user. Params ride_id (str) The unique ID of the Ride Request. cancel_confirmation_token (str) Optional string containing the cancellation confirmation token. Returns (Response) A Response object with successful stat... |
def rate_tip_ride(self, ride_id, rating, tip_amount=None, tip_currency=None, feedback=None ): """Provide a rating, tip or feedback for the specified ride. Params ride_id (str) The unique ID of the Ride Request. rating (int) An integer between 1 and 5 tip_amount Optional integer amount greater than 0 in minor currency u... |
def get_user_ride_history(self, start_time, end_time, limit=None): """Get activity about the user's lifetime activity with Lyft. Parameters start_time (datetime) Restrict to rides starting after this point in time. The earliest supported date is 2015-01-01T00:00:00Z end_time (datetime) Optional Restrict to rides starti... |
def refresh_oauth_credential(self): """Refresh session's OAuth 2.0 credentials if they are stale.""" credential = self.session.oauth2credential if credential.is_stale(): refresh_session = refresh_access_token(credential) self.session = refresh_session |
def setCovariance(self,cov): """ set hyperparameters from given covariance """ self.setParams(sp.log(sp.diagonal(cov))) |
def setCovariance(self, cov): """ makes lowrank approximation of cov """ assert cov.shape[0]==self.dim, 'Dimension mismatch.' S, U = la.eigh(cov) U = U[:,::-1] S = S[::-1] _X = U[:, :self.rank] * sp.sqrt(S[:self.rank]) self.X = _X |
def mountain_car_trajectories(num_traj): '''Collect data using random hard-coded policies on MountainCar. num_traj : int, number of trajectories to collect Returns (trajectories, traces) ''' domain = MountainCar() slopes = np.random.normal(0, 0.01, size=num_traj) v0s = np.random.normal(0, 0.005, size=num_traj) trajecto... |
def before_all(context): """Setup before all tests. Initialize the logger framework. :param context: test context. """ lf = LoggerFactory(config_file='../features/resources/test_config.yaml') lf.initialize() ll = lf.get_instance('environment') ll.info('Logger initialized: {}'.format(lf.config)) ll.info('Initial test co... |
def shell_escape(text, _safe=re.compile(r"^[-._,+a-zA-Z0-9]+$")): """Escape given string according to shell rules.""" if not text or _safe.match(text): return text squote = type(text)("'") return squote + text.replace(squote, type(text)(r"'\''")) + squote |
def get_pattern_mat(oracle, pattern): """Output a matrix containing patterns in rows from a vmo. :param oracle: input vmo object :param pattern: pattern extracted from oracle :return: a numpy matrix that could be used to visualize the pattern extracted. """ pattern_mat = np.zeros((len(pattern), oracle.n_states-1)) for ... |
def fake_upload_from_url(url): """ Return a 'fake' upload data record, so that upload errors can be mitigated by using an original / alternative URL, especially when cross-loading from the web. """ return parts.Bunch( image=parts.Bunch( animated='false', bandwidth=0, caption=None, views=0, deletehash=None, hash=None, n... |
def cache_image_data(cache_dir, cache_key, uploader, *args, **kwargs): """ Call uploader and cache its results. """ use_cache = True if "use_cache" in kwargs: use_cache = kwargs["use_cache"] del kwargs["use_cache"] json_path = None if cache_dir: json_path = os.path.join(cache_dir, "cached-img-%s.json" % cache_key) if u... |
def copy_image_from_url(url, cache_dir=None, use_cache=True): """ Copy image from given URL and return upload metadata. """ return cache_image_data(cache_dir, hashlib.sha1(url).hexdigest(), ImgurUploader().upload, url, use_cache=use_cache) |
def _main(): """ Command line interface for testing. """ import pprint import tempfile try: image = sys.argv[1] except IndexError: print("Usage: python -m pyrobase.webservice.imgur <url>") else: try: pprint.pprint(copy_image_from_url(image, cache_dir=tempfile.gettempdir())) except UploadError as exc: print("Upload erro... |
def upload(self, image, name=None): """ Upload the given image, which can be a http[s] URL, a path to an existing file, binary image data, or an open file handle. """ assert self.client_id, "imgur client ID is not set! Export the IMGUR_CLIENT_ID environment variable..." assert self.client_secret, "imgur client secret i... |
image # XXX open(image, "rb") image_repr = "file:" + image else: # XXX Not supported anymore (maybe use a temp file?) image_type = "base64" image_data = image_data.encode(image_type) image_repr = "<binary data>" # Upload image # XXX "name", name or hashlib.md5(str(image)).hexdigest()), client = ImgurClient(self.client_... |
def _parse_fmt(fmt, color_key='colors', ls_key='linestyles', marker_key='marker'): '''Modified from matplotlib's _process_plot_format function.''' try: # Is fmt just a colorspec? color = mcolors.colorConverter.to_rgb(fmt) except ValueError: pass # No, not just a color. else: # Either a color or a numeric marker style i... |
ValueError('Illegal format string; two marker symbols') result[marker_key] = c elif c in mcolors.colorConverter.colors: if color_key in result: raise ValueError('Illegal format string; two color symbols') result[color_key] = c else: raise ValueError('Unrecognized character %c in format string' % c) return result |
def plot(self, coordinates, directed=False, weighted=False, fig='current', ax=None, edge_style=None, vertex_style=None, title=None, cmap=None): '''Plot the graph using matplotlib in 2 or 3 dimensions. coordinates : (n,2) or (n,3) array of vertex coordinates directed : if True, edges have arrows indicating direction. we... |
np.atleast_2d(coordinates) assert 0 < X.shape[1] <= 3, 'too many dimensions to plot' if X.shape[1] == 1: X = np.column_stack((np.arange(X.shape[0]), X)) is_3d = (X.shape[1] == 3) if ax is None: ax = _get_axis(is_3d, fig) edge_kwargs = dict(colors='k', linestyles='-', linewidths=1, zorder=1) vertex_kwargs = dict(marker=... |
def to_html(self, html_file, directed=False, weighted=False, vertex_ids=None, vertex_colors=None, vertex_labels=None, width=900, height=600, title=None, svg_border='1px solid black'): '''Write the graph as a d3 force-directed layout SVG to an HTML file. html_file : str|file-like, writeable destination for the output HT... |
ValueError('len(vertex_ids) != num vertices.') if vertex_labels is not None: vlabels, vcolors = np.unique(vertex_labels, return_inverse=True) if len(vcolors) != len(vertex_ids): raise ValueError('len(vertex_labels) != num vertices.') elif vertex_colors is not None: vcolors = np.array(vertex_colors, dtype=float, copy=Fa... |
not hasattr(html_file, 'write'): fh = open(html_file, 'w') else: fh = html_file print(u'<!DOCTYPE html><meta charset="utf-8"><style>', file=fh) print(u'svg { border: %s; }' % svg_border, file=fh) if weighted: print(u'.links line { stroke-width: 2px; }', file=fh) else: print(u'.links line { stroke: #000; stroke-width: 2... |
def normalize_mapping_line(mapping_line, previous_source_column=0): """ Often times the position will remain stable, such that the naive process will end up with many redundant values; this function will iterate through the line and remove all extra values. """ if not mapping_line: return [], previous_source_column # N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.