content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def match_file(matcher, analyzer, ht, filename, hashList): """ Read in an audio file, calculate its landmarks, query against hash table. Return top N matches as (id, filterdmatchcount, timeoffs, rawmatchcount), also length of input file in sec, and count of raw query hashes extracted ""...
c8995fac958f029587072553970d19ce0b5df552
630,497
def splitBase(idx): """ Return a named used when a big case is split into several pieces """ name = '' if len(idx) == 0: return 'base' for ii, n in enumerate(idx): name += 'sp%d-split-%d-' % (ii, n) name = name[0:-1] return name
c2deee08225ec6a4973443108a0ae5fca32c0fe5
630,498
def average(numlist): """ Find average of a list of numbers. Uses for loop to iterate through parameter NUMLIST and adds the sum of each element until the end of the list. AVERAGE then returns the sum divided by the length of NUMLIST. """ numlist_sum = 0 # initialize sum to zero # ...
e4191ca069df41e773052a2e39bb5eb0d47d7b1f
630,499
def orig_atom(atom,big_table): """ Returns the 0-indexed position of atom from the full list of atoms in the supercell mapped back into the original unit cell """ n = 0 bonds_per_pair = len(big_table[0])/len(big_table) while atom > bonds_per_pair: atom -= bonds_per_pair n += ...
d8aafec556a49a3c61d67079a81b63ce86acb8c7
630,505
def bottom_remineralization(vs, source, sink, scale): """Exported material falling through the ocean floor is converted to nutrients Note ---- There can be no source, because that is handled by the sinking code Parameters ---------- scale Factor to convert remineralized material to...
d30c9f9ee29532fb8452e1c4130a43dc9f57024a
630,507
def create_lookup(results): """Create a lookup table by key name.""" return {key["key_name"]["web"]: key for key in results}
809c247b85a9b807c47848490572316f29e70107
630,511
def parse_line(line): """ Parse a queue trace line into a dict """ result = {} line = line.split() if len(line) < 5 or line[0][0] == "#": return result result["time"] = float(line[0]) result["from"] = int(line[1]) result["to"] = int(line[2]) result["len_bytes"] = float(line[3...
b1c4b5ed022b54c30072caf92d5257d401e106d8
630,517
from typing import Optional from typing import Tuple from pathlib import Path def dataset_adress( adress_archive_root: Optional[str], corpus_name: str, dataset_type: str, preprocess_args: str, ) -> Tuple[str, Path]: """Path of dataset archive file and contents directory. Args: adr...
77f87d18b5532b8381adc218a8c3a21fe30caf3c
630,519
def distribute(items, n): """ Distributes items into n (almost) equally large batches. Example: items = [1,2,3,4,5,6,7,8,9], n = 4 gives batches = [[1,5,9], [2,6], [3,7], [4,8]] Args: data ([any]): List of items of any type n (int): Number of max items of a batch ...
817b29aa20f7cdfbbdd7199d93676d46007967ca
630,520
async def ping(): """Inspects if the API instance is running.""" return {"ping": "pong"}
fb2cb7128a66bda332e0a0e65314bfd5e9fee305
630,524
import torch def _parabolic_trend_crosscov(S1, L1, S2, L2, gamma0, sigma0s, betas, s0): """ Same as above, but for non-stationary variance models. The model is the following: \sigma_i(s) = \sigma0_i + \beta_i * (s - s0)**2 The genial simplicity of the implementation is this: instead of having an...
a44e20aefa094189858f0f99b068070bba8ca60a
630,530
def is_left_bracket(token): """ returns true if token is left bracket """ return token == "("
d799afbdfd880edf127d43dfae1363783c5fe401
630,531
def dummy_tx_hist_file_content() -> dict: """ Return initial tx file content. """ content = { 'txid_stake_previous': '', 'txcount_previous': '0' } return content
9b06c8f70edefa39a851237730289199fc519a0e
630,534
from typing import Any def is_ref(entry: Any) -> bool: """ Checks if entry is a reference """ return isinstance(entry, dict) \ and '$ref' in entry
30381c5f7af9d53d33eb6e2a33fab412c6217909
630,538
def derive_unique_id(row, is_fabs): """ Derives the unique ID of a row and puts it in the proper format for the error/warning report. Args: row: the dataframe row to derive the unique ID for is_fabs: a boolean indicating if the submission is a FABS submission or not Returns...
78d455473baeda04f4cbf34197b740be46c25b94
630,540
def trim_attribs(elem_attribs, attrib_type="question"): """deletes non-useful data from attribs dict for questions / answers, returns remaining""" if attrib_type == "question": to_keep = ['Id', 'Body', 'Title', 'Tags', 'AnswerCount', 'AcceptedAnswerId', 'PostTypeId', 'Score', 'BodyParsed', 'TitlePArsed'...
32eead0b92fff2a49088465cb13c0d438f461a7b
630,543
def convert(lines): """Convert compiled .ui file from PySide2 to Qt.py Arguments: lines (list): Each line of of .ui file Usage: >> with open("myui.py") as f: .. lines = convert(f.readlines()) """ def parse(line): line = line.replace("from PySide2 import", "from ...
70324df5dfec895d6bbd5100d7634cbb8b6a358a
630,544
def _get_next_chunk(stream, chunk_size): """Get a chunk from an I/O stream. The ``stream`` may have fewer bytes remaining than ``chunk_size`` so it may not always be the case that ``end_byte == start_byte + chunk_size - 1``. Args: stream (IO[bytes]): The stream (i.e. file-like object). ...
fe9771cd98cc629f806bede0314cdfea629c65e7
630,546
from typing import Dict def enabled(gParameters: Dict, key): """Is this parameter set to True?""" return key in gParameters and gParameters[key]
924f55f9346da741dacd3992b7d8e836c83835dc
630,548
import typing def noop(data: typing.Any) -> typing.Any: """Return the input value Arguments: data {typing.Any} -- any value Returns: typing.Any -- input value """ return data
20b71c569c727e6dc66442f9fd7271bfdbe6f93d
630,552
def contains_digit(input_string): """ check if string contains digit >>> contains_digit("5") True >>> contains_digit("5a") True >>> contains_digit("cat") False """ return any(_.isdigit() for _ in input_string)
45afeb35d7bd29808d5dbeb3eba6715ae1a15916
630,554
def get_unique_parents(entity_list): """Translate a list of entities to a list of their (unique) parents.""" unique_parents = set(entity.parent for entity in entity_list) return list(unique_parents)
cf855369a632ca71a99b833a4f1373325c142e7d
630,557
from PIL import Image, ImageChops def apply_mask(layer, image, bbox=None): """ Apply raster mask to the image. This might change the size and offset of the image. Resulting offset wrt the psd viewport is kept in `image.info['offset']` field. :param layer: `~psd_tools.api.layers.Layer` :param...
40c9a809573b947e4ba103eab0adb922ee831880
630,558
import re def parse_dockerimage_string(instr): """ Parses a string you'd give 'docker pull' into its consitutent parts: registry, repository, tag and/or digest. Returns a dict with keys: host - hostname for registry port - port for registry repo - repository name and user/namespace if present...
da9aa8a32ce9bd194a10d57f746701e1d71bc37f
630,567
import json def create_eupeg_json(df): """Transforms a Pandas dataframe to a EUPEG json""" filtered = df.reset_index()[['locations','loc_spans','coord_points']] all_toponyms = [] for i in range(len(filtered)): row = filtered.iloc[i] json_entry = {'start':row['loc_spans'][0], 'end'...
d5e0a161961e9375df5dae13b8dcc7176630af36
630,574
def partial_word(secret_word, guessed_letters): """ Return the secret_word in user-visible format, with underscores used to replace characters that have not yet been guessed. """ result = '' for letter in secret_word: if letter in guessed_letters: result = result + letter ...
224a22d853d161b5711430d2bde31c8ff85d192c
630,576
import math def hexagon_points(radius, center, rotate): """ Computes the (x,y) points of a hexagon with the given properties. :param radius: radius of the hexagon :param center: (x,y) pair, the center of the hexagon :param rotate: degrees the hexagon is rotated. 0 -> flat top, 30 -> pointed top ...
58792412765b11ac789533a55cfda279704284af
630,577
import torch def compute_elastic_loss(jacobian, eps=1e-6, loss_type="log_svals"): """Compute the elastic regularization loss. The loss is given by sum(log(S)^2). This penalizes the singular values when they deviate from the identity since log(1) = 0.0, where D is the diagonal matrix containing the singular v...
58ae72ac9bb7c06bcc7e6d6d155af2d85eff4c9b
630,578
def convert_bool_to_int(value): """convert True/False to 1/0.""" if value is True: return int(1) if value is False: return int(0) return int(-1)
ab33bf7dd21cf31c3f84339b271d2b636f9d0713
630,579
import requests def set_website_preference_for_header( url_pref: str, session: requests.Session, ) -> requests.Session: """ Set the 'Email Headers' of the 'Archive Preferences' for the auth session to 'Show All Headers'. Otherwise only a restricted list of header fields is shown. """ u...
2293a0aa0e0b389617bfd31c084fa8423b90cdf0
630,581
def getMedianvalue(lst, points): """ Returns the median of a list of numerics. :param lst: A list of numerics from which the median will be retrieved. \t :type lst: [numerics] \n :returns: The median. \t :rtype: : Numeric \n """ if points[1] == -1: if len(lst) == 1: ...
1a0c92e312df93295f9395f805e520740540d757
630,590
import torch def compute_entropy_loss(logits, mask): """Return the entropy loss, i.e., the negative entropy of the policy.""" policy = torch.nn.functional.softmax(logits, dim=-1) log_policy = torch.nn.functional.log_softmax(logits, dim=-1) return torch.sum(policy * log_policy * mask.unsqueeze(-1)) / (...
dd9be96323567991653c4444c93b6d5f2367bd5e
630,594
def get_aws_env(args): """Returns a dictionary of AWS related environment variables based on command line args""" env = {} env_values = { "AWS_PROFILE": args.aws_profile, "AWS_ACCESS_KEY_ID": args.aws_access_key_id, "AWS_SECRET_ACCESS_KEY": args.aws_secret_access_key, "AWS_SE...
b15c5a4c30682d499488ad24ddfce17c293dfdf5
630,598
import math def string_similarity(string1, string2): """ This implements a "cosine-similarity" algorithm as described for example in *Proceedings of the 22nd International Conference on Computation Linguistics* (Coling 2008), pages 593-600, Manchester, August 2008. The measure-vectors used i...
29871f6f5a0652937938fb4cb58a08be6e7e6d31
630,601
import mpmath def invcdf(p, mu=0, b=1): """ Laplace distribution inverse CDF. This function is also known as the quantile function or the percent point function. """ if b <= 0: raise ValueError('b must be positive.') with mpmath.extradps(5): p = mpmath.mpf(p) mu = ...
2a751e717ca76ff6b7abd42a93b2581fe8617580
630,602
def wrap_p(value): """ Adds enclosing <p> and </p> tags to value. """ return '<p>%s</p>' % value
2837535c081795553616927b75b803f04ddf6592
630,603
def sub2indSH (m,n): """ i = sub2indSH(m,n) Convert Spherical Harmonic (m,n) indices to array index i Assumes that i iterates from 0 (Python style) """ i = n**2 + n + m return i
9700b78c8a06e58d207307e6b00f3948ba88e02b
630,607
from typing import Optional from typing import Match import re def is_attr_private(attrname: str) -> Optional[Match[str]]: """Check that attribute name is private (at least two leading underscores, at most one trailing underscore) """ regex = re.compile('^_{2,}.*[^_]+_?$') return regex.match(attrn...
cde57dd98a2eb4250a14d81438e8ffc056cb318c
630,608
def drop_constant_column(dataframe): """ Drops constant value columns of pandas dataframe. """ return dataframe.loc[:, (dataframe != dataframe.iloc[0]).any()]
cae8cc18e191a9373425ca679b8e152a5dd6e857
630,609
def parse_file_string(filestring): """ >>> parse_file_string("File 123: ABC (X, Y) Z") ('ABC (X, Y) Z', '') >>> parse_file_string("File 123: ABC (X) Y (Z)") ('ABC (X) Y', 'Z') >>> parse_file_string("File: ABC") ('ABC', '') >>> parse_file_string("File 2: A, B, 1-2") ('A, B, 1-2', '') ...
53bad5bcfed7ed66149a82bb5d604f6996c56bd0
630,610
def VStack_Calc(N, Vcell): """ Calculate VStack. :param N: number of single cells :type N :int :param Vcell: cell voltage [V} :type Vcell:float :return: VStack [V] as float """ try: result = N * (Vcell) return result except TypeError: print( ...
886e66f79a852da0da748d49d9cf01c272138f74
630,615
def update_point(move, point): """Returns new point representing position after move""" moves = { '^': (0, -1), '<': (-1, 0), 'v': (0, 1), '>': (1, 0), } return (point[0]+moves.get(move, (0, 0))[0], point[1]+moves.get(move, (0, 0))[1])
da19f62445973cffd7c89c5dcbc56efe11170c0d
630,616
def positive_fft_bins(n_bin, include_zero=False): """Give the range of positive frequencies of a complex FFT. This assumes we are using Numpy's FFT, or something compatible with it, like ``pyfftw.interfaces.numpy_fft``, where the positive frequencies come before the negative ones, the Nyquist frequency...
9ecb8d4b879e8dec113a440ac4207863b88ca86b
630,617
def get_risk_score(track, other): """ Get "risk" score between a track an another track. The "risk" evaluates how likely the two tracks are to be the same, lower being better, with 0 being a perfect match. This is a super handcrafted score, with little to no tuning, will probably not catch all possi...
4216a872c1c67aeb72002f9ce0dc03bc879e98dc
630,621
def fill_model( model, time_stop, time_step, initial_state, seed, n_points): """ Fill up model with output file and initial state and write it down in an input file Parameters ---------- model: str smoldyn model description time_stop: Float Simulation duration time_s...
778abce1319ca5c400d0c4a25f5b2ba6d759e508
630,624
import importlib def import_string(dotted_path): """ Import a dotted module path and return the attribute designated by the last name in the path. Raise ImportError if the import failed. """ module_path, attribute_name = dotted_path.rsplit('.', 1) module = importlib.import_module(module_path) ...
eb898d6c733ef6845bf50b4de7ed83beddcee894
630,625
import networkx as nx def nxMarkovGraph(self, all_vars=False): """Get networkx Graph object of the Markov graph of the model Example: >>> G = nxMarkovGraph(model) >>> nx.draw(G) """ G = nx.Graph() G.add_nodes_from( [v.label for v in self.X if (all_vars or v.states > 1)] ) for f in sel...
ffa8edd26488b3403b98759689722ced9dcaa68c
630,627
def get_message_type_from_message(message: str) -> str: """Parses the message_type from the message.""" return message.split(" ")[2].replace("\n", "")
94bd310785f3abce75e5cf7c7cb28eaabab561dc
630,630
import re import struct def GetFormatType(format_): """ Get format type and bitsize without prefix @param format_: format specifier @return: (format_, 0) or (format without prefix, bitsize) """ formattype = format_ bitsize = 0 if isinstance(format_, str): mat...
4f4cc9aa7dacbe766d93cee29e4b94f0b8ef9d8f
630,632
def retrieve_parameters(monitor, gradients=False): """Retrieves the parameters of the model or their gradients :param monitor: either a training or evaluation monitor :param gradients: whether to retrieve the gradients instead of the values :returns: the values of the parameters (or gradients) for each...
c0a297c973c83a43a80ba21d3b1deff8ff09ec33
630,637
def sum_mat_bins(mat): """ Compute the sum of matrices bins (i.e. rows or columns) using only the upper triangle, assuming symmetrical matrices. Parameters ---------- mat : scipy.sparse.csr_matrix Contact map in sparse format, either in upper triangle or full matrix. Re...
24b3140b6d2c5b74f03197144ceda6f72f7a6cde
630,639
def register_sql(spark, files, schema=None, sep=None, table_name="table", return_count=False): """ Register a list of files as a SQL temporary view. parameters: - files is overloaded: can be one file path or list of file paths. - spark: pyspark.sql.SparkSession - table_name: this is how we will...
f7f79211c2ad0dc8591dfdca7823e595f86ef035
630,642
def coloringToColorList(G, coloring): """ coloringToColorList(G, coloring) Calculate node colors based on an input graph and color dict. Parameters ---------- G : networkit.Graph The input graph. coloring : dict() Coloring scheme as dict. Returns ------- list(tuple(float, float, float)) List with col...
c78933a23f258232f01a027cbbb33e0f76fcfde4
630,645
import torch def get_ray_directions(H, W, focal): """ Get ray directions for all pixels in camera coordinate. Reference: https://www.scratchapixel.com/lessons/3d-basic-rendering/ ray-tracing-generating-camera-rays/standard-coordinate-systems Inputs: H, W, focal: image height, w...
71ed0146fc03630a38a10c0ed8b452e46a0a64f8
630,646
def trace(a, offset=0, axis1=0, axis2=1, dtype=None): """ Returns the sum along diagonals of the array. If `a` is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements ``a[i,i+offset]`` for all `i`. If `a` has more than two dimensions, then the axes specified ...
95f1549ca09c6bd6f38eec56f520e07077617e76
630,653
def openai(base_lr, num_processed_images, num_epochs, num_warmup_epochs): """ Learning rate scheduling strategy from openai/glow :param base_lr: base learning rate :type base_lr: float :param num_processed_images: number of processed images :type num_processed_images: int :param num_epochs:...
2ca1551ba3e0790c8f3e7d9457b7fa090ae5e4a0
630,655
def calculate_symmetric_kl_divergence(p, q, calculate_kl_divergence): """ This function calculates the symmetric KL-divergence between distributions p and q. In particular, it defines the symmetric KL-divergence to be: .. math:: D_{sym}(p||q) := \frac{D(p||q) + D(p||p)}{2} Args: ...
37793378b6b9020824d02dcc1707688404c55721
630,658
from dateutil import tz from datetime import datetime def fordtime_to_datetime(fordTimeString, useUTC=True): """Convert Ford UTC time string to local datetime object""" from_zone = tz.tzutc() to_zone = tz.tzlocal() try: utc_dt = datetime.strptime(fordTimeString, "%m-%d-%Y %H:%M:%S.%f") exc...
8aff092d60559f5fa8da8de7a430180b68b571a2
630,660
def create_obj(vertices, textures, normals, faces, filename=None): """ Create content of the OBJ file given the vertices, textures, normals, and faces. Args: vertices (list): list of vertices (for each corner of a triangular mesh) textures (list): list of textures normals (list): li...
30e07abcebc764889aef4e4bafa792c190fdca41
630,662
def transform_data(data_to_transform: list): """ Transforms data_to_transform from a 2d array to a 1d array Parameters ---------- data_to_transform: list the data which needs to be transformed Returns ------- new_data:list the transformed data """ new_data = [] ...
e9e38be008a7b603b20331dd912edcde9855ffa7
630,663
import torch def half_masker(batch_size, mask_shape, dim=0): """Return a mask which masks the top half features of `dim`.""" mask = torch.zeros(mask_shape).bool() slcs = [slice(None)] * (len(mask_shape)) slcs[dim] = slice(0, mask_shape[dim] // 2) mask[slcs] = 1 # share memory return mask.u...
5cac47871f1b22d44e306fc419d705ded54a9d6c
630,664
def clean_minmax(dic): """ Clean (set to zero) the MAX/MIN dictionary keys. """ # maximum and minimum values dic["FDMAX"] = 0.0 dic["FDDISPMAX"] = 0.0 dic["FDMIN"] = 0.0 dic["FDDISPMIN"] = 0.0 dic["FDSCALEFLAG"] = 0.0 # FDMIN/MAX not valid return dic
9947574eb54c1b54e59ae21d52370e29cacd6670
630,665
import torch def tanh(x: torch.Tensor) -> torch.Tensor: """Return torch.tanh(x)""" return torch.tanh(x)
f08460e1f2b53d565afbe29e37103d24efc6dccb
630,666
import re def remove_hanging_parenthesis(sample_string): """ Removes parenthesis at the end of strings. Args: sample_string (str): Input string Returns: str """ return re.sub(r"[^.*]\($", "", sample_string).strip()
23d4deb582973e209c5bb04f9b573c93997c7388
630,675
def _lemma_extractor(tokens): """Turn an iterable of tokens into language model input. :param tokens: An iterable of tokens (see :meth:`tokenize` for the token representation). :return: An iterable of token identifiers of the form ``(<graphic lemma variant>, <phonetic lemma variant>)``. "...
3d251303d70d045964718dba6ebf6c3643e4588b
630,677
def isWord(wordList, word): """ Determines if word is a valid word. wordList: list of words in the dictionary. word: a possible word. returns True if word is in wordList. Example: >>> isWord(wordList, 'bat') returns True >>> isWord(wordList, 'asdf') returns False """ wo...
ffead901ccc10797928c966b14cf4c2ac3f7f558
630,678
def color_to_hex(color): """ Converts a (R, G, B) tuple into a hex color string. """ return "#" + "".join('{:02X}'.format(x) for x in color)
60fe5c30fbf9bee81a225c027f564e3be9f891ee
630,679
import re def assets_from_string(text): """Correctly split a string containing an asset pair. Splits the string into two assets with the separator being on of the following: ``:``, ``/``, or ``-``. """ return re.split(r'[\-:/]', text)
250d57bd524d2090042058a5ce142340340c0f44
630,683
def get_min_rooms(lectures): """ Given an array of start and end times for lectures, find the minimum number of classrooms necessary. """ starts = sorted(start for start, _ in lectures) ends = sorted(end for _, end in lectures) num_rooms = 0 current_overlap = 0 start_idx, end_idx = ...
157f870ef7c83d1f4b5038ec0c5b0d5dded949cf
630,684
def _axis_label(label, unit=None): """Return a formatted label with units.""" return f"{label} / ({unit})" if unit not in [None, ""] else label
e9f2fc801a60f99fb2ce7ad8d4d69f8b4936b240
630,685
def cents_to_frequency(cents): """Converts cents to frequency in Hz""" return 10 * 2 ** (cents / 1200)
b1f6ed12ff5b8c94205eaa150188b9163b62b5a3
630,688
from datetime import datetime def add_set_time_to_state(state): """Annotate state the time of state creation""" state['setTime'] = datetime.now().timestamp() return state
8b229d76189457b88e80505860863a04ac34da78
630,693
import hashlib def generate_hash(content: bytes): """ Create md5 hash from bytes :param content: some data in bytes :type content: bytes :return: hash string :rtype: str """ return hashlib.sha3_512(content).hexdigest()
a6d1e5c06b5aedaef31fa7376ed782ec683ceb4f
630,696
def h2r(_hex): """ Convert a hex string to an RGB-tuple. """ if _hex.startswith('#'): l = _hex[1:] else: l = _hex return list(bytes.fromhex(l))
2cc6b758ef819b9e90b24e941e332ad610b76ecd
630,699
def namedtuples2dicts(namedtuples): """ Convert a dict of namedtuples to a dict of dicts. :param namedtuples: dict of namedtuples :return: dict of dicts """ return {k: dict(v._asdict()) for k, v in namedtuples.items()}
b227f2ef9baf44ed543c0fca616172acbb7e069a
630,700
import yaml def load_end2end_config(config_file): """ Loads end-to-end test setup file :param config_file: Name of the end-to-end config file. """ with open(config_file) as file: return yaml.full_load(file)
d3aee4f513ccdaf12cb75b53d2212b90388fad20
630,702
def get_caption(etype, cell_meta, resources): """return an ipypublish caption or False captions can either be located at cell_meta.ipub.<type>.caption, or at resources.caption[cell_meta.ipub.<type>.label] the resources version is proritised """ try: caption = cell_meta["ipub"][etype]["...
b8e08c734efb6d3f5d6204cb70930cb835800b4c
630,707
def hexify(s): """ Used to convert message to hex integers when encrypting. :param s: a string. :return: a string like '0x..', decode each character as a ascii hex number. """ if not s: # if input is null, evcrypt the message: '!' return '0x21' # ascii code for '!' lst = [] fo...
e457880c713cbc8d70ba3463a6fe9331a96ba5a8
630,709
def IBA_calc(TPR, TNR, alpha=1): """ Calculate IBA (Index of balanced accuracy). :param TNR: specificity or true negative rate :type TNR : float :param TPR: sensitivity, recall, hit rate, or true positive rate :type TPR : float :param alpha : alpha coefficient :type alpha : float :r...
7743df1e87791b6dcd1368f536f4e41f11ec9f45
630,710
def get_rect_even_dimensions(rect_item, even_dimensions=True): """ get the the graphics rectangle of the item, moved to position, with sides of even length Args: rect_item (QGraphicsRectItem) even_dimensions (bool): if False even dimensions are not enforced Returns ...
6f4cb39964be09f143ac47e45e2ee5dfc731e55a
630,711
def dictionary(input_list): """ To generate a dictionary. Index: item in the array. Value: the index of this item. """ return dict(zip(input_list, range(len(input_list))))
ccf6bf7b51dfb14fc87fbbc35d3509361bc535ef
630,712
import re from datetime import datetime def buildReportName(appName, reportName): """Constructs report name from app + user supplied report name""" reportName = reportName if reportName else '{}-{}'.format(appName, datetime.now().strftime('%Y-%m-%d-%H:%M:%S')) reportName = re.sub(r'[^\w\-:_\. ]', '_', reportNam...
5ef945946e2491955863d0c068034074b1ce2844
630,715
def z_score_normalize(tensor, scale_to_range=None): """Performs z-score normalization on a tensor and scales to a range if specified.""" mean = tensor.mean() std = tensor.std() tensor = (tensor - mean) / std if scale_to_range: delta1 = tensor.max() - tensor.min() delta2 = scale_to_...
3f217cdd5f3322a1b030ea0fe008f52792afab0c
630,716
def ami_architecture(ami_info): """ Finds source AMI architecture AMI tag. Parameters ---------- ami_info : dict AMI information. Returns ------- string Architecture of source AMI. """ for tag in ami_info['Tags']: if tag['Key'] == 'Architecture': ...
4cb7e811b7c3ba550ec36f97e9259d2b7ddd1999
630,717
def unmask_escape(text: str) -> str: """Replaces masking sequences with the original escaped characters. Args: text (str): masked string. Returns: str: unmasked string. """ return text.replace('ҪҪҪҪҪ', '&amp;').replace('ҚҚҚҚ', '&lt;').replace('ҺҺҺҺ', '&gt;')
ddad3486703af34f6b9cf1e47ba2d2faf8210e29
630,719
def _sq(x): """Square quickly.""" return x * x
c6f39e9ac7e1d9f9c4eed0c49bd10398ed2beb01
630,721
def get_len_of_bedtool(bed_obj, cov_col=3, cutoff=1): """ Get the number of rows (sites) of BedTool object :param bed_obj: :param cutoff: :return: """ # covList = [] # for row in bed_obj: # covList.append(int(row[cov_col])) # covSeries = pd.Series(covList) df = bed_obj.to...
c0efa1877ef153f1c8a6b1298cd610ce5042d1d0
630,723
def rreplace(s, old, new, occurrence): """ Function which replaces a string occurence in a string from the end of the string. """ return new.join(s.rsplit(old, occurrence))
fc1cfde420b60c9f4769c31d302272a02f708a0b
630,727
def generate_description(slug: str) -> str: """ Fungsi yang menerima input berupa string dengan kebab-case dan mengubahnya menjadi string UPPERCASE. Fungsi ini juga akan mengakronim input yang terlalu panjang (lebih dari 30 karakter). Contoh: >>> generate_description("home") 'HOME' ...
9fe1e270d799dc47d8a28d1c4e2eeb4c28525ef3
630,731
def find_plate_scale(dictionary): """ Find the plate scale determined by Astrometry.net This value is given inside a COMMENT header, hence we have to search for it Will return the plate scale as a float if it exists, None otherwise. """ try: comment_entry = dictionary["COMMENT"] exc...
0e75721d929918f48b1bae674d62ecfd7e38d25c
630,732
def _fix_snpeff_version_line(line, supported_versions): """Change snpEff versions to supported minor releases. ##SnpEffVersion="2.0.3 (build 2011-10-08), by Pablo Cingolani" """ start, rest = line.split('"', 1) version, end = rest.split(" ", 1) version_base = version.rsplit(".", 1)[0] for s...
1692310fe8f3f4658ce506e58a09f7c8b4bcbc70
630,735
def removesuffix(string, suffix): """ Returns <string> without the <suffix> suffix. Copied from https://www.python.org/dev/peps/pep-0616/#specification to support python versions < 3.9 :param str string: string from which to remove suffix :param str suffix: suffix to remove from string :re...
e2136ae568165fabf233a885a7b3526c3dbae5c8
630,737
def get_x(path, width): """Gets the x value from the image filename""" return (float(int(path.split("_")[1])) - width/2) / (width/2)
c387ce4415b75677f2c7b4a1bc27b12cba469d22
630,738
def cal_iou(box1, box2): """ :param box1: = [xmin1, ymin1, xmax1, ymax1] :param box2: = [xmin2, ymin2, xmax2, ymax2] :return: """ xmin1, ymin1, xmax1, ymax1 = box1 xmin2, ymin2, xmax2, ymax2 = box2 # 计算每个矩形的面积 s1 = (xmax1 - xmin1) * (ymax1 - ymin1) # C的面积 s2 = (xmax2 - xmin2) * ...
c962c1588f082921f2d22c3386ec757cc06438ae
630,743
def _ReadOrder(fo): """Read one example from the order file.""" line = fo.readline() if not line: return None line = line[:-1] order = line.split() order = [int(item) for item in order] return order
fd5d1ff3e71696e2e20963444e3a70551b31e4c3
630,745
import secrets def bernoulli_neg_exp(gamma, rng=None): """Sample from Bernoulli(exp(-gamma)). Adapted from "The Discrete Gaussian for Differential Privacy", Canonne, Kamath, Steinke, 2020. https://arxiv.org/pdf/2004.00010v2.pdf Parameters ---------- gamma : float Parameter to sample ...
36f2004607059d399ffe7bf6767e63a8fa26b82c
630,748
from typing import Optional from typing import Tuple def _get_validation_scope( has_valid_abbrev: bool, blacklist_policy: Optional[str], ) -> Tuple[str, str]: """Determine the validationScope for DST and abbreviations. Returns tuple of the C++ ValidationScope and a human-readable comment. """ ...
8afc0f90e0179d640c0ec80434fad0170257d911
630,756
def lemmatize(lemma_dict, word): """Lemmatize a word. Lemmatizes a word using a lemmatizer which is represented as a dict that has (word, lemma) as (key, value) pair. An example of a lemma list can be found in https://github.com/michmech/lemmatization-lists. If the word is not found in the diction...
a035c402663ff85753ae4ede1828e0007abedb32
630,757
def get_digits_matching_next(captcha, step_size=1): """Get digits from captcha that are matching next step_size digit.""" matching_digits = [] for index, digit in enumerate(captcha): next_index = (index + step_size) % len(captcha) if digit == captcha[next_index]: matching_digits....
c8b1c6f48ea12eb5a1ae72e3a99fda8a4f3e48a8
630,763
import torch def accuracy(output, target): """ Compute accuracy comparing the output of the model and the target. Args: output : [batch_size, num_classes, caps_dim] The output from the last caps layer. target : [batch_size] Labels for dataset. Returns: accuracy (float): The...
efaaaf987d05d07abeb8a97dc48fd0d2d81fd8ce
630,765