content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import torch import colorsys def getAfinityCenter(width, height, point, center, radius=7, img_affinity=None): """ Function to create the affinity maps, e.g., vector maps pointing toward the object center. Args: width: image wight height: image height point: (x,y) ce...
5c25274809820f6318b9756680d2967ba8f08a5d
16,400
def unwrap_phase_iterative_fft(mat, iteration=4, win_for=None, win_back=None, weight_map=None): """ Unwrap a phase image using an iterative FFT-based method as described in Ref. [1]. Parameters ---------- mat : array_like 2D array. Wrapped phase-image in t...
e79bb72441379531f70d32d07c4e6e9299a39062
16,401
def wallunderground(idf, bsdobject, deletebsd=True, setto000=False): """return a wall:underground if bsdobject (buildingsurface:detailed) is an underground wall""" # ('WALL:UNDERGROUND', Wall, s.startswith('Ground')) # test if it is an underground wall if bsdobject.Surface_Type.upper() == 'WALL': #...
739ca431088f049323b64e80649e6b23930d1318
16,402
def canonical_order(match): """ It does not make sense to define a separate bond between atoms 1 and 2, and between atoms 2 and 1. This function will swap the atoms in the bond if the first atom > second atom. """ # match[0][0:2] contains the ID numbers for the 2 atoms in the match atom0 =...
ea268fedaa365e0fad3ea49944cc1d1bb5fa7a51
16,403
def grant_db_access_to_role(role, db): # pylint: disable=invalid-name """Grant the role 'database_name', returns grant permission.""" return grant_obj_permission_to_role(role, db, 'database_access')
5adb5f8f06473b20d6e7f386acb889631e042dde
16,404
import json def execute_compute_job(): """Call the execution of a workflow. --- tags: - services consumes: - application/json parameters: - name: consumerAddress in: query description: The consumer address. required: true type: string - name...
3601cc1f9001d23d07ded604f9fa241fe11cebd3
16,405
from typing import List from pathlib import Path def files_filter_ext(files: List[Path], ext: str) -> List[Path]: """Filter files from a list matching a extension. Args: files: List of files. ext: Extension to filter. Returns: List of files that have the extension. """ re...
0ed134583f9fa4868111d1475b8be4d67ba4feb7
16,406
import os import click def update(locale_dir, pot_dir, languages, line_width=76): """ Update specified language's po files from pot. :param unicode locale_dir: path for locale directory :param unicode pot_dir: path for pot directory :param tuple languages: languages to update po files :param ...
8c86444999323b0cbf63dbdfcf04781b4d893b12
16,407
import six def interp_to_grid(tran,v,expand_x=True,expand_y=True): """ Return dense matrix for X,Y and V (from v, or tran[v] if v is str) expand_x: defaults to 1 more value in the X dimension than in V, suitable for passing to pcolormesh. expand_y: defaults to 1 more value in the Y dimension than ...
324e42329588860d6fd45cfa06988f49e56ca504
16,408
def simulation(G, tau, gamma, rho, max_time, number_infected_before_release, release_number, background_inmate_turnover, stop_inflow_at_intervention, p, death_rate, percent_infected, percent_recovered, social_distance, social_distance_tau, initial_infected_list): """Runs a simulation o...
1f9ab389ce2f301266ce6d796c303cfbb5ab4b44
16,409
def relative(link : str): """Convert relative link to absolute""" return f"#{document.URL.split('#')[1]}/{link}"
5f00da06f5277b4a85512b49e9348d8d22949058
16,410
from typing import Tuple from typing import List def _get_axes_names(ndim: int) -> Tuple[List[str], List[str]]: """Get needed axes names given the number of dimensions. Parameters ---------- ndim : int Number of dimensions. Returns ------- axes : List[str] Axes names. ...
4f9dc40131443520a2f43c287b7d0ab1428a878f
16,411
def multi_replace(text, replace_dict): """Perform multiple replacements in one go using the replace dictionary in format: { 'search' : 'replace' } :param text: Text to replace :type text: `str` :param replace_dict: The replacement strings in a dict :type replace_dict: `dict` :return: `str` ...
dc902c988fa57cd9a3d7f4def6089b78d36664c8
16,412
def function_expr(fn: str, args_expr: str = "") -> str: """ DEPRECATED. Please do not add anything else here. In order to manipulate the query, create a QueryProcessor and register it into your dataset. Generate an expression for a given function name and an already-evaluated args expression. This ...
81fc9dc55c7602722303c2623d20aa88ce12f532
16,413
import subprocess def many_to_one(nrows=[1000], N=5, percentages=[0.025], p=0.5): """ """ def update_joinable_relation_rows(table1, nrows, selecivity_percentage, \ N, relation_from_percentage=-1, \ relation_to_percentage=-1): ...
782a1e60d67c3afaaa06871c68c2989502102d65
16,414
from typing import Sequence def distribute(tensor: np.ndarray, grid_shape: Sequence[int], pmap: bool = True) -> pxla.ShardedDeviceArray: """ Convert a numpy array into a ShardedDeviceArray (distributed according to `grid_shape`). It is assumed that the dimensions of `tensor` are ...
5e0ca59a23f1cde027769334a938e5855b17bf62
16,415
import os def input_files_exist(paths): """Ensure all the input files actually exist. Args: paths (list): List of paths. Returns: bool: True if they all exist, False otherwise. """ for path in paths: if not os.path.isfile(path): return False return True
7feba57335cdf435950bef1e01b9ab09c1b5f9c1
16,416
def predict(w, X): """ Returns a vector of predictions. """ return expit(X.dot(w))
c3bcb56cdd700ddf96124792b3f356644680e356
16,417
import argparse def get_argument_parser(): """ Parse CLI arguments and return a map of options. """ parser = argparse.ArgumentParser( description="DC/OS Install and Configuration Utility") mutual_exc = parser.add_mutually_exclusive_group() mutual_exc.add_argument( '--hash-pass...
8c2a635461c60b2d51ae8edeb0e102c15b91481a
16,418
def maskrgb_to_class(mask, class_map): """ decode rgb mask to classes using class map""" h, w, channels = mask.shape[0], mask.shape[1], mask.shape[2] mask_out = -1 * np.ones((h, w), dtype=int) for k in class_map: matches = np.zeros((h, w, channels), dtype=bool) for c in range(channels)...
0af4d42fc2dfba4d56bf990df222895b94b3002d
16,419
def translate_error_code(error_code): """ Return the related Cloud error code for a given device error code """ return (CLOUD_ERROR_CODES.get(error_code) if error_code in CLOUD_ERROR_CODES else error_code)
f6cc38b296b330811e932d3e7227d201ed09fe80
16,420
def generate_oi_quads(): """Return a list of quads representing a single OI, OLDInstance. """ old_instance, err = domain.construct_old_instance( slug='oka', name='Okanagan OLD', url='http://127.0.0.1:5679/oka', leader='', state=domain.NOT_SYNCED_STATE, is_auto...
6b3466e81014d14f88f17e855d726a608afda946
16,421
import torch def graph_intersection(pred_graph, truth_graph): """ Use sparse representation to compare the predicted graph and the truth graph so as to label the edges in the predicted graph to be 1 as true and 0 as false. """ array_size = max(pred_graph.max().item(), truth_graph.max().item())...
c63ae9cb52c9a55d54bfb5237c43b1998c51c482
16,422
import requests def get_qid_for_title(title): """ Gets the best Wikidata candidate from the title of the paper. """ api_call = f"https://www.wikidata.org/w/api.php?action=wbsearchentities&search={title}&language=en&format=json" api_result = requests.get(api_call).json() if api_result["success...
663db71c7a1bbf1617941ba81c5fa3b7d359e00b
16,423
def experiment(L, T, dL, dT, dLsystm = 0): """ Performs a g-measurement experiment Args: L: A vector of length measurements of the pendulum T: A vector of period measurements of the pendulum dL: The error in length measurement dT: The error in period measurement ...
cdf7384518fb92295675eb1b15bec883b50a450f
16,424
def find_jobs(schedd=None, attr_list=None, **constraints): """Query the condor queue for jobs matching the constraints Parameters ---------- schedd : `htcondor.Schedd`, optional open scheduler connection attr_list : `list` of `str` list of attributes to return for each job, default...
9a6a32002a945d186ea40c534dbc28805458cec2
16,425
def create_vocab(sequences, min_count, counts): """Generate character-to-idx mapping from list of sequences.""" vocab = {const.SOS: const.SOS_IDX, const.EOS: const.EOS_IDX, const.SEP: const.SEP_IDX} for seq in sequences: for token in seq: for char in token: i...
40ca7b3ed88d4134c2949223ec93ef871a18a8fb
16,426
def get_ind_sphere(mesh, ind_active, origin, radius): """Retreives the indices of a sphere object coordintes in a mesh.""" return ( (mesh.gridCC[ind_active, 0] <= origin[0] + radius) & (mesh.gridCC[ind_active, 0] >= origin[0] - radius) & (mesh.gridCC[ind_active, 1] <= origin...
9e246c3c0d3d7750a668476f0d0d90b28c46fc27
16,427
def find_frame_times(eegFile, signal_idx=-1, min_interval=40, every_n=1): """Find imaging frame times in LFP data using the pockels blanking signal. Due to inconsistencies in the fame signal, we look for local maxima. This avoids an arbitrary threshold that misses small spikes or includes two nearby tim...
7ed6a6a5b3d873132575ed5af1d9132d22e3898b
16,428
def _interpolate_signals(signals, sampling_times, verbose=False): """ Interpolate signals at given sampling times. """ # Reshape all signals to one-dimensional array object (e.g. AnalogSignal) for i, signal in enumerate(signals): if signal.ndim == 2: signals[i] = signal.flatten()...
b72d8b5bbd55fb70107e36c551cb558953baed50
16,429
def mean_standard_error_residuals(A, b): """ Mean squared error of the residuals. The sum of squared residuals divided by the residual degrees of freedom. """ n, k = A.shape ssr = sum_of_squared_residuals(A, b) return ssr / (n - k)
6860ea11b2f2af29c9b519ef692ee990d2aef149
16,430
def cel2gal(ra, dec): """ Convert celestial coordinates (J2000) to Galactic coordinates. (Much faster than astropy for small arrays.) Parameters ---------- ra : `numpy.array` dec : `numpy.array` Celestical Coordinates (in degrees) Returns ------- glon : `numpy.array` ...
b1185ce199c0f929c3395c452e619b93e2ee66a9
16,431
def index(request): """Renders main website with welcome message""" return render(request, 'mapper/welcome.html', {})
37194ef3ccc415c6db39f664bc819d7df1b9665a
16,432
def tidy_output(differences): """Format the output given by other functions properly.""" out = [] if differences: out.append("--ACLS--") out.append("User Path Port Protocol") for item in differences: #if item[2] != None: #En algunos casos salían procesos con puerto None out.append("%s %s %...
2a7007ae16e91b111f556ea95eedc466a8606494
16,433
from typing import Dict from typing import Collection def get_issues_overview_for(db_user: User, app_url: str) -> Dict[str, Collection]: """ Returns dictionary with keywords 'user' and 'others', which got lists with dicts with infos IMPORTANT: URL's are generated for the frontend! :param db_user: Use...
02ab5314a961a7fa398df2d43792fed1321939c6
16,434
def load_file(file): """Returns an AdblockRules object using the rules specified in file.""" with open(file) as f: rules = f.readlines() return AdblockRules(rules)
a9783ec4e8a195af688456af1949e33fd17d3cb7
16,435
def isSV0_QSO(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None, gsnr=None, rsnr=None, zsnr=None, w1snr=None, w2snr=None, dchisq=None, maskbits=None, objtype=None, primary=None): """Target Definition of an SV0-like QSO. Returns a boolean array. Parameters ---------- ...
f8be10f2d5d52ed0afd06a23cf7a9f1a98af1f25
16,436
def show_df_nans(df, columns=None, plot_width=10, plot_height=8): """ Input: df (pandas dataframe), collist (list) Output: seaborn heatmap plot Description: Create a data frame for features which may be nan. Set NaN values be 1 and numeric values to 0. Plots a heat map where dark squar...
5f93f78eee905c81c7178a2a6ed7167597d4964c
16,437
def nocheck(): """Test client for an app that ignores the IP and signature.""" app = flask.Flask(__name__) app.config['DEBUG'] = True app.config['VALIDATE_IP'] = False app.config['VALIDATE_SIGNATURE'] = False return app.test_client()
c2894b6e47e35ee548dd1ab229037f3fbc7c9efd
16,438
def evaluate_accuracy(file1, file2): """ evaluate accuracy """ count = 0 same_count = 0 f1 = open(file1, 'r') f2 = open(file2, 'r') while 1: line1 = f1.readline().strip('\n') line2 = f2.readline().strip('\n') if (not line1) or (not line2): break ...
52fdb8054de07fe53f77dd74317f18ed1dfbbb36
16,439
import os def find_files(top, exts): """Return a list of file paths with one of the given extensions. Args: top (str): The top level directory to search in. exts (tuple): a tuple of extensions to search for. Returns: a list of matching file paths. """ return [os.path.join(...
bb13d91b234b7411fd51e66fda96d5622ec11a1d
16,440
def add_hp_label(merged_annotations_column, label_type): """Adds prefix to annotation labels that identify the annotation as belonging to the provided label_type (e.g. 'h@' for host proteins). Parameters ---------- merged_annotations_column : array-like (pandas Series)) An array containing ...
648f548931a1fae5d19291d81f2355a0a00877c3
16,441
import sys import json def JsonObj(data): """ Returns json object from data """ try: if sys.version >= '3.0': return json.loads(str(data)) else: return compat_json(json.loads(str(data), object_hook=compat_json), ignore_dicts=True) ...
12929f620779057d46605c2e9fc67018675c1303
16,442
def _serialize_value( target_expr: str, value_expr: str, a_type: mapry.Type, auto_id: mapry.py.generate.AutoID, py: mapry.Py) -> str: """ Generate the code to serialize a value. The code serializes the ``value_expr`` into the ``target_expr``. :param target_expr: Python expression of th...
6ec6051715ca34771bf32582bb86280d58af27d3
16,443
def return_union_close(): """union of statements, close statement""" return " return __result"
c1a1b6b6b1164a641a7f9e598eec346af13f2aa7
16,444
from typing import Union from typing import List from typing import Tuple def parse_unchanged(value: Union[str, List[str]]) -> Tuple[bool, Union[str, List[str]]]: """Determine if a value is 'unchanged'. Args: value: value supplied by user """ unchanges = [ SETTING_UNCHANGED, s...
b4f1e155064c053fa1df65d242e920ae4ecf2fe5
16,445
def get_val(tup): """Get the value from an index-value pair""" return tup[1]
5966bbbb28006c46eaf11afaef152573aaaa8d2a
16,446
import os def get_slurm_job_nodes(): """Query the SLURM job environment for the number of nodes""" nodes = os.environ.get('SLURM_JOB_NUM_NODES') if nodes is None: nodes = os.environ.get('SLURM_NNODES') if nodes: return int(nodes) print("Warning: could not determine the number of no...
e7b53ee550eaf03363aa8f377f7f71f458cf3fd7
16,447
import os import subprocess def repoinit(testconfig, profiler=None): """Determines revision and sets up the repo. If given the profiler optional argument, wil init the profiler repo instead of the default one.""" revision = '' #Update the repo if profiler == "gnu-profiler": if testconfig.r...
b2348bb6ba6eb8284119a9b7bcbe162702338946
16,448
def lnprior_d(d,L=default_L): """ Expotentially declining prior. d, L in kpc (default L=0.5) """ if d < 0: return -np.inf return -np.log(2) - 3*np.log(L) + 2*np.log(d) - d/L
fd7cf591c5095fe8129662794b5c05235eda8941
16,449
def textile(text, **args): """This is Textile. Generates XHTML from a simple markup developed by Dean Allen. This function should be called like this: textile(text, head_offset=0, validate=0, sanitize=0, encoding='latin-1', output='ASCII') """ return Textiler(text).pro...
051f2aa254c2c24e80640b0779712d2154a1b67d
16,450
def binary_info_gain(df, feature, y): """ :param df: input dataframe :param feature: column to investigate :param y: column to predict :return: information gain from binary feature column """ return float(sum(np.logical_and(df[feature], df[y])))/len(df[feature])
8aa4bbb6997b913001074e15fcdefb5f6047cab3
16,451
def get_all_instances(region): """ Returns a list of all the type of instances, and their instances, managed by the scheduler """ ec2 = boto3.resource('ec2', region_name=region) rds = boto3.client('rds', region_name=region) return { 'EC2': [EC2Schedulable(ec2, i) for i in ec2.instan...
daf6c4cc71f19c7b94f625a283eeb59f4fcae10f
16,452
import warnings import asyncio def futures_navigating(urls: list, amap: bool = True) -> dict: """ 异步 基于 drive url list 通过请求高德接口 获得 路径规划结果 :param urls: :param amap: 开关 :return: """ data_collections = [None] * len(urls) pack_data_result = {} all_tasks = [] # 准备 with warnings....
4b65488f2c3ba7ac7ecc46a2da949c15bffbbf9b
16,453
def getdim(s): """If s is a representation of a vector, return the dimension.""" if len(s) > 4 and s[0] == "[" and s[-1] == "]": return len(splitargs(s[1:-1], ["(", "["], [")", "]"])) else: return 0
7ad62245ad2ebf7a262f6442ff209b819b1fa36e
16,454
import matplotlib import scipy from scipy import interpolate def unstruct2grid(coordinates, quantity, cellsize, k_nearest_neighbors=3, boundary=None, crop=True): """Convert unstructured model outputs into gridded arrays. ...
18953cce9808ba73513bbf3d1b277bc7e8913192
16,455
import csv import sys import json def users_bulk_update(file, set_fields, jump_to_index, jump_to_user, limit, workers): """ Bulk-update users from a CSV or Excel (.xlsx) file The CSV file *must* contain a "profile.login" OR an "id" column. All columns which do not contain a dot...
e2b172a1f7db08a9a52d334c3d5c706c5e410871
16,456
def numToString(num: int) -> str: """Write a number in base 36 and return it as a string :param num: number to encode :return: number encoded as a base-36 string """ base36 = '' while num: num, i = divmod(num, 36) base36 = BASE36_ALPHABET[i] + base36 return base36 or BASE36...
419759cdbe7b4e0dcf38c3f79f0de6dec4f84131
16,457
import math def cir(request): """ Return current cirplot """ config={ "markerSizeFactor": float(request.GET.get('marker-size-factor', 1)), "markerColorMap": request.GET.get('marker-color-map', 'winter'), "xAxisLabels": [ (math.radians(10), 'Kontra'), (...
6483521c929de9cf1fdfc3da2c32584cab83b6aa
16,458
def parse_enumeration(enumeration_bytes): """Parse enumeration_bytes into a list of test_ids.""" # If subunit v2 is available, use it. if bytestream_to_streamresult is not None: return _v2(enumeration_bytes) else: return _v1(enumeration_bytes)
ce7104f30eda416a59cb1397736886422af866fd
16,459
import re def register_user(username, passwd, email): # type: (str, str, str) -> Optional[str] """Returns an error message or None on success.""" if passwd == "": return "The password can't be empty!" if email: # validate the email only if it is provided result = validate_email_address(e...
d7960dc9c66ee584787b9a2b25f367fcbc7455e8
16,460
def _train_n_hmm(data: _Array, m_states: int, n_trails: int): """Trains ``n_trails`` HMMs each initialized with a random tpm. Args: data: Possibly unporcessed input data set. m_states: Number of states. n_trails: Number of trails. Returns: Best model regarding to log...
db5864ca45ac6fb939a0d1fd63fcb0b61e0ce6b9
16,461
def get_metric_function(name): """ Get a metric from the supported_sklearn_metric_functions dictionary. Parameters ---------- name : str The name of the metric to get. Returns ------- metric : function The metric function. """ if name in supported_sklearn_metric...
ba490650f55fd5d9a480fc9b9b94c5e71fefe23c
16,462
def ping(enode, count, destination, interval=None, quiet=False, shell=None): """ Perform a ping and parse the result. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param int count: Number of packets to send. :param str destination: The destination...
e9fce1819ea21ad801468653e534350e863e123b
16,463
def calculate_EHF_severity( T, T_p95_file=None, EHF_p85_file=None, T_p95_period=None, T_p95_dim=None, EHF_p85_period=None, EHF_p85_dim=None, rolling_dim="time", T_name="t_ref", ): """ Calculate the severity of the Excess Heat Factor index, defined as: EHF_severity = ...
e82d54f0bd67c5cd4c938dbdd335aed70fe3c521
16,464
import argparse def parse_args(): """Parse input arguments Return: parsed arguments struncture """ parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='type') subparsers.required = True parser_file = subparsers.add_parser('file') parser_file.add_argume...
bb2fe92206bd786492dda2668ffa9c2d0d54004e
16,465
from typing import Dict from typing import List from typing import Tuple def arrange_train_data(keypoints: Dict, beg_end_times: List[Tuple], fps: float, MAX_PERSONS: int) -> Dict: """ Arrange data into frames. Add gestures present or not based on time ranges. Generate each frame and also, add dummy when neces...
ef433809c5e59d2b870a84c9cfce9e31faa4659a
16,466
def length(list): """Return the number of items in the list.""" if list == (): return 0 else: _, tail = list return 1 + length(tail)
35864cd8cdd065463592d3737077a4d06b38aad1
16,467
def buzz(x): """ Takes an input `x` and checks to see if x is a number, and if so, also a multiple of 5. If it is both, return 'Buzz'. Otherwise, return the input. """ return 'Buzz' if isinstance(x, Number) and x % 5 == 0 else x
b24a37816d218a6cc1d960bfd767cb1a2052067d
16,468
from typing import Iterable from typing import Any from typing import Tuple def _tuple_of_big_endian_int(bit_groups: Iterable[Any]) -> Tuple[int, ...]: """Returns the big-endian integers specified by groups of bits. Args: bit_groups: Groups of descending bits, each specifying a big endian ...
78d3b739a8d8a3f724dca2b226e976cde93426dd
16,469
def make_simple_server(service, handler, host="localhost", port=9090): """Return a server of type TSimple Server. Based on thriftpy's make_server(), but return TSimpleServer instead of TThreadedServer. Since TSimpleServer's constructor doesn't accept kwargs...
42fc9f0bdcfbe4a509d5a682821ea3e71386f699
16,470
def morph(clm1, clm2, t, lmax): """Interpolate linearly the two sets of sph harm. coeeficients.""" clm = (1 - t) * clm1 + t * clm2 grid_reco = clm.expand(lmax=lmax) # cut "high frequency" components agrid_reco = grid_reco.to_array() pts = [] for i, longs in enumerate(agrid_reco): ilat =...
a6e6ca0070cc38b54f2bfd41b0fe69e2a5bb21f8
16,471
import re from typing import OrderedDict def read_avg_residuemap(infile): """ Read sequence definition from PSN avg file, returning sequence Map :param infile: File handle pointing to WORDOM avgpsn output file :return: Returns an internal.map.Map object mapping the .pdb residues to WORDOM id...
92c4cbe53edcd3d894a038d7cb9308c653e37146
16,472
import argparse import sys def get_arguments(): """Run argparse and return arguments.""" try: # Use argparse to handle devices as arguments description = 'htop like application for PostgreSQL replication ' + \ 'activity monitoring.' parser = argparse.ArgumentParse...
819981583720294a13a1babeb6aa60a9d4c536b1
16,473
def schedule_remove(retval=None): """ schedule(retval=stackless.current) -- switch to the next runnable tasklet. The return value for this call is retval, with the current tasklet as default. schedule_remove(retval=stackless.current) -- ditto, and remove self. """ _scheduler_remove(getcurren...
8ba10819d4de5cc676583e7b05036be49e6958cf
16,474
def check_region(read, pair, region): """ determine whether or not reads map to specific region of scaffold """ if region is False: return True for mapping in read, pair: if mapping is False: continue start, length = int(mapping[3]), len(mapping[9]) r = [s...
c71378d9ee674a117635634e3153f3cb7650fab3
16,475
import sys def create_template_AL_AR(phi, diff_coef, adv_coef, bc_top_type, bc_bot_type, dt, dx, N): """ creates 2 matrices for transport equation AL and AR Args: phi (TYPE): vector of porosity(phi) or 1-phi diff_coef (float): diffusion coefficient adv_coef (...
51b835ab2464189c8d0f10fae25da923f9fb6a07
16,476
def millisecond_to_clocktime(value): """Convert a millisecond time to internal GStreamer time.""" return value * Gst.MSECOND
8359b65a015febedba8bb6b68d310d70b1b8e1a6
16,477
def SE2_exp(v): """ SE2 matrix exponential """ theta, x, y = v if np.abs(theta) < 1e-6: A = 1 - theta**2/6 + theta**4/120 B = theta/2 - theta**3/24 + theta**5/720 else: A = np.sin(theta)/theta B = (1 - np.cos(theta))/theta V = np.array([[A, -B], [B, A]]) R...
f94454bf4b134fac7b45d89d4c3798b1d6c201fa
16,478
def skip_on_hw(func): """Test decorator for skipping tests which should not be run on HW.""" def decorator(f): def decorated(self, *args, **kwargs): if has_ci_ipus(): self.skipTest("Skipping test on HW") return f(self, *args, **kwargs) return decorated return decorator(func)
6cbde5ce9b70c9d9f71330470f5f2ae913f56021
16,479
def rxns4tag(tag, rdict=None, ver='1.7', wd=None): """ Get a list of all reactions with a given p/l tag Notes ----- - This function is useful, but update to GEOS-Chem flexchem ( in >v11) will make it redundent and therefore this is not being maintained. """ # --- get reaction dictionar...
32243bcdb66c9320679d580da2b6f9ee086179d2
16,480
def DateTime_GetCurrentYear(*args, **kwargs): """DateTime_GetCurrentYear(int cal=Gregorian) -> int""" return _misc_.DateTime_GetCurrentYear(*args, **kwargs)
5f25e4387e72497673ea49d6f67f06e9894e29af
16,481
def exp_lr_scheduler(optimizer, epoch, init_lr=0.01, lr_decay_epoch=10): """Decay learning rate by a f# model_out_path ="./model/W_epoch_{}.pth".format(epoch) # torch.save(model_W, model_out_path) actor of 0.1 every lr_decay_epoch epochs.""" lr = init_lr * (0.8**(epoch // lr_decay_epoch)) ...
2095eda8493e0e53bca5e6f1b9149b544c34da61
16,482
def wait(duration): """ Waits the duration, in seconds, you specify. Args: duration (:any:`DoubleValue`): time, in seconds, this function waits. You may specify fractions of seconds. Returns: float: actual seconds waited. This wait is non-blocking, so other tasks will run while th...
0a40028bbe88d290cc309dc94ef7be48522ded02
16,483
from datetime import datetime def yesterday_handler(update: Update, context: CallbackContext): """ Diary content upload handler. Uploads incoming messages to db as a note for yesterday. """ # get user timezone user_timezone = Dao.get_user_timezone(update.effective_user) # calculate time at use...
7b37d1157fc40ec01703aac92a5b176d14ab2f27
16,484
def get_lens_pos(sequence): """ Calculate positions of lenses. Returns ------- List of tuples with index and position of OPE in sequence. """ d = 0.0 d_ = [] for idx, ope in enumerate(sequence): if ope.is_lens(): d_.append((idx, d)) else: d +=...
f1f1ebb4212406e78e48613584f67f5e2b6f2265
16,485
def disorientation(orientation_matrix, orientation_matrix1, crystal_structure=None): """Compute the disorientation another crystal orientation. Considering all the possible crystal symmetries, the disorientation is defined as the combination of the minimum misorientation angle and the misorientation ax...
eefca78d7736de073646c97190f736bedb302136
16,486
from re import DEBUG def response_minify(response): """ minify html response to decrease site traffic """ if not DEBUG and response.content_type == u'text/html; charset=utf-8': response.set_data( minify(response.get_data(as_text=True)) ) return response return ...
f766a6afe2bd7113ea630db739cab21a0ce9b1f8
16,487
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" label_map = {label : i for i, label in enumerate(label_list,1)} features = [] for (ex_index, example) in enumerate(examples): # example : InputExample obj t...
5d844b9d88fa7bbd5532547b772fef9c1811e039
16,488
def to_json_compatible_object(obj): """ This function returns a representation of a UAVCAN structure (message, request, or response), or a DSDL entity (array or primitive), or a UAVCAN transfer, as a structure easily able to be transformed into json or json-like serialization Args: obj: ...
131fa3a43abf55fd0f51b1e3160ba2f1486d2e25
16,489
def rot_box_kalman_filter(initial_state, Q_std, R_std): """ Tracks a 2D rectangular object (e.g. a bounding box) whose state includes position, centroid velocity, dimensions, and rotation angle. Parameters ---------- initial_state : sequence of floats [x, vx, y, vy, w, h, phi] Q_std...
ac0bca07b6d7b08c3b27439855fac93bddffcb91
16,490
def validate_schema(path, schema_type): """Validate a single file against its schema""" if schema_type not in _VALID_SCHEMA_TYPES.keys(): raise ValueError(f"No validation schema found for '{schema_type}'") return globals()["validate_" + schema_type](path)
8883226eff948de2b05d442157818ab0b3904e47
16,491
def import_vote_internal(vote, principal, file, mimetype): """ Tries to import the given csv, xls or xlsx file. This is the format used by onegov.ballot.Vote.export(). This function is typically called automatically every few minutes during an election day - we use bulk inserts to speed up the import....
03eacf90418fd68bcf24c0a731f2d1216beb786b
16,492
def get_mail_count(imap, mailbox_list): """ Gets the total number of emails on specified account. Args: imap <imaplib.IMAP4_SSL>: the account to check mailbox_list [<str>]: a list of mailboxes Must be surrounded by double quotes Returns: <int>: total emails """ ...
8c8fd2d6849d58860f3bd6c20335e7a399bee99d
16,493
def get_bdb_path_by_shoulder_model(shoulder_model, root_path=None): """Get the path to a BerkeleyDB minter file in a minter directory hierarchy. The path may or may not exist. The caller may be obtaining the path in which to create a new minter, so the path is not checked. Args: shoulder_model...
c694306d18ed940cf229a46dae6fb72d2207418e
16,494
def getDefuzzificationMethod(name): """Get an instance of a defuzzification method with given name. Normally looks into the fuzzy.defuzzify package for a suitable class. """ m = __import__("fuzzy.defuzzify."+name, fromlist=[name]) c = m.__dict__[name] return c()
c3306ba9fc4ce21eae9adb1bde1b04505dd6b24f
16,495
def celestial(func): """ Transform a point x from cartesian coordinates to celestial coordinates and returns the function evaluated at the probit point y """ def f_transf(ref, x, *args, **kwargs): y = cartesian_to_celestial(x) return func(ref, y, *args) return f_transf
e6980abfbc0833639b9d1eb716633d1c6d6dcda2
16,496
def _rescale_to_width( img: Image, target_width: int): """Helper function to rescale image to `target_width`. Parameters ---------- img : PIL.Image Input image object to be rescaled. target_width : int Target width (in pixels) for rescaling. Returns ------- ...
38efe7bbbd1681abfd2d48bcf4765b817a28fa27
16,497
def compute_exact_R_P(final_patterns, centones_tab): """ Function tha computes Recall and Precision with exact matches """ true = 0 for tab in final_patterns: for centon in centones_tab[tab]: check = False for p in final_patterns[tab]: if centon == p: ...
d82e6fccacdc09bb078d6e954150c143994df1ca
16,498
def build_embedding(embedding_matrix, max_len, name): """ Build embedding by lda :param max_len: :param name: :return: """ # build embedding with initial weights topic_emmd = Embedding(embedding_matrix.shape[0], embedding_matrix.shape[1], wei...
87a89462bfb2eee285099353f78e151394c7c74a
16,499