code stringlengths 1 18.2k |
|---|
def toplevel_packages(): """ Get package list, without sub-packages. """ packages = set(easy.options.setup.packages) for pkg in list(packages): packages -= set(p for p in packages if str(p).startswith(pkg + '.')) return list(sorted(packages)) |
def set_position(self, position, midpoint=False, surface=None): """This method allows the button to be moved manually and keep the click on functionality. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: position - This is the x, y position of the top left corner of the button. (defining... |
# such that the position passed in is in the middle of the button if midpoint: self.pos = (position[0] - imagemidp[0], position[1] - imagemidp[1]) else: self.pos = position # set the rectangle to be used for collision detection self.rect = pygame.Rect(self.pos, self.image.get_size()) # Set up the information that is ne... |
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. ... |
mid == 'x': offset = (offset[0] - imagemidp[0], offset[1]) if mid == 'y': offset = (offset[0], offset[1] - imagemidp[1]) if mid == 'c': offset = (offset[0] - imagemidp[0], offset[1] - imagemidp[1]) self.pos = offset for i in self.buttonlist: i.rect[0] += offset[0] i.rect[1] += offset[1] try: for i in self.widgetlist: i... |
def widget_status(self): """This method will return the status of all of the widgets in the widget list""" widget_status_list = [] for i in self.widgetlist: widget_status_list += [[i.name, i.status]] return widget_status_list |
def update(self, screen, clock): """Event handling loop for the menu""" # If a music file was passed, start playing it on repeat if self.music is not None: pygame.mixer.music.play(-1) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Check if any of the... |
def Screens(self, text, prog, screen, clock): """Prog = 0 for first page, 1 for middle pages, 2 for last page""" # Initialize the screen class BaseScreen.__init__(self, self.size, self.background) # Determine the mid position of the given screen size and the # y button height xmid = self.size[0]//2 # Create the header ... |
def create_commerce(): """ Creates commerce from environment variables ``TBK_COMMERCE_ID``, ``TBK_COMMERCE_KEY`` or for testing purposes ``TBK_COMMERCE_TESTING``. """ commerce_id = os.getenv('TBK_COMMERCE_ID') commerce_key = os.getenv('TBK_COMMERCE_KEY') commerce_testing = os.getenv('TBK_COMMERCE_TESTING') == 'True' if... |
def get_config_tbk(self, confirmation_url): ''' Returns a string with the ``TBK_CONFIG.dat``. :param confirmation_url: URL where callback is made. ''' config = ( "IDCOMERCIO = {commerce_id}\n" "MEDCOM = 1\n" "TBK_KEY_ID = 101\n" "PARAMVERIFCOM = 1\n" "URLCGICOM = {confirmation_path}\n" "SERVERCOM = {confirmation_host}\... |
def indent(indent_str=None): """ An example indentation ruleset. """ def indentation_rule(): inst = Indentator(indent_str) return {'layout_handlers': { Indent: inst.layout_handler_indent, Dedent: inst.layout_handler_dedent, Newline: inst.layout_handler_newline, OptionalNewline: inst.layout_handler_newline_optional, Ope... |
def _is_lang_change(self, request): """Return True if the lang param is present and URL isn't exempt.""" if 'lang' not in request.GET: return False return not any(request.path.endswith(url) for url in self.exempt_urls) |
def add(self, *matches, **kw): # kw=default=None, boolean=False '''Add an argument; this is optional, and mostly useful for setting up aliases or setting boolean=True Apparently `def add(self, *matches, default=None, boolean=False):` is invalid syntax in Python. Not only is this absolutely ridiculous, but the alternati... |
kw after this line! It's a hack; it should never have been there in the first place. positional = None names = [] for match in matches: if match.startswith('--'): names.append(match[2:]) elif match.startswith('-'): names.append(match[1:]) elif positional: # positional has already been filled names.append(match) else: #... |
def parse(self, parser): """Main method to render data into the template.""" lineno = next(parser.stream).lineno if parser.stream.skip_if('name:short'): parser.stream.skip(1) short = parser.parse_expression() else: short = nodes.Const(False) result = self.call_method('_commit_hash', [short], [], lineno=lineno) return n... |
def flatten(nested, containers=(list, tuple)): """ Flatten a nested list by yielding its scalar items. """ for item in nested: if hasattr(item, "next") or isinstance(item, containers): for subitem in flatten(item): yield subitem else: yield item |
def get_template_context_processors(exclude=(), append=(), current={'processors': TEMPLATE_CONTEXT_PROCESSORS}): """ Returns TEMPLATE_CONTEXT_PROCESSORS without the processors listed in exclude and with the processors listed in append. The use of a mutable dict is intentional, in order to preserve the state of the TEMP... |
def get_middleware(exclude=(), append=(), current={'middleware': MIDDLEWARE_CLASSES}): """ Returns MIDDLEWARE_CLASSES without the middlewares listed in exclude and with the middlewares listed in append. The use of a mutable dict is intentional, in order to preserve the state of the MIDDLEWARE_CLASSES tuple across multi... |
def get_apps(exclude=(), append=(), current={'apps': INSTALLED_APPS}): """ Returns INSTALLED_APPS without the apps listed in exclude and with the apps listed in append. The use of a mutable dict is intentional, in order to preserve the state of the INSTALLED_APPS tuple across multiple settings files. """ current['apps'... |
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()) DLMt = self.D()[:, :, sp.newaxis] * LMt RV = vei_CoR_veX(DLMt, R=self.Lr().T, C=self.Lc().T) if len(Mt.shape)==2: RV = RV[:, :, 0] return RV |
def invariants(mol): """Generate initial atom identifiers using atomic invariants""" atom_ids = {} for a in mol.atoms: components = [] components.append(a.number) components.append(len(a.oatoms)) components.append(a.hcount) components.append(a.charge) components.append(a.mass) if len(a.rings) > 0: components.append(1) ... |
def ecfp(mol, radius=2): """Compute the Extended-Connectivity fingerprint for a molecule. :param mol: molecule object parsed from SMILES string :param radius: The number of iterations to perform. Defaults to 2 which is equivilent to ECFP4. :rtype: dictionary representing the molecular fingprint (atom identifiers and th... |
nbsr for item in sublist] nbsr.insert(0, atom_ids[a.index]) nbsr.insert(0, layer) round_ids[a.index] = gen_hash(nbsr) neighborhoods_this_round.append( (round_atom_neighborhoods[a.index], round_ids[a.index], a.index) ) for lst in neighborhoods_this_round: if lst[0] not in neighborhoods: fp[lst[1]] = fp.get(lst[1], 0) + ... |
def send(self): """ Post fields and files to an HTTP server as multipart/form-data. Return the server's response. """ scheme, location, path, query, _ = urlparse.urlsplit(self.url) assert scheme in ("http", "https"), "Unsupported scheme %r" % scheme content_type, body = self._encode_multipart_formdata() handle = getatt... |
def _encode_multipart_formdata(self): """ Encode POST body. Return (content_type, body) ready for httplib.HTTP instance """ def get_content_type(filename): "Helper to get MIME type." return mimetypes.guess_type(filename)[0] or 'application/octet-stream' boundary = '----------ThIs_Is_tHe_b0uNdaRY_%d$' % (time.time()) lo... |
def perturbed_mst(X, num_perturbations=20, metric='euclidean', jitter=None): '''Builds a graph as the union of several MSTs on perturbed data. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 8 jitter refers to the scale of the gaussian noise added for each perturbation. When jitter is None, it defaults to the... |
(num_perturbations + 1.0) return Graph.from_adj_matrix(W) |
def disjoint_mst(X, num_spanning_trees=3, metric='euclidean'): '''Builds a graph as the union of several spanning trees, each time removing any edges present in previously-built trees. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 9.''' D = pairwise_distances(X, metric=metric) if metric == 'precomputed': D ... |
def kernelize(self, kernel): '''Re-weight according to a specified kernel function. kernel : str, {none, binary, rbf} none -> no reweighting binary -> all edges are given weight 1 rbf -> applies a gaussian function to edge weights ''' if kernel == 'none': return self if kernel == 'binary': if self.is_weighted(): return... |
def barycenter_edge_weights(self, X, copy=True, reg=1e-3): '''Re-weight such that the sum of each vertex's edge weights is 1. The resulting weighted graph is suitable for locally linear embedding. reg : amount of regularization to keep the problem well-posed ''' new_weights = [] for i, adj in enumerate(self.adj_list())... |
def connected_subgraphs(self, directed=True, ordered=False): '''Generates connected components as subgraphs. When ordered=True, subgraphs are ordered by number of vertices. ''' num_ccs, labels = self.connected_components(directed=directed) # check the trivial case first if num_ccs == 1: yield self raise StopIteration i... |
def minimum_spanning_subtree(self): '''Returns the (undirected) minimum spanning tree subgraph.''' dist = self.matrix('dense', copy=True) dist[dist==0] = np.inf np.fill_diagonal(dist, 0) mst = ssc.minimum_spanning_tree(dist) return self.__class__.from_adj_matrix(mst + mst.T) |
def neighborhood_subgraph(self, start_idx, radius=1, weighted=True, directed=True, return_mask=False): '''Returns a subgraph containing only vertices within a given geodesic radius of start_idx.''' adj = self.matrix('dense', 'csr', 'csc') dist = ssc.dijkstra(adj, directed=directed, indices=start_idx, unweighted=(not we... |
def isograph(self, min_weight=None): '''Remove short-circuit edges using the Isograph algorithm. min_weight : float, optional Minimum weight of edges to consider removing. Defaults to max(MST). From "Isograph: Neighbourhood Graph Construction Based On Geodesic Distance For Semi-Supervised Learning" by Ghazvininejad et ... |
(u,v) in enumerate(candidates): W_uv = np.where(W < cand_weights[i], W, 0) len_uv = ssc.dijkstra(W_uv, indices=u, unweighted=True, limit=2)[v] if len_uv > 2: to_remove[i] = True ii, jj = candidates[to_remove].T return self.remove_edges(ii, jj, copy=True) |
def circle_tear(self, spanning_tree='mst', cycle_len_thresh=5, spt_idx=None, copy=True): '''Circular graph tearing. spanning_tree: one of {'mst', 'spt'} cycle_len_thresh: int, length of longest allowable cycle spt_idx: int, start vertex for shortest_path_subtree, random if None From "How to project 'circular' manifolds... |
def cycle_cut(self, cycle_len_thresh=12, directed=False, copy=True): '''CycleCut algorithm: removes bottleneck edges. Paper DOI: 10.1.1.225.5335 ''' symmetric = not directed adj = self.kernelize('binary').matrix('csr', 'dense', copy=True) if symmetric: adj = adj + adj.T removed_edges = [] while True: c = _atomic_cycle(... |
def fuzz_string(seed_str, runs=100, fuzz_factor=50): """A random fuzzer for a simulated text viewer application. It takes a string as seed and generates <runs> variant of it. :param seed_str: the string to use as seed for fuzzing. :param runs: number of fuzzed variants to supply. :param fuzz_factor: degree of fuzzing =... |
def fuzzer(buffer, fuzz_factor=101): """Fuzz given buffer. Take a buffer of bytes, create a copy, and replace some bytes with random values. Number of bytes to modify depends on fuzz_factor. This code is taken from Charlie Miller's fuzzer code. :param buffer: the data to fuzz. :type buffer: byte array :param fuzz_facto... |
def number_of_bytes_to_modify(buf_len, fuzz_factor): """Calculate number of bytes to modify. :param buf_len: len of data buffer to fuzz. :param fuzz_factor: degree of fuzzing. :return: number of bytes to change. """ return random.randrange(math.ceil((float(buf_len) / fuzz_factor))) + 1 |
def _fuzz_data_file(self, data_file): """Generate fuzzed variant of given file. :param data_file: path to file to fuzz. :type data_file: str :return: path to fuzzed file. :rtype: str """ buf = bytearray(open(os.path.abspath(data_file), 'rb').read()) fuzzed = fuzzer(buf, self.fuzz_factor) try: _, fuzz_output = mkstemp(p... |
def _execute(self, app_, file_): """Run app with file as input. :param app_: application to run. :param file_: file to run app with. :return: success True, else False :rtype: bool """ app_name = os.path.basename(app_) args = [app_] args.extend(self.args[app_]) args.append(file_) process = subprocess.Popen(args) time.sl... |
def __parse_app_list(app_list): """Parse list of apps for arguments. :param app_list: list of apps with optional arguments. :return: list of apps and assigned argument dict. :rtype: [String], {String: [String]} """ args = {} apps = [] for app_str in app_list: parts = app_str.split("&") app_path = parts[0].strip() apps.... |
def _make_tonnetz_matrix(): """Return the tonnetz projection matrix.""" pi = np.pi chroma = np.arange(12) # Define each row of the transform matrix fifth_x = r_fifth*(np.sin((7*pi/6) * chroma)) fifth_y = r_fifth*(np.cos((7*pi/6) * chroma)) minor_third_x = r_minor_thirds*(np.sin(3*pi/2 * chroma)) minor_third_y = r_minor... |
def _to_tonnetz(chromagram): """Project a chromagram on the tonnetz. Returned value is normalized to prevent numerical instabilities. """ if np.sum(np.abs(chromagram)) == 0.: # The input is an empty chord, return zero. return np.zeros(6) _tonnetz = np.dot(__TONNETZ_MATRIX, chromagram) one_norm = np.sum(np.abs(_tonnetz)... |
def distance(a, b): """Compute tonnetz-distance between two chromagrams. ---- >>> C = np.zeros(12) >>> C[0] = 1 >>> D = np.zeros(12) >>> D[2] = 1 >>> G = np.zeros(12) >>> G[7] = 1 The distance is zero on equivalent chords >>> distance(C, C) == 0 True The distance is symetric >>> distance(C, D) == distance(D, C) True >>... |
def fail_print(error): """Print an error in red text. Parameters error (HTTPError) Error object to print. """ print(COLORS.fail, error.message, COLORS.end) print(COLORS.fail, error.errors, COLORS.end) |
def import_oauth2_credentials(filename=STORAGE_FILENAME): """Import OAuth 2.0 session credentials from storage file. Parameters filename (str) Name of storage file. Returns credentials (dict) All your app credentials and information imported from the configuration file. """ with open(filename, 'r') as storage_file: sto... |
def create_lyft_client(credentials): """Create an LyftRidesClient from OAuth 2.0 credentials. Parameters credentials (dict) Dictionary of OAuth 2.0 credentials. Returns (LyftRidesClient) An authorized LyftRidesClient to access API resources. """ oauth2credential = OAuth2Credential( client_id=credentials.get('client_id'... |
def spawn_managed_host(config_file, manager, connect_on_start=True): """ Spawns a managed host, if it is not already running """ data = manager.request_host_status(config_file) is_running = data['started'] # Managed hosts run as persistent processes, so it may already be running if is_running: host_status = json.loads(... |
def parse_input(s): """Parse the given input and intelligently transform it into an absolute, non-naive, timezone-aware datetime object for the UTC timezone. The input can be specified as a millisecond-precision UTC timestamp (or delta against Epoch), with or without a terminating 'L'. Alternatively, the input can be s... |
0: raise ValueError(original) elif pos > 0: # If we find a unit letter, we're dealing with an offset. Default # to positive offset if a sign wasn't specified. if sign is None: sign = 1 ts += int(s[:pos]) * __timedelta_millis(unit[1]) s = s[min(len(s), pos + 1):] if s: ts += int(s) return date_from_utc_ts(ts) if not sig... |
def render_delta(d): """Render the given delta (in milliseconds) as a human-readable delta.""" s = '' if d >= 0 else '-' d = abs(d) for unit in _SORTED_UNITS: span = __timedelta_millis(unit[1]) if d >= span: count = int(d // span) s += '{0}{1}'.format(count, unit[0]) d -= count * span if d or not s: s += str(d) return ... |
def render_date(date, tz=pytz.utc, fmt=_FULL_OUTPUT_FORMAT): """Format the given date for output. The local time render of the given date is done using the given timezone.""" local = date.astimezone(tz) ts = __date_to_millisecond_ts(date) return fmt.format( ts=ts, utc=date.strftime(_DATE_FORMAT), millis=ts % 1000, utc_... |
def parse(self, complete=True, args=None): '''Parse a list of arguments, returning a dict See BooleanParser.parse for `args`-related documentation. If `complete` is True and there are values in `args` that don't have corresponding arguments, or there are required arguments that don't have args, then raise an error. '''... |
more items, but True/False if there is a next item # if this argument looks for a subsequent (is set as boolean), and the subsequent is not a flag, consume it if argument.boolean is False and next_is_flag is False: opts[name] = next_name # finally, advance our iterator, but since we already have the next values, just d... |
propagate aliases and defaults: for argument in self.arguments: # merge provided value from aliases for name in argument.names: if name in opts: value = opts[name] # we simply break on the first match. break else: # if we iterate through all names and fine none in opts, use the default value = argument.default for name... |
def setRandomParams(self): """ set random hyperparameters """ params = sp.randn(self.getNumberParams()) self.setParams(params) |
def perturbParams(self, pertSize=1e-3): """ slightly perturbs the values of the parameters """ params = self.getParams() self.setParams(params+pertSize*sp.randn(params.shape[0])) |
def Kgrad_param_num(self,i,h=1e-4): """ check discrepancies between numerical and analytical gradients """ params = self.getParams() e = sp.zeros_like(params); e[i] = 1 self.setParams(params-h*e) C_L = self.K() self.setParams(params+h*e) C_R = self.K() self.setParams(params) RV = (C_R-C_L)/(2*h) return RV |
def parallel_snr_func(num, binary_args, phenomdwave, signal_type, noise_interpolants, prefactor, verbose): """SNR calulation with PhenomDWaveforms Generate PhenomDWaveforms and calculate their SNR against sensitivity curves. Args: num (int): Process number. If only a single process, num=0. binary_args (tuple): Binary a... |
= csnr(wave.freqs, wave.hc, hn_vals, wave.fmrg, wave.fpeak, prefactor=prefactor) if len(signal_type) == 1: out_vals[key + '_' + signal_type[0]] = snr_out[signal_type[0]] else: for phase in signal_type: out_vals[key + '_' + phase] = snr_out[phase] if verbose > 0 and (num+1) % verbose == 0: print('Process ', (num+1), 'is... |
def parallel_ecc_snr_func(num, binary_args, eccwave, signal_type, noise_interpolants, prefactor, verbose): """SNR calulation with eccentric waveforms Generate PhenomDWaveforms and calculate their SNR against sensitivity curves. Args: num (int): Process number. If only a single process, num=0. binary_args (tuple): Binar... |
for key in noise_interpolants: hn_vals = noise_interpolants[key](wave.freqs) integrand = 1./wave.freqs * (wave.hc**2/hn_vals**2) snr_squared_out = np.trapz(integrand, x=wave.freqs) if 'modes' in signal_type: out_vals[key + '_' + 'modes'] = prefactor*np.sqrt(snr_squared_out) if 'all' in signal_type: out_vals[key + '_' +... |
def snr(*args, **kwargs): """Compute the SNR of binaries. snr is a function that takes binary parameters and sensitivity curves as inputs, and returns snr for chosen phases. Warning: All binary parameters must be either scalar, len-1 arrays, or arrays of the same length. All of these can be used at once. However, you c... |
max_length snr_main = SNR(**kwargs) if squeeze: snr_out = snr_main(*args) return {key: np.squeeze(snr_out[key]) for key in snr_out} return snr_main(*args) |
def smilin(smiles, transforms=[figueras.sssr, aromaticity.aromatize]): """(smiles)->molecule Convert a smiles string into a molecule representation""" builder = BuildMol() tokenize(smiles, builder) mol = builder.mol for transform in transforms: mol = transform(mol) ## implicit hcount doesn't make any sense anymore... f... |
def parse(self, args=None): '''Parse a list of arguments, returning a dict. Flags are only boolean if they are not followed by a non-flag argument. All positional arguments not associable with a flag will be added to the return dictionary's `['_']` field. ''' opts = dict() if args is None: import sys # skip over the pr... |
a subsequent (is set as boolean), # and the subsequent is not a flag, consume it if next_is_flag is False: opts[name] = next_name # finally, advance our iterator, but since we already have the next values, just discard it arglist.next() else: # if there is no next thing, or the next thing is a flag, # all the boolean=F... |
def sq_dist(X1,X2=None): """ computes a matrix of all pariwise squared distances """ if X2==None: X2 = X1 assert X1.shape[1]==X2.shape[1], 'dimensions do not match' n = X1.shape[0] m = X2.shape[0] d = X1.shape[1] # (X1 - X2)**2 = X1**2 + X2**2 - 2X1X2 X1sq = sp.reshape((X1**2).sum(1),n,1) X2sq = sp.reshape((X2**2).sum(... |
def setdbo(self, bond1, bond2, dboval): """Set the double bond orientation for bond1 and bond2 based on this bond""" # this bond must be a double bond if self.bondtype != 2: raise FrownsError("To set double bond order, center bond must be double!") assert dboval in [DX_CHI_CIS, DX_CHI_TRANS, DX_CHI_NO_DBO], "bad dboval... |
def set_symbol(self, symbol): """(symbol, bondorder) -> set the bondsymbol of the molecule""" raise "Deprecated" self.symbol, self.bondtype, bondorder, self.equiv_class = \ BONDLOOKUP[symbol] if self.bondtype == 4: self.aromatic = 1 else: self.aromatic = 0 |
def xatom(self, atom): """(atom)->return the atom at the other end of this bond or None if atom is not part of this bond""" handle = atom.handle if handle == self.atoms[0].handle: return self.atoms[1] elif handle == self.atoms[1].handle: return self.atoms[0] return None |
def save_segments(outfile, boundaries, beat_intervals, labels=None): """Save detected segments to a .lab file. :parameters: - outfile : str Path to output file - boundaries : list of int Beat indices of detected segment boundaries - beat_intervals : np.ndarray [shape=(n, 2)] Intervals of beats - labels : None or list o... |
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None): """Wraps Django's reverse to prepend the correct locale.""" prefixer = get_url_prefix() if prefixer: prefix = prefix or '/' url = django_reverse(viewname, urlconf, args, kwargs, prefix) if prefixer: url = prefixer.fix(url) # Ensure any unicode ch... |
def split_path(path_): """ Split the requested path into (locale, path). locale will be empty if it isn't found. """ path = path_.lstrip('/') # Use partitition instead of split since it always returns 3 parts first, _, rest = path.partition('/') lang = first.lower() if lang in settings.LANGUAGE_URL_MAP: return settings... |
def get_language(self): """ Return a locale code we support on the site using the user's Accept-Language header to determine which is best. This mostly follows the RFCs but read bug 439568 for details. """ if 'lang' in self.request.GET: lang = self.request.GET['lang'].lower() if lang in settings.LANGUAGE_URL_MAP: retur... |
def get_best_language(self, accept_lang): """Given an Accept-Language header, return the best-matching language.""" LUM = settings.LANGUAGE_URL_MAP langs = dict(LUM.items() + settings.CANONICAL_LOCALES.items()) # Add missing short locales to the list. This will automatically map # en to en-GB (not en-US), es to es-AR (... |
def extensions(): """Returns list of `cython` extensions for `lazy_cythonize`.""" import numpy from Cython.Build import cythonize ext = [ Extension('phydmslib.numutils', ['phydmslib/numutils.pyx'], include_dirs=[numpy.get_include()], extra_compile_args=['-Wno-unused-function']), ] return cythonize(ext) |
def plot_main(pid, return_fig_ax=False): """Main function for creating these plots. Reads in plot info dict from json file or dictionary in script. Args: return_fig_ax (bool, optional): Return figure and axes objects. Returns: 2-element tuple containing - **fig** (*obj*): Figure object for customization outside of thos... |
'show_figure' in pid['figure'].keys(): if pid['figure']['show_figure'] is True: plt.show() if return_fig_ax is True: return running_process.fig, running_process.ax return |
def execute(connection: connection, statement: str) -> Optional[List[Tuple[str, ...]]]: """Execute PGSQL statement and fetches the statement response. Parameters ---------- connection: psycopg2.extensions.connection Active connection to a PostGreSQL database. statement: str PGSQL statement to run against the database. ... |
libraries (e.g. SQLAlchemy) that don't inherently respect # PostGreSQL's autocommit isolation-level, since the transaction is # properly completed for each statement. with connection: with connection.cursor(cursor_factory=Psycopg2Cursor) as cursor: cursor.execute(statement) connection.commit() # Get response try: respo... |
def append(self, traverse): """(traverse)->append the traverse to the current traverse""" self.data.extend(traverse.data) self.atoms.extend(traverse.atoms) self.bonds.extend(traverse.bonds) |
def human_size(size): """ Return a human-readable representation of a byte size. @param size: Number of bytes as an integer or string. @return: String of length 10 with the formatted result. """ if isinstance(size, string_types): size = int(size, 10) if size < 0: return "-??? bytes" if size < 1024: return "%4d bytes" %... |
def iso_datetime(timestamp=None): """ Convert UNIX timestamp to ISO datetime string. @param timestamp: UNIX epoch value (default: the current time). @return: Timestamp formatted as "YYYY-mm-dd HH:MM:SS". """ if timestamp is None: timestamp = time.time() return datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:... |
def human_duration(time1, time2=None, precision=0, short=False): """ Return a human-readable representation of a time delta. @param time1: Relative time value. @param time2: Time base (C{None} for now; 0 for a duration in C{time1}). @param precision: How many time units to return (0 = all). @param short: Use abbreviati... |
] # Kill leading zero parts while len(parts) > 1 and parts[0][1] == 0: parts = parts[1:] # Limit to # of parts given by precision if precision: parts = parts[:precision] numfmt = ("%d", "%d"), ("%4d", "%2d") fmt = "%1.1s" if short else " %s" sep = " " if short else ", " result = sep.join((numfmt[bool(short)][bool(idx)]... |
def to_unicode(text): """ Return a decoded unicode string. False values are returned untouched. """ if not text or isinstance(text, unicode if PY2 else str): return text try: # Try UTF-8 first return text.decode("UTF-8") except UnicodeError: try: # Then Windows Latin-1 return text.decode("CP1252") except UnicodeError: ... |
def to_utf8(text): """ Enforce UTF8 encoding. """ # return empty/false stuff unaltered if not text: if isinstance(text, string_types): text = "" return text try: # Is it a unicode string, or pure ascii? return text.encode("utf8") except UnicodeDecodeError: try: # Is it a utf8 byte string? if text.startswith(codecs.BOM_... |
def p_program(self, p): """program : source_elements""" p[0] = self.asttypes.ES5Program(p[1]) p[0].setpos(p) |
def p_source_element_list(self, p): """source_element_list : source_element | source_element_list source_element """ if len(p) == 2: # single source element p[0] = [p[1]] else: p[1].append(p[2]) p[0] = p[1] |
def p_block(self, p): """block : LBRACE source_elements RBRACE""" p[0] = self.asttypes.Block(p[2]) p[0].setpos(p) |
def p_boolean_literal(self, p): """boolean_literal : TRUE | FALSE """ p[0] = self.asttypes.Boolean(p[1]) p[0].setpos(p) |
def p_null_literal(self, p): """null_literal : NULL""" p[0] = self.asttypes.Null(p[1]) p[0].setpos(p) |
def p_numeric_literal(self, p): """numeric_literal : NUMBER""" p[0] = self.asttypes.Number(p[1]) p[0].setpos(p) |
def p_string_literal(self, p): """string_literal : STRING""" p[0] = self.asttypes.String(p[1]) p[0].setpos(p) |
def p_regex_literal(self, p): """regex_literal : REGEX""" p[0] = self.asttypes.Regex(p[1]) p[0].setpos(p) |
def p_identifier(self, p): """identifier : ID""" p[0] = self.asttypes.Identifier(p[1]) p[0].setpos(p) |
def p_reserved_word(self, p): """reserved_word : BREAK | CASE | CATCH | CONTINUE | DEBUGGER | DEFAULT | DELETE | DO | ELSE | FINALLY | FOR | FUNCTION | IF | IN | INSTANCEOF | NEW | RETURN | SWITCH | THIS | THROW | TRY | TYPEOF | VAR | VOID | WHILE | WITH | NULL | TRUE | FALSE | CLASS | CONST | ENUM | EXPORT | EXTENDS |... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.