content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def normalize_time_window(time_window, values_per_time_point): """ Bring all values in time window to -1, 1 range and center them around 0. :param time_window: vector of values for set of time points :param values_per_time_point: number of numeric values describing one time ...
4ee9fb63dfe30736f4c33ab1d97bd49d1f4aa944
71,234
def mean(nums): """ Gets mean value of a list of numbers :param nums: contains numbers to be averaged :type nums: list :return: average of nums :rtype: float or int """ counter = 0 for i in nums: counter += i return counter / len(nums)
d3ea7af8792f4fdd503d5762b5c0e54765ce2d99
71,235
def process_data(dr): # 统一输入单词的长度,不足补0,此方法会增加训练时间 """ :param dr: class data reader :return: process X, Y """ return dr.XTrain, dr.XTest, dr.YTrain, dr.YTest # 这是为了统一一个表达方式,和之前的章节一样
cc05605d77e25ed7363da3de9407d1f51b7dbf4b
71,236
def conv_block(x, growth_rate, name, activation, momentum, epsilon): """Convolutional block defined in Densenet architecture, It is its base layers Args: x: input tensor form the precedent layer growth_rate : float number, growth rate or number of filters (ref. paper) ...
125597246999c38630c8c9392e0ef874dbe863df
71,237
def question_2(data): """ Plots 2 graphs: Temperature change as a function of 'DayOfYear', and STD of daily temperatures as a function of 'Month'. Parameters ---------- data: preprocessed of city temperature dataset Returns ------- A tuple of: 1. A design matrix...
610067d77957ef36170e97d7152e2e1bc1b84e11
71,238
def map_id_to_value(nodes, value): """Maps Node id to another value""" return remove_colons(nodes).set_index('id')[value].to_dict()
b1f20a25df51cd93d13e16de197affbb768908e9
71,239
def PlotAA(df, eom=9, show_plot=True): """ Summary ------- Plot of annual average bar chart. No documentation as of 2018-10-31. Future Development ------------------ 1. Add comma separator to y-axis. 2. Add option to view by Sacramento Index Water Year Types. """ # Obtain ...
b258b0ecee7676a994558d9b2f89583b89a425b3
71,240
from .parser import read def df_from_sas(target, meta_df, skiprows=None, nrows=None, chunksize=None): """Deprecated. Use pyhcup.parser.read()""" print "WARNING: pyhcup.sas.df_from_sas() is deprecated and is scheduled for removal in pyhcup 0.1.6; use pyhcup.parser.read()" result = read(target, meta_df...
4afd2fd61dcd6af489cb63977ff8ad1dc222749d
71,241
def all(functions): """Returns function that returns True when all components return True.""" def apply_to(*args, **kwargs): return conjoin(functions, *args, **kwargs) return apply_to
6279be8d9e1977454e24d35d3cc94228f64dda35
71,242
def CombineProvenanceConst_get_decorator_type_name(): """CombineProvenanceConst_get_decorator_type_name() -> std::string""" return _RMF.CombineProvenanceConst_get_decorator_type_name()
6542246ac76545da6f98ada6f15653850b6ccc5e
71,243
def BuildVRTInternalObjects(*args): """ BuildVRTInternalObjects(char const * dest, int object_list_count, GDALBuildVRTOptions options, GDALProgressFunc callback=0, void * callback_data=None) -> Dataset """ return _gdal.BuildVRTInternalObjects(*args)
e5eb1aef230c79e6ff68a8f57fed0ef106c2e181
71,244
from typing import Tuple def _has_line_of_sight(matrix: np.ndarray, start: Tuple[int, int], end: Tuple[int, int]) -> bool: """ Return True if two points on a grid have line of sight. Return True if start == end. """ if start == end: return True start_y, start_x ...
fa9ecdb54fba90c43586f710b58bc51f37992048
71,245
def threshold1(x, col, thresh): """ 1-dimensional classification using a threshold function. """ return x[:, col] <= thresh
5814ab93fe41e2e92f4648bfee1f8033ff0864b6
71,246
import torch def compute_rank(predictions, targets): """Compute the rank (between 1 and n) of of the true target in ordered predictions Example: >>> import torch >>> compute_rank(torch.tensor([[.1, .7, 0., 0., .2, 0., 0.], ... [.1, .7, 0., 0., .2, 0., 0.], ...
0aed5b14ef9b0f318239e98aa02d0ee5ed9aa758
71,249
def load_dataset(dataset_path, sequence_length, src_vocab_file, tgt_vocab_file, batch_size, buffer_size): """Create a tf.data Dataset. Args: dataset_path: Path to the files to load text from sequence_length: Maximun Length of the Sequence vocab_file: Location of vocab file batch...
b831403cbdf3ee2351aab72099031cf3dd780af7
71,250
def udfize_lambda_string(code: str): """Return a string with the code as a function""" return "lambda input: ({})".format(code) # return "lambda input: (%s)" % code
c519c8ec408b00f033878b6083d4a922f32d2ac9
71,253
import json def load_scalabel_frames( scalabel_frames_path ): """ Loads Scalabel frames from a file. Handles both raw sequences of Scalabel frames as well as labels exported from Scalabel.ai's application. Raises ValueError if the data read isn't of a known type. Takes 1 argument: scalab...
7e5467d0f184dba1e3efc724391931ed4053a683
71,254
def ovs_version_str(host): """ Retrieve OVS version and return it as a string """ mask_cmd = None ovs_ver_cmd = "ovs-vsctl get Open_vSwitch . ovs_version" with host.sudo(): if not host.exists("ovs-vsctl"): raise Exception("Unable to find ovs-vsctl in PATH") mask_cmd = host.r...
607ffbb2ab1099e86254a90d7ce36d4a9ae260ed
71,255
def maximum_displacement(initial_velocity): """Derived from s = 0.5 u + u t + 0.5 a t^2 at t = u and a = -1. The (0.5 u) term comes from the order of rules of the motion of the probe, the displacement changes before the velocities are updated.""" return int(0.5 * initial_velocity * (1 + initial_vel...
c4b71ad83d787cae9ad9abe7d044b0e2d66b9cc0
71,256
from typing import List def csv_rows(s: str) -> List[List[str]]: """Returns a list of list of strings from comma-separated rows""" return [row.split(',') for row in s.split('\n')]
7a6ea8c0f69801cfb1c0369c238e050502813b63
71,257
import math def getRotationMatrix(a, b, c): """ Compute Rotation Matrix given RPY euler angles. """ # Roll R_x = np.array([[1, 0, 0], [0, math.cos(a), -math.sin(a)], [0, math.sin(a), math.cos(a)] ]) # pitch R_y = np.array([[math.cos(b),...
5b68425a0b3244579528fd601b52c43add5de03e
71,258
def GetMatchURL(soup): """Gets the ongoing match URL""" live_match_url = soup.find("a", attrs={"class": "match-status-3"})["href"] return live_match_url
bae3658c46976c7d43234e063d78eeea027d3095
71,260
def get_flattened_axes(x): """ Ordered list of axis visible to MKLDNN """ return Axes.as_flattened_list(x)
aa4ec87d1a2bbe254eb88f9356f1a76aaaf71f43
71,261
def get_service(service_name): """ Gets the service VerificationService, checks if there is already one in the memory, if so return that one. :param service_name: e.g. phone, email """ # Check if service_name in USER_VERIFICATIOn if not settings.USER_VERIFICATION.get(service_name, None): ...
38eeece00518fd638df8246878a597cee825bd5e
71,262
def wait_to_fetch(ctx, interval): """Check if an unscored solution exists in a database by calling query every "interval" seconds. :param ctx: Click context :param interval: int: Interval to access a database (second) :return solution_id: ID of a solution that has not been scored. """ w...
372da8b7e4c19b6d2d0f728753a1584a3ccd40cb
71,263
def ctab2inchiKey(): """ Converts CTAB to InChi Keys. CTAB is either single molfile or SDF file. cURL examples: curl -X POST --data-binary @aspirin.mol ${BEAKER_ROOT_URL}ctab2inchiKey curl -X POST -F "file=@aspirin.mol" ${BEAKER_ROOT_URL}ctab2inchiKey """ data = list(request.files.values())[0].fil...
8cadc1683e4f644f673751e95f560a45822593a4
71,264
def matmul(a: ndarray, b: ndarray) \ -> ndarray: """ Matrix product of two arrays. """ return ndarray(af.matmul(a._af_array, b._af_array))
afdf18f72fcaf915e32b829d696eb605887254d1
71,266
def flam2epp(lam, flam, ddisp): """ Convert flux density [erg/s/cm2/A] to photons per pixel [photons/s/cm2/pixel] Args: lam (array-like): wavelength array associated to the spectrum flam (array-like): spectrum in units of erg/s/cm2/A ddisp (float): ...
4018c7346bf842b93f25a72b4249269ad245f31b
71,267
def demo_delete(id, **kwargs): """ swagger_from_file: Swagger/demo/del.yml """ return quickly_del(Demo, id)
499045763cecd62e67334045b031929de61c5070
71,268
from numpy import sum def load_LSRK(file,lstype='2S',has_emb=False): """ Load low storage methods of the types 2S/2S*/3S*/2S_pair/3S_pair from a file containing the low-storage coefficient arrays. If has_emb=True, the method has an embedded method that requires an extra register. ...
c8bef2e6973f73720c10e757cd01e536d027c67c
71,270
import calendar def create_disjunctive_constraints(solver, flat_vars): """ Create constrains that forbids multiple events from taking place at the same time. Returns a list of `SequenceVar`s, one for each day. These are then used in the first phase of the solver. """ events_for_day = [[] for _...
f7f8592ac00c8cac9808bb80d425ff1c1cf10b9e
71,271
def interp_quad(x, y, d, rLCFS, r): """Function 'interp' used for kinetic profiles. """ f = interp1d(x, np.log(y), kind="quadratic", assume_sorted=True, copy=False) idx = np.searchsorted(r, rLCFS) core = np.exp(f(np.clip(r[:idx] / rLCFS, 0, x[-1]))) edge = core[..., [idx - 1]] * np.exp( ...
d877c4521cc29046ca827f7235e2401d808b8257
71,272
def generateWalkJumpSample(adjacency_list, p, jump_probability): """ Generate random walk sample from real graph """ sample_network = dict() nodes = set() edges = set() number_of_edges = sum([len(adjacency_list[u]) for u in adjacency_list.keys()]) / 2 desired_num_edges = int(p * number_o...
fa3c1ea0df20c97e2587c2f55e954a6680856d9b
71,273
def pick_cluster(session,picks,pickwindow,pickaveraging_norm,counter): """ Cluster picks from different components on the same station. """ # | | /\ # | | / \ /\ # | | /\ /\ / ...
00ad6ca61efbd7093c827b0d57271c41ece1bc22
71,274
def echo(): """ Method used to test how Python is handling PowerBuilder requests. Will decode data sent from PB and return it to the requester. :return: Decoded data sent from the requester. """ try: return request.data.decode("utf-8"), 200 except UnicodeDecodeError as why_ude: ...
9b077c0603baef42dac91f7dd47020af110f2866
71,275
def minhash_xor_192(features_32, masks=PERMS_192_NP): """Numpy & Numba supported implementation""" hashes = np.full(192, np.uint32(MAX_UINT32)) for f in features_32: hashes = np.minimum(hashes, np.bitwise_xor(masks, f)) return hashes
67d1c913bb6cc8596b04c19fb28deccfd76ba198
71,278
def fit_nelson_siegel_yield(tau, y, theta_0=None): """For details, see here. Parameters ---------- tau : array, shape (n_,) y : array, shape (n_,) theta_0: array, shape (4,) Returns ------- theta : array, shape (4,) """ n_ = len(tau) def minimization_...
feeeeef81cab003d006bf3d64076cf119c6f6c6f
71,279
def magic_string(string: str, filename: str = None): """ Returns tuple of (num_of_matches, array_of_matches) arranged highest confidence match first If filename is provided it will be used in the computation. :param string: string representation to check :param filename: original filename :retu...
8ce083418921a9a3da675a8ddbb144df29e096d2
71,280
import torch def correct_resize_label(tensor, size): """ Resize torch.Tensor label Parameters ---------- tensor : torch.Tensor size : Tuple[int] Returns ------- resized_tensor : torch.Tensor """ device = tensor.device tensor = tensor.detach().cpu() resized = [] ...
e2c6601e6c17fa894c0b6f83f61087d9f75e32b6
71,281
def read_data1(filename): """ This function reads the data from .txt file. :param filename: reading directory :return: lists of word_ids, words, emphasis probabilities, POS tags """ lines = read_lines(filename) + [''] word_id_lst, word_id_lsts = [], [] post_lst, post_lsts = [], [] se...
c31de2ff853c799078468d675d7a7adf4bb2fa12
71,282
def workflow_add_tags(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /workflow-xxxx/addTags API method. For more info, see: https://documentation.dnanexus.com/developer/api/introduction-to-data-object-metadata/tags#api-method-class-xxxx-addtags """ return DXHTTPRequest('/...
440d39e622f1dc6336118ce9704a187842e2ca06
71,283
def login(var=random.randint(0, 1000), error=None): """ The function can get a POST or GET requests. if the request is GET: returns the html login_page template if the request is POST: checks the data(email and password) in the users database. """ global clients_connecting if request.method ...
1e397ec4dc571f2c21893b70993c7b5a296293cb
71,284
def get_body(request): """ Return the body of a concrete publication. """ context = request['context'] entities = request['entities'] feed = context['feed'] ordinal = entities['ordinal'][0]['value'] body = feed[ordinal]['summary_detail']['value'] context['body'] = body return con...
53080b1727f0230a30b9fc4435d455a06e927be3
71,285
def get_default_snapshot_id(project): """ Generate a snapshot id from data on the given project. :param project: project object :return: snapshot id """ def snapshot_id_from_branch_name(name): return "{}:HEAD".format(name.replace('/', ':')) default_branch = project.git.get_default_branc...
2c542678036541372fa675e61b4f5a969cd5ab0f
71,286
import random def filter_shuffle(seq): """ Basic shuffle filter :param seq: list to be shuffled :return: shuffled list """ try: result = list(seq) random.shuffle(result) return result except: return seq
3f2dce2133ba32d8c24d038afaecfa14d37cbd4e
71,287
def read_vcf_file(vcf_file_address): """ Reading the vcf file input: vcf file outputs: lines_list: list of string. each string is a line of phased vcf file. var_pos_het_list: genomic position of phased hetrozygous variants in the vcf file. line_number_het_list: list...
f4e9718d8fc21f5c1dc37aa570f6bf1615b82452
71,288
def ipd_download_new_or_modified(organizer: Organizer, info: IpdDownloadInfo) -> bool: """ Accepts new files or files with a more recent modification date. """ resolved_file = organizer.resolve(info.path) if not resolved_file.exists(): return True if not info.modification_date: P...
36cbf48347b6bc4e7557cb06f316dbd912ae6e44
71,289
def sushi_report_all(request): """Report from SUSHI, shared common data.""" return parse_sushi_file(request.param)
9ae44e8ea80c74d1580662e9ce1bbd530214356a
71,290
def get_package_list_from_file(path): """ Create a list of packages to install from a provided .txt file Parameters __________ path: Filepath to the text file (.txt) containing the list of packages to install. Returns ______ List of filepaths to packages to install. Notes ...
91ef3e634e98afd116d2be9c803620f672acd950
71,291
def property_view(request, slug, property_id): """ """ return render(request, 'property/property.html', {'slug': slug, 'id': property_id})
05b28046274cfb1f09bfbe9c352888202b4fb485
71,292
def read_comment_line(line, verbose=0): """ Use pyleri to parse an extxyz comment line """ result = grammar.parse(line) parsed_part = result.tree.children[0].string if not result.is_valid: raise SyntaxError(f"Failed to parse entire input line, only '{parsed_part}'. " ...
dfdbea582dcfa14f5e3aefec89eb3959cde67685
71,293
def escaped_commands(line): """Transform escaped commands - %magic, !system, ?help + various autocalls. """ if not line or line.isspace(): return line lineinf = LineInfo(line) if lineinf.esc not in tr: return line return tr[lineinf.esc](lineinf)
84dea2fba22c7a7da6d75e8257b597c68aab67ef
71,294
def has_postgres() -> bool: """ Whether to use postgres """ return find_spec("asyncpg") is not None
0d6348f52fb01114bc57cc539d3874815da16ec8
71,295
def passthru(func): """Return value of function by same name in proxied object. Proxied object is located as an attribute named `_wrapped` in proxy object. """ @wraps(func) def _wrapper(self, *args, **kwargs): name = func.__name__ return getattr(self._wrapped, func.__name__)(*args,...
bc33e482b9b0c46f4e48f9dbe1367e60d47f5d04
71,296
def _sources_from_virtual_sink_port(sink_port, _traversed=None): """ Resolve the source port that is connected to the given virtual sink port. Use the get source from virtual source to recursively resolve subsequent ports. """ source_ports_per_virtual_connection = ( # there can be multiple p...
3a378632702afe62166f5ee75b43ba930b712a75
71,297
def parse_jcamp_line(line,f): """ Parse a single JCAMP-DX line Extract the Bruker parameter name and value from a line from a JCAMP-DX file. This may entail reading additional lines from the fileobj f if the parameter value extends over multiple lines. """ # extract key= text f...
84061c3f4bc42a62e308d5f93877e5c55d85efc1
71,298
def get_grounded_agent(gene_name): """Return a grounded Agent based on an HGNC symbol.""" db_refs = {'TEXT': gene_name} if gene_name in hgnc_map: gene_name = hgnc_map[gene_name] hgnc_id = hgnc_client.get_hgnc_id(gene_name) if not hgnc_id: hgnc_id = hgnc_client.get_current_hgnc_id(gen...
e4501fefe4d1617bd9d32679fd966b101708297d
71,299
def _check_header(line, length): """check if headers first_header_line :: <=>+ second_header_line :: <->+ normal_header :: <#>+<span_element> """ if length * '=' == line: return {'prev_block_type': 'h1'} if length * '-' == line: return {'prev_block_type': 'h2'} if length ...
4674750c2c7bcd39327c1818a8d81f3e6671ec3b
71,300
def power_spectrum(kx, ky, n): """ Calcs power specturm, which is proportional of k**n = (kx,ky)**n :param kx: :param ky: :param n: :return: """ if kx == 0 and ky == 0: return 0 else: return np.sqrt(kx ** 2 + ky ** 2) ** n
1d0775bb55701fa7fa08066ed7c1ae5265d49fe2
71,301
def unwrapText(text): """Unwrap text to display in message boxes. This just removes all newlines. If you want to insert newlines, use \\r.""" # Removes newlines text = text.replace("\n", "") # Remove double/triple/etc spaces text = text.lstrip() for i in range(10): text = text.repl...
f37aafa3a003b3b06b8e9e1a03c833d05c5c0deb
71,302
import urllib import json def get_sources(meals): """ Function to retrieve meals list from the api """ get_latest_url = 'http://www.themealdb.com/api/json/v1/1/latest.php' get_category_url = 'http://www.themealdb.com/api/json/v1/1/list.php?c=list' get_search_url = 'http://www.themealdb.com/a...
b93695fe79da47f52d2d4e3f863de26210292802
71,303
import urllib def get_queue_length(queue_name, xqueue_session): """ Returns the length of the queue """ try: success, response = util._http_get(xqueue_session, urllib.parse.urljoin(settings.XQUEUE_INTERFACE['url'], urls.XqueueURLs.get_queuelen), {'queue_name': queue_name}) if not success: ...
61fc0c73f300c93aaad449fd4386179601e8a5d2
71,304
from typing import Callable from typing import List from typing import Tuple from typing import Union from typing import Sequence import torch def calc_exact_shapley_values( fn: Callable, num_features: int, shapley_factors: List[Tuple[List[int], int]], new_data: Union[Tensor, Sequence[Tensor]], ba...
4b62855bb2eea715cb2920e5b218af6940768328
71,306
def imshow_det_rbboxes(img, bboxes=None, labels=None, segms=None, class_names=None, score_thr=0, bbox_color='green', text_color='green', ...
63d225dc0d016fdc434ea35fc65844ec9dc5c128
71,307
def lab2rgb(lab:np.ndarray): """ input lab as pytorch tensor of size (batch_size, 3, h, w) or (3, h, w) """ if ndim(lab)==4: channel_idx=1 if int_shape(lab)[1]==3: channel_idx = 1 elif int_shape(lab)[-1]==3: channel_idx = -1 rgb=xyz2rgb(lab2xyz(la...
969c7676cd3c030171ec7451b96274ea4ab7e349
71,308
def feed_clf(filename): """ prepare data for classifier 1. 6 subcategories: ['valueScore', 'locationScore', 'sleepScore', 'roomScore', 'cleanScore', 'serviceScore'] 2. find sentences contain ['value', 'location', 'sleep', 'room', 'clean', 'service'] 3. if the related score is 1,2, put nega...
cfb3a38d5fa73f650ff30b3ad382feb29117d084
71,309
def _play(agents, game_state, time_limit, match_id): """ Run a match between two agents by alternately soliciting them to select a move and applying it to advance the game state. Parameters ---------- agents : tuple agents[i] is an instance of isolation.Agent class (namedtuple) game_st...
2162f3d84856966699834066c227e4c163c0cfa9
71,311
import torch def prepare_batch_tensor(batch, device, non_blocking, new_shape=None): """Prepare the batch data for training/inference, move data to GPU, reshape the target if necessary. Args: batch (torch.Tensor): A batch of data. device (torch.device or str): Device to load the backbone a...
95594fea61dd598e2c6442211bc2ee72cad8af03
71,312
def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date, until_date=None): """ Gets all cases with a specified owner ID that have been modified since a particular reference_date (using the server's timestamp) """ return [ row['id'] for row in CommCareCase.get_db().view( ...
c5353088960671c14e1e48ad1f3fa497fdfff205
71,313
def getSubNode(prgNode, NodeName): """ Find Sub-Node in Programm Node Arguments: prgNode {ua PrgNode} -- Programm node to scan NodeName {[type]} -- Name of Sub-Node to find Returns: ua Node -- Sub-Node """ for child in prgNode.get_children(): if child.get_display_na...
2da431eff566d7e2c76d4ca4646e15f762c00d4d
71,314
def clean_data(df): """ Clean data and create categories Columns. :param df: Pandas Dataframe. Dataframe Input :return: Pandas Dataframe. Dataframe cleaned with categories at your own column """ # create a dataframe of the 36 individual category columns categories = df['categories'].str.sp...
38a6dec9e59c7e6ce10e9b66180332ac61c7c7bc
71,315
def seq2ngrams(seq, n): """ 'AGAMQSASM' => [['AGA', 'MQS', 'ASM'], ['GAM','QSA'], ['AMQ', 'SAS']] """ a, b, c = zip(*[iter(seq)] * n), zip(*[iter(seq[1:])] * n), zip(*[iter(seq[2:])] * n) str_ngrams = [] for ngrams in zip(a, b, c): for ngram in ngrams: str_ngrams.append("".jo...
d207183aba274dc2c374dec5b9c6dc9c8c8e8847
71,316
def check_genotypes(glstring): """ Takes a GL String, and checks to see if any unphased genotypes contain more than one locus. A list of tuples is returned. Each tuple consists of the genotype, a set of loci found in the genotype, and a text string. For unphased genotypes, the text string is either ...
2dc0b0e3cbc148b90173e957dc5e0be738309623
71,319
def stations_by_river(stations): """This function returns a Python dict (dictionary) that maps river names (the key) to a list of station objects on a given river.""" y = {} for n in stations: if n.river not in y: y[n.river] = [n.name] else: y[n.river].append(n.name) ret...
1e1023cdad87a3fdd5921d08448a4a2e9ceb311c
71,320
def summary(request): """ View function for Summary of site. """ brokers = [] all_trades = Transaction.objects.filter(type='Buy').values() for i in all_trades: if i['broker'] not in brokers: brokers.append(i['broker']) summList = [] for i in brokers: IPOPL...
df06ceb8aad283c61c13a5b3120c28a47d1b41ab
71,321
def Tensor2Image(img): """ input (FloatTensor) output (PIL.Image) """ img = img.cpu() img = img * 0.5 + 0.5 img = transforms.ToPILImage()(img) return img
dbf6510ef907a74adbbaa53415832212fb84a3aa
71,322
def lc_ksvd(X, y, D, Q, alpha=1, beta=1, lambda1=1, lambda2=1, sparse_coder=None, max_iter=2, approx=False, mmap=False, verbose=False, n_jobs=1): """ X: the data matrix with shape (n_features,n_samples) y: the vector that contains the label of each datapoint Q: a matrix with shape (n_atoms,n...
2a46353a84357d314416b06303ff19b1472ca4c0
71,323
import re def parse_align_seq(align_seq, ref_base, max_insertion_size): """ 解析比对结果中某个位置的所有碱基 """ base_list = [] it = re.finditer(pattern, align_seq) for match in it: base = match.group() if base.startswith("^") or base == "$": continue elif base == "." or ba...
3cadfa627f4398e9397474bdd914f3007da7a8da
71,324
from typing import Tuple def xyz_to_bev( xyz: NDArrayFloat, voxel_resolution: Tuple[float, float, float], grid_size_m: Tuple[float, float, float], cmap: NDArrayFloat, ) -> NDArrayByte: """Convert a set of points in Cartesian space to a bird's-eye-view image. Args: xyz: (N,3) List of p...
e06c154dcf1a725fa3a52c37d45556df0ac55909
71,325
import six def determine_position(position, img, mark): """ Options: TL: top-left TR: top-right BR: bottom-right BL: bottom-left C: centered R: random X%xY%: relative positioning on both the X and Y axes X%xY: relative positioning on the X axis a...
b4a4ee83778723dceea6a10441d714f0c9b31064
71,326
def is_serializable_descendant(base): """ Args: base (type): Base class to examine Returns: (bool): True if `base` is a descendant of `Serializable` (but not `Serializable` itself) """ if "Serializable" in globals(): # We're doing a forward reference here, class is defined below ...
1b2da0de39148ead3b9177496b7cdbd6895e3533
71,328
def part_2(input_data: str) -> int: """Need to rack an 'aim'. Commands mean different: down X increases your aim by X units. up X decreases your aim by X units. forward X does two things: It increases your horizontal position by X units. It increases your depth by...
60cf6a884bb6a0a9c69d214a0b883ab7321f7d1b
71,329
def doTest(n): """Runs a test. returns score.""" score = 0 l = list(range(1,16)) for i in l: if input("what is {} to the power of 3? ".format(i)) == str(i**3): score += 1 print("Correct.") else: print("Wrong, the correct answer is {}".format(i**3)...
83f32bec718e7459218b8863e229d5ecbd479d2c
71,330
def binarize_time_series(layer_state, threshold, absolute=False): """ Given a threshold return a binary matrix of 0's or 1's based on threshold :param layer_state: TxN matrix where N is the number of neurons. :param threshold: threshold above which the value is considered 1. :param absolute: whether...
ae4b4059cc4eb85f07461e330c7389dbaa5efc83
71,331
def compoundInterestPresentValue(p, r, c, n): """Compound interest present value Returns: present value Input values: p : principal r : interest rate c : number of compounding periods in a year n : (c * t), total number of compounding periods """ pv = (p / ((1 + (r / c)) ** n)) ...
eef2b1628caa7d0f986f6bfd06f336083e9cb76a
71,332
def ResourcePageDetails(request, pk): """ Retrieve, update or delete a job posting. """ try: resource_page = ResourcePage.objects.get(pk=pk) except Resource.DoesNotExist: return HttpResponse(status=500) if request.method == "GET": serializer = ResourcePageSerializer(reso...
98e0ed57ffb2581bc69bc6fdcc2cc8e145f043c8
71,333
def cifar10_classification_model(): """ CIFAR10 classification """ return get_model( False, (3, 32, 32), [7,7,7], [1,2,2], [32,64,128], 10, 1, 13, 0.9, 1, 1, 1, False, False, False, ...
f2d780f4e9568c0a7362d5a7858a898589713378
71,334
def build_turbine_loc(turbine_x, turbine_y): """ Make a DataFrame containing plant layout info (wind turbine locations). Args: turbine_x (np.array): wind turbine locations (east-west). turbine_y (np.array): wind turbine locations (north-south). Returns: turbineLoc (pd.DataF...
2786e0539bcabbf099cfd540b90f84976b9b1b38
71,335
from typing import Dict from typing import Any def _BigQueryToElwc(pipeline: beam.Pipeline, exec_properties: Dict[str, Any], split_pattern: str) -> beam.pvalue.PCollection: """Read from BigQuery and transform to ExampleListWithContext. When a field has no value in BigQuery, a feature with no ...
68a854cdd054cac5739a744ea69a05d35bff6d4f
71,336
def clean_spiketimes(spikeTimes, mindT=0.7): """ Clean up spike time array, removing all less than mindT spikeTimes is a 1-D list or array mindT is difference in time, same units as spikeTimes If 1 or 0 spikes in array, just return the array """ if len(spikeTimes) > 1: dst = np.diff(...
6e5667961243ac6a51173f7da6eb661f78c9d368
71,337
from pathlib import Path def euler(radius = 3, angle = 90, p = 1.0, use_eff = False, num_pts = 720): """ Create an Euler bend (also known as "racetrack" or "clothoid" curves) that adiabatically transitions from straight to curved. By default, `radius` corresponds to the minimum radius of curvature of the...
e3808021e512bef6b6f4642f3a657893712dd317
71,339
import numpy def best_dice(l_a, l_b): """ Best Dice function :param l_a: list of binary instances masks :param l_b: list of binary instances masks :return: best dice estimation """ result = 0 for a in l_a: best_iter = 0 for b in l_b: inter = 2 * float(numpy....
d00c668fe8c97fa2a78a62ac94492c665dc4a311
71,340
def isTestHub(node): """Check if a node is a Plugable 7-Port Hub (Model USB2-HUB7BC) The topology of this device is a 4-port hub, with another 4-port hub connected on port 4. """ if not isinstance(node, find_usb_devices.USBDeviceNode): return False if 'Test HUB' not in node.desc: return False if...
c5255364d3fee0e5f30d08f0d1e6bb8273b63343
71,341
def dither(tensor, shape, amount, time=0.0, speed=1.0): """ """ height, width, channels = shape white_noise = basic([height, width], [height, width, 1], time=time, speed=speed, distrib=ValueDistribution.simplex) return effects.blend(tensor, white_noise, amount)
7134eb292d276c735f23f27969aaf5ad77ada933
71,343
def hex_list_to_dec(hex_list): """Takes a hexidecimal number as a list of its digits represented as strings. Returns the base 10 conversion of the hex as an integer. """ hex_dict = gen_hex_dict() hex_list.reverse() dec_sum = 0 for i, h in enumerate(hex_list): dec_sum += hex_dict[h] ...
f1814bea274e7c156dc471a88131d6a053a5a1e5
71,346
def path_to_tensor(img_path): """ Getting a tensor from a given path. """ # Loading the image img = image.load_img(img_path, target_size=(512, 512)) # Converting the image to numpy array x = image.img_to_array(img) # convert 3D tensor to 4D tensor with shape (1, 512, 512, 3) x = ...
42cf19b3f26afa02ba124ed8dd7f6b8fa7335ea1
71,348
def preorder(root): """Preorder depth-first traverse a binary tree.""" ans = [] stack = [root] while stack: node = stack.pop() if node: ans.append(node.val) stack.extend([node.right, node.left]) return ans
e322df77a973f30b0745b36540a0f66b2ce29e6d
71,349
def scramble(a, axis=0): """ Return an array with the values of `a` independently shuffled along the given axis """ b = a.swapaxes(axis, -1) n = a.shape[axis] idx = np.random.choice(n, n, replace=False) b = b[..., idx] return b.swapaxes(axis, -1)
94720f93886fd72163ede0e79c7423095a2a08bd
71,350
def cylindrical_to_cartesian(ro, phi, z, degrees=True): """ Convert cylindrical coordinates (ro, phi, zeta) to cartesian (x, y, z). Parameters ---------- ro: (N,) ndarray Radial distance. phi: (N,) ndarray Angular position. z: (N,) ndarray Altitude. degrees: bool...
8393d936c316605718fe20d7ae44cf9771394214
71,352
async def _get_subscribers_prompt(channel: str) -> str: """Take prompt about channel subscribers""" subscribers = await MediatorDependency.mediator.channels.get_subscribers(channel) prompt = f"<b>{channel} subscribers:</b>\n" if subscribers: prompt += "".join(f"/{s.telegram_id} - {s.name}\n" for...
cd5dc28ddffd777dc75b8dbc8a5ba28ced5ab1c8
71,353