content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import argparse def get_argument_parser(): """Set up command line arguments and usage.""" parser = argparse.ArgumentParser() parser.add_argument( 'location', type=str, help='file or directory containing unit tests' ) parser.add_argument( '--pattern', '-p', default='^(test_.*|.*_test...
0b60c62918693fe2c1a246c2461fe8a63749ef26
53,800
from pathlib import Path import tempfile import os def plotVisibility(xi, yi, zi, save_dir='.'): """ 功能: 绘制能见度等值线 输入: xi: 插值格点后的经向numpy array yi: 插值格点后的纬向numpy array zi: 经过matplotlib.mlab.griddata插值后的二维numpy array 输出: save_dir/tem...
e1ba2288122a36c164d4427fe72d2ea238c3e583
53,801
def get_mentored_team(mentor, hackathon): """ Retrieve all mentored teams for a Judge at a Hackathon """ mentored_teams = None mentored_teams = mentor.mentored_teams.filter( hackathon=hackathon).order_by('display_name') return mentored_teams
de6e25b3c116b4bca4c4559b3a204d46ed5b38ba
53,802
def get_ranges(uid_number, inc=0): """ Return two block ranges to be used to create subnets for Atmosphere users. NOTE: If you change MAX_SUBNET then you should likely change the related math. """ MAX_SUBNET = 4064 # Note 16 * 256 n = uid_number % MAX_SUBNET # 16-31 block1 = (...
b364a9051a8c8a9ea68dcee76fc7b993e30c13af
53,803
def returnRectangles(a,x): """ Returns 2D discrete integral array using the rectangle method The calculation for each array element is :math:`(\Delta y_i = 0.5(a_{n-1}+a_{n})*(x_{n-1}-x_{n})` Parameters ---------- a : numpy.ndarray Description: Array of y(x) function with N+1 elements ...
dd9931bcc2eae7d6712d4e809b23e3145ee4555b
53,804
import requests import re def google(query: str, suggestion_count: int = 0) -> bool: """Uses Google's search engine parser and gets the first result that shows up on a Google search. Notes: - If it is unable to get the result, Jarvis sends a request to ``suggestqueries.google.com`` - This is ...
50ca2f22a7f13323438b80f9a7b76d3a74697ce3
53,805
def strip_id(url): """Get MP database ID from url.""" url = url.split('/') return url[-2]
fa4ae6a3f58067b99fd5f89a2d1f10b49bc27f5e
53,806
from typing import Any from pathlib import Path import json def load_json_fixture(filename: str) -> Any: """Load a json fixture.""" path = Path(Path(__file__).parent.joinpath("fixtures"), filename) return json.loads(path.read_text(encoding="utf-8"))
262a0466cdf225c12046cc573fce781c2cfea17d
53,807
from typing import List def extract_notes_from_midi(midi_file: music21.stream.Stream) -> List: """ This function extract all the notes out of the midi files in the signed data path :param midi_file: Midi file :return: return list of notes out of the midi files """ notes = [] parts = musi...
bd439b0b3b5810837b3bca52b420b26eecf76ec7
53,808
def find_channel(channel_name, source): """ Search for channel by name on the given object """ name = channel_name.lower() for channel in source.channels: if channel.name.lower() == name: return channel return None
2b9feb9f60986392137deb6c8364e6c2d7e5efd4
53,809
import os def render_file(path: str): """ Route for getting either a supporting file or the root index.html file for the UI :param path: the path requested for a UI file to render, note this is a catch all, so may improperly catch other misspelled routes and therefore fail to render them ...
c36cdbd0411471820567d61acb93dfedc2516a93
53,810
import requests def get_device_status(host): """ :param host: Hostname or ip to fetch status from :type host: str :return: The device status as a named tuple. :rtype: pychromecast.dial.DeviceStatus or None """ try: req = CC_SESSION.get( FORMAT_BASE_URL.format(host) + "...
427a79319a44d2b6d59488c0e5bd0e8eb3c78243
53,811
def delta_V(V_0, V_f, beta_0, inc_0, inc_f): """Compute required increment of velocity.""" delta_i_f = abs(inc_f - inc_0) if delta_i_f == 0: return abs(V_f - V_0) return V_0 * np.cos(beta_0) - V_0 * np.sin(beta_0) / np.tan( np.pi / 2 * delta_i_f + beta_0 )
384be9dfe213bcbaea87efdc4849365fc8414543
53,812
from typing import Optional def depth_first_solve(puzzle: SudokuPuzzle) -> Optional[SudokuPuzzle]: """ An iterative depth first search to solve the puzzle. """ if puzzle.is_solved(): return puzzle puzzle_queue = puzzle.extensions() while puzzle_queue: curr = puzzle_queue.pop() ...
3ea46ee715fc9b68b74e3254ab39ed53d8c4f8cc
53,813
def quicksort_recursive(arr): """ 1. Pick a random element arr[pivotindx] as pivot 2. Construct three arrays (a) less: all values < arr[pivotindx] (b) same: all values = arr[pivotindx] (c) more: all values > arr[pivotindx] 3. recursively apply function to less and more """ ...
50ab23a865b2de57e6e0b4278e4378d3615af801
53,814
import os def Interp_doppler_savememory(grid, wteff, wlogg, wmu, wwav, jteff, jlogg, jmu, jwav, mu_grid, area, val_mu): """ Simple interpolation of an atmosphere grid having axes (logtemp, logg, wav). This grid interpolation is made for a grid which is linear in the velocity or redshift space, e.g. l...
9e9e33299712142c1592a37960bd8cc56e0f9958
53,815
def conf(db, context, log, fields): """Perform CONF command. This is supposed to adjust the configuration of the Crusher database. """ """Configure the database.""" db.configure(fields[1]) """Copy the configuration command to the log.""" log.write("{}\t{}\n".format(fields[0], fields[1])) ...
89ac0019a1b2beccc6852f57616239a776575be2
53,816
def sample_diversity(labels, features, max_to_return=20): """ Attempt to create a diverse, model-independent sample of images to tag. PCA-reduce feature vectors an then use k-means for sampling. :features: (num_samples, input_dim) array of feature vectors :max_to_return: if not None; max nu...
9067bd43e482b4fa99f217f8819db7ef7ef55279
53,817
def validate(filters): """ Validation of function parameters """ def decorator(f): @wraps(f) def wrapper(request, data): _strip(data) data = _check(data, filters) return f(request, data) return wrapper return decorator
3222777dc6e71404019d056a87854908fbfed640
53,818
from typing import Optional def clean_decimal_2(text: Text) -> Optional[Decimal]: """ Remove $ and , from a string, return a Decimal. >>> clean_decimal_2("$1,234.56") Decimal('1234.56') """ if text is None: return None return Decimal(replace(replace(text, "$", ""), ",", ""))
4624eac5796e1e12a2161271cae6f88b8cfc14b2
53,819
def make_san_mask(xs, xlens, unidirectional=False, lookahead=0): """Mask self-attention mask. Args: xs (FloatTensor): `[B, T, d_model]` xlens (InteTensor): `[B]` (on CPU) unidirectional (bool): pad future context lookahead (int): lookahead frame Returns: xx_mask (Byt...
04e1ec3f6103ad4ddd701024225e2b4e7b27feae
53,820
def calc_R_sq_adj(var_basis, matrix_coeffs, responses): """ Inputs: var_basis- evaluated variable basis matrix_coeffs- matrix coefficients responses- vector of responses Calculates the adjusted R squared statistic for the given system. Design and Analysis of Experiments...
bab62b0b58b5d0b9e2d94231af2262fe6b70d71a
53,821
def assert_submission_id(method): """Decorate `method` to guard against unset submission ID. """ @wraps(method) def wrapped(self, *args, **kwds): if not self.submission_id: lgr.warning("Cannot check status without a submission ID") return "unknown", None return m...
6421b7857e868b602ce23e473895bc2668d8a16c
53,822
def a08_curve_function(curve: CustomCurve): """ Computes the lower and upper bound of class number of the maximal order of the endomorphism algebra Upper bound: Inequality class number<= sqrt(d)*log(d)*constant (see below) #https://en.wikipedia.org/wiki/Class_number_formula#Dirichlet_class_number_f...
e784ca6ad1c5a1a744b1b1043b639097579b57ca
53,823
def arithmatex_fenced_format(**kwargs): """Specify which type of formatter you want and the wrapping tag.""" mode = kwargs.get('mode', 'generic') tag = kwargs.get('tag', 'div') preview = kwargs.get('preview', False) if mode == 'generic': return partial(_fence_generic_format, tag=tag) e...
e54b44f7fb16383fbca9902eb1c0efbfcc90f191
53,824
from skimage.morphology import reconstruction def fill_holes(image, thresh=0.001): """Fill holes in a binary image Args: image: thresh: Returns: """ seed = np.copy(image) seed[1:-1, 1:-1] = image.max() mask = image filled = reconstruction(seed, mask, method='erosio...
0336614a4337a23a3e77288cef01d12f0732dc4f
53,825
import argparse def get_search_args() -> None: """Parse command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "exec_fname", metavar="C", type=str, default="main.py", help="Filename to import `main(config)` function from.", ) pars...
be42a2435bf8af6b7733a2589954761c6bb1d215
53,826
def _allreduce(tensor, name=None): """An op which reduces an input tensor over all the Bluefog processes. The default reduction is a sum. The reduction operation is keyed by the name of the op. The tensor type and shape must be the same on all Bluefog processes for a given name. The reduction will ...
b30141cf359dc3934242a570703d9b35183e0215
53,827
def bbox_transform_inv(boxes, deltas, mean=None, std=None): """ Applies deltas (usually regression results) to boxes (usually anchors). Before applying the deltas to the boxes, the normalization that was previously applied (in the generator) has to be removed. The mean and std are the mean and std as appli...
dc853f3fda3f4ec7533eda95b086c30944261136
53,828
def make_custom_entity( device: hm_device.HmDevice, address: str, custom_entity_class: type, device_enum: EntityDefinition, group_base_channels: list[int], ) -> list[hm_entity.BaseEntity]: """ Creates custom_entities. We use a helper-function to avoid raising exceptions during object-ini...
a244c8ea4a3975368b134e79ea433a5aa3ab64c3
53,829
import os def classroom_add_student_new(course_id): """ Adds a student to a course, the teacher has access to. The file token.json stores the user's access and refresh tokens, and is created automatically when the authorization flow completes for the first time. Load pre-authorized user creden...
04be03dec89bf4d80688ae68d0328699c04568f6
53,830
import uuid def gru_with_backend_selection(inputs, init_h, kernel, recurrent_kernel, bias, mask, time_major, go_backwards, sequence_lengths, zero_output_for_mask, return_sequences): """Call the GRU with optimized backend kernel selection. Under the ho...
c089b080baabbdba39004dc4694e11ac15e5f52b
53,831
def pull_csvs(glob_mask: str = '*.csv'): """ This convenience function loads the maternity csvs. I've made it add the file name as some of the files have columns that are all over the place. It combines the csvs into a dataframe end on end. :param glob_mask: str this should be a glob expression ...
99f9e7433d5c090c31789927a523ebbe6ab08bce
53,832
def gaussian(x, a, x0, sigma,c): """ gaussian function for fitting """ return a * np.exp(-(x-x0)**2/(2*sigma**2)) + c
5153de29b24aae695fd4d8a9ed9639b1c0fca676
53,833
def spectrum_selection(pth, oms_list, requested_m, requested_n=None): """ collects spectrum availability and call the select_candidate function # step 1 collects pth spectrum availability # step 2 if n is not None try to assign the spectrum # if the spectrum is not available then sends back a...
083090e8a110592395c3df3d80e72b7dd45071ba
53,834
def graph_BFS(graph, start): """ My Python implementation of BFS for a graph Traverses a graph from a starting vertex and returns an array of the vertices in traversal order Time complexity: O(V + E), V = Number of vertices, E = Number of edges Space complexity: O(V) """ # Track BFS traversal ...
2897d6c90c5f585f10b84908e1c99be6b5c590bc
53,835
from typing import Optional def to_sparse_tensor(edge_index: Tensor, edge_weight: Optional[Tensor] = None, num_nodes: Optional[int] = None, is_sorted: bool = False) -> SparseTensor: """Convert edge index to a torch_sparse sparse tensor Parameters ---------- edge_index : Tensor ...
71b9b0acbfe1104554a55abfc923bcc73f2943ee
53,836
def get_metadata(data): """Gets metadata from the input cloutformation file content.""" return data['Metadata']
5fed88a19704430272b73751938f34a3a7a09d8d
53,837
def cross_count_helper(df, i): """ tools for multy thread bi_count """ name = "count_"+ '_'.join(i) df[name] = df.groupby(i)[i[0]].transform('count') return df[[name]].fillna(-99999).astype(np.int32)
326dce19961bf5113015946494c9eac539f4f8f3
53,838
import itertools def _convert_path(element): """ Convert an OSM way element into the format for a networkx path. Parameters ---------- element : dict an OSM way element Returns ------- path : dict """ path = {"osmid": element["id"]} # remove any consecutive dupli...
2829643db7c237f22f72c3a01fbb83ed20c22ba2
53,839
def spike(time, flux): """ Function to calculate the metric called "spike" for K2 objects. When spike > 1.0, the object is said to have bad arc drift. args time : time reference for light curve (seconds) flux : flux of light curve returns spike : spike metric """ ...
2b46d6a257d271eec63ffeaa97a608841777d99b
53,840
def prv_axis(dcm): """compute the principle rotation vector from a dcm :param dcm: direction cosine matrix to extract rotation vector from :return evec: principle rotation vector (eigvec corres. to the eigval of +1) :return phi: magnitude of the angle of rotation (radi...
62924f472615792e25b3edb6b345f76adbc53c00
53,841
from typing import List from typing import Union from typing import Generator def knuth_plass_breaks(paragraph:List[Spec], line_lengths:Union[List[Num], Num, \ Generator[Num, None, None]], # l1, l2,... in the paper looseness:int=0, # q in the paper tolerance...
8161ce4d0bfab654b907acf4b6dda6a211d3d7fe
53,842
from typing import List def most_repeatable_cycles(data: np.ndarray, /) -> List[int]: """ Get the indexes of the most repeatable cycles in TimeSeries or array. This function returns an ordered list of the most repeatable to the least repeatable cycles. It works by recursively discarding the cycl...
75169438028b48d7dae5238b9e06c76e64ad20aa
53,843
import typing async def guild_create(client: "Client", gateway: "Gateway", event: "GatewayDispatch") -> typing.List[typing.Awaitable]: """ |coro| This event is called when a guild is created. It does see whether the guild is cached and if not, it caches it. Parameters ----...
ca97f0d5a6ac0cd534f44481fdf3a14ba89d7558
53,844
import torch import scipy def topographic_similarity(utts: torch.Tensor, labels: torch.Tensor, max_samples=10000): """ (quoting Angeliki 2018) "The intuition behind this measure is that semantically similar objects should have similar messages." a and b should be discrete; 2-dimensional. with item in...
ca56c612d4c6bcc061111db60ce44ff8ff841329
53,845
import csv def _split_file(header, path, dialect=None, list_columns=None, list_separator=None, encoding='utf-8'): """Split a CSV file into columns, one column per file. :arg str header: The names for each column of the file. :arg str path: The full path to the file. :arg Dialect diale...
5653993d8350836effa5428a3c5a4a058bd37b8d
53,846
def run_evaluation_with_invocab(query_mat, query_words, corpus_mat, corpus_words, train_vocab, drop_first=False): """ Same as run_evaluation, but also saving separate statistics for in vocabulary queries. """ num_queries = len(query_mat) log.d("Running {} queries...".format(num_queries)) recall ...
ba59bbbdea0ba225cfec6a50915ab2a816d8fbc7
53,847
def dicttonx( treedict, h5file, h5path="/", mode="w", overwrite_data=False, create_dataset_args=None, ): """ Write a nested dictionary to a HDF5 file, using string keys as member names. The NeXus convention is used to identify attributes with ``"@"`` character, therefor the datas...
14823b316c96c8e334726adafd1a372c33c2191e
53,848
def init_actions_(service, args): """ This needs to return an array of actions representing the depencies between actions. Looks at ACTION_DEPS in this module for an example of what is expected """ # some default logic for simple actions return { 'test': ['install'] }
7954f5a204d31a8c0f8dd6bf586a93e7bf3a52c7
53,849
def eff_pol(suc, disch): """Polytropic efficiency. Parameters ---------- suc : ccp.State Suction state. disch : ccp.State Discharge state. Returns ------- eff_pol : pint.Quantity Polytropic efficiency (dimensionless). """ wp = head_pol(suc, disch) ...
1f4af07f7bb613b4e12b45be45303eadc2c173d8
53,850
def get_l16_config(): """Returns the ViT-L/16 configuration.""" config = ml_collections.ConfigDict() config.name = 'ViT-L_16' config.patches = ml_collections.ConfigDict({'size': (16, 16)}) config.hidden_size = 1024 config.transformer = ml_collections.ConfigDict() config.transformer.mlp_dim = 4096 config...
f552f1a9566826b223ea7dbf3338dc01830e9300
53,851
def get_featurizer(name, **kwargs): """Put new featurizers here! """ if name == "tabular": return TabularFeaturizer(**kwargs) if name == "propositional": return PropositionalFeaturizer(**kwargs) if name == 'SARState': return SARStateFeaturizer(**kwargs) if name == 'SAR...
fcedffc7071e7efce03ffe1e314b5244ab8d41c2
53,852
import socket def get_ip_and_port(): """The network information function. """ s = socket.socket( family=socket.AF_INET, type=socket.SOCK_DGRAM, proto=0, fileno=None) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 0) s.connect(('<broadcast>', 0)) ip, port ...
e26e2b7462eedb967380c163f8d848b0e00df369
53,853
import os import cv2 import random def prepare_input(imagePaths, img_size): """ Prepare input IA: not for production """ GRAY_SCALE_VEC = False if GRAY_SCALE_VEC: print(">ia> Converting to grayscale ...") # initialize the data and labels print(">ia> Loading images...") da...
af831c9ae2b5c5196de00c9cbfea68c46a568a6e
53,854
import json def get_dict(db,name): """ Retrieve python dictionary stored in redis database as json string. """ data_json = db.get(name) data_dict = json.loads(data_json,object_hook=json_tools.decode_dict) return data_dict
591b2ed32640caa67796d82200be80778bb24dee
53,855
import json def sentinel2_get_info(bucket, scene_path, request_pays=False): """Get sentinel-2 metadata.""" data = json.loads( aws.get_object(bucket, f"{scene_path}/tileInfo.json", request_pays=request_pays) ) return { "sat": data["productName"][0:3], "coverage": data.get("dataC...
afc159fd0806b988ff934f4882ae2b3b2f69b674
53,856
def svn_wc_prop_set(*args): """ svn_wc_prop_set(char const * name, svn_string_t const * value, char const * path, svn_wc_adm_access_t * adm_access, apr_pool_t pool) -> svn_error_t """ return _wc.svn_wc_prop_set(*args)
b1b014149c05a7737032fbeb3f74e026c2e90b4f
53,857
import pytz def to_naive_utc(dtime): """convert a datetime object to UTC and than remove the tzinfo, if datetime is naive already, return it """ if not hasattr(dtime, 'tzinfo') or dtime.tzinfo is None: return dtime dtime_utc = dtime.astimezone(pytz.UTC) dtime_naive = dtime_utc.replace...
4d76ef2a3a5f11efeeedb9f920bc15b55c996da3
53,858
def revise_item(ebay_id, site_id=HOME_SITE_ID, item_dict=None): """Perform a ReviseItem call.""" revise_dict = {'Item': item_dict or {}} revise_dict['Item']['ItemID'] = ebay_id try: # Initialize TradingAPI api = get_trading_api(site_id=site_id, api_call='ReviseItem', ...
41beb993be2ea381a2578e9fae5a3436d670e3bf
53,859
def closing(managed): """ If the managed object already provides its own context management via the __enter__ and __exit__ methods, it is returned unchanged. However, if the instance does not, a ClosingContext will be created to wrap it. When the ClosingContext exits, it will call managed.close(...
9c33c7167344663708f9102e376001a6024d25e4
53,860
import os def compute_spearman_distance(election_1: OrdinalElection, election_2: OrdinalElection) -> int: """ Compute Spearman distance between elections """ votes_1 = election_1.votes votes_2 = election_2.votes params = {'voters': election_1.num_voters, 'candidates': election_1.num_candidates} ...
797d7ebed7ad85987bf71a1d43c98b36604615f6
53,861
import sys import os def dfSegsNodesNDataDpkt( VersionsDir=r"C:\3s\Projekte\Projekt\04 - Versionen\Version82.3" ,Model=r"MDBDOC\FBG.mdb" # a Access Model ,am=None # a Access Model already processed ,SEGsDefPattern='(?P<SEG_Ki>\S+)~(?P<SEG_Kk>\S+)$' # RSLW-Beschreibung: liefert die Knotennamen der Se...
d566ed0ede6b62865a464e8270b5a66c9553be39
53,862
def conv2d_direct(*args, **kwargs): """Schedule function for directly-scheduled conv2d.""" assert not kwargs, "Do not support kwargs in template function call" args = deserialize_args(args) data, kernel = args[:2] layout = args[-2] cfg = autotvm.get_config() args = [cfg] + args conv = co...
0ffecea7097813eb2d4c6284062dbf6be187a93c
53,863
def Image_Cmc(gallery_features, gallery_ids, gallery_cams, query_features, query_ids, query_cams, rank_size): """ features: numpy array of shape (n, d) label`s: numpy array of shape (n) """ # Sample query data = {'feature':gallery_features, 'id':gallery_ids, 'cam':gallery_cams} g_idx = np.ar...
168e82f139da8456053fb4e76b49d22a58d66918
53,864
def create_dummy_class(klass, dependency): """ When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. Returns: class: a class object """ clas...
8a231524743ebcf4f632d450f98d5b1e90f2e7ff
53,865
import subprocess def persistent_ios_simulator(simctl_path, minimum_os, sim_device, sim_os_version): """Finds or creates a persistent compatible iOS simulator. Boots the simulator if needed. Does not shut down or delete the simulator when done. Args: simctl_path: The path to...
bcacc8d6a2b96ee5a5bb74b291b1553630a834f8
53,866
import ctypes import marshal def loads_function(s): """Restores a function serialized with :func:`dumps_function`.""" name, code, globals_, defaults, closure, func_dict, doc, qualname, kwdefaults, annotations = loads(s) code = marshal.loads(code) for k, v in globals_.items(): if isinstance(v, ...
c2f4dc62d998a61254aea0890b722a4c99dd175c
53,867
def convert_single_example(ex_index, example, max_seq_length, tokenizer): """Converts a single `InputExample` into a single `InputFeatures`.""" tokens = tokenizer.tokenize(example.text) # Account for [CLS] and [SEP] with "- 2" if len(tokens) > max_seq_length - 2: tokens = tokens[...
7739f25633083fa89b09121d55ec24c4087d4074
53,868
def load(repo_dir: str, repo_url: str) -> t.Optional[RepoUtil]: """ Load git repository from local directory into Python object. :param repo_dir: (str) directory where .git file is located :param repo_url: (str) url to Github repository """ repo = RepoUtil(repo_url) try: repo....
bfd1a8dc5d1b14b7d9c1f14f5a67b03aa90a1fd2
53,869
import re def loads(s, bqm): """Load a COOrdinate formatted binary quadratic model from a string.""" pattern = re.compile(_LINE_REGEX) for line in s.split('\n'): match = pattern.search(line) if match is not None: u, v, bias = int(match.group(1)), int(match.group(2)), float(ma...
785b045d5bfd48cab44c74c78b5b8179a46643bb
53,870
def remove_duplicate_joints(seq): """ :param seq: [n_frames x 96] """ n_frames = len(seq) if len(seq.shape) == 2: assert seq.shape[1] == 96, str(seq.shape) seq = seq.reshape((n_frames, 32, 3)) assert len(seq.shape) == 3, str(seq.shape) valid_jids = [ 0, 1, 2, 3, 4, 5,...
7c69d9bb04a8683e512d2fbcb25ec05d6681e5c6
53,871
def strip_non_printing(text): """Removes non-printing (including control) characters from text. (same as moses script). """ return ''.join([c for c in text if c.isprintable()])
c38290e6bb59b6dabd7dc0892c2501eaa2f02ead
53,872
def ntp_bottle_to_cast( sB, tB, pB, S, T, P, tol_p=1e-4, interp="linear", eos="gsw", grav=None, rho_c=None, ): """Find the neutral tangent plane from a bottle to a cast Finds a point on the cast salinity, temperature, and pressure `(S, T, P)` where the salinity, ...
edb0ef1655e3f414ae7f545370433586197318e7
53,873
from pathlib import Path def polyline(*points): """Converts a list of points to a Path composed of lines connecting those points (i.e. a linear spline or polyline). See also `polygon()`.""" return Path(*[Line(points[i], points[i+1]) for i in range(len(points) - 1)])
cf195cedaceafe0aeded1269c84a1e62e7919963
53,874
from operator import concat def transfer(alias, sub_nas, args): """ :param alias: :param sub_nas: \n:param args [new_owner, type]: \n:returns True if success or False if failed: \nif sub_nas defined passes call to sub_nas otherwise we try to transfer alias """ # handle sub_nas firs...
6fd45d845a82bc710108300851f36e6afbb78dfb
53,875
def get_true_positives(data, classifier): """Find the total positives that also are selected by our classifier.""" return data[data["foundSegment"] & classifier(data)].size
2d1581e5f9ade4ff299557c76f3a9507c4dc5a55
53,876
def africa(container, images): """Creates the Africa tab container within a parent container""" multipane = ttk.Notebook(container) f11 = ttk.Frame(multipane) f12 = ttk.Frame(multipane) multipane.add(f11, text='South Africa') multipane.add(f12, text='Northwest Africa') multipane.grid(row=...
b6e0882a97c9fdf0929d6e96263e656d9cf14204
53,877
def make_app(file="./random-mac-classifier.pickled"): """ This is the app factory. Parameters ---------- file : str The name of the file containing the saved (pickled) classifier. Returns ------- flask app An instance of the app. """ # Restore (unpickle) the classifier. classifier ...
f7bb64c9b9635d090dbdde381a1812738214d459
53,878
def cc_forbidden_error_response(account_id): """Build a crown charge registration class access forbidden error response.""" message = CROWN_CHARGE_FORBIDDEN.format(account_id=account_id) current_app.logger.info(str(HTTPStatus.FORBIDDEN.value) + ': ' + message) return jsonify({'message': message}), HTTPS...
85f87587f6e486c0411022d990a2f115d3affad5
53,879
def fit_func_invexp(x, a, b, c): """Fits an inverse exponential function to the semivariogram.""" if a < 0: return -9999 if b < 0: return -9999 if c < 0: return -9999 # Here a is sigma2_o, b is sigma2_b, and c is L_b return a + b*(1. - np.exp(-1*x/c))
b7ffb937780ba45299981ad440bd07ac162e9052
53,880
import random def omniglot_tasksets( train_ways, train_samples, test_ways, test_samples, root, **kwargs ): """ Benchmark definition for Omniglot. """ data_transforms = transforms.Compose([ transforms.Resize(28, interpolation=LANCZOS), transforms.ToTensor(), ...
28fd19bb8f19000160fa353baccb37fef0f8f338
53,881
from typing import Tuple def if_gte_python37() -> Tuple[int, int]: # pragma: py-gte-37 """Test function for pragma ``py-gte-37``.""" return (3, 7)
61996859cea7ef5fe74c3901050b6cdab1525d2b
53,882
from typing import TextIO from typing import List def tsv_to_list(stream: TextIO) -> List[List[yattag.doc.Doc]]: """Turns a tab-separated table into a list of lists.""" table = [] first = True type_index = 0 for line in stream.readlines(): if not line.strip(): continue ...
9de7cdbd4994b1ed2bde461aa11d5d49fc2ab3da
53,883
import random def CustomShortestPath(p1, p2, m, n): """This should be a faster way to find the shorest path, as we only have a cartesian grid. So Dijkstra might be overkill This function takes p1 and p2 in cartesian coords, and returns a simple path between them by correcting x pos. then y pos. ...
5b512cc938a23bde6c5bbc514b11796e6e67056f
53,884
from typing import Tuple from typing import List from typing import Dict def _resolve(o): """ Make sure that this object becomes a Query object. In case of a tuple/list, create a QueryTuple/List, otherwise, return a Static """ if isinstance(o, Query): return o elif isinstance(o, t...
c1a661e2c512a5d37e3411df141f1d1eecf7642c
53,885
import json import sys import requests def add_fields_to_cr(cr_id, patient_fields): """Use the Omicia API to fill in custom patient fields for a clinical report e.g. patient_fields: '{"Patient Name": "Eric", "Gender": "Male", "Accession Number": "1234"}' """ #Construct request url = "{}/reports/{}...
fb13723fa9d7b9e1b317d696480577d90fa4c13e
53,886
def checkin_command(gbxtag_as_str): """ This command will navigate to the edit asset page on lansweeper ,change the contact and location to "5TH FLOOR IT STORAGE ROOM and remove any associated user relations """ gbxtag = gbxtag_as_str theteachingsofbuddha = 1 # This step navi...
5f0e9491c3147fc81704c2b7587c50b53c2d5ed5
53,887
def handle_klio(*args, max_thread_count=None, thread_limiter=None, **kwargs): """Serialize & deserialize incoming PCollections as a KlioMessage. Behind the scenes, this generates :class:`KlioContext <klio.transforms.core.KlioContext>`, handles de/serialize the incoming PCollection as a Klio Message, as...
f8edd3ddb7b63c4b4f1886526aac551a590ab020
53,888
def specgram_func(i, gtime, duration, padding, node_id, channel, NFFT, noverlap, freq_range, filter=None): """Worker process to compute specgrams""" session = globals()['mppool'].g_session # Worker process namespace is a bit odd # actually read the audio data data = session.ReadDataAtGTime(node_id, gti...
9dca997918c95193e0b3c23175d622657badf104
53,889
def getBleu(bleus): """ """ return sum(bleus, BleuStats()).bleu()
d7b3cef78728bb026068dc76511dde1a160407bd
53,890
def normalize_val(val, min_v, max_v): """ print 'nomalized depth value' nomalize values to 0-255 & close distance value has low value. """ return (((val - min_v) / (max_v - min_v)) * 255).astype(np.uint8)
581221e0f5a7d9736591166833e8a781b30855cf
53,891
def make_sasl_acl(perm, krb_realm): """Create SASL ACL""" scheme = 'sasl' principal = '{}/{}@{}' host_principal = principal.format(CURRENT_USER, HOSTNAME, krb_realm) acls = [kazoo.security.make_acl(scheme, host_principal, read='r' in perm, ...
4212035f435839c1208b7e00cbb2f4fda27edf5e
53,892
def fill_coords(datafr): """ Interpoleert op cellen met NaN waarden :return DataFrame """ # df_dropped_na = datafr.dropna() # nonNA = list(df_dropped_na.index.values) # # for i in range(len(nonNA) - 1): # prev_lat = datafr.at[nonNA[i], 'latitude'] # diff_lat = abs(datafr...
2fed07b6c594551bcf96484fceae3f57d52ebf83
53,893
def mldivide(A, b): """Solve systems of linear equations Ax = B for x. The matrices A and B must contain the same number of rows. If A is a square n-by-n matrix and B is a matrix with n rows, then x = A\B is a solution to the equation A*x = B, if it exists. Parameters ---------- b : numpy....
61c584a81e8089070354ac0b8c8d6ff2a644aa44
53,894
def precision_at_k(vanilla_topk, fair_topk): """ calculate precision @ K :param vanilla_topk: top K nodes in vanilla mining result :param fair_topk: top K nodes in debiased mining result :return: precision @ K """ topk = set(fair_topk) groundtruth = set(vanilla_topk) return len(topk....
073abf75d0a66d492541d13c799b67c1b09662f8
53,895
def update_batch_child_count( batch_execution_job_id, added_count, ): """Updates the status of a given batch_execution_job_id and returns true if completed Parameters ---------- batch_execution_job_id: id of the job to update the status status: BatchExecutionMetadata status to be in add...
d0188b361228110a76c8b62804997b066f93d54a
53,896
def sample(sample_size=5000, noise=0.0): """ return [(s, u, s_next)] """ mdp = PlanarObstaclesMDP(noise=noise) # place holder for data x_data = np.zeros((sample_size, mdp.width, mdp.height), dtype="float32") u_data = np.zeros((sample_size, mdp.action_dim), dtype="float32") x_next_data =...
f1956d74eef77d1fe128c81e50ceff828d41e545
53,897
def turn_features(turns): """Turn-based features. Parameters ---------- turns: iterable, Sequence of (gap, prev_user, prev_tokens, prev_pos) as returned by the turns_from_chat function. """ turn_features = [] for prev_turn, curr_turn in zip(turns, turns[1:]): featu...
589a794760cff45a6cd2581dba51eb409b728929
53,898
def inttools_Parameter(*args): """ :param P: :type P: gp_Pnt :param Curve: :type Curve: Handle_Geom_Curve & :param aParm: :type aParm: float & :rtype: int """ return _IntTools.inttools_Parameter(*args)
9f38b82c35a0b979b9d1961c9b81de411b1cee3e
53,899