content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def iterm2hex(root): """Get hex codes from iterm xml Args: root (xmlroot): xmlroot Returns: dict: iterm keys to hex """ keys = root.findall("./dict/key") dicts = root.findall("./dict/dict") iterm = {} for i, _key in enumerate(keys): keyName = keys[i].text r = g = b = None for index, item in enumerat...
db499fc5d648727974bc449e5a801eeaa1f5ae46
3,614,300
def __increaseCombinationCounter(root): """ increase the combination-counter, which is located in the provided root-node """ if root['type']=='graphroot': root['combination'] += 1 return root
c2f7c88ef2eca4f8c4bf6532cc76ed5a1833dfe6
3,614,301
async def get_complaints(request: Request): """Get complains Get complaints for User. - If user has role complainer, returns complaints created by this user. - If user has role aprover, returns complains in status pending The user have been authenticate!!!. Args: request (Request): ...
aabb8eff59a79f8f8d6a3965914634f1a9c40da0
3,614,302
import winreg def supports_color(): """ Return True if the running system's terminal supports color, and False otherwise. """ def vt_codes_enabled_in_windows_registry(): """ Check the Windows Registry to see if VT code handling has been enabled by default, see https://super...
5b3460d0c4da46de1c707a34c471c8278128830c
3,614,303
def make_list_of_model_filenames(model,fc_dates,lt): """ returns: flst - list of model files to be opened dlst - list of dates to be chosen within each file """ #fn = make_model_filename_wrapper('mwam4',datetime(2021,1,1,1),1) flst = [] for d in fc_dates: fn = make_model_fil...
0961d7f7c6a6ed952d3ec93013e6c411ecfb765e
3,614,304
def mask_to_lbl(mask, label): """Convert mask to label image.""" lbl = np.empty(mask.shape, dtype=np.int32) lbl[mask] = label lbl[~mask] = -1 return lbl
590109ed73d06737551875da4e44117cb8546ff7
3,614,305
from . import support def setup_resources(resources=None): """ Call either with a list of resources or a resource string. If ``None`` is given, get the resource string from the environment. """ if isinstance(resources, str) or resources is None: resources = parse_resources(resources) ...
ea9a736e071a3f9f8525c68776e026bd3be6c966
3,614,306
def approx_average_is_average(hand): """ :param hand: list - cards in hand. :return: bool - is approximate average the same as true average? """ median = hand[len(hand)//2] approx_average = (hand[0] + hand[-1])/2 avg = card_average(hand) return median == avg or approx_average == avg
49b6373858a28e7bc9420f1ff561cf0cb0909822
3,614,307
def test_runner_names(): """Get iterable of test-runner plugin names.""" return ExtensionManager('cosmic_ray.test_runners').names()
1d0af25928c1224ebafc9801fc5e1c05877b3060
3,614,308
def get_options(): """Create user interface options.""" user_options = {} user_options['chassis'] = {'label': 'Chassis', 'type': 'stringList', 'default': 'benzene', 'values': chassis_list} user_options['center-...
dce5c29735b2a0d20dd60cf2df165c4ce2fd4d99
3,614,309
def compute_dissymmetries(diffables_a, diffables_b): """Return a list of dissymmetry from two given diffable lists.""" if not diffables_a and not diffables_b: return [] dissymmetries = [] for a, b in _outer_join_diffables(diffables_a, diffables_b): if not a: dissymmetry = b....
f8e66a23fbeaf44f9942bf8eea3db009d63a3a55
3,614,310
def getInterestHistory(asset="", isolatedSymbol="", startTime="", endTime="", current="", size="", archived="", recvWindow=""): """# Get Interest History (USER_DATA) #### `GET /sapi/v1/margin/interestHistory (HMAC SHA256)` ### Weight: 1 ### Parameters: Name |Type |Mandatory |Description --------|--------|--------...
2f9abb185241386dd6b072c8c73210112a71332e
3,614,311
def orthonormalize(A): """Return an orthonormal basis in which `A` has a sparse representation. `A` will have support only on the first three elements. The first element is guaranteed to be proportional to the identity. This basis is constructed using Gram-Schmidt orthogonalization. Parameters ...
6e5a0aecf1f3036bdaccf1ab8e3e39846185e69b
3,614,312
import numpy as np import pandas as pd from .export_image import export_image from .. statistics.cdf import cdf import matplotlib.pyplot as plt from .utils import format_plot, get_label import probscale def probability_plot(data, wt=None, lower=None, upper=None, logscale=True, ax=None, figsize=None, ...
8b48241fa8dcc0b2c0fa14e93110b0e9e7dd86b6
3,614,313
import time def get_time_human_readable(): """ returns well formated time string. for example: Donnerstag, 21:00 """ return time.strftime("%A, %H:%M")
2dfc67ba6eec8b830a9bacb5f4d9c6baaab17943
3,614,314
def proc_annotation(file_path, ann_dict, split, trimmed, class_to_id_map): """Process the annotations and return list of file_paths and corresponding annotations Arguments: file_path (str): File path for the corresponding annotation ann_dict (dict): The annotation dictionary spl...
182fa2f8bb168c7d91f0669ff4c2066db6b34869
3,614,315
def get_csv_filename(name: str) -> str: """ Returns the name of a CSV file corresponding to the input file `name`. If `name` is a CSV file already (that is: does not have an .xls ending or some extension of this suffix) the `name` is returned unchanged. If on the other hand `name` is the name of a s...
eb4e61fb926d5295571146aba343e0ee00c1261e
3,614,316
def findpeaks(data, spacing=1, limit=None): """Finds peaks in `data` which are of `spacing` width and >=`limit`. :param data: values :param spacing: minimum spacing to the next peak (should be 1 or more) :param limit: peaks should have value greater or equal :return: """ len = data.size ...
a47b5e0767fff2541906160ab358d4dc35c80979
3,614,317
import argparse import os def parse_command_line(): """ Parse the command line. Returns: Namespace: The parsed command line container. """ parser = argparse.ArgumentParser() # All reference encoders refcoders = ["ref-1.7", "ref-2.5-neon", "ref-2.5-sse2", "ref-2.5...
6293051e99583f982222552cff150e33d2a7178b
3,614,318
import numpy def gaussian_kernel(x1, x2, sigma): """ Computes the radial basis function Returns a radial basis function kernel between x1 and x2. Parameters ---------- x1 : numpy ndarray A vector of size (n, ), representing the first datapoint. x2 : numpy ndarray A vecto...
09305fe216a1994e597b9c44c83e7f0fc5283575
3,614,319
def _extractSpecCAP(config, tab, kernelDict, method = 'CAP', diskRadiusArcmin = 4.0, highPassFilter = False, estimateErrors = True): """See extractSpec. """ # Define apertures like Schaan et al. style compensated aperture photometry filter innerRadiusArcmin=diskRadiusA...
46cf8a477f3ef3b74e8f5b6af5431fedc618d85c
3,614,320
def uniform_on_unit_sphere(N, D): """Draw ``N`` points uniformly distributed on the surface of a ``D``-dimensional unit sphere. Example ------- .. plot:: :include-source: import matplotlib.pyplot as pl import bluebell as bb import bluebell.plot as bbplot x = bb...
a59c89119207713cf68b6ba14fcd4d284be93eb7
3,614,321
def freq_title_format(freq): """ e.g. Frequency: 440 Hz e.g. Frequency: 15.0 kHz """ if freq < 10000: title = f"Frequency: {round(freq, 1)} Hz" elif freq >= 10000: freq = round(freq * 1e-3, 1) title = f"Frequency: {freq} kHz" return title
f2235efcb8d25c33741923ca44962e0ef6bb0899
3,614,322
def mat_toeplitz(h, g): """ Constructs a Toeplitz matrix from the given sequences Parameters ---------- h: list[] A sequence defining the matrix for non-negative indices. This will define the number of rows. g: list[] A sequence defining the matrix for negative indices. ...
b9c3cacccd8c230180c1c28ac4e9f2cf2b991a2a
3,614,323
def validateShot(msg): """Valida tiro dado e retorna uma resposta formatada. Parameters ---------- msg : str Mensagem do client. Returns ------- response : str Resposta formatada. """ # Pegar linha e coluna do tabuleiro line = msg[3] # linha column = msg[4...
1652af53ed35d17f59289e4cd6135b708a9cd288
3,614,324
import time import tempfile import os import subprocess import shlex import scipy import shutil def dsift_llc(image_filenames, image_ids): """ For each image_id in the list, compute the Dense SIFT feature, LLC coded with a 10K-dimensional codebook (obtained by subsampling a 100K-dimensional codebook. ...
24775c60dd729c380979020ebca9ae347b42bea6
3,614,325
from typing import Tuple from typing import List def _normalize_einsum_in_subscript(subscript: str, in_operand_shape: ShapeT, index_to_descr: PMapT[str, EinsumAxisAccess], ...
32feadca7092805e27b1d1fb763b4d50327e781e
3,614,326
def poincareSeedsLine(POT, nPoints = 500, start=-1, stop=1, center = [0,0,0]): """ returns an array of the positions to seed the stream tracing the positions lie on a line from going from center through the degenerate torus. start should be negative for the points to start before the degenerate to...
e3fdedf82351bd6e4159af53a723bfc9c25bd541
3,614,327
import pandas as pd import os def caterpillars(path): """Caterpillars Measurements on a sample of Manduca Sexta caterpillars A dataset with 267 observations on the following 18 variables. `Instar` Coded from 1 (smallest) to 5 (largest) indicating stage of the caterpillar's life `ActiveFeeding` I...
ea102db502ad6736bc29650a54040bbdd89b4a95
3,614,328
import os import warnings def fetch_adhd(n_subjects=None, data_dir=None, url=None, resume=True, verbose=1): """Download and load the ADHD resting-state dataset. Parameters ---------- n_subjects: int, optional The number of subjects to load. If None is given, all the 40 ...
4940e4a9fffc9354a025303f6394536f29dadd26
3,614,329
from typing import Dict from typing import Any def modify_openapi() -> Dict[str, Any]: """modify_openapi.""" if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="MySQL-AutoXtrabackup", version=f"{VERSION}", description="Rest API doc for MySQ...
8f0422ad65734ba4807de67b084ab2ede7b12d64
3,614,330
def get_atol(atol=None): """Get default numerical threshold for regression test.""" # _TODO: get from env variable, different threshold might # be needed for different device and dtype return 1e-20 if atol is None else atol
a0bc20b0608d981d162e1dfead5cbe900333f696
3,614,331
import os def path(*parts): """ Joins the path parts with the #project_path, which is initialized with the parent directory of the file that first imported this module (which is usually the Python plugin file). """ path = os.path.join(*parts) if not os.path.isabs(path): path = os.path.join(project_p...
8730ff796d6b27bbed9e10cdc9270109969e352a
3,614,332
def bootstrap(values, nIter, alpha): """ bootstrapping to create error bounds, uses resmapling with replacement of sample size n-4 :param values: n-by-m matrix, n = number of runs to resmaple from, m = observations per run :param nIter: int, number of resamples :param alpha: float, percentile bounds...
02b2dbf9ba170ebf2e931100fb63d365395d8f1a
3,614,333
def resolve_required_interfaces(): """Helper function to build a map of required interfaces based on the OpenStack release being deployed. @returns dict - a dictionary keyed by high-level type of interfaces names """ required_ints = deepcopy(REQUIRED_INTERFACES) if CompareOpenStackReleases(os_r...
f7c2a85b99817e3fc32b56d49a841e02a73815da
3,614,334
from typing import Optional from typing import Union from pathlib import Path from typing import List from typing import Dict def create_run( logger: Optional[HasuraLogger] = None, config: Optional[Union[Path, str]] = None, charts: Optional[List[dict]] = None, metadata: Optional[Dict] = None, swee...
e08222ae1ed5369a9d1118b6c96168aa5ce6aa80
3,614,335
from typing import List from textwrap import dedent def generate_bootstrap_sql_bal_erg(header: Header, outputs: List[Output]) -> str: """ Bootstrap sql for erg balance tables Watcher checks latest height in bal.erg_diffs to determine if bootstrapping is needed and if so, from which height. Here, we s...
88cb1510570f78c75fcf5c3f30db0da34821c0a0
3,614,336
def _gen_id(prefix, suffix=None): """ Generates the id """ suffix = "-{}".format(suffix) if suffix else "" return "{prefix}-{uid}{suffix}".format(prefix=prefix, uid=uuid4(), suffix=suffix)
31fc98e3325a7794e34cd929365df219be840038
3,614,337
def _add(set, item): """Adds an item to the set and returns the set""" set[item] = _EMPTY return set
0bc459c267fc2b88116f74e3fb597004241f7153
3,614,338
import os def ensure_symlink (src, dst): """Ensure the existence of a symbolic link pointing to src named dst. Returns a boolean indicating whether the symlink already existed. """ try: os.symlink (src, dst) except OSError as e: if e.errno == 17: # EEXIST return True ...
0ff95fc22f59f9436e8bf1ab6fe8732c46f953cb
3,614,339
import math from datetime import datetime def suntime(date_time,latitude,longitude): # -*- coding: utf-8 -*- """ Created on Thu Dec 21 10:36:23 2017 @author: Roland Proud """ T = date_time.timetuple() ### time (today) ## (year, month, day, hour, minutes, seconds) ## lat lon for hobart, tasmania #lat1 =...
353a678bc20fe0e991fe69edf158cf586a33f7b6
3,614,340
def _get_batch(data, i, seq_len): """バッチ毎にデータを取得する """ slen = min(seq_len, data.shape[0] - i) inputs = data[i:i + slen] target = inputs.copy() # tensorflowのopに変換 # dataは変数ではないのでconstantとする return tf.constant(inputs), tf.constant(target)
68ed3536cf720446c1f5523c65efd386b9fc77c8
3,614,341
from typing import List def calibrate_universal(observations: List, detector, num_radial=2, tangential=True, zero_skew=True, mirror_offset=None): """ Calibrate a fisheye camera using Universal Omni model. :param observations: List of {"points":(boofcv detections),"width":(image wi...
46cc216e2072a70afa55f34d105056ac720f4e40
3,614,342
from typing import Optional from typing import Callable import functools import threading import logging def wrap_with_logs(fn: Optional[Callable] = None, target: str = __name__) -> Callable: """Calls the supplied function, and logs whether that function raised an exception or terminated normally. This i...
baff17c8a1cdee2e5f81c0d06db620951bbfb94c
3,614,343
def first_pass(text): """ Find links, comments, escaped (or non wiki-formatted text), templates and template arguments :param text: :return: list containing 2 lists (first one gives the locations of links, templates and template arguments, second ...
fabe9a121070c6b91e43701d3545df046e38b2ff
3,614,344
def map_url_out(request, env, application, controller, function, args, other, scheme, host, port, language=None): """ Supply /a/c/f (or /a/lang/c/f) portion of outgoing url The basic rule is that we can only make transformations that map_url_in can reverse. Suppose that the incomin...
179aba72008865250b3b1f36b92192ce9338e560
3,614,345
from typing import Union from pathlib import Path import os def gen_mocs_image(fits_file: str, outdir: Union[str, Path] = '.', write: bool = False ) -> Union[MOC, STMOC]: """ Generate a MOC and STMOC for a single fits file. Args: fits_file:...
bcb89bbf0fc383c20481c2ae05da9f9b840de6a3
3,614,346
import re def remove_numbers(s): """Removes numbers, including times.""" return re.sub('\d+(:\d*)*(\.\d*)?', ' ', s)
b234b914cc84b04cd183ba086674df0775f3b098
3,614,347
def process_lightcurve_into_numpy_array(hdulist, row, replace_outliers=True): """The function is to get the time series and the flux series from the original light curve file.""" ## get planetary and stellar parameters quality = hdulist[1].data['QUALITY'] tess_mag = hdulist[0].header['TESSMAG'] sta...
cfa5cbdfd0a2beff706f33ab1b6cf707d834df7a
3,614,348
import pandas as pd import os def florida(path): """Florida County Voting The `Florida` data frame has 67 rows and 11 columns. Vote by county in Florida for President in the 2000 election. This data frame contains the following columns: GORE Number of votes for Gore BUSH Number of votes fo...
5bee7ed7542032636466667b66408561a0da5179
3,614,349
import collections def char_ngram_count_normalised(text, n, number_of_terms = 0): """Returns a list of ngram frequencies given a text text -- the text from which the word frequencies are to be extracted n - the number of grams (2 indicates bigram) number_of_terms -- number of terms to extr...
952e2366f91ca6d43204276922ad2a179e95e946
3,614,350
def entropy_difference_timeseries(usage_distribution, absolute=True, intervals=None): """ :param usage_distribution: a CxT diachronic usage distribution matrix :return: array of entropy differences between contiguous usage distributions """ if absolute: return np.array([abs(d) for d in np.di...
ae63ee91ad0712da4d04a1f00904c091ea7fd85e
3,614,351
import logging def merge_files(left_file: str, right_file: str, columns: list, keep: str = 'none', keep_missing: str = 'none') -> pd.DataFrame: """ Merges two csv files Parameters: left_file (str): Path to first file right_file (str): Path to second file column (str): Name of column to merge ...
feca64766f5505ed95e4717a1d8e1ece94bc9157
3,614,352
def transformMeshPosOri(vertices, normals, pos=(0., 0., 0.), ori=(0., 0., 0., 1.)): """Transform a mesh. Transform mesh vertices and normals to a new position and orientation using a position coordinate and rotation quaternion. Values `vertices` and `normals` must be the same shape. This is intended to...
281bc002555ef30980d9c382557a7dddbdfa1210
3,614,353
def rmse_over_time(pred_time_series, meas_time_series, normalization=None): """ Calculates the NRMSE over time, Args: pred_time_series (np.ndarray): predicted/simulated data, shape (T, d) meas_time_series (np.ndarray): observed/measured/real data, shape (T, d) normalization (str_or_None...
d560e319847df7ef7a06c9b72840e05fd0621edb
3,614,354
def SampleSelection_v2(setOfPoints,nSamples,returnIndicies=False, nTrials=10, debug=False): """Using Convex Hull to select boundary points. Filling the rest by performing random selections """ nPoints = setOfPoints.shape[0] hull = ConvexHull(setOfPoints) indicies = hull.vertices.tolist() boundaryPo...
40f9111f72e16ca6ab2125605441464ef71a76a0
3,614,355
def planFree(world,hand,qtarget): """Plans a free-space motion for the robot's arm from the current configuration to the destination qtarget""" globals = Globals(world) cspace = TransitCSpace(globals,hand) robot = world.robot(0) qmin,qmax = robot.getJointLimits() #get the start/goal con...
4281f2cd1ffa759d2fceec927a11c04c99f52605
3,614,356
import torch def squash_tensor(x, min_val, max_val): """Normalize a tensor to a specific range.""" x_np = x.clone().numpy() sq = np.interp(x_np, (x_np.min(), x_np.max()), (min_val, max_val)) return torch.from_numpy(sq)
d64326d15b06bc0e9be11e66655bfff158645fe2
3,614,357
def test_downstream_message_sending_via_recipewrapper_with_unnamed_output(): """Test sending messages via the RecipeWrapper when the current step does not have named outputs, or any output at all. """ def downstream_message(dest, payload, path=()): """Helper function to generate expected messag...
ebf070c63e72a749321e210f7a40d0093af78251
3,614,358
from werkzeug.exceptions import SecurityError def get_host(environ, trusted_hosts=None): """Return the host for the given WSGI environment. This first checks the ``Host`` header. If it's not present, then ``SERVER_NAME`` and ``SERVER_PORT`` are used. The host will only contain the port if it is differ...
292b949a5ab2b5f1eb52d06c1a785a61935b6f54
3,614,359
import copy def feature_engineering(df, ft_requests, idcol): """ The Feature Engineering module needs FeatureTools installed to work. So please do "pip install featuretools" before trying out this module. It takes a given data set, df and adds features based on the requet types in ft_requests whic...
d43bdb0895162922e9c927181f906244cb2175bd
3,614,360
def rss(type: RSSType): """Get the RSS feed url for the entire site depending on which feed type you want Parameters ----------- type : RSSType The type of feed you desire to get Returns -------- str URL for the feed type """ return f"https://rss.moddb.com/{type.nam...
f12b35057e15bcd8aea31007a9441e641eefcc38
3,614,361
def explode_df(df, schema): """ Transform ouroborous DR1/DR2 extracts into unified vote table Designed for Ouroborous raw data extract, after removing rare answers. Args: df (pd.DataFrame): rows by classification, columns by question (e.g. 'decals-0'), values by answer (e.g. 'a-0') schem...
ea997a0920e8b2919f659901fd5629ca146da95f
3,614,362
def fold(ts, period, bins, subints=None): """ Fold TimeSeries at given period Parameters ---------- ts : TimeSeries Input time series to fold period : float Period in seconds bins : int Number of phase bins subints : int or None, optional Number of desire...
9d53355bcdc0cf073f030886962de8daba0090bc
3,614,363
def is_image(im, cv2_ok=True, pil_ok=True): """ Check if the input is a valid image or not Args: im: image cv2_ok (bool, optional): check cv2. Defaults to True. pil_ok (bool, optional): check pil. Defaults to True. """ assert cv2_ok or pil_ok if cv2_ok: flag_cv2 = is...
d96d99c2e7a93a4389239dfccc3013fd87cebd40
3,614,364
def get_ois_using_template(template, type_ois: TypeOis, rp: Qcf.RecPay, notional: float, start_date: Qcf.QCDate, tenor: Qcf.Tenor, fixed_rate_value: float, spread: float, gearing: float): """ """ template_dict = template[type_ois] meses = tenor.get_y...
0898b8c9f5c5d1c03318f2b31a2507e5cec6988c
3,614,365
from typing import Iterable from pathlib import Path def get_versions( dependency: str, granularity: str = "minor", # ascending: bool = False, limit: Optional[int] = None, # allow_prerelease: bool = False, ) -> Iterable[str]: """Yield all versions of `dependency` considering version constraints ...
82853c6728de30aa55368d3230ccfc285a9e34eb
3,614,366
import numpy def insert_dummy_atom(zma, x_key, x_key_mat, x_name_mat, x_val_dct): """ insert a dummy atom at a given position in the z-matrix """ syms = symbols(zma) key_mat = numpy.array(key_matrix(zma)) name_mat = numpy.array(name_matrix(zma)) # check whether x_name_mat overlaps with name_m...
82115070c618bae5ed01995fdcea2c9b90e20897
3,614,367
def prepare_plane_to_curved_flat_arbitrary(k, rs_support, num_pointss, z, xo, yo, qs_center=(0, 0), kz_mode='local_xy'): """Prepare propagator from uniformly sampled plane to arbitrarily sampled curved surface. The zero-th order component (k_z) is included (arbitrarily) in Px. Args: k (scalar): Wav...
620601d45384c0942d02fc047c06fd627300b8c3
3,614,368
def deprecated_alias(**aliases): """ A deprecation decorator constructor. Parameters ---------- aliases: str The key-value pairs of mapping old --> new argument names of a function. Returns ------- callable A decorator for the specific mapping of deprecated argu...
f9b71682a55a298c4626e51f3b53864ff8adf44c
3,614,369
from typing import Optional def get_asset_encryption_key(account_name: Optional[str] = None, asset_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetA...
6c794a2347a4a939857342ef7f6558d11c6b10bb
3,614,370
def _escapeWildCard(klassContent): """ >>> _escapeWildCard('') '' >>> _escapeWildCard(':*') '' >>> _escapeWildCard(':Object') ':Object' """ return klassContent.replace(':*', '')
537b3969dabb46c3a093dacc3ba49a58833f8c18
3,614,371
def convert_xyz_to_rgb(x, y, z, *, space, reference, clip=True): """ Converts give XYZ values to RGB (0-1). Note: For general purpose use, directly use conversion functions like `xyz_to_srgb`, `xyz_to_adobe_rgb` etc. instead using this function. :param x: X :param y: Y :param z: Z :par...
da909f979013e47806e3ea364db3022d439b5868
3,614,372
def _show_graph() -> None: """Function that sets the plt configuration then calls matplotlib.show(). plt configuration is set from _GLOBAL_GRAPH_CONFIGS """ _configure_plot(_GLOBAL_GRAPH_CONFIGS) plt.show() return None
f9cb085828e414c0fc306d2ecd2dd6d7275d74d9
3,614,373
import logging import tqdm def pr3_search(bursts, obs_mjds, obs_durations, pmin=1.57, pmax=62.8, nbins=8, pres = None, nopbar=False): """ Periodicity search using Pearson chi square method used in The CHIME/FRB Collaboration et al 2020 :param bursts: List or array of burst MJDs :param obs_mjds: Start...
a1e8014d0e3f52352ea5cdd75da308adaeb21773
3,614,374
import gzip import tqdm import json def get_df(path): """ Apply raw data to pandas DataFrame. """ idx = 0 df = {} length = len(gzip.open(path, 'rb').readlines()) g = gzip.open(path, 'rb') # progress = g progress = tqdm(g, desc='transforming', total=length, leave=False, unit_scale=True) ...
9c22ae55c4a95b8a891d923541cba79d967263bf
3,614,375
def width_required_for_column(header, values): """ Spaced needed to display column in a single line, accounts for the two extra characters that the tabulate package adds to the header when the content is too short """ values_max = -1 if not values else max(len(str(v)) for v in values) return...
1ec812af0da623f4b52edc6708f265a5c14fb03a
3,614,376
from datetime import datetime def get_coinbase_stats(access_token, currency, period): """ Get historical investment data across all accounts. """ client = OAuthClient(access_token, access_token) cache_date = datetime.datetime.date(datetime.datetime.now()) user, accounts = _get_user_and_account...
dbe0e7f3a762b12bb4feaecacf0cb2ee0fbbc650
3,614,377
def token_to_tuple(token: Token) -> tuple: """Convert token to tuple.""" return (token['txn_hash'], token['owner'], token['value'], token['signature'])
43429d0995d5f45c78fc80326ca3e7d718bb0137
3,614,378
import torch import os import json def evaluate(args, accelerator, dataloader, eval_set, model, checkpoint, has_labels=True, write_to_file=True): """Evaluate a model checkpoint on the given evaluation data.""" num_examples = args.num_examples[eval_set] eval_metric = None completed_steps = 0 eval_...
ab61e81406e9cf475c1e8b4b89fecd8d8fa4634b
3,614,379
def _setup_entities(hass, dev_ids, platform): """Set up Tuya Climate device.""" tuya = hass.data[DOMAIN][TUYA_DATA] entities = [] for dev_id in dev_ids: device = tuya.get_device_by_id(dev_id) if device is None: continue entities.append(TuyaClimateEntity(device, platfo...
e50189e52c1495028b2fd1a3432eaa8f80ad2a64
3,614,380
import torch import re import collections def imed_collate(batch): """Collates data to create batches Args: batch (dict): Contains input and gt data with their corresponding metadata. Returns: list or dict or str or tensor: Collated data. """ error_msg = "batch must contain tenso...
553e27cedc2767270ae2d70490af0af19e1da16f
3,614,381
import time def throttle(s): """Decorator ensures function that can only be called once every `s` seconds. """ def decorate(f): t = None def wrapped(*args, **kwargs): nonlocal t t_ = time() if t is None or t_ - t >= s: result = f(*args, ...
5095b9477958099798d1a00740e313d007e346e4
3,614,382
import numpy def _tot_recovery_op(habitat_arr, num_arr, denom, max_rating): """Calculate and reclassify habitat recovery scores to 1 to 3. The equation for calculating reclassified recovery score is: score = 3 * (1 - num/denom/max_rating) If 0 < score <= 1, reclassify it to 1. If 1 < score <=...
7f538374e62884a355b2976707125505fd93550d
3,614,383
import posixpath def rdsamp(record_name, sampfrom=0, sampto=None, channels=None, pn_dir=None, channel_names=None, warn_empty=False, return_res=64): """ Read a WFDB record, and return the physical signals and a few important descriptor fields. Parameters ---------- record_name : str...
d2271ff273b34d7871b944aab9c925e771b33dad
3,614,384
import tkinter def create_puzzle_frame(parent_frame, n, current_puzzle_frame=None, read_only=False): """ Creates a new puzzle frame inside a parent frame and if the puzzle frame already exists, first destroys it. This is done because when the n changes we have to change the puzzle frame's grid row and col...
9017d288c2ae33a789af3a1197d09375282e3fdf
3,614,385
async def tag_info_command(ctx: utils.PrefixContext) -> None: """Get info about a tag Args: <name|alias>: The tag name or alias to get info about. """ name = ctx.options.name.lower() query = ( "SELECT t.tagname, t.tagowner, t.uses " "FROM tags t FULL OUTER JOIN tag_aliases a...
0dc13ef6f7e484fb96146625afff687a7adf2dec
3,614,386
def fric_pipe(FlowRate, Diam, Nu, Roughness): """Return the friction factor for pipe flow. For laminar flow, the friction factor is 64 is divided the Reynolds number. For turbulent flows, friction factor is calculated using the Swamee-Jain equation, which works best for Re > 3000 and ε/Diam < 0.02. ...
43ec6c1e2e21f839cf549d990cdc4dc4d412f8d4
3,614,387
import os def load_model(model_uri, local_destination_path=None): """ Load an ONNX model from a local file or a run. :param local_destination_path: The local path for downloading the model artifacts from the artifact store. :param model_uri: The location, in URI format, of the MLflow model, for examp...
913d13934adc276f05ec2735d114f2e8e86e3d95
3,614,388
def geocode_address(input_address): """ Geocode an address to (lat, lon) """ try: latlng = geocoder.arcgis(input_address).latlng return latlng except: pass try: latlng = geocoder.osm(input_address).latlng return latlng except: pass try: ...
cc7200135197e7801e1338819b450eeb87d447e5
3,614,389
def R1(w): """ R1 is the region after the first non-vowel following a vowel, or the end of the word if there is no such non-vowel. """ m = RE_R1.search(w) if m: return w[m.end():] return ""
7c3981d577e27351a8502af4ea30667204d6945d
3,614,390
import gzip import shutil def md_from_fast5_file(f5_file): """Read from a specified fast5 file and return a dict of metadata """ if f5_file.endswith('.gz'): # Unpack the entire file in memory - much faster than a direct read from gzip handle with BytesIO() as bfh: with gzip.ope...
85dbbe0601b61100dbe61e37b060107213d9b0d9
3,614,391
def db(): """Recover the current configured DB instance. If no default instance is configured then ValueError will be raised. :returns: The DB instance configured through init(). """ if not __db: raise ValueError("No DB instance configured! Call init() first.") return __db
c2aa62ad17c6a3c6784e1f6b23943f3664c1f5c3
3,614,392
def check_fields(default_dict, new_dict): """ Return the dictionary with default keys and values updated by using the information of ``new_dict`` :param dict default_dict: Dictionary with default values. :param dict new_dict: Dictionary with new values. :return: dict. """ # ...
c31508cc7ac3e4a717285c2fd082fc6bd7c2eb32
3,614,393
def plot_iv(*args, **kwargs): """Alias for uspy.leem.plotting.plot_intensity() with xaxis set to "energy".""" return plot_intensity(*args, xaxis="energy", **kwargs)
56c59db75e08fe19db5088ae1597f0b0f75e0031
3,614,394
def snapgene_file_to_gbk(read_file_object, write_file_object): """Convert a file object.""" def analyse_gs(dic, *args, **kwargs): """Extract gs block in the document.""" if "default" not in kwargs: kwargs["default"] = None for arg in args: if arg in dic: ...
2c21f6d00b41917a46316c7d8bd550e69457a752
3,614,395
import token import logging def get_total_click(link): """ Requests the total number of clicks at the moment : param link: Byt.ly link for verification : return: number of clicks """ params = { 'unit': 'day', 'units': '-1' } url = f'https://api-ssl.bitly.com/v4/bitli...
3d2c7f62cb47fd52ae01ee4364619ac830b49cb6
3,614,396
from typing import Dict def get_default_retries() -> Dict[Retry, RetryConfig]: """Returns all default retry values.""" return { Retry.PORT_INFO: set_retry(count=25, seconds_between=1), Retry.JUPYTER_JSON: set_retry(count=15, seconds_between=1), Retry.SCHEDULER_CONNECT: set_retry(count=...
b05e214e145d0118fb3d589f0041e4f6b2410ca9
3,614,397
from typing import Any def tsv_escape(x: Any) -> str: """ Escape data for tab-separated value (TSV) format. """ if x is None: return "" x = str(x) return x.replace("\t", "\\t").replace("\n", "\\n")
febefd579773aa4deea90e589114d39c5b8a4784
3,614,398
import yaml import requests def create_dataset(connection_key: str, yaml_path: str): """ Create a dataset in fidesops given a YAML manifest file. Requires the `connection_key` for the PostgreSQL connection, and `yaml_path` that is a local filepath to a .yml dataset Fides manifest file. Returns the...
0eca5f219f542d3eca2a69d2faab142531e1f149
3,614,399