code stringlengths 1 18.2k |
|---|
def fit(self, X, y): """ Fit CAIM Parameters ---------- X : array-like, pandas dataframe, shape [n_samples, n_feature] Input array can contain missing values y: array-like, pandas dataframe, shape [n_samples] Target variable. Must be categorical. Returns ------- self """ self.split_scheme = dict() if isinstance(X, pd.D... |
1 while (k <= min_splits) or ((global_caim < best_caim) and (allsplits)): split_points = np.random.permutation(allsplits).tolist() best_scheme = None best_point = None best_caim = 0 k = k + 1 while split_points: scheme = mainscheme[:] sp = split_points.pop() scheme.append(sp) scheme.sort() c = self.get_caim(scheme, xj,... |
def transform(self, X): """ Discretize X using a split scheme obtained with CAIM. Parameters ---------- X : array-like or pandas dataframe, shape [n_samples, n_features] Input array can contain missing values Returns ------- X_di : sparse matrix if sparse=True else a 2-d array, dtype=int Transformed input. """ if isins... |
def prettyhtml(value, autoescape=None): 'Clean (and optionally escape) passed html of unsafe tags and attributes.' value = html_cleaner(value) return escape(value) if autoescape\ and not isinstance(value, SafeData) else mark_safe(value) |
def hash(value, chars=None): 'Get N chars (default: all) of secure hash hexdigest of value.' value = hash_func(value).hexdigest() if chars: value = value[:chars] return mark_safe(value) |
def read_noise_curve(noise_curve, noise_type_in='ASD', noise_type_out='ASD', add_wd_noise=False, wd_noise='HB_wd_noise', wd_noise_type_in='ASD'): """Simple auxillary function that can read noise curves in. This function can read in noise curves from a provided file or those that are preinstalled with this installation.... |
or PLHB (Proposed LISA Higher Break). See the arXiv paper above for the meaning behind each choice and a plot with each curve. noise_type_in/noise_type_out (str, optional): Type of noise input/output. Choices are `ASD`, `PSD`, or `char_strain`. Default for both is `ASD`. add_wd_noise (bool, optional): If True, include ... |
'char_strain'] if noise_type_in not in possible_noise_types: raise ValueError('noise_type_in must be either ASD, PSD, or char_strain.') if noise_type_out not in possible_noise_types: raise ValueError('noise_type_out must be either ASD, PSD, or char_strain.') # find the noise curve file if noise_curve[-4:] == '.txt': no... |
amp_n_wd = globals()[noise_type_in.lower() + '_to_' + noise_type_out.lower()](f_n_wd, amp_n_wd) f_n, amp_n = combine_with_wd_noise(f_n, amp_n, f_n_wd, amp_n_wd) return f_n, amp_n |
def combine_with_wd_noise(f_n, amp_n, f_n_wd, amp_n_wd): """Combine noise with wd noise. Combines noise and white dwarf background noise based on greater amplitude value at each noise curve step. Args: f_n (float array): Frequencies of noise curve. amp_n (float array): Amplitude values of noise curve. f_n_wd (float arr... |
def show_available_noise_curves(return_curves=True, print_curves=False): """List available sensitivity curves This function lists the available sensitivity curve strings in noise_curves folder. Args: return_curves (bool, optional): If True, return a list of curve options. print_curves (bool, optional): If True, print e... |
def expand_curlys(s): """Takes string and returns list of options: Example ------- >>> expand_curlys("py{26, 27}") ["py26", "py27"] """ from functools import reduce curleys = list(re.finditer(r"{[^{}]*}", s)) return reduce(_replace_curly, reversed(curleys), [s]) |
def _split_out_of_braces(s): """Generator to split comma seperated string, but not split commas inside curly braces. >>> list(_split_out_of_braces("py{26, 27}-django{15, 16}, py32")) >>>['py{26, 27}-django{15, 16}, py32'] """ prev = 0 for m in re.finditer(r"{[^{}]*}|\s*,\s*", s): if not m.group().startswith("{"): part ... |
def expand_factor_conditions(s, env): """If env matches the expanded factor then return value else return ''. Example ------- >>> s = 'py{33,34}: docformatter' >>> expand_factor_conditions(s, Env(name="py34", ...)) "docformatter" >>> expand_factor_conditions(s, Env(name="py26", ...)) "" """ try: factor, value = re.spli... |
def matches_factor_conditions(s, env): """"Returns True if py{33, 34} expanded is contained in env.name.""" env_labels = set(env.name.split('-')) labels = set(bash_expand(s)) return bool(labels & env_labels) |
def split_on(s, sep=" "): """Split s by sep, unless it's inside a quote.""" pattern = '''((?:[^%s"']|"[^"]*"|'[^']*')+)''' % sep return [_strip_speechmarks(t) for t in re.split(pattern, s)[1::2]] |
def replace_braces(s, env): """Makes tox substitutions to s, with respect to environment env. Example ------- >>> replace_braces("echo {posargs:{env:USER:} passed no posargs}") "echo andy passed no posargs" Note: first "{env:USER:}" is replaced with os.environ.get("USER", ""), the "{posargs:andy}" is replaced with "and... |
def _replace_match(m, env): """Given a match object, having matched something inside curly braces, replace the contents if matches one of the supported tox-substitutions.""" # ditch the curly braces s = m.group()[1:-1].strip() try: # get the env attributes e.g. envpython or toxinidir. # Note: if you ask for a env metho... |
def _replace_envvar(s, _): """env:KEY or env:KEY:DEFAULT""" e = s.split(":") if len(e) > 3 or len(e) == 1 or e[0] != "env": raise ValueError() elif len(e) == 2: # Note: this can/should raise a KeyError (according to spec). return os.environ[e[1]] else: # len(e) == 3 return os.environ.get(e[1], e[2]) |
def _replace_config(s, env): """[sectionname]optionname""" m = re.match(r"\[(.*?)\](.*)", s) if m: section, option = m.groups() expanded = env.config.get(section, option) return '\n'.join([expand_factor_conditions(e, env) for e in expanded.split("\n")]) else: raise ValueError() |
def _replace_posargs(s, env): "posargs:DEFAULT" e = re.split(r'\s*\:\s*', s) if e and e[0] == "posargs": from ctox.main import positional_args return (" ".join(positional_args(env.options)) or (e[1] if len(e) > 1 else "")) else: raise ValueError() |
def csnr(freqs, hc, hn, fmrg, fpeak, prefactor=1.0): """Calculate the SNR of a frequency domain waveform. SNRCalculation is a function that takes waveforms (frequencies and hcs) and a noise curve, and returns SNRs for all binary phases and the whole waveform. Arguments: freqs (1D or 2D array of floats): Frequencies cor... |
array of floats): Peak frequency of each binary separating merger from ringdown phase. (0.014/M) Shape is (num binaries,) if more than one binary. hn: (1D or 2D array of floats): Characteristic strain of the noise. Shape is (num binaries, num_points) if 2D. Shape is (num_points,) if 1D for one binary. prefactor (float,... |
arrays freqs_in = freqs.flatten() hc_in = hc.flatten() hn_in = hn.flatten() num_binaries, length_of_signal = hc.shape # prepare outout arrays snr_cast = ctypes.c_double*num_binaries snr_all = snr_cast() snr_ins = snr_cast() snr_mrg = snr_cast() snr_rd = snr_cast() # find SNR values c_obj.SNR_function(ctypes.byref(snr_a... |
def solve_t(self, Mt): """ Mt is dim_r x dim_c x d tensor """ if len(Mt.shape)==2: _Mt = Mt[:, :, sp.newaxis] else: _Mt = Mt LMt = vei_CoR_veX(_Mt, R=self.Lr(), C=self.Lc()) DMt = self.D()[:, :, sp.newaxis] * LMt WrDMtWc = vei_CoR_veX(DMt, R=self.Wr().T, C=self.Wc().T) ve_WrDMtWc = sp.reshape(WrDMtWc, (WrDMtWc.shape[0]... |
def _O_dot(self, Mt): """ Mt is dim_r x dim_c x d tensor """ DMt = self.D()[:, :, sp.newaxis] * Mt WrDMtWc = vei_CoR_veX(DMt, R=self.Wr().T, C=self.Wc().T) ve_WrDMtWc = sp.reshape(WrDMtWc, (WrDMtWc.shape[0] * WrDMtWc.shape[1], Mt.shape[2]), order='F') Hi_ve_WrDMtWc = la.cho_solve((self.H_chol(), True), ve_WrDMtWc) vei_... |
def clearFixedEffect(self): """ erase all fixed effects """ self._A = [] self._F = [] self._B = [] self._A_identity = [] self._REML_term = [] self._n_terms = 0 self._n_fixed_effs = 0 self._n_fixed_effs_REML = 0 self.indicator = {'term':np.array([]), 'row':np.array([]), 'col':np.array([])} self.clear_cache('Fstar','Asta... |
def addFixedEffect(self,F=None,A=None, REML=True, index=None): """ set sample and trait designs F: NxK sample design A: LxP sample design REML: REML for this term? index: index of which fixed effect to replace. If None, just append. """ if F is None: F = np.ones((self.N,1)) if A is None: A = np.eye(self.P) A_identity =... |
self.clear_cache('Fstar','Astar','Xstar','Xhat', 'Areml','Areml_eigh','Areml_chol','Areml_inv','beta_hat','B_hat', 'LRLdiag_Xhat_tens','Areml_grad', 'beta_grad','Xstar_beta_grad','Zstar','DLZ') |
def removeFixedEffect(self, index=None): """ set sample and trait designs F: NxK sample design A: LxP sample design REML: REML for this term? index: index of which fixed effect to replace. If None, remove last term. """ if self._n_terms==0: pass if index is None or index==(self._n_terms-1): self._n_terms-=1 F = self._F... |
def Y(self,value): """ set phenotype """ self._N,self._P = value.shape self._Y = value self.clear_cache('Ystar1','Ystar','Yhat','LRLdiag_Yhat', 'beta_grad','Xstar_beta_grad','Zstar','DLZ') |
def Lr(self,value): """ set row rotation """ assert value.shape[0]==self._N, 'dimension mismatch' assert value.shape[1]==self._N, 'dimension mismatch' self._Lr = value self.clear_cache('Fstar','Ystar1','Ystar','Yhat','Xstar','Xhat', 'Areml','Areml_eigh','Areml_chol','Areml_inv','beta_hat','B_hat', 'LRLdiag_Xhat_tens','... |
def Lc(self,value): """ set col rotation """ assert value.shape[0]==self._P, 'Lc dimension mismatch' assert value.shape[1]==self._P, 'Lc dimension mismatch' self._Lc = value self.clear_cache('Astar','Ystar','Yhat','Xstar','Xhat', 'Areml','Areml_eigh','Areml_chol','Areml_inv','beta_hat','B_hat', 'LRLdiag_Xhat_tens','LRL... |
def d(self,value): """ set anisotropic scaling """ assert value.shape[0]==self._P*self._N, 'd dimension mismatch' self._d = value self.clear_cache('Yhat','Xhat','Areml','Areml_eigh','Areml_chol','Areml_inv','beta_hat','B_hat', 'LRLdiag_Xhat_tens','LRLdiag_Yhat','Areml_grad', 'beta_grad','Xstar_beta_grad','Zstar','DLZ') |
def Zstar(self): """ predict the value of the fixed effect """ RV = self.Ystar().copy() for term_i in range(self.n_terms): if self.identity_trick and self.A_identity[term_i]: RV-=np.dot(self.Fstar()[term_i],self.B_hat()[term_i]) else: RV-=np.dot(self.Fstar()[term_i],np.dot(self.B_hat()[term_i],self.Astar()[term_i])) se... |
def Areml_eigh(self): """compute the eigenvalue decomposition of Astar""" s,U = LA.eigh(self.Areml(),lower=True) i_pos = (s>1e-10) s = s[i_pos] U = U[:,i_pos] return s,U |
def predict(self): """ predict the value of the fixed effect """ RV = np.zeros((self.N,self.P)) for term_i in range(self.n_terms): RV+=np.dot(self.Fstar()[term_i],np.dot(self.B()[term_i],self.Astar()[term_i])) return RV |
def getGradient(self,j): """ get rotated gradient for fixed effect i """ i = int(self.indicator['term'][j]) r = int(self.indicator['row'][j]) c = int(self.indicator['col'][j]) rv = -np.kron(self.Fstar()[i][:,[r]],self.Astar()[i][[c],:]) return rv |
def XstarT_dot(self,M): """ get dot product of Xhat and M """ if 0: #TODO: implement this properly pass else: RV = np.dot(self.Xstar().T,M) return RV |
def getResiduals(self): """ regress out fixed effects and results residuals """ X = np.zeros((self.N*self.P,self.n_fixed_effs)) ip = 0 for i in range(self.n_terms): Ki = self.A[i].shape[0]*self.F[i].shape[1] X[:,ip:ip+Ki] = np.kron(self.A[i].T,self.F[i]) ip += Ki y = np.reshape(self.Y,(self.Y.size,1),order='F') RV = re... |
def getParams(self): """ get params """ rv = np.array([]) if self.n_terms>0: rv = np.concatenate([np.reshape(self.B[term_i],self.B[term_i].size, order='F') for term_i in range(self.n_terms)]) return rv |
def setParams(self,params): """ set params """ start = 0 for i in range(self.n_terms): n_effects = self.B[i].size self.B[i] = np.reshape(params[start:start+n_effects],self.B[i].shape, order='F') start += n_effects |
def _set_toChange(x): """ set variables in list x toChange """ for key in list(x.keys()): self.toChange[key] = True |
def _update_indicator(self,K,L): """ update the indicator """ _update = {'term': self.n_terms*np.ones((K,L)).T.ravel(), 'row': np.kron(np.arange(K)[:,np.newaxis],np.ones((1,L))).T.ravel(), 'col': np.kron(np.ones((K,1)),np.arange(L)[np.newaxis,:]).T.ravel()} for key in list(_update.keys()): self.indicator[key] = np.conc... |
def _rebuild_indicator(self): """ update the indicator """ indicator = {'term':np.array([]), 'row':np.array([]), 'col':np.array([])} for term in range(self.n_terms): L = self.A[term].shape[0] K = self.F[term].shape[1] _update = {'term': (term+1)*np.ones((K,L)).T.ravel(), 'row': np.kron(np.arange(K)[:,np.newaxis],np.one... |
def vei_CoR_veX(X, C=None, R=None): """ Args: X: NxPxS tensor C: CxC row covariance (if None: C set to I_PP) R: NxN row covariance (if None: R set to I_NN) Returns: NxPxS tensor obtained as ve^{-1}((C \kron R) ve(X)) where ve(X) reshapes X as a NPxS matrix. """ _X = X.transpose((0,2,1)) if R is not None: RV = sp.tensor... |
def initialize_shade(self, shade_name, shade_color, alpha): """This method will create semi-transparent surfaces with a specified color. The surface can be toggled on and off. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: Shade_name - String of the name that you want to associate with... |
def toggle_shade(self, shade): """This method will overlay a semi-transparent shade on top of the tile's image. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: shade - This will designate which shade you wish to turn on or off. Blue and red shades are available by default. (doc string u... |
def adjacent_tiles(self, tile, pattern): """This will return a list of the tiles adjacent to a given tile. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: tile - This is the tile object for which the method will find adjacent tiles. pattern - This will designate the pattern type that yo... |
1][column]] if row + 1 != len(self): adj_tiles += [self[row + 1][column]] if column - 1 >= 0: adj_tiles += [self[row][column - 1]] if column + 1 != len(self[row]): adj_tiles += [self[row][column + 1]] def diagonal(self, row, column): nonlocal adj_tiles if column - 1 >= 0: if row - 1 >= 0: adj_tiles += [self[row - 1][co... |
tiles touching the four corners of the input tile elif pattern == 'x': diagonal(self, row, column) # Return all of the tiles surrounding the input tile elif pattern == 'b': plus_sign(self, row, column) diagonal(self, row, column) return adj_tiles |
def set_offset(self, offset, mid=None): """This method will allow the menu to be placed anywhere in the open window instead of just the upper left corner. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: offset - This is the x,y tuple of the position that you want to move the screen to. ... |
j.rect[1] += offset[1] |
def bread(stream): """ Decode a file or stream to an object. """ if hasattr(stream, "read"): return bdecode(stream.read()) else: handle = open(stream, "rb") try: return bdecode(handle.read()) finally: handle.close() |
def bwrite(stream, obj): """ Encode a given object to a file or stream. """ handle = None if not hasattr(stream, "write"): stream = handle = open(stream, "wb") try: stream.write(bencode(obj)) finally: if handle: handle.close() |
def decode(self, check_trailer=False): # pylint: disable=I0011,R0912 """ Decode data in C{self.data} and return deserialized object. @param check_trailer: Raise error if trailing junk is found in data? @raise BencodeError: Invalid data. """ try: kind = self.data[self.offset] except IndexError: raise BencodeError("Unexp... |
( self.offset, self.data[self.offset:self.offset+32] )) self.offset = end+1 elif kind == 'l': # List self.offset += 1 obj = [] while self.data[self.offset:self.offset+1] != 'e': obj.append(self.decode()) self.offset += 1 elif kind == 'd': # Dict self.offset += 1 obj = {} while self.data[self.offset:self.offset+1] != 'e... |
def encode(self, obj): """ Add the given object to the result. """ if isinstance(obj, int_like_types): self.result.append("i%de" % obj) elif isinstance(obj, string_types): self.result.extend([str(len(obj)), ':', str(obj)]) elif hasattr(obj, "__bencode__"): self.encode(obj.__bencode__()) elif hasattr(obj, "items"): # Di... |
def calc_delta_c(c200): """Calculate characteristic overdensity from concentration. Parameters ---------- c200 : ndarray or float Cluster concentration parameter. Returns ---------- ndarray or float Cluster characteristic overdensity, of same type as c200. """ top = (200. / 3.) * c200**3. bottom = np.log(1. + c200) - (... |
def show(self, notebook=notebook_display): """Display cluster properties and scaling relation parameters.""" print("\nCluster Ensemble:") if notebook is True: display(self._df) elif notebook is False: print(self._df) self.massrich_parameters() |
def calc_nfw(self, rbins, offsets=None, numTh=200, numRoff=200, numRinner=20, factorRouter=3): """Calculates Sigma and DeltaSigma profiles. Generates the surface mass density (sigma_nfw attribute of parent object) and differential surface mass density (deltasigma_nfw attribute of parent object) profiles of each cluster... |
: int, optional Parameter to pass to SurfaceMassDensity(). Number of bins to use for integration over R_off, for calculating offset profiles (no effect for offsets=None). Default 200. numRinner : int, optional Parameter to pass to SurfaceMassDensity(). Number of bins at r < min(rbins) to use for integration over Sigma(... |
units.Mpc, num=self.number) self.rbins = utils.check_units_and_type(rbins, units.Mpc) rhoc = self._rho_crit.to(units.Msun / units.pc**2 / units.Mpc) smd = SurfaceMassDensity(self.rs, self.delta_c, rhoc, offsets=self._sigoffset, rbins=self.rbins, numTh=numTh, numRoff=numRoff, numRinner=numRinner, factorRouter=factorRout... |
def Y(self,value): """ set phenotype """ assert value.shape[1]==1, 'Dimension mismatch' self._N = value.shape[0] self._Y = value |
def F(self,value): """ set phenotype """ assert value.shape[0]==self._N, 'Dimension mismatch' self._K = value.shape[1] self._F = value self.clear_cache('predict','Yres') |
def B(self,value): """ set phenotype """ assert value.shape[0]==self._K, 'Dimension mismatch' assert value.shape[1]==1, 'Dimension mismatch' self._B = value self.clear_cache('predict','Yres') |
def draw(molecule, TraversalType=SmilesTraversal): """(molecule)->canonical representation of a molecule Well, it's only canonical if the atom symorders are canonical, otherwise it's arbitrary. atoms must have a symorder attribute bonds must have a equiv_class attribute""" result = [] atoms = allAtoms = molecule.atoms ... |
def random_graph(out_degree): '''Random graph generator. Does not generate self-edges. out_degree : array-like of ints, controlling the out degree of each vertex. ''' n = len(out_degree) out_degree = np.asarray(out_degree, dtype=int) if (out_degree >= n).any(): raise ValueError('Cannot have degree >= num_vertices') row... |
def delaunay_graph(X, weighted=False): '''Delaunay triangulation graph. ''' e1, e2 = _delaunay_edges(X) pairs = np.column_stack((e1, e2)) w = paired_distances(X[e1], X[e2]) if weighted else None return Graph.from_edge_pairs(pairs, num_vertices=X.shape[0], symmetric=True, weights=w) |
def urquhart_graph(X, weighted=False): '''Urquhart graph: made from the 2 shortest edges of each Delaunay triangle. ''' e1, e2 = _delaunay_edges(X) w = paired_distances(X[e1], X[e2]) mask = np.ones_like(w, dtype=bool) bad_inds = w.reshape((-1, 3)).argmax(axis=1) + np.arange(0, len(e1), 3) mask[bad_inds] = False weights... |
def solve(self,b,overwrite_b=False,check_finite=True): """ solve A \ b """ if self._s is not None: res = self._U.T.dot(b) res /= self._s[:,np.newaxis] res = self._U.dot(res) elif self._chol is not None: res = la.cho_solve((self._chol,self._lower),b=b,overwrite_b=overwrite_b,check_finite=check_finite) else: res = np.zer... |
def solve(self,b,overwrite_b=False,check_finite=True, p=None): """ solve A \ b """ if p is None: assert b.shape[:2]==(len(self.solver),self.dof_any) solution = np.empty(b.shape) #This is trivially parallelizable: for p in range(self.P): solution[p] = self.solver[p].solve(b=b[p]) return solution else: return self.solver... |
def solve(self, b_any, b, check_finite=True, p=None): """ solve A \ b """ #assert b.shape[:2]==(len(self.solver),self.dof_any) if self.schur_solver is None and self.A_any_solver is None: assert ( (b is None) or (b.shape[0]==0) ) and ( (b_any is None) or (b_any.shape[0]==0) ), "shape missmatch" return b, b_any elif self... |
def preparse(template_text, lookup=None): """ Do any special processing of a template, including recognizing the templating language and resolving file: references, then return an appropriate wrapper object. Currently Tempita and Python string interpolation are supported. `lookup` is an optional callable that resolves ... |
template = InterpolationTemplate(template_text) template.__file__ = template_path template.__text__ = template_text return template |
def hdf5_read_out(self): """Read out an hdf5 file. Takes the output of :class:`gwsnrcalc.genconutils.genprocess.GenProcess` and reads it out to an HDF5 file. """ with h5py.File(self.WORKING_DIRECTORY + '/' + self.output_file_name, 'w') as f: header = f.create_group('header') header.attrs['Title'] = 'Generated SNR Out' ... |
data = f.create_group('data') # read out x,y values in compressed data set dset = data.create_dataset(self.x_col_name, data=self.xvals, dtype='float64', chunks=True, compression='gzip', compression_opts=9) dset = data.create_dataset(self.y_col_name, data=self.yvals, dtype='float64', chunks=True, compression='gzip', com... |
def txt_read_out(self): """Read out txt file. Takes the output of :class:`gwsnrcalc.genconutils.genprocess.GenProcess` and reads it out to a txt file. """ header = '#Generated SNR Out\n' header += '#Generator by: Michael Katz\n' header += '#Date/Time: {}\n'.format(datetime.datetime.now()) for which in ['x', 'y']: heade... |
header += '#Added note: None\n' header += '#--------------------\n' header += self.x_col_name + '\t' header += self.y_col_name + '\t' for key in self.output_dict.keys(): header += key + '\t' # read out x,y and the data x_and_y = np.asarray([self.xvals, self.yvals]) snr_out = np.asarray([self.output_dict[key] for key in... |
def trigger_function_installed(connection: connection): """Test whether or not the psycopg2-pgevents trigger function is installed. Parameters ---------- connection: psycopg2.extensions.connection Active connection to a PostGreSQL database. Returns ------- bool True if the trigger function is installed, otherwise False... |
def trigger_installed(connection: connection, table: str, schema: str='public'): """Test whether or not a psycopg2-pgevents trigger is installed for a table. Parameters ---------- connection: psycopg2.extensions.connection Active connection to a PostGreSQL database. table: str Table whose trigger-existence will be chec... |
def install_trigger_function(connection: connection, overwrite: bool=False) -> None: """Install the psycopg2-pgevents trigger function against the database. Parameters ---------- connection: psycopg2.extensions.connection Active connection to a PostGreSQL database. overwrite: bool Whether or not to overwrite existing i... |
def uninstall_trigger_function(connection: connection, force: bool=False) -> None: """Uninstall the psycopg2-pgevents trigger function from the database. Parameters ---------- connection: psycopg2.extensions.connection Active connection to a PostGreSQL database. force: bool If True, force the un-registration even if de... |
def install_trigger(connection: connection, table: str, schema: str='public', overwrite: bool=False) -> None: """Install a psycopg2-pgevents trigger against a table. Parameters ---------- connection: psycopg2.extensions.connection Active connection to a PostGreSQL database. table: str Table for which the trigger should... |
def uninstall_trigger(connection: connection, table: str, schema: str='public') -> None: """Uninstall a psycopg2-pgevents trigger from a table. Parameters ---------- connection: psycopg2.extensions.connection Active connection to a PostGreSQL database. table: str Table for which the trigger should be uninstalled. schem... |
def absolutify(url): """Takes a URL and prepends the SITE_URL""" site_url = getattr(settings, 'SITE_URL', False) # If we don't define it explicitly if not site_url: protocol = settings.PROTOCOL hostname = settings.DOMAIN port = settings.PORT if (protocol, port) in (('https://', 443), ('http://', 80)): site_url = ''.joi... |
def create_config_loader(config=None, env_prefix='APP'): """Create a default configuration loader. A configuration loader takes a Flask application and keyword arguments and updates the Flask application's configuration as it sees fit. This default configuration loader will load configuration in the following order: 1.... |
will be issued. :param config: Either an import string to a module with configuration or alternatively the module itself. :param env_prefix: Environment variable prefix to import configuration from. :return: A callable with the method signature ``config_loader(app, **kwargs)``. .. versionadded:: 1.0.0 """ def _config_l... |
def create_conf_loader(*args, **kwargs): # pragma: no cover """Create a default configuration loader. .. deprecated:: 1.0.0b1 Use :func:`create_config_loader` instead. This function will be removed in version 1.0.1. """ import warnings warnings.warn( '"create_conf_loader" has been renamed to "create_config_loader".', D... |
def _build_headers(self, method, auth_session): """Create headers for the request. Parameters method (str) HTTP method (e.g. 'POST'). auth_session (Session) The Session object containing OAuth 2.0 credentials. Returns headers (dict) Dictionary of access headers to attach to request. Raises LyftIllegalState (ApiError) R... |
def _authorization_headers_valid(self, token_type, token): """Verify authorization headers for a request. Parameters token_type (str) Type of token to access resources. token (str) Server Token or OAuth 2.0 Access Token. Returns (bool) True iff token_type and token are valid. """ if token_type not in http.VALID_TOKEN_T... |
def check_units_and_type(input, expected_units, num=None, is_scalar=False): """Check whether variable has expected units and type. If input does not have units and expected units is not None, then the output will be assigned those units. If input has units that conflict with expected units a ValueError will be raised. ... |
array or scalar with expected units, unless a conflict of units or array length occurs, which raise errors. """ if hasattr(input, 'unit'): # check units if expected_units is None: raise ValueError('Expecting dimensionless input') elif input.unit != expected_units: raise ValueError('Expecting input units of ' + str(expe... |
def check_array_or_list(input): """Return 1D ndarray, if input can be converted and elements are non-negative.""" if type(input) != np.ndarray: if type(input) == list: output = np.array(input) else: raise TypeError('Expecting input type as ndarray or list.') else: output = input if output.ndim != 1: raise ValueError('I... |
def main(): """ This example shows how to parse a music mxl file (music21 and musescore/finale required) and create a simple oracle representation. The output is a reshuffled midi stream shown in either musescore or finale based on your installation of music21. OPTIONAL ARGS: seq_len: an integer for the length of the o... |
= music21.converter.parse(filename) c = s.getElementById('Violoncello') m = c.flat.notes note_obj_seq = [x for x in m if type(x) is music21.note.Note] bo = vmo.build_oracle(note_obj_seq,'f') bo.name = 'bach_cello_example' if len(sys.argv) == 1: b, kend, ktrace = gen.generate(bo, len(note_obj_seq), 0.0, 0, LRS=2, weight... |
def error_handler(response, **kwargs): """Error Handler to surface 4XX and 5XX errors. Attached as a callback hook on the Request object. Parameters response (requests.Response) The HTTP response from an API request. **kwargs Arbitrary keyword arguments. Raises ClientError (ApiError) Raised if response contains a 4XX s... |
def object_attributes( thing, all=False ) : ''' Return a sorted list of names defined by thing that are not also names in a standard object, except include __doc__. ''' standard_names = set( dir( object() ) ) things_names = set( dir( thing ) ) if not all : things_names -= standard_names things_names |= set( ['__doc__']... |
def print_object_attributes( thing, heading=None, file=None ): ''' Print the attribute names in thing vertically ''' if heading : print( '==', heading, '==', file=file ) print( '\n'.join( object_attributes( thing ) ), file=file ) |
def print_attr_values( thing, all=False, heading=None, file=None ): ''' Print the attributes of thing which have non-empty values, as a vertical list of "name : value". When all=True, print all attributes even those with empty values. ''' if heading : if isinstance( heading, int ) : # request for default heading headin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.