content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import warnings def certification_to_csv(stats, filepath, product_id): """Writes certification outputs to the file specified. Parameters ---------- stats : list of dict list of statistical outputs from the function `thermostat.compute_summary_statistics()` filepath : str f...
23f1a84fa2d9c5ad25eb04d23ea9646cf2849286
24,400
def get_ipns_link(name: str) -> str: """Get the ipns link with the name of it which we remember it by Args: name (str): Name we call ipns link Returns: str: Returns the IPNS url Raises: ValueError: if link not found >>> import random >>> key_name = str(random.getrand...
1c171e0539013aecd3e45a7cf7ca2c2907df3955
24,401
def joint_sim(num_samp, num_dim, noise=0.5): """ Function for generating a joint-normal simulation. :param num_samp: number of samples for the simulation :param num_dim: number of dimensions for the simulation :param noise: noise level of the simulation, defaults to 0.5 :return: the data matri...
71296c5093aa3113b7df70cb8966ac9ca06ccb31
24,402
def calculate_seasonal_tilt(axial_tilt, degrees): """Find the seasonal tilt offset from axial tilt and orbit (in degrees) axial_tilt -- The planet's tilt. e.g. Earth's tilt is 23.44 degrees. degrees -- How far along is the planet in its orbit around its star? (between 0 and 360. 0/360 and 180 are equino...
a31e072f95d9d856b2c2d7549b7f96a97a4d6b60
24,403
import logging def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0): """Select the best match in a list or dictionary of choices. Find best matches in a list or dictionary of choices, return a generator of tuples containing the match and its score. I...
784a619b06fed48a5b7d4c8f4c711da954125c9c
24,404
def mark_dts_nn(marked_dict): """Loops through a dictionary representation of the XML-text where determiners have been "focus"-marked. Finds the "focus"-marked determiners and looks for their nouns from the words after the determiner until the end of the current sentence. The found noun is then marked with "foc...
2db6e21a3ea1f4249ef13fd7a235839a8a2d1871
24,405
def reservation_rollback(context, reservations, project_id=None, user_id=None): """Roll back quota reservations.""" return IMPL.reservation_rollback(context, reservations, project_id=project_id, user_id=user_id)
fcb5a82522320ffe6a6d262eb6571153aaa55b29
24,406
def encrypt( security_control: SecurityControlField, system_title: bytes, invocation_counter: int, key: bytes, plain_text: bytes, auth_key: bytes, ) -> bytes: """ Encrypts bytes according the to security context. """ if not security_control.encrypted and not security_control.aut...
f03066da2ab54e784063f01255b9f3f53050a2cf
24,407
def leftmost_turn(((x0, y0), (x1, y1)), (x, y), zs): """Find the line segment intersecting at the leftmost angle relative to initial segment. Arguments: (x0, y0) – where we started (x1, x2) – direction travelling in (x, y) – where intersected one or more alternative line segments ...
bfe1650a92e38612461942ddfcee5faaad96ad5f
24,408
def maya_window(): """Get Maya MainWindow as Qt. Returns: QtWidgets.QWidget: Maya main window as QtObject """ return to_qwidget("MayaWindow")
bea4ef97a14bb93a461f0dd54dbb6e9a25a14a63
24,409
def soap2Dict(soapObj): """A recursive version of sudsobject.asdict""" if isinstance(soapObj, sudsobject.Object): return {k: soap2Dict(v) for k, v in soapObj} elif isinstance(soapObj, list): return [soap2Dict(v) for v in soapObj] return soapObj
46d5b767640a1b8c506f85d03580508d9b2278f0
24,410
def generate_sequential_BAOAB_string(force_group_list, symmetric=True): """Generate BAOAB-like schemes that break up the "V R" step into multiple sequential updates E.g. force_group_list=(0,1,2), symmetric=True --> "V0 R V1 R V2 R O R V2 R V1 R V0" force_group_list=(0,1,2), symmetric=False --> ...
7710775e365f0caae81a9737feec18c662790bde
24,411
def _get_active_tab(visible_tabs, request_path): """ return the tab that claims the longest matching url_prefix if one tab claims '/a/{domain}/data/' and another tab claims '/a/{domain}/data/edit/case_groups/' then the second tab wins because it's a longer match. """ matching_...
ac9cd34d4b4ee1c1c0356499b389c1f6a7195585
24,412
import os def path_normalize(path, target_os=None): """Normalize path (like os.path.normpath) for given os. >>> from piecutter.engines.jinja import path_normalize >>> path_normalize('foo/bar') 'foo/bar' >>> path_normalize('foo/toto/../bar') 'foo/bar' Currently, this is using os.path, i.e...
581713d5ffa48db4f0c368a69ad2cfc932f92a51
24,413
import logging def fit_scale_heights(data, masks, min_lat = None, max_lat = None, deredden = False, fig_names = None, return_smoothed = False, smoothed_width = None, xlim = None, ylim = None, robust = True, n_boot = 10000): """ Fits scale height data and returns slopes Parameters -----...
fe2cd6d1cc1dfa18b7a78593e326f80ee99222bc
24,414
from typing import List from typing import Dict from typing import Tuple from typing import Set import warnings def _check_meas_specs_still_todo( meas_specs: List[_MeasurementSpec], accumulators: Dict[_MeasurementSpec, BitstringAccumulator], stopping_criteria: StoppingCriteria, ) -> Tuple[List[_Measuremen...
bacb0a7b666a1a59bb0df722fe60530b0d4f4d6e
24,415
def get_aircon_mock(said): """Get a mock of an air conditioner.""" mock_aircon = mock.Mock(said=said) mock_aircon.connect = AsyncMock() mock_aircon.fetch_name = AsyncMock(return_value="TestZone") mock_aircon.get_online.return_value = True mock_aircon.get_power_on.return_value = True mock_air...
68833445b94b2194f73c9b699d925bb92dca010b
24,416
def mutation(individual): """ Shuffle certain parameters of the network to keep evolving it. Concretely: - thresh, tau_v, tau_t, alpha_v, alpha_t, q """ individual[0].update_params() return individual,
8ccd373f991cbf2e8161e6bbe32375ca8826e48c
24,417
def truncate_repeated_single_step_traversals_in_sub_queries( compound_match_query: CompoundMatchQuery, ) -> CompoundMatchQuery: """For each sub-query, remove one-step traversals that overlap a previous traversal location.""" lowered_match_queries = [] for match_query in compound_match_query.match_querie...
b5d264640fb65ff7162209a714257b0a65128e89
24,418
def intersect(list1, list2): """ Compute the intersection of two sorted lists. Returns a new sorted list containing only elements that are in both list1 and list2. This function can be iterative. """ result_list = [] idx1 = 0 idx2 = 0 while idx1 < len(list1) and idx2 < len(list...
d0f50b466108f685dc74d227554ab057cac018ae
24,419
import typing def get_parent_project_ids(project_id: int, only_if_child_can_add_users_to_parent: bool = False) -> typing.List[int]: """ Return the list of parent project IDs for an existing project. :param project_id: the ID of an existing project :param only_if_child_can_add_users_to_parent: whether...
b0c9d2241a0b114b3fcf531592b7f05000596fec
24,420
import glob import os def get_all_object_names(bucket, prefix=None, without_prefix=False): """ Returns the names of all objects in the passed bucket Args: bucket (str): Bucket path prefix (str, default=None): Prefix for keys withot_prefix (bool, default=False) ...
c3f0757cd8416cc966fb0b11fbb74fb348ea7f48
24,421
def integral_length(v): """ Compute the integral length of a given rational vector. INPUT: - ``v`` - any object which can be converted to a list of rationals OUTPUT: Rational number ``r`` such that ``v = r u``, where ``u`` is the primitive integral vector in the direction of ``v``. EXAM...
54d2b2726bea848e1a5836425516371fc09f54b3
24,422
def load_classification_pipeline( model_dir: str = "wukevin/tcr-bert", multilabel: bool = False, device: int = 0 ) -> TextClassificationPipeline: """ Load the pipeline object that does classification """ try: tok = ft.get_pretrained_bert_tokenizer(model_dir) except OSError: tok =...
0811cdc4ddaac3992e1cec7f43d88df276356c5c
24,423
def skew_image(img, angle): """ Skew image using some math :param img: PIL image object :param angle: Angle in radians (function doesn't do well outside the range -1 -> 1, but still works) :return: PIL image object """ width, height = img.size # Get the width that is to be added to the i...
5b52a87edc44669e9fad82efd5c594df12edee41
24,424
import logging def test_process_bto_order_high_risk(monkeypatch, capsys, caplog): """BTO order should be correctly processed with high risk flag set """ caplog.set_level(logging.INFO) monkeypatch.setitem(USR_SET, "high_risk_ord_value", 1000) monkeypatch.setitem(USR_SET, "buy_limit_percent", 0.03) ...
0981a09686670ad8d941a438514832c17b541863
24,425
import types import doctest def _load_tests_from_module(tests, module, globs, setUp=None, tearDown=None): """Load tests from module, iterating through submodules. """ for attr in (getattr(module, x) for x in dir(module) if not x.startswith("_")): if isinstance(attr, types.ModuleType): ...
068eb24fd826192730bfb7dde2c978ef42fb8475
24,426
def calculate_full_spectrum(xs, cp, ep=None, betas=(0,0), data=None): """Direct solution of the k-eigenvalue problem in integral transport by the collision probability method. Input data are the xs list and the collision probabilities in cp. Only isotropic scattering is allowed. A relation of albedo for...
ad145dc3fc5ae57f6512cb01b1119a2fc150b4bd
24,427
def get_connectors_by_type(type : str): """ Convenience method for `get_connectors()`. """ return get_connectors(type)
7e41c2a37173a4d72d7d947aa5a166c23f102da0
24,428
def crawl(alphabet, initial, accepts, follow): """ Create a new FSM from the above conditions. """ states = [initial] accepting = set() transition = dict() i = 0 while i < len(states): state = states[i] if accepts(state): accepting.add(i) transitio...
c72b743ed4d06691fea020e2e66236a54d53df5f
24,429
def mpncovresnet101(pretrained=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = MPNCOVResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_ur...
bad52e5b47a84faabdb9d82fb50e585ee287b392
24,430
def cathegory_encoder(data, labelCathegory=labelCathegory): """ Encode cathegorical labels """ for k in labelCathegory: encoder = sklearn.preprocessing.LabelEncoder() encoder.fit(list(data[k].values)) data[k] = encoder.transform(list(data[k].values)) return data
dc4c549e58097d219ade1b7140a9e09356692cd8
24,431
import logging import os def _make_symbols_cg_df(symbols, benchmark): """ 相关性金融数据收集,子进程委托函数,子进程通过make_kl_df完成主进程委托的symbols个 金融数据收集工作,最终返回所有金融时间序列涨跌幅度pd.DataFrame对象 :param symbols: 可迭代symbols序列,序列中的元素为str对象 :param benchmark: 进行数据收集使用的标尺对象,数据时间范围确定使用,AbuBenchmark实例对象 :return: 所有金融时间序列涨跌幅度pd.Data...
6472a2e77d0d6c5ef1c3639cb48e0cd80461a4c1
24,432
def split_dataset(args, dataset): """Split the dataset Parameters ---------- args : dict Settings dataset Dataset instance Returns ------- train_set Training subset val_set Validation subset test_set Test subset """ train_ratio, v...
1fbaac75655694bc1ca3a5e8ed06d31401d3dd9c
24,433
def depthwise_conv2d_nchw(inputs, weight, bias=None, stride=1, padding=0, dilation=1): """Depthwise convolution 2d NCHW layout Args: ----------------------------- inputs : tvm.te.tensor.Tensor shape [batch, channel, height, width] weight : tvm.te.tensor.Tensor shape [in_channel, f...
bd4f5f0f7dc3a12adefce0e19fa010919e9b9407
24,434
def xtransformed(geo, transformation): """Returns a copy of the transformed Rhino Geometry object. Args: geo (:class:`Rhino.Geometry.GeometryBase`): a Rhino Geometry object transformation (:class:`Transformation`): the transformation. Returns: (:class:`Rhino.Geometry.GeometryBase`)...
9d21ad58358bff07b10e18c7c3593cca68f07541
24,435
def function_calls(libfuncs): """ libfuncs is the list of library functions called in script. Returns ths list of all library functions required in script """ libfuncs2 = set() while libfuncs: func = libfuncs.pop() libfuncs2.add(func) for func in called_functions(func): ...
3c6e29930f0a59cc2ad5a3b24ca22c07f3fca28b
24,436
def preprocess_yaml_config(config: SimpleNamespace, prefix_keys=False) -> SimpleNamespace: """ Preprocess a simple namespace. Currently, - prepend the prefix key to all the configuration parameters - change 'None' strings to None values :param config: The SimpleNamespace containing the configuration...
52c4e79334bc95c573b795a6962e83d949cf9639
24,437
from numpy.core import isinf, errstate def gisinf(x): """ Like isinf, but always raise an error if type not supported instead of returning a TypeError object. Notes ----- `isinf` and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function i...
cc525ffc10e87b44a5cee3e93fc1c4466bc7a171
24,438
def make_const(g, # type: base_graph.BaseGraph name, # type: str value, # type: np.ndarray uniquify_name=False # type: bool ): """ Convenience method to add a `Const` op to a `gde.Graph`. Args: g: The graph that the node should be added to name:...
fd8493c6ea33c2fd4f930f78fd906ddb5fcdf12e
24,439
def find_maxima(x): """Halla los índices de los máximos relativos""" idx = [] N = len(x) if x[1] < x[0]: idx.append(0) for i in range(1, N - 1): if x[i-1] < x[i] and x[i+1] < x[i]: idx.append(i) if x[-2] < x[-1]: idx.append(N - 1) return idx
8be862981e46ac2534a78354adf52993ca78426a
24,440
def _transform_rankings(Y): """Transform the rankings to integer.""" Yt = np.zeros(Y.shape, dtype=np.int64) Yt[np.isfinite(Y)] = Y[np.isfinite(Y)] Yt[np.isnan(Y)] = RANK_TYPE.RANDOM.value Yt[np.isinf(Y)] = RANK_TYPE.TOP.value return Yt
7a89bc4dd2ff1ad8b00456198f4051ab9030ccbc
24,441
import os import json def get_config(key=None, default=None, raise_error=False): """Read expyfun preference from env, then expyfun config Parameters ---------- key : str The preference key to look for. The os environment is searched first, then the expyfun config file is parsed. d...
7f05779658ddffd6008cd44984a34b52ef9f3ac9
24,442
import os import sys def check_exist(path, mode, flag_exit=True): """ function to check for file existence @param path(str): target file path @param mode(int): 1(existence) / 2(existence for file) / 3(existence for dir) @param flag_exit(bool): Exit if not present (Default: True) @param (bool) or exit(None) """...
4eda0d241b61d1b813593d91edbf8a14bd4df036
24,443
import math def convert_pf_patch_to_cg_patch(p, simnum): """Converts a pfpatch p to a CG patch.""" # Print patch info LOGGER.info("Macro patch is:") LOGGER.info(str(p)) LOGGER.info("Patch id = {}".format(p.id)) LOGGER.info("Protein bead ids = {}".format(p.protein_ids)) LOGGE...
91a455104f2319d041a6ccafa3b73c65c1b7a491
24,444
def find_error_detect(image_path): """ 给一张图片,判断是否检查正确,错误则保存下来。 :param image_path: :return: """ save_path = './ctpn_detect_error.txt' image = cv2.imread(image_path) # 传输给服务器的数据 data = {'fname': image_path, 'img_str': _img_to_str_base64(image)} # test by EAST mode res_east_d...
e76d6f2b21d0b735a4e811d5aacfde0e273075d2
24,445
def appendItem(): """Includes product into invoice and redirect""" app.logger.debug('This is appendItem to PO process') if request.method == 'POST': (prod_properties, check_up) = checkProduct(request.form) if check_up: appendProduct(prod_properties, session['userID']) session...
3f5b77b8817f5f5d068e86bcd1b8a5137aab9113
24,446
import io import gzip def gzip_bytes(bytes_obj): """byte: Compress a string as gzip in memory. """ if isinstance(bytes_obj, (str,)): bytes_obj = bytes_obj.encode() out_ = io.BytesIO() with gzip.GzipFile(fileobj=out_, mode='w') as fo: fo.write(bytes_obj) return out_
68d0a6b3c64b8633a3084114f617ccd792a688f9
24,447
def ones_like(other_ary): """ Create a PitchArray with all entry equal 1, whose shape and dtype is the same as other_ary """ result = PitchArray(other_ary.shape, other_ary.dtype) result.fill(1) return result
7bbdbdaa409de3986db66c98eedc3670d2483b2b
24,448
def inference_multiview(views, n_classes, keep_prob): """ views: N x V x W x H x C tensor """ n_views = views.get_shape().as_list()[1] # transpose views : (NxVxWxHxC) -> (VxNxWxHxC) views = tf.transpose(views, perm=[1, 0, 2, 3, 4]) view_pool = [] for i in xrange(n_views): # set...
b9fd30db4d130aad29333d80a24c9cac6a6ce580
24,449
def trueReturn(data, msg): """ 操作成功结果 """ result = { "status": True, "data": data, "msg": msg } return JSONResponse(content=result)
7eabfe62bb0cf11b92d146cae3171fe391c27d5f
24,450
from pathlib import Path import re def parse_slurm_times(job_id: str, path: Path = Path.cwd()) -> float: """Performs the parsing of the file slurm-{job_id}.out by returning in milliseconds the time measured by Slurm. Args: out_file (str): The job slurm output file path to parse. path (Pat...
22cc642aa711ab302772273d3d05f7d5615e21d1
24,451
import torch def bprl(positive: torch.Tensor, negative: torch.Tensor) -> torch.Tensor: """ Bayesian Personalized Ranking Loss https://arxiv.org/ftp/arxiv/papers/1205/1205.2618.pdf """ dist = positive - negative return -F.logsigmoid(dist).mean()
0fb13f41c27880e821548298a369091f0b96c0c1
24,452
def select2_js_url(): """ Return the full url to the Select2 JavaScript library Default: ``None`` # Example {% select2_js_url %} """ return sl2.select2_js_url()
6866c7ad1a00e8d23c15f94fd9169412213aa4f0
24,453
def _SharedSuffix(pattern1, pattern2): """Returns the shared suffix of two patterns.""" return _SharedPrefix(pattern1[::-1], pattern2[::-1])[::-1]
c48792aaaf3e470571cbf4d16f6af0b00a671c3f
24,454
import credstash import argparse import getpass def run(args): """Handle credstash script.""" parser = argparse.ArgumentParser( description=("Modify Home Assistant secrets in credstash." "Use the secrets in configuration files with: " "!secret <name>")) pa...
832abd0f137e31f2045883edc32ef2a13d408589
24,455
import os import mimetypes def handle_request_files_upload(request): """ Handle request.FILES if len(request.FILES) == 1. Returns tuple(upload, filename, is_raw, mime_type) where upload is file itself. """ # FILES is a dictionary in Django but Ajax Upload gives the uploaded file # an ID based ...
437be6e8bf6881224900034e51df04dc754fe716
24,456
def vgg16(num_class): """VGG 16-layer model (configuration "D") with batch normalization """ model = VGG(make_layers(cfg['D'], batch_norm=True), num_classes=num_class) return model
abdb0a48bd5190cd7c7e50193f3d950af5195770
24,457
def IFS(*args) -> Function: """ Evaluates multiple conditions and returns a value that corresponds to the first true condition. Learn more: https//support.google.com/docs/answer/7014145 """ return Function("IFS", args)
395c67b524b4cccbeabba73666bc1a8f78668ff2
24,458
def idwt_joined_(w, rec_lo, rec_hi, mode): """Computes single level discrete wavelet reconstruction """ n = len(w) m = n // 2 ca = w[:m] cd = w[m:] x = idwt_(ca, cd, rec_lo, rec_hi, mode) return x
4b7371a36abc4bd094a3cd86faa1005ff5d6fd69
24,459
def _get_pattern_nts(rule): """ Return a list of NT names present in given rule. """ nt_names = [] for bt in rule.ipattern.bits: if bt.is_nonterminal(): nt_name = bt.nonterminal_name() nt_names.append(nt_name) return nt_names
e690e9187aaff0cf3138444db085e15adfda3847
24,460
def stopping_player(bot, state): """ A Player that just stands still. """ return bot.position
72628e39d26760eedc9a0e85a8279ac530ab851d
24,461
def check_continue(transformer: transformer_class.Transformer, check_md: dict, transformer_md: dict, full_md: dict) -> tuple: """Checks if conditions are right for continuing processing Arguments: transformer: instance of transformer class Return: Returns a tuple containining the return code...
78348046acde489a129fc8a4426a9b11ee2e2238
24,462
def getFlatten(listToFlat): """ :param listToFlat: anything ,preferably list of strings :return: flatten list (list of strings) #sacred """ preSelect=mc.ls(sl=True,fl=True) mc.select(cl=1) mc.select(listToFlat) flatten = mc.ls(sl=True, fl=True) mc.select(preSelect) return...
91d1376d81140fd258c80bcc23cb220ce0f99926
24,463
def can_exit_room(state: State, slot: int) -> bool: """ Return True if amphipod can escape a room because all amphipods are in their place Not exhaustive! If there are amphipods above it, it may still be stuck """ amphipod = state[slot] assert amphipod != EMPTY_SLOT room = slot // 4 bott...
914881e90c2e9b357d49fb44d56b7f864b4973c0
24,464
def square_matrix(square): """ This function will calculate the value x (i.e blurred pixel value) for each 3*3 blur image. """ tot_sum = 0 # Calculate sum of all teh pixels in a 3*3 matrix for i in range(3): for j in range(3): tot_sum += square[i][j] return tot_sum/...
4f378736c19c33f104be462939b834ece403f713
24,465
def before_after_text(join_set, index, interval_list): """ Extracts any preceeding or following markup to be joined to an interval's text. """ before_text, after_text = '', '' # Checking if we have some preceeding or following markup to join with. if join_set: if index > 0: ...
b2c63fe1e7ea5bb204e41b27bc79d2c81964369a
24,466
import os def load_data(outputpath): """Load the numpy data as stored in directory outputpath. Parameters ---------- outputpath : str directory where the numpy files are stored Returns ------- x_train y_train_binary x_val y_val_binary x_test y_test_binary ...
46f355fdafcc73b371514b3dcb5c32b6935f26a0
24,467
import socket import ssl def create_server_ssl(addr, port, backlog): """ """ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((addr, port)) server.listen(backlog) context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_default_certs() wrap = context.wrap_...
3bcd3d8a157401f23c50e6c35fe9b8e45f4659d6
24,468
def other_ops(request): """ Other Operations View """ args = { 'pending': OtherOperation.objects.filter(status=0).count(), 'active': OtherOperation.objects.filter(status=1).count(), 'done': OtherOperation.objects.filter(status=2).count(), 'cancelled': OtherOperation.objec...
727e620d0ba5798eb0bcdc31e31a831a9332e802
24,469
def distance_point_2_line(point, seg): """Finds the minimum distance and closest point between a point and a line Args: point ([float, float]): (x,y) point to test seg ([[float, float], [float, float]]): two points defining the line Returns: A list of two items: * Distance ...
4627639f4b900b72a0b88104df44e498ef123cb4
24,470
def load_glove_from_file(glove_filepath): """ Load the GloVe embeddings Args: glove_filepath (str): path to the glove embeddings file Returns: word_to_index (dict), embeddings (numpy.ndarary) """ word_to_index = {} embeddings = [] with open(glove_filepath, "r") as fp: ...
30d8a0fb8e1b0728ae9943dd0f5c2387dbcdb778
24,471
def make_pd(space: gym.Space): """Create `ProbabilityDistribution` from gym.Space""" if isinstance(space, gym.spaces.Discrete): return CategoricalPd(space.n) elif isinstance(space, gym.spaces.Box): assert len(space.shape) == 1 return DiagGaussianPd(space.shape[0]) elif isinstance...
0849e947061221ba08bf113f6576c531ca2df2cd
24,472
import typing import requests def download_file_from_google_drive( gdrive_file_id: typing.AnyStr, destination: typing.AnyStr, chunk_size: int = 32768 ) -> typing.AnyStr: """ Downloads a file from google drive, bypassing the confirmation prompt. Args: gdrive_file_id: ID str...
29cdcc509aa21a6f2ae14ed18f2c0523bbdbd5a4
24,473
import inspect import functools def attach(func, params): """ Given a function and a namespace of possible parameters, bind any params matching the signature of the function to that function. """ sig = inspect.signature(func) params = Projection(sig.parameters.keys(), params) return functools.partial(func, **...
35116b9b3be12f1e19789e2b1c36b7c34b6138ea
24,474
def question_route(): """ 題庫畫面 """ # 取得使用者物件 useruid = current_user.get_id() # 嘗試保持登入狀態 if not keep_active(useruid): logout_user() return question_page(useruid)
1b752709aa8264fdc19aaa44f2233b2e0382e1b5
24,475
import base64 def generate_qrcode(url: str, should_cache: bool = True) -> str: """ Generate a QR code (as data URI) to a given URL. :param url: the url the QR code should reference :param should_cache: whether or not the QR code should be cached :return: a data URI to a base64 encoded SVG image ...
ab89cf09d7d50217960f48f75ff17b1d46513f52
24,476
def get_conflict_fks_versions(obj, version, revision, exclude=None): """ Lookup for deleted FKs for obj, expects version to be obj version from the same revision. If exclude provided - excludes based on that from versions to check. Expects exclude to be a dict of filter string, value i.e {'pk': 1}. ...
2e4e3b8842b1c17cc6973143254f39ae4a42da68
24,477
def hz2mel(f): """Convert an array of frequency in Hz into mel.""" return 1127.01048 * np.log(f/700 +1)
84522419c972bf9b78c9931aef871f97a8a0d292
24,478
def figure(figsize=None, logo="iem", title=None, subtitle=None, **kwargs): """Return an opinionated matplotlib figure. Parameters: figsize (width, height): in inches for the figure, defaults to something good for twitter. dpi (int): dots per inch logo (str): Currently, 'iem', 'dep' is...
fd89e550a891ccf6f639f8c981215aa25fa0ad06
24,479
def run_epoch(session, model, eval_op=None, verbose=False): """Runs the model on the given data.""" costs = 0.0 iters = 0 state = session.run(model.initial_state) fetches = { "cost": model.cost, "final_state": model.final_state, "accuracy":model.accuracy, "y_new":mo...
a69ed33e930245118e0d4054a10d6c1fd61cc0da
24,480
from typing import Any def is_scoo(x: Any) -> bool: """check if an object is an `SCoo` (a SAX sparse S-matrix representation in COO-format)""" return isinstance(x, (tuple, list)) and len(x) == 4
96d3937d9884198b75440e3de75949c713b8e16a
24,481
import base64 import os def createNonce(): """Creates a new nonce and stores it in the session.""" nonce = base64.b64encode(os.urandom(32)) flask_session['nonce'] = nonce return nonce
0a4135537d9bce3a35cb2ee681f16b2dffda2d13
24,482
def project_rename_folder(object_id, input_params={}, always_retry=False, **kwargs): """ Invokes the /project-xxxx/renameFolder API method. For more info, see: https://documentation.dnanexus.com/developer/api/data-containers/folders-and-deletion#api-method-class-xxxx-renamefolder """ return DXHTTPR...
60bfe648eb9846bf06125fd65436e9c7cf5c2fd6
24,483
def full(shape, fill_value, dtype=None): """Returns a new array of given shape and dtype, filled with a given value. This function currently does not support ``order`` option. Args: shape (tuple of ints): Dimensionalities of the array. fill_value: A scalar value to fill a new array. ...
99d1505382395c4990b35115edfaef267d00f3f9
24,484
def is_seq(a): """Return `True` if `a` is a Z3 sequence expression. >>> print (is_seq(Unit(IntVal(0)))) True >>> print (is_seq(StringVal("abc"))) True """ return isinstance(a, SeqRef)
1429fb3fd800a3688700a62dd0665df7536b56d9
24,485
from re import T def identity(__obj: T, /) -> T: """Identity function""" return __obj
8c96839e48e1ec270bd57616abcc3234b6f0958f
24,486
def lines_in_file(filename: str) -> int: """ Count the number of lines in a file :param filename: A string containing the relative or absolute path to a file :returns: The number of lines in the file """ with open(filename, "r") as f: return len(f.readlines())
d71b5c8de1b4eb9a45988e06c17a129f4a19f221
24,487
import argparse from sys import path def readargs(): """ Read input arguments if run as separate program Returns ------- None. """ parser = argparse.ArgumentParser(description=( 'Convert data from WiPL format to binary SimRadar-compatible format.' )) parser.add_arg...
51cac24d106f8776e27aa78841870926b05c1ef7
24,488
import click def validate_input_parameters(live_parameters, original_parameters): """Return validated input parameters.""" parsed_input_parameters = dict(live_parameters) for parameter in parsed_input_parameters.keys(): if parameter not in original_parameters: click.echo( ...
226b95d0d9b42e586e395107def239d4e61c057a
24,489
def _upper_zero_group(match: ty.Match, /) -> str: """ Поднимает все символы в верхний регистр у captured-группы `let`. Используется для конвертации snake_case в camelCase. Arguments: match: Регекс-группа, полученная в результате `re.sub` Returns: Ту же букву из группы, но в верхн...
311dbc41c17b1c6fde39b30d8126eb4c867d7a6f
24,490
def _concatenate_shapes(shapes, axis): """Given array shapes, return the resulting shape and slices prefixes. These help in nested concatenation. Returns ------- shape: tuple of int This tuple satisfies: ``` shape, _ = _concatenate_shapes([arr.shape for shape in arrs], axis)...
2ca93f3c656f1629fa3fdb7f5c8cb325abd40cf2
24,491
import re def md_changes(seq, md_tag): """Recreates the reference sequence of a given alignment to the extent that the MD tag can represent. Note: Used in conjunction with `cigar_changes` to recreate the complete reference sequence Args: seq (str): aligned segment sequence ...
f8591d0084f6c10c9bbd1a39b3f9e13cfe952e68
24,492
def _get_partitions(dev): """Return partition information (num, size, type) for a device.""" dev_path = utils.make_dev_path(dev) out, _err = utils.execute('parted', '--script', '--machine', dev_path, 'unit s', 'print', run_as_root=True) lines = [...
35f671609b7776166263163d712ecd85c9ceb7d2
24,493
def get_cs_token(accesskey="",secretkey="",identity_url="",tenant_id=""): """ Pass our accesskey and secretkey to keystone for tokenization. """ identity_request_json = json.dumps({ 'auth' : { 'apiAccessKeyCredentials' : { 'accessKey' : accesskey, 'secretKey' : secretkey }, "tenantId": tenant_i...
a14324651039687bb52e47f4068fcee74c34aa65
24,494
def get_auto_scaling_group(asg, asg_name: str): """Get boto3 Auto Scaling Group by name or raise exception""" result = asg.describe_auto_scaling_groups(AutoScalingGroupNames=[asg_name]) groups = result["AutoScalingGroups"] if not groups: raise Exception("Auto Scaling Group {} not found".format(a...
07176e538cdb265ae86b16a5d36bf1b274f45c19
24,495
def guiraud_r(txt_len: int, vocab_size: int) -> np.float64: """ The TTR formula underwent simple corrections: RTTR (root type-token ratio), Guiraud, 1960. """ return vocab_size / np.sqrt(txt_len)
9c054d6d741fabb64ec0659b280474385b5cfa79
24,496
def serialize_dagster_namedtuple(nt: tuple, **json_kwargs) -> str: """Serialize a whitelisted named tuple to a json encoded string""" check.tuple_param(nt, "nt") return _serialize_dagster_namedtuple(nt, whitelist_map=_WHITELIST_MAP, **json_kwargs)
fbe6606d0001d425593c0f4f880a6b314f69b94b
24,497
def join_epiweek(year, week): """ return an epiweek from the (year, week) pair """ return year * 100 + week
fdbc50f8a953ef7307e9558019b3c2b50bc65be4
24,498
def get_or_create_api_key(datastore: data_store.DataStore, project_id: str) -> str: """Return API key of existing project or create a new project and API key. If the project exists, return its API key, otherwise create a new project with the provided project ID and return its API key. ...
2cb5b04dcf44b0e39d171683a0bd184d582eaf34
24,499