content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def calc_diarization_error(pred, label, label_delay=0): """ Calculates diarization error stats for reporting. Args: pred (ndarray): (T,C)-shaped pre-activation values label (ndarray): (T,C)-shaped labels in {0,1} label_delay: if label_delay == 5: pred: 0 1 2 3 4 | 5 6 ... 99 10...
8149d872ccf25998ae4f352cfd78504a150ad83c
51,500
def lineage_proof_for_coin_spend(coin_spend: CoinSpend) -> Program: """Take a coin solution, return a lineage proof for their child to use in spends""" coin = coin_spend.coin parent_name = coin.parent_coin_info amount = coin.amount inner_puzzle_hash = None if coin.puzzle_hash == LAUNCHER_PUZZLE...
15dd1febbec472a6a59ed72722745f67b7961d6f
51,501
import sqlalchemy.orm def literalquery(statement): """NOTE: This is entirely insecure. DO NOT execute the resulting strings.""" if isinstance(statement, sqlalchemy.orm.Query): statement = statement.statement return statement.compile( dialect=LiteralDialect(), compile_kwargs={'liter...
a0a4b63c235e790015940f6bc449b8ee1ab692f4
51,502
def filter_nb(nb): """Returns the parts of nb tagged for export and a list of question metadata.""" new_cells = [] for i, cell in enumerate(nb['cells']): if is_question_cell(cell): src = str(cell["source"]) assert len(nb['cells']) > i + 1, 'A response cell must follow questio...
111214b1f1f8e408ffea7ea9a9baceee20000e99
51,503
def status_embed(ctx, member: Member) -> Embed: """ Construct status embed for certain member. Status will have info such as member device, online status, activity, roles etc. :param ctx: context variable to get the member :param member: member to get data from :return: discord.Embed """ ...
572edc0be0326c397e25b146a9de5e1a0fd6099d
51,504
import os import re def get_fw_version(): """ Try to get version of the framework. First try pkg_resources.require, if that fails read from setup.py :return: Version as str """ version = 'unknown' try: pkg = require(get_fw_name())[0] except DistributionNotFound: # Icete...
10d6f407b49e16dbde292afea46db16860a1cbb6
51,505
def sequentially_resolve_permutation( blocks: tf.Tensor, window: tf.Tensor, loss_fn: LossType = _mag_stft_mse_loss) -> tf.Tensor: """Resolves permutation between overlapping blocks. Args: blocks: Waveform in blocks (blocks, sources, samples) window: Window function used to obtain the blocks. ...
48305c140e8698600a8292fb880ac3f74fcb2387
51,506
import os import re def read_SLR_geocenter(geocenter_file, RADIUS=None, HEADER=0, COLUMNS=['time','X','Y','Z','X_sigma','Y_sigma','Z_sigma']): """ Reads monthly geocenter files from satellite laser ranging Arguments --------- geocenter_file: Satellite Laser Ranging file Keyword arguments...
f67dc3cb666349a0cc96ab0d2bebb89101c16e74
51,507
async def invalid_content_length_and_chunking(request: HttpRequest) -> HttpResponse: """A response handler which sends it's body in chunks with an invalid content length""" headers = [ (b'content-type', b'text/plain'), (b'content-length', str(int(len(request.info['text']) / 2)).encode('...
f65b7f793201bacbe810ed2a8aab20b045b04f70
51,508
import os import json def get_activity(profile_id): """ only API_INSTANCE that will be serve /a/.* """ if os.environ['API_INSTANCE'] in request.url_root: http = credentials.authorize(httplib2.Http(memcache)) service_http = discovery.build("plus", "v1", http=http) activities = service_h...
fde96861abe2d8b6d7b5e473978e1a0c04d55f23
51,509
def linear_increasing_velocity(model_param_set, **kwargs): """ Friendly wrapper for instantiating the linear-increased-velocity medium model. """ # Setup the defaults model_config = dict(z_delta=None, min_ppw_at_freq=(6,10.0), # 6ppw at 10hz y_length=None, y_...
1000cbdff9cdf086946da5eddbe6e6a420aedf6a
51,510
from typing import OrderedDict import math def determine_fit_quality(imglist, filtered_table, catalogs_remaining, print_fit_parameters=True): """Determine the quality of the fit to the data Parameters ---------- imglist : list output of interpret_fits. Contains sourcelist tables, newly comput...
930767957621fc537d8e6bd833f0de18685fcb9e
51,511
def fetch_movies_for(category_id): """ Fetches movies for the selected category Updates the placeholder text for the Movies column :param category_id: :return: index.html """ categories = Category.query.order_by(Category.name).all() selected_category = Category.query.filter_by( c...
8c9d902d22fffa6bc2712873eb8e8041648376c6
51,512
def interp1d(x, y, target): """ return 1d linear interpolation """ return np.interp(target, x, y)
7546d37b1a083f4e5197c3717335ee5316d229d0
51,513
def get_vm_ip(vmName, poolName): """Get IP address for a VM on a NIMBUS cluster 'vmName' is required. For example, vmName='pgu-repTest-01' """ command = 'NIMBUS=%s /mts/git/bin/nimbus-ctl ip %s' % (poolName, vmName) output = run_cmd_on_pdc(command) print 'Got IP address on %s for %s: %s' % (pool...
6277668ab0b933f005753309968dd9613a36b055
51,514
def fin_diff(): """Pytest fixture for basic FiniteDifference class with centered method.""" dic = {"Grid": {"N": 10, "r_min": 0, "r_max": 10}, "Clock": {"start_time": 0, "end_time": 10, "num_steps": 100}, "Tools": {}, "PhysicsModules": {...
4697c837559dc733eefa589a7299df519b14f78a
51,515
import collections def scope_symbols(dfg): """ Returns all symbols used in scopes within the given DFG, separated into (iteration variables, symbols used in subsets). """ iteration_variables = collections.OrderedDict() subset_symbols = collections.OrderedDict() for n in dfg.nodes(): if...
49ee517f65ffa05d4a9a8f3bc927d34b9d465d74
51,516
import subprocess def query(): """ Query the attached TEMPer device via temper-query command and parse the result. """ p = subprocess.run(['/usr/local/bin/temper_query'], stdout=subprocess.PIPE) p.check_returncode() temp = float(p.stdout.decode(encoding='ascii').strip()) return temp
c1b00f79b78b73f46f65fa7f4a98695e4501710e
51,517
import string def solve(moves, nr=16): """Return program order after doing all the moves. :moves: dance moves, separated by commas :nr: number of programs :returns: program order >>> solve('s1,x3/4,pe/b', nr=5) 'baedc' """ pgms = list(string.ascii_lowercase[:nr]) for move in mo...
92fed6e01bd09a60d8b9b81ac63bef7045b9ccd6
51,518
def values(): """Get the full current set of B3 values. :return: A dict containing the keys "X-B3-TraceId", "X-B3-ParentSpanId", "X-B3-SpanId", "X-B3-Sampled" and "X-B3-Flags" for the current span or subspan. NB some of the values are likely be None, but all keys will be present. """ result = {}...
2d6324a319a13b93a0fa019f8d0b7de51d6bf977
51,519
def sort_flavors(flavors): """ Sorting flavors, flavors with low resources first :param flavors: flavor list in JSON :return: sorted flavor list in JSON """ return sorted(flavors, key=compare_flavors)
98b02e72f69e7c2b764eb6707ac92ac5685ad10c
51,520
def convert_file_encoding(filename: str, target_encoding: str): """Convert the text encoding of the file to the desired one. The file may already be in the target encoding, in which case nothing is changed. Parameters ---------- 1. filename : str - The full path and name of the file in ques...
135dc12b61e3d3da908451e3b445c9dbe23a4691
51,521
def test_decorator(f): """Decorator that does nothing""" return f
b60b815e336a3f1ca3f12712a2d1d207a5fe110c
51,522
def get_audio(file_path: str) -> mutagen.File: """Get audio object from file""" return mutagen.File(file_path)
0d32e6b95687361590990ad6bcecb177fef18771
51,523
def find_machine_id(agents, host): """ :param agents: Array of mesos agents properties (machine_id + additional infos) :type: list of dict :param host: Host to find. Can be ip, hostname of agent ID :type: string :returns: a machine_id :rtype: dict """ for agent in agents: # d...
706bb16d02aec1fe6844f3ed49b13e6fe54a08a6
51,524
def get_unit_values(ds_inds, ds_vals, dim_names=None, all_dim_names=None, is_spec=None, verbose=False): """ Gets the unit arrays of values that describe the spectroscopic dimensions Parameters ---------- ds_inds : h5py.Dataset or numpy.ndarray Spectroscopic or Position Indices dataset d...
4a3ac92c49fb0c0469fd33a5a285313e59f6fce3
51,525
def get_connection_string(include_password=True): """ Return the connection string based on the configuration specified in the `merlin.yaml` config file. """ broker = CONFIG.broker.name config_path = CONFIG.celery.certs if broker not in BROKERS: raise ValueError(f"Error: {broker} is...
6b97a1cf84447c6dcf503c190d80ea331e3c13f0
51,526
import torch import tqdm def train(train_path, learning_rate, latent_dim, batch_size=128, device='cpu', num_iters=10000, **kwargs): """ Train a 64x64 DCGAN network. """ dis = DCGANDiscriminator().to(device) gen = DCGANGenerator(nz=latent_dim).to(device) image_size = kwargs.get('im...
fa9bea82d633541f020f0720d1d373838fa87d46
51,527
from typing import Dict def _create_Particles_dict() -> Dict[str, dict]: """ Create a dictionary of dictionaries that contains physical information for particles and antiparticles that are not elements or ions. The keys of the top-level dictionary are the standard particle symbols. The values...
5f737b79ac18d4332be1b88d948aa1212c8d595d
51,528
def load_from_secretsmanager(environment=None): """ Load the secrets into a dictionary, skip if no environment available """ if environment is None: try: environment = environ["MICROCOSM_ENVIRONMENT"] except KeyError: # noop return load_from_dict(dict...
9880d7478d44d0794e86cd8ce235d544edfc08b0
51,529
def _dfs_out(atom): """Traverse an Atom's outgoing neighborhood iteratively with a depth-first search.""" atoms = [atom] stack = list(atom.out) while stack: atom = stack.pop(0) atoms.append(atom) stack[0:0] = atom.out return atoms
099258d3d9a51782cacf274e6a3dea6dcd5e6464
51,530
def _read_csv_with_fallback_encoding(filepath, dtypes=None): """read a CSV to a pandas DataFrame using default utf-8 encoding, but try alternate Windows-compatible cp1252 if unicode fails """ try: logger.info('Reading CSV file %s' % filepath) df = pd.read_csv(filepath, comment='#', dty...
1e09a47b90b9e2a3cd0466eb6cf56d00e4824c43
51,531
def cnn_model(features, labels, mode): """CNN model function. Arguments: features -- Batch features from input function labels -- Batch labels from input function mode -- train, eval, predict, instance of tf.estimator.Modekeys Returns: The estimator spec depending on the chosen mode """ ...
a16bc923075bc957cc64adbef435fe0b58e0bc07
51,532
def create_classification_dataset(n_samples, n_features, n_informative, n_redundant, n_repeated, n_clusters_per_class, weights, n_classes, random_state=None): """ Creates a binary classifier dataset :param n_samples: number of observations :param n_features: number of ...
f245fa4dda1c3f73840b7c01cd932d4779a547d5
51,533
def median(data, interval=34): """Calculate the median and ``interval`` size quartile uncertainties. Parameters ---------- data: numpy.nparray Needs to be an 1D array. interval: int The percentile (to one side) you want for uncertainties. Returns ------- numpy.nparray...
0019e7b1671c5be451fddbaa8556039faba889ac
51,534
def npgettext(context, singular, plural, num, **variables): """Translates `singular` and `plural` and returns the appropriate string based on `number` and `context`. """ return _translate('npgettext', context, singular, plural, num, **variables)
95cbb18ddb253104a82616bcf8765f5bf748e0b5
51,535
def load_data(in_path, out_path, in_vocab, out_vocab, max_input_len=56, max_output_len=66): """Loads the data from the given path and preprocesses the data by converting the tokens into ID's using the vocab dictionary. Additionally, token...
5a9d842ed654f6b20409306d874213e7c0d81a18
51,536
def is_compatible(subreddit, index_type, status): """ Checks if the submission exists and belongs to the required type of subreddit """ if status == 'Exists': if index_type == 'AV': keys = list(subreddits[index_type].keys()) for key in keys: if s...
11ce4f3af63a5610f857e8da104ebbb5a9ae3844
51,537
def makePoint(x, y): """ create a point or a dict """ if type(x) == float: return Point(x, y) else: return { 'x': x, 'y': y }
72e3af9e307c9f8f45fa5ab0317748a7181143a3
51,538
import json def search_page(): """Page Search DICOM Instances""" def get_unique_series_ids(instances): """Retrieve the list of series ID related to the instances""" result = [] for instance in instances: series_id = instance[1] if not series_id in result: result.append(series_id...
55c222d28dbd36ee28049126dad3ed63b546ccea
51,539
def convert_confusion_matrix_to_MCM(conf_matrix): """ Converts a confusion matrix into the MCM format for precision/recall/fscore/ support computation by sklearn. The format is as specified by sklearn below: In multilabel confusion matrix :math:`MCM`, the count of true negatives is :math:`MCM_{:,0,0...
78017974a3d99c506f93e0767df0042bce1d3e91
51,540
def setup(hass, config): """Setup the Hello State component. """ _LOGGER.info("The 'hello state' component is ready!") # Get the text from the configuration. Use DEFAULT_TEXT if no name is provided. text = config[DOMAIN].get(CONF_TEXT, DEFAULT_TEXT) # States are in the format DOMAIN.OBJECT_ID ...
5ddc9259ad752a04ca9ed443bc99d810fa28a001
51,541
def render_report(jobs_with_error): """Build a text report for the jobs with errors """ output = [] for job in jobs_with_error: errors_count = job.info.get('errors_count', 0) close_reason = job.info.get('close_reason') job_id = job.info["id"].split('/') url = 'https://ap...
42c0ef405b3b684830433aa5ddd38d4283c7472c
51,542
def in_range(target, bounds): """ Check whether target integer x lies within the closed interval [a,b] where bounds (a,b) are given as a tuple of integers. Returns boolean value of the expression a <= x <= b """ lower, upper = bounds return lower <= target <= upper
ac9dee9092388d150611ab5e1a4a800b72cf8f83
51,543
def get_default_settings(): """Return a dict of default values.""" default_settings = { 'debug': False, 'parse_lines': False, 'output_file': False, 'output_mqtt': False, 'frequency': 433748300, 'binary': "/usr/bin/rtl_433", 'file_path': "/tmp/433sensors", ...
6039d4172427be540a9455b1a72bf04b74e0499e
51,544
def score_sent(text, sent_data, normalize=False): """ Evaluate the data """ test_sent = next(iter(sent_data.values())) sents = np.zeros_like(test_sent).astype(np.float).reshape(-1) tokens = word_tokenize(text.lower()) for token in tokens: try: sent = np.array(sent_data[t...
c1c85685a2b9231e58a11e3db9e3d96200726eff
51,545
def is_master_process(rank=0): """Check if master process or not..""" if not dist.is_initialized(): return True if rank == dist.get_rank(): return True return False
077423bd97175ce271a5edd2e5734e47ed5de4a1
51,546
import zmq import gc import time def test_zmq_with_poller(count): """single thread zmq with poller""" print(".", end="", flush=True) ctx = zmq.Context() router = ctx.socket(zmq.ROUTER) router.bind("tcp://127.0.0.1:*") address = router.getsockopt(zmq.LAST_ENDPOINT).rstrip(b"\0") dealer = ct...
b6ac176b684d306b8e33480ecdd1cf3f17b1a1be
51,547
def _parse_path_segment(acc, segment): """ Parse a single path segment. If the segment is an identifier or wildcard, it's constraint is also derived. :param _ParsedRoutePath acc: Accumulated parse result. :param unicode segment: Path segment. :rtype: _ParsedRoutePath """ match = _t...
03d7d53a9bee78df083b1bc077366f0403699947
51,548
def valid_chrom(): """ Valid chromosomes should be 1 - 22, X, Y, and MT. Validity is not checked or enforced """ return '1'
050baa71f61eaa1f8160953aacfe3f1cd0193899
51,549
def annotateTree(bT, fn): """ annotate a tree in an external array using the given function """ l = [None]*bT.traversalID.midEnd def fn2(bT): l[bT.traversalID.mid] = fn(bT) if bT.internal: fn2(bT.left) fn2(bT.right) fn2(bT) return l
c254a1258e0bc4b0bbbe17c9a2830b955f6a7a55
51,550
import scipy def plotRadiants(pickle_trajs, plot_type='geocentric', ra_cent=None, dec_cent=None, radius=1, plt_handle=None, label=None, plot_stddev=True, **kwargs): """ Plots geocentric radiants of the given pickle files. Arguments: pickle_trajs: [list] A list of trajectory objects loaded from ...
bbbccf1ff5c68fbaf39aff39929ab83762d223c4
51,551
def read_o01(fn): """Read a formatted output file of the ENVIRO program and extract the electric and magnetic fields across the model's transect, returning them in a DataFrame args: fn - str, path to the target file, must have a ".o01" extension returns: df - DataFrame of fields across the t...
470a83064f56abb5d295782f55a1fd0bce60dc00
51,552
def median_squared_percentage_error( y_true, y_pred, horizon_weight=None, multioutput="uniform_average", square_root=False, symmetric=True, **kwargs, ): """Median squared percentage error (MdSPE) or square root version. If `square_root` is False then calculates MdSPE and if `square...
a9e12d9ae34e5d7fb08512e840b581290b436ef0
51,553
import traceback def error_response(ex): """ Handles any errors raised in the execution of the backend Builds a JSON representation of the error messages, to be handled by the client Complies with the Swagger definnition of an error response """ if 'code' in ex: code = ex.code elif...
ed6a492e34a3cd6b00b6e751ccfa58152922a993
51,554
def simulate_from_psd(S_func, m=2000, dt=1, ymean=0, sigma=0.2, size=1, seed=None, **args): """ Simulate light curve given input times, model PSD, and ymean S_func: model PSD function S(omega) [note omega = 2 pi f] m: number of bins [output will have length 2(m - 1)] dt: equal spacing in time ...
c4118d1e31e3f9b70a8518576a161b4fa18c3277
51,555
def eta_error_no_initial(ratio, k1, k2, k3, p1, p2, p3, sratio, sp1, sp2, sp3): """ :param ratio: :param k1: :param k2: :param k3: :param p1: :param p2: :param p3: :param sratio: :param sp1: :param sp2: :param sp3: :return: """ aux0 = ((((-((1. +ratio) ** -2....
f360c462be605c83f797905036e1dc153919efef
51,556
def beta_gen_lasso(p): """ Generate the linear model coefficient in constrained lasso case. @param p int: dimension. @return np.array(p,1): the coefficient. """ cardi = 0.005 return np.array([0]*int(p-int(cardi*p)) + [1]*int(cardi*p))
7618a84bc983596aa17749f56cb79be895281597
51,557
from typing import Optional from typing import Dict import logging def extract_bibliographic_data(node: ET.Element) -> Optional[Dict]: """ Find bibliographic data like title, authors and editors """ data = dict() title = node.find(f"{TEI}titleStmt") if not title is None: extract_title(...
44b9418da114243ab4767fe388b115bf4f29d885
51,558
from typing import Optional def whiten( strain, dt, phase_shift=0, time_shift=0, interp_psd: Optional[np.ndarray] = None, psd: Optional[np.ndarray] = None, ): """Whitens strain data given the psd and sample rate, also applying a phase shift and time shift. Args: strain (nd...
6da702f6f849466a8ef30bddb8fef8007b99854c
51,559
def separator(node, label=None): """Create a visual separator for the channel box using a dummy attribute. This create a maya enum attribute at the last position of the channel box. The name section will be left empty, and the enum section will be filled with the value specified in the ``label`` param...
91459855e98580873a6b743bfdd0f32f9c1934b1
51,560
from typing import Tuple from typing import Optional def find_operating_point( x: np.ndarray, y: np.ndarray, z: np.ndarray, required_x: float ) -> Tuple[float, Optional[float], Optional[float]]: """ Find the highest y (and corresponding z) with x at least `required_x`. Returns ------- x, y, z...
be1489ea8cfa85d0c0a15c0a355fae5c3eac4b0c
51,561
import json import requests def save_request(url, output_file): """ Attempts to read from file. If there's no file, then it will save the contents of a url in json/html """ # check for cached version try: with open(output_file) as fp: data = fp.read() try: ...
79d20b101b0fe811ef9129a701c6f5487e2c8a84
51,562
def load_dependency_files(path): """ Recursively (if necessary) gather all the manifests referenced by the starting_path and return as list :param starting_path: :return: """ f = load_dependency_file(path) files = [f] # recursively call if f.dparser: for file in f.dparser.re...
9af8fde21a65b5ce7e0288abcd8d2fd41d3a9a45
51,563
def accuracy(pred, target, topk): """accuracy = top-k correct""" correct_k = topk_correct(pred, target, topk) accuracy_list = [(x / pred.size(0)) * 100.0 for x in correct_k] return accuracy_list
258b42c760552952adff3a9b7b197badc717d0cf
51,564
import doctest def load_tests(loader, tests, ignore): """Run doctests and file-based doctests.""" tests.addTests(doctest.DocTestSuite(server)) return tests
cf2fbb713885393167782dce783b4292044107ca
51,565
def get_avg_heart_rate(envelope=None, sampling_rate=1000.): """Compute average heart rate from the signal's homomorphic envelope. Follows the approach described by Schmidt et al. [Schimdt10]_, with code adapted from David Springer [Springer16]_. Parameters ---------- envelope : ar...
8f007908c40170835b4963f0ee6aea7f9343990c
51,566
from random import random def busqueda_local(solucion_inicial, evaluacion, obtener_vecinos, T_max, T_min, reduccion): """ Simulated Annealing. """ solucion_mejor = solucion_actual = solucion_inicial evaluacion_mejor = evaluacion_actual = evaluacion(solucion_actual) sol...
f21a03657161d75ca513b6f0f56cc3d9a0c5f27b
51,567
from typing import Dict from typing import Any def _get_aggregate_funcs( df: DataFrame, aggregates: Dict[str, Dict[str, Any]], ) -> Dict[str, NamedAgg]: """ Converts a set of aggregate config objects into functions that pandas can use as aggregators. Currently only numpy aggregators are supported....
5f3730c4be4c285154096a943b6b2c68b3c05305
51,568
from scipy.spatial.distance import pdist, squareform from typing import Optional def distance_weights( X: "npt.ArrayLike", y: "npt.ArrayLike", grouping: "Optional[npt.ArrayLike]" = None, ) -> np.ndarray: """ Compute weights based on Manhattan distance of the X-values. This function ignores inform...
0c581b3674466963603748c7c28fa66c9d83e431
51,569
def flatten_array(grid): """ Takes a multi-dimensional array and returns a 1 dimensional array with the same contents. """ grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))] while type(grid[0]) is list: grid = flatten_array(grid) return grid
4c0361cf8e63d7608b4213ddd8f8a4c498282dcf
51,570
from typing import Callable from typing import Tuple def plot_2d(*plotters: Callable) -> Tuple: """Plot multiple spatial objects in 2D.""" fig, ax = plt.subplots() for plotter in plotters: plotter(ax) return fig, ax
7eb169f19ba83e5ebb9d98e9ead7ef3cd0041af0
51,571
import torch def cosine_sim(x1, x2, dim=1, eps=1e-8): """Returns cosine similarity between x1 and x2, computed along dim.""" x1 = torch.tensor(x1) x2 = torch.tensor(x2) w12 = torch.sum(x1 * x2, dim) w1 = torch.norm(x1, 2, dim) w2 = torch.norm(x2, 2, dim) return (w12 / (w1 * w2).clamp(min=...
a4992b3f3a4a483c96a5b18bbc3402df70a8b44d
51,572
import os import pathlib def find_files(path, exts=None): """ 查找路径下的文件,返回指定类型的文件列表 :param: * path: (string) 查找路径 * exts: (list) 文件类型列表,默认为空 :return: * files_list: (list) 文件列表 举例如下:: print('--- find_files demo ---') path1 = '/root/fishbase_issue' ...
342a6c4d79dca23676502a116be2b242aeb9d086
51,573
def cut_descendants(D, nodes, page_tree): """Given the distance matrix D, a set of nodes and a PageTree perform a multicut of the complete graph of nodes separating the nodes that are descendant/ascendants of each other according to the PageTree""" index = {node: i for i, node in enumerate(nodes)} ...
4cbf96bfde518fcd8d4f76fd0a002bf672568140
51,574
import math def rotate_around_point(xy, radians, origin=(0, 0)): """Rotate a point around a given point. I call this the "high performance" version since we're caching some values that are needed >1 time. It's less readable than the previous function but it's faster. """ x, y = xy off...
f4d2c5639b8ac8378ad1f7dafeaa6563350fe92a
51,575
from typing import Dict import re import os def map_ids_to_bounding_boxes( inkscape: str, xml: etree.Element, ) -> Dict[str, BoundingBox]: # noinspection SpellCheckingInspection """ Query an svg file for bounding-box dimensions :param inkscape: path to an inkscape executable on your local fil...
15a42905fcc98088e957d2351b30a64c9c634a09
51,576
def create_ensemble(datasets, mf_flag=False): """Create an xarray datset of ensemble of climate simulation from a list of netcdf files. Input data is concatenated along a newly created data dimension ('realization') Returns a xarray dataset object containing input data from the list of netcdf files concate...
45ae20e7d3dffc5b67efd99df2432baa57c89dcb
51,577
def isabs(s): """Test whether a path is absolute. """ return s.startswith('/')
c8d33faabd7a1ec0d5fc4902e2d271057037111c
51,578
import pandas import os def load_csv_as_dataframe(gcs_bucket, filename, dtype=None, chunksize=None, parse_dates=False, thousands=None): """Loads csv data from the provided gcs_bucket and filename to a DataFrame. Expects the data to be in csv format, with the first row as the colum...
c40ea4c1ca66c857b8ce93da5ec4f755b773dae7
51,579
import psutil def check_memory(): """Return True when less than 0.5gb RAM available""" mu = psutil.virtual_memory() # memory in GB GB_mem_free = mu.available/(2**30) stats["check_memory_wrap"] = (f"\n Total RAM available(in GB): {mu.total/(2**30):.2f}\n\ Available RAM(in GB): {GB_mem_free:.2f}") if GB...
2fc3703cfe62c61d4b556b959466a4f16d560bbb
51,580
def read_csv(fname, log = True, since_midnight = True): """Generates a single Peak instance from a file or list of files Arguments --------- fname: string or list of strings log: bool. If the actual or the log of the amplitude is given. If log is True the value in the file will be 10**amp ...
75ea31a66154e57e194290780a4f1512b9c86af2
51,581
def aer2geodetic(az, el, srange, lat0, lon0, h0, ell=None, deg=True): # type: (float, float, float, float, float, float, Ellipsoid, bool) -> tuple """ gives geodetic coordinates of a point with az, el, range from an observer at lat0, lon0, h0 Parameters ---------- az : float azimut...
c84d331a50aaaaca795e8814b79a540926f18d0b
51,582
async def play_game_human(client, player_id, realtime, game_time_limit): """Allow humans to play""" while True: state = await client.observation() if client.game_result: return client.game_result[player_id] if game_time_limit and (state.observation.observation.game_loop * 0.7...
1428a097f3c90fb07cce9c1865d351b90572912b
51,583
import binascii def random_secret_exponent(curve_order): """ Generates a random secret exponent. """ random_256bit_hex_string = binascii.hexlify(get_entropy(32)) random_256bit_int = int(random_256bit_hex_string, 16) int_secret_exponent = fit_number_in_range(random_256bit_int, 1, curve_order) retu...
42f95df6164647d6bdc376e91debba9bc5a2812f
51,584
import os def get_tile_num(fname, key='tile'): """ Given 'key' extract 'num' from 'key_num' in string. """ l = os.path.splitext(fname)[0].split('_') # fname -> list i = l.index(key) return int(l[i+1])
f0bd167bef38834609cda377aa7f28b06be79cac
51,585
def astype(value, types=None): """Return argument as one of types if possible.""" if value[0] in '\'"': return value[1:-1] if types is None: types = int, float, str for typ in types: try: return typ(value) except (ValueError, TypeError, UnicodeEncodeError): ...
47d066d9d4bb5b0b96216cc722c6896d6fdcf1a4
51,586
from functools import reduce import operator def adjlist_to_metis(adjlist, nodew=None, nodesz=None): """ Rudimentary adjacency list converter. Primarily of use if you don't have or don't want to use NetworkX. :param adjlist: A list of tuples. Each list element represents a node or vertex in the...
1b4854904ce40f2d03e76db78763639044bc167a
51,587
def _minmax(*args): """ Return the min and max of the input arguments """ min_ = min(*args) max_ = max(*args) return(min_, max_)
9985ebbffd3ee0b03dc751a3c90db00e922ab489
51,588
def find_variable(text, start): """ Return `(name, var_start, var_end)` or None. The variable may be of two forms: `$XYZ` or `{$XYZ}`. The latter is to be used when otherwise the variable name would be followed by a name character, which would make it ambiguous. """ result = None i = text....
35f8d0a1ead0abb54746399321e406fcb9d67b0b
51,589
def get_payday_leap_years( payday, frequency='biweekly', count=5, starting_year=date.today().year ): """Get the next n payday leap years. Return a list of the next n payday leap years, where n is specified by `count`. Args: payday (date): A payday from the specified pay calenda...
87808c0ee596005c2dd90db30b2cd168cf7ebf63
51,590
import json def output_message(message): """This function will output an error message formatted in JSON to display on the StatusBoard app""" output = json.dumps({"error": message}, indent=4) return output
06f9ed6350cfc9e721cfb1e24b9a695bff6d9ffe
51,591
def xslt(req, *opts): """ Transform the working document using an XSLT file. :param req: The request :param opts: Options (unused) :return: the transformation result Apply an XSLT stylesheet to the working document. The xslt pipe takes a set of keyword arguments. The only required argument is 'stylesheet' which i...
f224399ab7968bdf21930206959d59b66445611d
51,592
def _time_distributed_dense(x, w, b=None, dropout=None, input_dim=None, output_dim=None, timesteps=None, training=None): """Apply `y . w + b` for every temporal slice y of x. # Arguments x: input tensor. w: weight matrix. b: optiona...
8d81621ef720c9eed044f7d58c55030bdd9eea30
51,593
from typing import Callable import collections def build_scheduled_client_work( model_fn: Callable[[], model_lib.Model], learning_rate_fn: Callable[[int], float], optimizer_fn: Callable[[float], TFFOrKerasOptimizer], metrics_aggregator: Callable[[ model_lib.MetricFinalizersType, computation_ty...
a4e2c0b635ffab3cd781a8584aff0811b1d2bd4d
51,594
from typing import Set from typing import Iterator def filter_by_letterset(letters: Set[str], words_set: Iterator[str]) \ -> Iterator[str]: """ Filters the words in the dictionary by the letter-set. So, the set {'h', 'o', 'w'} will match 'how' and 'who' but not 'whom' Args: letters: Th...
a072c80c3bddf0f7ff06437c635f46f4b2e43c97
51,595
import copy def evaluate_confusion_matrix(y_true, y_pred, labels): """ Calculates a Confusion for each each of for y_true / y_pred and returns a formatted dictionary with the results. :param ndarray y_true: The (potentially multiple) observed targets :param ndarray y_pred: The (potentially multiple) ...
fa83931c085b147dd6c432bb45ba0a1eb773f0e7
51,596
from typing import Callable from typing import Optional from pydantic import BaseModel # noqa: E0611 def get_redirects(func_name: str, attr: str, redirect_from: Callable) -> Optional[BaseModel]: """Get an attribute :code:`attr` from function :code:`func_name` from context of :code:`redirect...
25a4bfc1e6872bcff45cb6b67b3cfde3e8e075bb
51,597
import msgpack def send_msgpack(socket, obj, flags=0, protocol=-1): """pickle an object, and zip the pickle before sending it""" p = msgpack.packb(obj, use_bin_type=True) return socket.send(p, flags=flags)
e80dee26986c4975b46e4527f8425e25cecf0621
51,598
import glob import os def decompile_apk_dir(apps_dir, out_dir=None): """depr""" apk_ls = glob(os.path.join(apps_dir, '*.apk')) assert all(apk.endswith('.apk') for apk in apk_ls) # count = 0 app_dir_ls = [] for apk_fn in apk_ls: try: app_dir, package = prep_dir_apk(apps_dir...
eced2c85775b586bf3ccc4bb8e48e4aeb4e4a643
51,599