content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_series_val(series): """ Get value series """ # Create a clean timeseries list of (dt,val) tuples val = [float(vd['value']) for vd in series['values']] val = np.ma.masked_equal(val, -9999) val = np.ma.masked_equal(val, 0.0) return val
e6295979e506de61406378bc1a4660507ee38e0f
50,310
def get_embeds_portkey(list_of_dicts_of_metadata): """make and return portkey archive embeds for story metadata""" embeds_list = [] for data in list_of_dicts_of_metadata: data = data["story"] sid = data["id"] embed = Embed( title= data['title'], url= f"https:...
44db656c6dc16bc33eabcdb450283755d98f54e0
50,311
def shear_y_only_bboxes(image, bboxes, prob, level, replace): """Apply shear_y to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper( image, bboxes, prob, shear_y, func_changes_bbox, level, r...
085bb3c0608f5a99b9661ded6e63718a798292c5
50,312
from typing import Tuple from typing import List def split_by_commas(maybe_s: str) -> Tuple[str, ...]: """Split a string by commas, but allow escaped commas. - If maybe_s is falsey, returns an empty tuple - Ignore backslashed commas """ if not maybe_s: return () parts: List[str] = [] ...
ca21e5103f864e65e5ae47b49c161e8527036810
50,313
def postscriptFullNameFallback(info): """ Fallback to *openTypeNamePreferredFamilyName openTypeNamePreferredSubfamilyName*. """ return "%s %s" % ( getAttrWithFallback(info, "openTypeNamePreferredFamilyName"), getAttrWithFallback(info, "openTypeNamePreferredSubfamilyName"), )
dcf166ee98374ca8391fc9758595592ff1df96ab
50,314
import hashlib def _normalize_and_hash(s): """Normalizes and hashes a string with SHA-256. Private customer data must be hashed during upload, as described at: https://support.google.com/google-ads/answer/7474263 Args: s: The string to perform this operation on. Returns: A norma...
a280ab613796443ee054db748329244856164080
50,315
import re def replace_flooded_chars(text): """replace 3 or more repetitions of any character patterns w/ 2 occurrences of the shortest pattern""" return re.sub(r'(.+?)\1\1+', r'\1\1', text)
1e7a4403cc55b155a4088185b701dd4f9ac95019
50,316
import json async def add_pack_member(request, pack_id): """Add a member to the roles of a pack""" log_request(request) required_fields = ["id"] validate_fields(required_fields, request.json) pack_id = escape_user_input(pack_id) conn = await create_connection() pack_resource = await packs...
a91cc5bc57111e930f4fdbe261c44859a8153d37
50,317
def dataset_currency_selection_currency_name_post(currencyName): # noqa: E501 """Selects a specific currency type The currency type should be either bitcoin, bitconnect, dash, ethereum, iota, litecoin, monero, nem, neo, numeraire, omisego, qtum, ripple, stratis, or waves # noqa: E501 :param currencyName:...
a48d8f75f4e00a053dc719aacac6109adeded0ea
50,318
def compress_G1(pt: G1Uncompressed) -> G1Compressed: """ A compressed point is a 384-bit integer with the bit order (c_flag, b_flag, a_flag, x), where the c_flag bit is always set to 1, the b_flag bit indicates infinity when set to 1, the a_flag bit helps determine the y-coordinate when decompressin...
6f718df6ed330c793996ca45bddf0f4efc67cedc
50,319
def pairwise_correlation(df): """docstring goes here""" metric = pd.DataFrame() for index_i, row_i in df.iterrows(): row_i_to_all_rows(df, index_i, row_i, metric) return metric
faac14cc26315f818d6fc7fd9a621e411325832a
50,320
import cgi import re def plaintext2html(text, container_tag=False): """ Convert plaintext into html. Content of the text is escaped to manage html entities, using cgi.escape(). - all \n,\r are replaced by <br /> - enclose content into <p> - 2 or more consecutive <br /> are consider...
5943942da1946073e3b79db87af3ac77ac943e03
50,321
def trend(data): """ Calcul de la pente. """ argmin = np.argmin(data) argmax = np.argmax(data) divider = (data[argmax] + data[argmin]) if divider == 0.0: return 0.0 if argmin < argmax: return (data[argmax] - data[argmin]) / (data[argmax] + data[argmin]) elif argmin...
354a1c5cec2ae9f9c767e5d90d4bb86ada6fce15
50,322
def getAtomType(atom, bonds): """ Determine the appropriate atom type for an :class:`Atom` object `atom` with local bond structure `bonds`, a ``dict`` containing atom-bond pairs. """ cython.declare(atomSymbol=str) cython.declare(molFeatureList=cython.list, atomTypeFeatureList=cython.list) ...
4db8d9bf8af148d89a9467a6ab2f3ad42ed6e3bc
50,323
def sim_poisson_pop(n_seconds, fs, n_neurons=1000, firing_rate=2): """Simulate a Poisson population. Parameters ---------- n_seconds : float Simulation time, in seconds. fs : float Sampling rate of simulated signal, in Hz. n_neurons : int, optional, default: 1000 Number ...
2bf8a52ce30a4b54cfa6abc87599066e14187984
50,324
def visualize_boxes_and_labels_on_image_array_V1(image, boxes, scores_step1, instance_masks=None, keypoints=None, ...
25a512e483510648fe28ab15a0b310d6c86bdfea
50,325
from typing import Any from typing import Coroutine def slash_default_member_permission(permission: "Permissions") -> Any: """ A decorator to permissions members need to have by default to use a command. Args: permission: The permissions to require for to this command """ def wrapper(fu...
0cb18723b83dcae7a0af299bb5fad4bcb0dded9b
50,326
from typing import Union from typing import Optional def create_or_update_move_stop_by_dist_time( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], dist_radius: Optional[float] = 30, time_radius: Optional[float] = 900, label_id: Optional[Text] = TRAJ_ID, new_label: Optional[Text] = SEG...
ad4d3af6ca6ec160f9f63dd0b11436bc42d4c472
50,327
def _build(tmplspec, *repls): """Create raw parsed tree from a template revset statement >>> _build(b'f(_) and _', (b'string', b'1'), (b'symbol', b'2')) ('and', ('func', ('symbol', 'f'), ('string', '1')), ('symbol', '2')) """ template = _cachedtree(tmplspec) return parser.buildtree(template, ('...
b3fd8edf518b12b3d0db26c0aae9affce72bc02b
50,328
def kalman_predict(m, P, A, Q): """Kalman filter prediction step""" m_p = A @ m P_p = A @ P @ A.T + Q return m_p, P_p
a43e644693d02e317f2ac67a36f0dc684e93f3d5
50,329
def limit(df: pd.DataFrame, rows: int) -> pd.DataFrame: """Limit the number of rows in a data frame. Returns a data frame that contains at most the first n (n=rows) rows from the input data frame. Parameters ---------- df: pd.DataFrame Input data frame. rows: int Limit on number...
6ac5174684b419e2ed1b4ff1dc6ad07dbf7f75f7
50,331
def _fill_gaps(wires, out): """Fill 1-minute gaps.""" mask = np.array([[1, 0, 1]]) return np.logical_or( wires, ndimage.binary_hit_or_miss(wires, mask), out=out)
342be9cd556b14b982c5bd6e9e1153986f17abf5
50,332
def has_prefix(sub_s, dic): """ :param sub_s: (str) apart of word :return: (bool) if correct: True """ for word in dic: if word.startswith(sub_s): return True return False
ae87c8babc8c28a853ecef0c6814cc3b51af6a2e
50,333
def nansum(*args, **kwargs): """ This will check for numpy array first and call np.sum otherwise use builtin for isntance c={1,2,3} and sum(c) should work also """ args = _convert_cat_args(args) if isinstance(args[0], np.ndarray): return args[0].nansum(*args[1:], **kwargs) return...
68fa967b653da7615b688b570251ed463fd66ff3
50,335
def get_publictag(tagkey): """ Return tag and bookmarks in this public tag collection """ this_tag = PublicTag.get(PublicTag.tagkey == tagkey) bookmarks = Bookmark.select().where( Bookmark.userkey == this_tag.userkey, Bookmark.tags.contains(this_tag.tag), Bookmark.status == Bookmark....
3fd8b8d3cf7907f50c78cc1d9bf387cfbf6985bc
50,336
def _get_window(point, image, radius, padding_value): """Extract a square 2d window around a given pixel in the image. If the point has coordinates (-1, -1), the window will be filled with `padding_value`. Args: point: The coordinates of the center point in the extracted window. image: The image to ex...
9d08b13f4e4923875f14288ef2ba2a5ae648a713
50,338
from typing import OrderedDict import collections def make_docs(*args, **kwargs): """Make the documents for a `Request` or `OpReply`. Takes a variety of argument styles, returns a list of dicts. Used by `make_prototype_request` and `make_reply`, which are in turn used by `MockupDB.receives`, `Reques...
0857fce27c9f0b954b81f75e95974e8cb99b797e
50,339
from operator import concat def Divider(clk, rst, io): """ A 32-bit divider. WARNING: the op_divs/op_divu signal must be asserted only one cycle. Keeping it asserted for more than one cycle will restart the operation. The operation can be aborted by asserting the reset sig...
8a135c193d87068b2858d5be7a1a08ce5e3d96d7
50,341
def is_probably_gzip(response): """ Determine if a urllib response is likely gzip'd. :param response: the urllib response """ return (response.url.endswith('.gz') or response.getheader('Content-Encoding') == 'gzip' or response.getheader('Content-Type') == 'application/x-gzip...
30ca3774f16debbac4b782ba5b1c4be8638fe344
50,342
def quat_to_SO3(quat): """ :param quat: (N, 4, ) or (4, ) np :return: (N, 3, 3) or (3, 3) np """ x = RotLib.from_quat(quat) R = x.as_matrix() return R
c5a315d87b65a56b68f89cb18ea52c90a967b682
50,343
from typing import List def word_tokenizer(text: str) -> List[Word]: """Return words from sentence. Removing stopwords and punctuation. do lowarcase e.g: "Hello World!" >> "hello", "world" """ return WORD_TOKENIZER(text)
d9f8094c73649871bafa7a01e596885049d2ed11
50,344
def l1_loss(inputs, target, reduction='none'): """ Computes l1 loss. Args: inputs(akg.tvm.Tensor): Supported data type is float16, float32. target(akg.tvm.Tensor): With same type as inputs. reduction(str): Default is 'none', could be 'sum' or 'mean', if 'mean', loss result will be d...
a72d4bec59cd0fdb860c526318ca330c5080a417
50,345
def correlated_uniforms(N,rho=0): """ This function generates N uniform random variables (0,1) that may or may not be correlated, default is independent; when rho=0""" # check the correlation has acceptable value if rho>1 or rho<-1: print("Error, correlation coefficient must be between -1 an...
39144a63ef309a704f2f27b3cd58ad851be453cf
50,347
def _create_observable_table(yaml_dict: dict): """ Creates an observable table from the observable block in the given yaml_dict. Arguments: yaml_dict Returns: observable_table: pandas data frame containing the observable table. (if observable block is not empty, else None)...
d359a8a192791c766a4312e3c2bc987288afc120
50,348
import random import math def buffon(needlesNbr, groovesLen, needlesLen): """Simulates Buffon's needle experiments.""" intersects = 0 for i in range(needlesNbr): y = random.random() * needlesLen / 2 angle = random.random() * math.pi z = groovesLen / 2 * math.sin(angle) if y <= z: intersects += 1 exp...
34bbb29346690b5d0ef519282699f0b3b82d93cb
50,349
import time import numpy def ucerf_classical(rupset_idx, ucerf_source, src_filter, gsims, monitor): """ :param rupset_idx: indices of the rupture sets :param ucerf_source: an object taking the place of a source for UCERF :param src_filter: a source filter returning the sites af...
067b43d05c45e200915e8323073b9c2e1e0dcce7
50,350
def SNRvsTPR(data, true_flags, flags): """ Calculates the signal-to-noise ratio versus true positive rate (recall). """ SNR = np.linspace(0.0, 4.0, 30) snr_tprs = [] data_ = np.copy(data) flags_ = np.copy(flags) true_flags_ = np.copy(true_flags) for snr_ in SNR: snr_map = np....
b2a0199bbcf69abc3eb83af2a69e44a0c3794f1c
50,351
def stringify(plaintext): """ Used to convert hex integers into a string when decrypting. :param plaintext: a hex integer number. :return: a ascii string. """ if len(plaintext) % 2 == 1: plaintext = '0' + plaintext lst = [] end = len(plaintext) // 2 for i in range(end): ...
ddab6a748b9194ce763fd82c38ee428a41a50c72
50,352
def get_new_snp(vcf_file): """ Gets the positions of the new snp in a vcf file :param vcf_file: py_vcf file :return: list of new snp """ new_snp = [] for loci in vcf_file: if "gff3_notarget" in loci.FILTER: new_snp.append(loci) return(new_snp)
1385a5552f9ad508f5373b2783d14938ab04b9c5
50,353
def map(data, settings): """ Returns a new DataFrame applying the expression to the specified column. :param data: A pandas's DataFrame; :param settings: A dictionary that contains: - function: A lambda function; - alias: New column name; :return: Returns pandas's DataFrame with th...
aa72e29e3858b3fb3c5c8cac083bc9465ece3e95
50,354
def my_function() -> dict: """Return a set of data into a dictionary""" hills_of_rome = { 'Aventine Hill': {'Latin': 'Aventinus', 'Height': 46.6, 'Italian': 'Aventino'}, 'Caelian Hill': {'Latin': r'Cælius', 'Height': 50...
2482a65efc45c9c7f30a12f20bef2ba069c37d0a
50,355
def forced_vibration_particular(vt, k, m, F0, Omega, zeta): """ Particualr solution to forced harmonic vibrations, , x=H0 sin(Omega t - Phi) """ omega0 = np.sqrt(k / m) H0, phi = forced_vibration_particular_cst(Omega/omega0, F0/k, zeta) x_particular = H0 * np.sin(Omega * vt + phi) ...
fdb0d69ba6fa3cb3de60c5b76ed8de4ce3af7c0f
50,356
def most_freq(neighbors): """ Returns the dominant color with the greater frequency Example: num_dominating = [paper, paper, paper, spock, spock, spock, spock, spock] Returns: spock """ return max(set(neighbors), key=neighbors.count)
09c041b27dbf55f6e862d73bde421a86ac265f42
50,357
from re import M def test5(): """ test graph mark for cnn1 with NaiveSGD optimizer """ num_classes = 1470 model = M.cnn1(num_classes=num_classes) inputs = FloatTensor([32, 3, 448, 448], name="data") weights = list(model.weights) mse_loss = nn.MSELoss() labels = FloatTensor([32, nu...
7d69f37c546f2f8f3df194cfa00ef904aed6f45e
50,358
def create_scratch(request): """ Create a scratch """ ser = ScratchCreateSerializer(data=request.data) ser.is_valid(raise_exception=True) data = ser.validated_data platform = data.get("platform") compiler = data.get("compiler") if platform: if CompilerWrapper.platform_from...
233a4eee19e85e56c3da4fe1f924906b9f37d74d
50,360
import base64 def encrypt(password, key, challenge=None): """Encrypts password with a key and returns the base64 encoded string""" ciph = _get_ciph(key, challenge) return base64.b64encode(ciph.encrypt(password))
8591d9f94625a01334b5014d8c13e3c3f349e16c
50,361
def get_func_store() -> dict: """Returns a dictionary with Callable objects supported in our function store, indexed by their function names.""" return {o[0]: o[1] for o in getmembers(knowledge_horizons) if isfunction(o[1])}
89798e4cfdd1d6abb73defa8f894aafd27b4a691
50,362
from typing import Tuple from typing import List def verify_contents_quiet(unicodestring:str, filename:str, book_code:str, lang_code:str) -> Tuple[List[str],str]: """ This is called by the USFM linter. """ global error_log error_log = [] # e...
315e6dbc84f5c33aebcb60d51b5ef54b6cea2d6a
50,364
def email2dict(msg: Message, include_all: bool = False) -> "MessageDict": """ Convert a `Message` object to a `dict`. All encoded text & bytes are decoded into their natural values. Need to examine a `Message` but find the builtin Python API too fiddly? Need to check that a `Message` has the conte...
18e0e1569c5b9d6b1e69024d5bcacf0a8f56926e
50,365
from datetime import datetime def greater_than_days_cutoff(timestamp, cutoff): """ Helper function to calculate if PR is past cutoff """ # Convert string to datetime object last_update = datetime.strptime(timestamp[0:22], '%Y-%m-%dT%H:%M:%S.%f') # Get the number of days since this PR has been la...
2dd1a9c01112d30a77ca2f5826db32d29f26d830
50,366
def expand_for_dithers(indict, verbose=True): """Expand a given dictionary to create one entry for each dither. Supports parallel observations. Moved here and modified from apt_inputs.py Parameters ---------- indict : dict dictionary of observations Returns ------- expand...
b5fb6b60b71de797f1413fc3eaa25361e2de1e3a
50,368
from datetime import datetime import json def download_trace(): """Provide the trace of the current exploration to be downloaded. Note: The file will be saved in the configured upload folder and WILL NOT be deleted afterwards. A trick is to use the /tmp directory for them to be automa...
27160550411f96e25805ebfee594a7d03ca04059
50,369
import requests def discover_oidc_provider_config(oidc_provider_config_endpoint, client_id, mccmnc): """ Make an HTTP request to the ZenKey discovery issuer endpoint to access the carrier’s OIDC configuration """ oidc_provider_config_url = '%s?client_id=%s&mccmnc=%s' % ( oidc_provider_...
b5fe999cbd8a2515d689b564d1de6df30c28bde3
50,370
def response_plain_text_ga(output, continuesession): """ create a simple json plain text response """ return { "payload": { 'google': { "expectUserResponse": continuesession, "richResponse": { "items": [ { ...
70ee09b3fc3e22ad626fb1a963a3f3f7c528008a
50,371
import token def NodeName(node): """Produce a string name for a given node. For a Leaf this is the token name, and for a Node this is the type. Arguments: node: a tree node Returns: Name as a string. """ # Nodes with values < 256 are tokens. Values >= 256 are grammar symbols. if node.type < 2...
305a494e57f731274ed1739bb6459a91b0d24191
50,372
from datetime import datetime def get_current_weather(): """ returns the lates entry from the weather table """ return Weather.query.with_entities(Weather.temp, Weather.weather_id).filter( Weather.created_at >= (datetime.now() - timedelta(days=2))).order_by( Weather.id.desc()).first()
918dcaf3d2ad9289dd4558de96ecdb9f46aa0b81
50,373
def _GetChangesForMask(config_sed_input): """Get changes to config and run scripts for MaskRCNN. Also update train_mlperf.py if nvprof is used. Args: config_sed_input: Input list of sed pairs for config_DGXA100.sh. Returns: config_sed_output: Output list of sed pairs for config_DGXA100.sh. """ co...
ac92385d605dc2a9b9b122e4fce0d7831ca72d87
50,375
def reportnulls(df): """ Takes a data frame and check de nulls and sum the resutls and organizes them from highest to lowest """ null_counts = df.isnull().sum().sort_values(ascending=False) # return count of null values return null_counts
a3dc20feeaaf0f3467de76812531f1d0b791dc01
50,376
from io import StringIO def decode(data): """ Decode a binary string into the original Python types. """ buffer = StringIO(data) try: value = decoder[buffer.read(1)](buffer) except KeyError as e: raise DecodeError("Type prefix not supported. (%s)" % e) return value
de9ecff37d228707aa48d418f658b7b976b6f215
50,378
def getConstrainedTargets(driver, constraint_type='parentConstraint'): """ Gets all the transforms the given driver is driving through the giving constraint type. Args: driver (PyNode): The transform that is driving the other transform(s) through a constraint. constraint_type (string): The...
4e94a4cf1e72012e2413f1889ec76ccd0a76800e
50,379
from typing import List from pathlib import Path def get_isbr2_nii_file_paths(dir_paths: List[Path], file_selector: str) -> List[Path]: """Returns all the .nii.gz file paths for a given file_selector type. Arguments: dir_paths: a list of sample dir paths, each directory holds a full scan file_...
fc04b9fa48e2d44c532344c36bdbdefe71f24f67
50,380
def divide_mnist_data(mnist): """ load mnist dataset input:None output:split these data into train valid and test data. """ mnist_X, mnist_y = shuffle(mnist.data, mnist.target, random_state=42) # normalize mnist_X = mnist_X/255.0 train_X, test_X, train_y, test_y = train_test_split(m...
5a212f5e3c1557b24071732978f97c938593cc79
50,381
def fillPixels(im, N=1): """ Fill in the dead pixels. If a dead pixel has a least 4 finite neighbour pixel, than replace the center pixel with a mean valuse of the neighbours """ X = im.shape[0]-1 Y = im.shape[1]-1 imcopy = np.copy(im) for n in range(N): # skip = int(np.floor((3+n...
6fc8dacc27a9c5f9be9ae399aba486370e38157d
50,382
def get_mac_table(netmiko_session, vdc=None): """Get mac-address-table""" mac_table = [] get_macs = 'show mac address-table' if vdc is not None: vdc_command = f"switchto vdc {vdc}" get_vdcs = send_command(netmiko_session, vdc_command) table = send_command(netmiko_session, get_macs...
aa695cf4741fa585ca60cb3bc979ebb0953f9dc5
50,383
def GetBoundaryVertexes( wire = None, tol = 1e-7, single = True, add = True, infa = True ): """ Description: Gets boundary vertexes from a wire and put them into a group. Arguments: # wire Description: The input wire. Type: Wire GUI selection: yes Selection by name: yes R...
c3c2b8c8acb76d8debb489ef70f2581303900937
50,384
def WgBin2DFunc(v1, v2, wgs, Nbin1, Nbin2): """ Calculate the weighted quantile by given bin numbers designed for 2D numpy array """ # Define the probabilities for the quantiles based on the number of bins pq1 = np.linspace(0,1.0,Nbin1+1) pq2 = np.linspace(0,1.0,Nbin2+1) # Calculat...
304b8287d57409a1eb10ce8df47a049598c4be85
50,385
def convert_length(length: float, from_unit: Unit, to_unit: Unit) -> float: """Changes length measurements between units Parameters ---------- length : float measurement to convert from_unit : Unit [description] to_unit : Unit [description] Returns ------- f...
0dbf914e4071f4e72b7c5b6ec89c3d9ffdf9f93c
50,387
def one_hot_encoder(batch_inds, num_categories): """Applies one-hot encoding from jax.nn.""" one_hots = jax.nn.one_hot(batch_inds, num_classes=num_categories) return one_hots
1e31331316163700512065e7e4abb3deea11db3d
50,388
def get_decks(f): """ Get card deck categories, colors and text contents from Excel file. Always loads the first sheet i.e. the active one """ wb = openpyxl.load_workbook(f.name) ws = wb.active # Pick up deck names from the first row decks = [] for j in range(1, ws.max_column+1): i = ws...
07b3e7fd01b46880b054c83eb42f4347d70ee777
50,389
import random def topic_sample( review_source: pd.DataFrame, sample_frame: dict, topic_number: int, sample_size: int = 5, ) -> list: """ Returns a sample of reviews for a given topic Args: review_source - Panda's dataframe: a dataframe with all of the relevant reviews samp...
13ad6b7ce2daa6239c0cb8ac5ad79731bedea005
50,390
from typing import Type def do_login(): """ @api {post} /cookbook/auth/login User Login @apiName authenticate @apiDescription Example of an authentication service using sqlite3 and the froggy framework. @apiGroup Authentication @apiParam {String} email=kermit@muppets.com Email of the use...
c6f0b72f20aa543407fc87d29600a9f62a5d7336
50,391
from typing import List from typing import Dict def directory_to_trainer_input(file_names: List[str], text_processor: TextProcessor) -> Dict[str, List]: """generate images from example caption_list""" captions_per_file: Dict[str, List] = {} for file_name in file_names: print('Load examples from:',...
f8c2035e54e6c9f6181925c0b162f88a311c942f
50,392
def get_num_gophers(blades, remainders, M): """Find no. of gophers given no. of blades and remainders.""" for i in range(1, M + 1): congruences = all([i % b == r for b, r in zip(blades, remainders)]) if congruences: return i return None
0467bd7a9ab56181b03c26f0048adf52b1cc8228
50,394
def adata_to_cluster_expression(adata, cluster_label, scale=True, add_density=True): """ Convert an AnnData to a new AnnData with cluster expressions. Clusters are based on `label` in `adata.obs`. The returned AnnData has an observation for each cluster, with the cluster-level expression equals to the average ...
076a153e8cf6671b5a5190eeb6fdcc5e060af6b2
50,395
def rtaph_yap(ya, yb, yamc): """ For post-CSP data, 'wrap' the YA value for YA in [0,1]. From rtaph.c. :param ya: Y axis wiggle. :type ya: numpy.ndarray :param yb: Y axis coarse clock. :type yb: numpy.ndarray :param yamc: Raw Y detector position in FEE pixels. :type yamc: numpy.nda...
0655ab38e0dc9b45242371f4f55d3726bb7e6a75
50,397
def correct_drift(data: ForcData, config: Config) -> ForcData: """Correct the raw magnetization for drift. If the measurement space is Hc/Hb, dedicated drift points must have been measured. If the measurement is H/Hr, the last datapoint along each curve is used. In either case, the points used for drif...
9f20bc078b3c495fbabe668133d1e7ef1524d99c
50,398
def svn_prop_dup(*args): """svn_prop_dup( prop, apr_pool_t pool)""" return _core.svn_prop_dup(*args)
2cd5fabe2220c2501529e553246230e8a03ffc5f
50,399
import math def __calc_entropy_passphrase(word_count, word_bank_size, pad_length, pad_bank_size): """ Approximates the minimum entropy of the passphrase with its possible deviation :param word_count: Number of words in passphrase :param word_bank_size: Total number of words in the word bank :param...
c3597b8d8fc35387638e1e0e4923316c2b99aaa8
50,400
def masked_softmax(X, valid_lens): """通过在最后一个轴上掩蔽元素来执行 softmax 操作""" if valid_lens is None: return ops.Softmax(-1)(X) else: shape = X.shape if valid_lens.ndim == 1: valid_lens = mnp.repeat(valid_lens, shape[1]) else: valid_lens = valid_lens.reshape(-1)...
6895ac2da748167f469e317d27c1eb814be20d79
50,401
from nexinfosys.command_generators import Issue, IType def any_error_issue(issues): """ Just iterate through a list of Issues (of the three types) to check if there is any error :param issues: :return: """ any_error = False for i in issues: if isinstance(i, dict): if i...
de308851af2d7a8a8e64a11f298517d328d45370
50,402
def join_string(list_string, join_string): """ Join string based on join_string Parameters ---------- list_string : string list list of string to be join join_string : string characters used for the joining Returns ------- string joined : string a string whe...
bcb55fb72b9579dd5ab548b737a0ffd85cbc7f43
50,403
def value_from_example(example, feature_name): """Returns the feature as a Python list.""" feature = example.features.feature[feature_name] feature_type = feature.WhichOneof('kind') return getattr(feature, feature_type).value[:]
8c73b2ecec80255de219911b0628fc89359a220a
50,404
def apply_control(sys, u_opt): """ evaluates the controlled system trajectory """ states = sys.states # if not MPC: timesteps = sys.timesteps x_new = np.zeros([states, timesteps]) x_new[:, 0] = sys.state cost = 0 for t in range(timesteps - 1): u = u_opt[:, t] # retur...
201e6ba6a23c9d00b1cce8ccc1d74d91ce9cb3bf
50,405
async def chained_filter_repositories_labels( client, headers, account_id, date_from, date_to, exclude_inactive, repos, timezone, ): """Chain the request to get filtered repos and labels.""" filtered_repositories, fr_datapoint = await filter_repositories( client, headers, int(account...
34268f4824c29e65d457c79a1503bc875cb06f1d
50,407
from typing import Any def return_value_from_dict_extended(some_dict: dict, path_string: str) -> Any: """ Возвращает значение ключа в словаре по пути ключа "key.subkey.subsubkey" :param some_dict: :param path_string: :return: """ check = access_dot_path(some_dict...
e23f4c5ded43f78e92b026f4bf2f892235da428c
50,408
import requests def search(term, country='UA', media='music', entity=None, attribute=None, limit=50): """ Returns the result of the search of the specified term in an array of result_item(s) :param term: String. The URL-encoded text string you want to search for. Example: Steven Wilson. T...
c577ca67a3f0c73ef92bd251deda30c75145eb55
50,409
def returnFiles(path): """Collects a list of files within a file :rtype: list """ if path: onlyFiles = [join(path, f) for f in listdir(path) if isfile(join(path, f))] # print("onlyFiles: ", onlyFiles) return onlyFiles # print("Path: ", listdir(path)) return None
88b49aff59941cfafeca62cc08578b318dc4c55d
50,410
from typing import Tuple def minus(a: Tuple[int], b: Tuple[int]) -> Tuple[int]: """ Vektor a minus Vektor b. :param a: Von den Werten in dieser Liste wird subtrahiert. :param b: Diese Werte werden subtrahiert. :return: Elementweise Differenz. """ assert len(a) == len(b) return tuple(ax...
1cfbbb98fd2ac0eb422ef5d5e27fa9871f0272d0
50,412
from typing import get_args def ccds(): """ Returns list of Consensus CDS IDs by query paramaters --- tags: - Query functions parameters: - name: ccdsid in: query type: string required: false description: 'Consensus CDS ID' default: 'CCDS1357...
ea55fa1fe705a3a3696181cfee3d2bc5118c6e7b
50,413
from datetime import datetime def today_w_time(): """ Returns today in format 'Y-m-d H:i:s' """ today = datetime.datetime.now() today = today.replace(microsecond=0) return today.isoformat(' ')
4084b1f5b387c92a38e705267f76c03a6863a8f2
50,414
from datetime import datetime def GetLast7DaysYesterday(): """ Set date range as 7 days before yesteday up to yesterday Returns startDate: date object. Start of period. endDate: date object. End of period. countOfDays: integer. Number of days between start and end date ""...
3f8dc77e1d795e7fdd4c2498552c5c116c1262a5
50,415
def top_level_nodes(ig_service): """test fixture gets the top level navigation nodes""" response = ig_service.fetch_top_level_navigation_nodes() return response["nodes"]
323a88402a2790d672273001826d0ae3d25c017d
50,416
import logging def ldap_add_memberuid(email, member_id): """ Update an existing LDAP account by adding another memberUid to it. """ logger = logging.getLogger('membership.utils.ldap_add_memberuid') conn = settings.LDAP_CONN cn = f'cn={email},{settings.LDAP_DOMAIN_CONTROLLER}' changes = {'...
f0111103aba95e5bc91fb368977866ee0b7bf1a3
50,419
def is_unique_bloom_filter(bloom_filter, item): """ Converts Redis results to boolean representing if item was unique (aka not found). Keyword arguments: bloom_filter -- the bloom filter item -- the item to check Returns: boolean -- True if unique (aka not found) Throws: Assertion...
1a42f43a4eb058c2861ca0f9e20f95e74e42acff
50,421
import psutil def get_avain_instance_count(): """ Return the number of currently active AVAIN processes """ instance_count = 0 for proc in psutil.process_iter(): try: for elem in proc.cmdline(): if elem.endswith("/avain.py") or elem == "/usr/local/bin/avain": ...
9fdb90c5ec7b273b5652d0702a59ef850cd83895
50,422
import math def incidence_rate_ci(events, time, alpha=0.05): """Calculate two-sided (1-alpha)% Wald Confidence interval of Incidence Rate Returns (incidence rate, lower CL, upper CL, SE) events: -number of events/outcomes that occurred time: -total person-time contributed in this gro...
7287eefa4f087ece3702ffa95be71a771bc69db8
50,423
def make_costate_rates(ham, states, costate_names, derivative_fn): """Make costates.""" costates = [SymVar({'name': lam, 'eom':derivative_fn(-1*(ham), s)}) for s, lam in zip(states, costate_names)] return costates
2c1a40d215866e5cd4622c1afab21c1ec5273aea
50,424
from re import T def projection(): """ RESTful CRUD controller """ if deployment_settings.get_security_map() and not s3_has_role("MapAdmin"): unauthorised() tablename = module + "_" + resourcename table = db[tablename] # CRUD Strings ADD_PROJECTION = T("Add Projection") LIST_PR...
3fe952cb86efcfa30b0ff54c512b191ccd03c49c
50,425
def parse_segments(segments_str): """ Parse segments stored as a string. :param vertices: "v1,v2,v3,..." :param return: [(v1,v2), (v3, v4), (v5, v6), ... ] """ s = [int(t) for t in segments_str.split(',')] return zip(s[::2], s[1::2])
4adfaff824ceb12772e33480a73f52f0054f6f5d
50,426
def GetFirstWord(buff, sep=None):#{{{ """ Get the first word string delimited by the supplied separator """ try: return buff.split(sep, 1)[0] except IndexError: return ""
ce01a470ff5ba08f21e37e75ac46d5a8f498a76a
50,427