content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def create_fsi_file(name, content): """creates a fsi extension named name filled with content""" path = os.path.join(EFP, name) return create_file(path, content)
3f70d6b5f2dbaad5bfbd005e845039880162fabc
3,624,900
def top(values, number=5): """ Return the dict containg the top number(defaults to 5) values. If we ask for the top 2 and the data looks like {"A": 5, "B": 5, "C": 5} we will sort on the keys and take A and B. Args: values: the dict with data number: how many we include (default=5) ...
aaa8516c3074f0cc2bc3c37f24ae27acc2844029
3,624,901
def booleanize(value) -> bool: """ This function will try to assume that provided string value is boolean in some way. It will accept a wide range of values for strings like ('y', 'yes', 'on', '1', 'true' and 't'. Any other value will be treated as false :param value: any value :return: boolean stat...
ecf1ff7c8e9e093fc356c0eec8013e659056c1ed
3,624,902
import gzip from pandas import DataFrame import os def read_umi_tools(filename, dtype: str='float32') -> AnnData: """Read a gzipped condensed count matrix from umi_tools. Parameters ---------- filename File name to read from. """ # import pandas for conversion of a dict of dicts into a...
a851adc3906b89fb608877711f6c88e2b02651eb
3,624,903
from typing import Optional from typing import Mapping from typing import Tuple from typing import List def calculate_average_score_by_annotation( graph: BELGraph, annotation: str, key: Optional[str] = None, runs: Optional[int] = None, use_tqdm: bool = False, ) -> Mapping[str, float]: """Calcu...
4bdb8922027f88a4f096b5d627466e6eb3fb1f2e
3,624,904
def _get_file(): """ Route to handle sending file content from server. Parameters: 1. file_pathname: Name of the file that user want to get. Result: Returns a file object, otherwise error object. """ # Get current user object current_user = get_current_user(_get_file.role, _ge...
d0113434074d9236c4736debf3d4d8b166382a78
3,624,905
import random def draw_cv2(raw_strokes, size=256, lw=6, time_color=True, base_size=256, point_drop_prob=0.0, channel=1): """ 将一个涂鸦数据转换成一张黑百图, (size, size, channel) time_color: 若为true, 则每一笔颜色不一样,随着时间推移而变浅. 若为false,则颜色都为纯黑 lw: 线段宽度 point_drop_prob: 以此概率丢弃掉point, 0.05 - 0.15差不多 channel: 必须为1或3 ...
62baf3b6ac1ed997f3d051b8d78262db4779500d
3,624,906
def force_line_char_limit(line, indent): """ If line is longer than limit then create new line at a space in the text :param line: :return: """ clim = 120 if len(line) <= clim: return line rem = line oline = '' for i in range(clim): j = clim - i if rem[j]...
21858c137cb3c75771bbe911e1c13aa7782acfa6
3,624,907
def read_var(f, verbose): """Reads one variable from Octave binary file Format is described in libinterp/corefcn/ls-oct-binary.cc recalled below. Data (one set for each item): ============================ object type bytes ------ ---- ----...
84c97e78c576061e75fd6b1a6b644cca2760014c
3,624,908
from typing import List def diversification_factor(weights: List[float], sigma: np.array) -> float: """ Calculate the negative diversification factor which is the ratio between the weighted average of instrument volatility and resulting portfolio volatility :param weights: instrument weights :param s...
f57dee1785823cbe1c73ccc0c66810ba892e4abc
3,624,909
import torch def get_grid_full(pose, grid_size, full_size, device): """ Input: `pose` FloatTensor(bs, 3) `grid_size` 4-tuple (bs, _, grid_h, grid_w) `device` torch.device (cpu or gpu) Output: `rot_grid` FloatTensor(bs, grid_h, grid_w, 2) `trans_grid` FloatTensor(bs,...
bed84bd77c9030ec71465d446aa7aaad31a9b95d
3,624,910
def _xresnet_block(x,filters,kernel_size,strides,conv_shortcut,name, trainable=True): """ Build a block of residual convolutions for the xresnet model family Args: x (KerasTensor): The input Keras tensorflow tensor that will be passed through the stack. filters (int): The number of output filters kernel_si...
93fdec4557a67e5b0bf0261fc1ef061a2c4ef871
3,624,911
def dataset_from_jsons(json_files, dataset_name): """ Parameters ---------- json_files : :obj:`list` List of loaded JSON files. Each item could be a list of dictionaries or a dictionary. """ theory = '' atom_nums = [] coords = [] energies = [] gradients = [] ...
e8b91af7c12385235386730bcde2ed01a246bc18
3,624,912
import os def _eval_optenv(name, default=''): """ Eval_optenv Returns the value of the environment variable or default @name: name of the environment variable @return: enviroment variable value or default """ if name in os.environ: return os.environ[name] return default
06a126274ed9091e7e545ec5bc6d9fa99c093445
3,624,913
import random import string def get_random_file_name(length: int) -> str: """Returns a random file name. File name consists of lowercase letters, uppercase letters, and digits. :param length: File name length. """ return ''.join(random.choice(string.ascii_lowercase ...
c6a7b2f58bc6d2eb457cee2c01222757c50f7eb9
3,624,914
def is_valid_followup_permutation(perm, prev_perm): """ Checks if a given permutation is a valid following permutation to all previously known permutations. (only one more) """ for p in prev_perm: if len(perm - p) == 1: return True return False
7195f48ec57273af6f5bf3942e501360558678ab
3,624,915
def sentihood_strict_acc(y_true, y_pred): """ Calculate "strict Acc" of aspect detection task of Sentihood. """ total_cases=int(len(y_true)/4) true_cases=0 for i in range(total_cases): if y_true[i*4]!=y_pred[i*4]:continue if y_true[i*4+1]!=y_pred[i*4+1]:continue if y_true...
82b8f35fd449fb112f12c263c6fa40c4efdf381e
3,624,916
from typing import Dict import re def _parse_fileobj(fileobj) -> dict: """Parses the actual content of the file object""" d: Dict[str, str] = {} current_keyword = None for line in fileobj: m_keyword = re.match(r"^(.+?):\s(.*)", line) m_continuation = re.match(r"^\s+", line) if...
428a7128e00af0c92354c0de8a58a27e2aa334b7
3,624,917
import requests from bs4 import BeautifulSoup def stock_em_hsgt_hold_stock( market: str = "沪股通", indicator: str = "年排行" ) -> pd.DataFrame: """ 东方财富网-数据中心-沪深港通持股-个股排行 http://data.eastmoney.com/hsgtcg/list.html :param market: choice of {"北向", "沪股通", "深股通"} :type market: str :param indicator:...
0694ff062029e7a5f20e3e43edf905f1809071b6
3,624,918
def migrated_file_single(): """LtfseeFile example in migrated state.""" files = [ LtfseeFile(state="M", replicas=1, tapes=[], path="/gpfs/gpfs0/sample_file2"), ] return files
b59d334c6e734b77a0bd642815a17b7f84021ff7
3,624,919
import platform def clipboard_paste(): """ Hopefully cross platform, paste from a clipboard. :return: A platform specific paste function. """ current_platform = platform.system().upper() if current_platform == 'WINDOWS': return __windows_paste() elif current_platform == 'LINUX': ...
1f16494e460b9015ebb6cd45b6ca31d52a9b68e0
3,624,920
import torch def _linear_decorrelate_color(t): """Multiply input by sqrt of empirical (ImageNet) color correlation matrix. If you interpret t's innermost dimension as describing colors in a decorrelated version of the color space (which is a very natural way to describe colors -- see discussion in Fe...
9bb953c5f5c3f2fa219c80b2fae4d2d355f29cc7
3,624,921
import random def get_n_random_colors(n): """ Creates n random RGB color tuples :param n: Integer, the number of colors to create :return: a list of RGB color tuples """ d = [] for i in range(n): d.append((random(), random(), random())) return d
3096cceda79b6ac5c55afc6ae15242bc4b13e44e
3,624,922
def compute_nc(X, G): """Computes the novelty curve from the self-similarity matrix X and the gaussian kernel G.""" N = X.shape[0] M = G.shape[0] nc = np.zeros(N) for i in range(M // 2, N - M // 2 + 1): nc[i] = np.sum(X[i - M // 2:i + M // 2, i - M // 2:i + M // 2] * G) # Norma...
00c3f2b1665375ffb3d7e84c7d4cd17ede909db8
3,624,923
def logout(): """Logout authenticated user.""" logout_user() return redirect(url_for('blog'))
252f9ab4b1722f2def0edc477db85ea143588223
3,624,924
def parse_spacecharge(line): """ Spacecharge (type -8) if bytpe = −8, switch on/off the space-charge calculation at given location V3(m) according to the sign of V2 (> 0 on, otherwise off). """ v = v_from_line(line) d={} d['s'] = float(v[3]) if float(v[2]) >0: d['i...
d33cbc1e67a305a83314683e32190eb9818a28ac
3,624,925
import os import shutil def check_if_dir_exists_create_it_if_not_remove_content(preprocessed_data_dir): """ A helper function used mainly by: - prepare_and_dispatch_lion_detection_data - prepare_and_dispatch_lion_counting_data """ # Check if CONST_PREPROCESSED_DATA_DIR exists. pdd = os.p...
54a35a1c6ebbce571e2380c842839133409a4288
3,624,926
def multi_weighted_logloss(y_true:np.array, y_preds:np.array): """ @author olivier https://www.kaggle.com/ogrellier multi logloss for PLAsTiCC challenge """ # class_weights taken from Giba's topic : https://www.kaggle.com/titericz # https://www.kaggle.com/c/PLAsTiCC-2018/discussion/67194 # w...
de8a4c928a89a2faf58ad106a781b8ed45a9f058
3,624,927
def reverse_string(a_string: str): """Take the input a_string and return it reversed (e.g. "hello" becomes "olleh".""" reversed_string = "" for i in range(len(a_string)): reversed_string += a_string[~i] return reversed_string
888127122856a3537eea99d4e2bad0aa0f1921d1
3,624,928
def xray_edges(element): """get dictionary of x-ray absorption edges: energy(in eV), fluorescence yield, and jump ratio for an element. Args: element (int, str): atomic number, atomic symbol for element Return: dictionary of XrayEdge named tuples. Notes: ...
902aacf67a16644f35e0cfaab10c5ee7616ea81c
3,624,929
from sys import version from datetime import datetime from textwrap import dedent def pcr(): """docstring.""" if request.method == "GET": return render_template("pcr.html", results=results, version=version) if 'clear' in request.form: ...
2fe4bff0d3974bc3811285d242daa8d20d65cf6d
3,624,930
from typing import Optional from re import T from typing import Union from typing import Callable def guild_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]: """A decorator that indicates this command can only be used in a guild context. This is **not** implemented as a :func:`check`, and is inst...
97ee966c7ad913d0602fd78238d6169df455be64
3,624,931
def discover_tree(urlconf=None): """Finds all ApiNode usage in given or default urlconf""" if urlconf is None: urlconf = settings.ROOT_URLCONF if isinstance(urlconf, basestring): urlconf = import_module(urlconf) nodes = set() for item in urlconf.urlpatterns: for p in item....
9f215186d8134cc1c02a58e57e653bc80a4daf9d
3,624,932
def _iterations_implicit_bwd(res, gr): """Runs Sinkhorn in backward mode, using implicit differentiation. Args: res: residual data sent from fwd pass, used for computations below. In this case consists in the output itself, as well as inputs against which we wish to differentiate. gr: gradients...
8617b6bd8cab2535409e863dae31a928f4de81db
3,624,933
import torch def huber_loss_temporal(dvf): """ Calculate approximated temporal Huber loss Args: dvf: (Tensor of shape (N, 2, H, W)) displacement vector field estimated Returns: loss: (Scalar) huber loss temporal """ eps = 1e-8 # numerical stability # magnitude of the d...
12329846e15c18ff9d59aee2f27377ce38eb8208
3,624,934
from typing import List def _check_header(swagger: swagger_to.swagger.Swagger) -> List[Complaint]: """ Check whether the swagger header conforms to our style guide. :param swagger: parsed Swagger spec :return: the list of failed checks """ complaints = [] # type: List[Complaint] if swag...
0f7a15ae38504d570f9a6800464ae12a4fd8d0e2
3,624,935
import os import mmap def is_cnf1(filename): """ Brute force detection if a SRF file is using CNF1/CNF4 records """ max_header = 1024 ** 2 PROGRAM_ID = b'PROGRAM_ID\000' cnf4_apps = set((b"solexa2srf v1.4", b"illumina2srf v1.11.5.Illumina.1.3")) if not is_srf(filename...
529099be12d2578eb1949277a469270161f861e6
3,624,936
def handler(msg): """ Writes input argument back-out to the standard output returning input as output. Generated by: `SQL Server Big Data Cluster` :param msg: The message to echo. :type msg: str :return: The input message `msg` as output `out`. """ print(msg) out = msg return ...
b90133e486092c6277f63c2a4f5aa0c2317fa44e
3,624,937
def temperal_cross_validation( model, X: pd.DataFrame, y: pd.Series, num_split: int = 5, xls_path: str = None, # type: ignore shuffle: bool = True, ): """ Implement temporal cross-validation and calculate the error metrics :param model: Trained model :param X: predictors :...
de145435ce20f23cf3cda66899bd187c300c7a46
3,624,938
def safeFormatSipUri(uri, default_proto='sip', default_user='', default_port=5060, default_params={}): """ Given a SIP URI of questionable validity, parse out the good stuff, and fill in the rest :param uri: URI to format / validate :type uri: str :param default_proto: de...
f5e957c26a34e6f086a0d3b85d1d838abd542312
3,624,939
def _key_for_namespace(namespace, app): """Return the __namespace__ key for a namespace. Args: namespace: The namespace whose key is requested. app: The id of the application that the key belongs to. Returns: A db.Key representing the namespace. """ if namespace: return db.Key.from_path(meta...
b1a52fdf2175f39160777ca388134b12a6eaa36e
3,624,940
import sys def _get_remote_or_bail(repo, name): """Get remote by name. name may be None. _get_remote_or_bail(Repo, str) -> Remote """ remote_name = name if not remote_name: # Default to origin since it's the convention. remote_name = 'origin' try: return repo.remo...
e709c57fa46e0fe232a30ca21b97d40030e36ee9
3,624,941
from pathlib import Path def get_file_path(): """ 固有名詞のdfのpathのリスト """ p = Path(__file__).parent.resolve() / ".." / "toots_log" file_paths = sorted([f for f in p.iterdir() if f.is_file()]) return(file_paths)
e51c2683f3ebd40f6d4b05b72e82273c153aa014
3,624,942
import os def readinput(filename): """Read input file contents and return it as one '\\n' separated string Arguments: filename {str} -- name of the file to be read """ path = os.path.join(INPUT_PATH, filename) with open(path) as file: contents = "\n".join(file.readlines()) ret...
d875d7641b801d31ffd596c7d8083d0681c3d5ba
3,624,943
def jpm_wide_to_long(df, set_date_name, set_index_name, set_values_name): """ :param df: :param set_date_name: :param set_index_name: :param set_values_name: :return: """ return ( pd.melt( (df .replace('-', np.NaN) .rename(columns={'Unnamed:...
c1ee5dbe4def2801362518bc6891580ef99010f0
3,624,944
import math def RerangeEulerAngle(angle,deadzone,max1): """ Rerange the angles to [-1 - +1] If one angle is in the deadzone it is set to 0 Angles are cubed for better control Deadzone and max is configurable max1 ---/ /: / : ...
a8443cfd9f1c234e16e15efa97db6d7cead5ab46
3,624,945
def inf_set_min_ea(*args): """ inf_set_min_ea(_v) -> bool """ return _ida_ida.inf_set_min_ea(*args)
dfb4151795295d2cabc102da58e310eeca6f9b73
3,624,946
from datetime import datetime def _add_months(date, months): """ Add ``months`` months to ``date``. Unfortunately we can't use timedeltas to add months because timedelta counts in days and there's no foolproof way to add N months in days without counting the number of days per month. """ ...
c8e6af3ce5230ae746a81f89d292e04eaf7d230d
3,624,947
def allowgames(bot, cmd, params, user, room): """ Independent command for changing permissions for games in this room. Reserved for room owners. They can decide to allow games/activities in their room. Args: bot: PokemonShowdownBot, the instance of PokemonShowdownBot that called this function. ...
e70d99cb15b4a3579784564649a60ee4138279ee
3,624,948
def str_basis(n, m): """Return analytic expression for a given Zernike in LaTeX syntax""" signed_m = int(m) m = int(np.abs(m)) n = int(np.abs(n)) terms = [] for k in range(int((n - m) / 2) + 1): coef = ((-1) ** k * factorial(n - k) / (factorial(k) * factorial((n + m) / 2...
16b2ed510aaa5fbcb7cdc7baccc8fcbededfe4f9
3,624,949
def get_frr_config(conn_obj, device="dut"): """ API to get frr config from frr.conf file Author: Sooriya G (sooriya.gajendrababu@broadcom.com) :param conn_obj: :param device: :return: """ command = " sudo cat /etc/sonic/frr/frr.conf" if device=="dut": return utils_obj.remove_...
ca02d9a2c5ac38dcb2b927041e715661a0685d01
3,624,950
import json import hashlib from datetime import datetime import os def generate_kml(): """Generate KML file from geojson.""" uuid = request.values.get('uuid', None) campaign_name = request.values.get('campaign_name', None) campaign = Campaign(uuid) # Get json for each type. types = campaign.g...
499d5cc4b3408a6ca4db1a7f8c33f25c4a55008f
3,624,951
def bilinear_pooling(x): """ 实现双线性池化,双线性池化出要使用在细粒度图像分类中 具体参考论文:Bilinear CNN Models for Fine-grained Visual Recognition 论文链接:http://vis-www.cs.umass.edu/bcnn/docs/bcnn_iccv15.pdf 传入x:普通分类网络的最后一个卷积层的输出 如果想要放置在池化层之后需要进行适当的修改 可以直接插入,最后一个卷积层与全连接层之前 """ shape_detector = x.shape print(...
b7e9cbab5c091acf13f3d1102a4159f68261c60b
3,624,952
import csv import random def loadData(paths, reduce_zero_measurement=1, side_image_prob=1, correction_dist=40.0, gauss_noise=0.01, measurement_threshhold=0): """ Loads the cvs files from all given paths. Args: paths: list of paths which contain the training data ...
0dd317d99b8bfb5bee74c3edfc21fa0458a2db37
3,624,953
def processMultiline(string, removeEmpty=True, removeComments=False, doStrip=True): """split a string into lines, with some default post-processing. Caution if using removeEmpty=False and removeComments==True, it will fail if empty lines are present""" lines = string.split('\n') if doStrip: lines = (f.strip()...
e1367f5094a17363872c297ee898168c0378c5fe
3,624,954
from app.api.operation_api import send_all_operations_message import json async def get_callback_commands(callback_id: int, loaded_only: bool = False): """ Get an array of dictionaries of all the possible commands for the specified callback :param callback_id: the id of the callback in question :param...
7d4c9c76ac5f130f20902e2cf45880e922f6505b
3,624,955
def load(f): """Load from pickle_file. Which will be used by the listener and generator modules in another Machine(VM , Host). """ with open(f, 'rb') as pickle_file: return loads(pickle_file.read())
193a26b7ff0977ec24034cf8983f54f196bedfd3
3,624,956
def split_ZH(orgin_path, write_path): """ 对中文数据集进行处理,删除<title>等标签信息 :param orgin_path: 原始文件路径 :param write_path: 写入文件路径 :return: None """ splited_data = [] print("Reading origin file and split...") # 原始数据集 with open(orgin_path, encoding='utf8') as file: line = file.readli...
b2da56a066ee2e706e2f12534c4aa26e489f91ea
3,624,957
def locked_view_with_ip_exception_ipv6_subnet(request): """View, locked except for the configured IPv6-subnet.""" return HttpResponse('A locked view.')
5b4c2ee7e57b11c40556beb9e205af940eeb4f17
3,624,958
import io def nouvel_item(title: str, link: str, description: str, author: str, pubDate: Dt) -> parse: """ Crée un nouvel item (article) dans un flux RSS. Parameters ---------- title : str Titre de l'item. link : str Lien vers l'item. description : str ...
b2c41cd5ee0efe388a15d4726ae56def2c938e54
3,624,959
def run() -> bool: """Runs the test. :param out_name: name of the output file. :param err_name: name of the error information file. :return: True, if all went well. """ res = True catalog = get_catalog() for algorithm in catalog: single_file = catalog[algorithm...
3fdb467f1d0f2908c254e3f8a19303c14a99bd62
3,624,960
import argparse from pathlib import Path def parse_arguments() -> argparse.Namespace: """ Parse arguments from the command line using argparse. :return: command line arguments :rtype: argparse.Namespace """ parser = argparse.ArgumentParser(__file__) parser.add_argument('base_conf', type=P...
f3fbdcbda119669d25287b410c63b59d5e513b07
3,624,961
import re def remove_words(text, pattern): """ This function removes words based on those found in the pattern. test: String of text pattern: List of words to remove returns: new string with specified words removed """ new_string = re.sub(r"\b(%s)\b" % "|".join(pattern), "", tex...
90499bb65dff72065cc118eeb186b6c0cd30b0c5
3,624,962
def is_valid_slice(frame, pos, pizza, constraints): """ Validates whether the slice is valid in terms of position on the pizza, ingredient composition and overlaps. :param frame: :param pos: :param pizza: :param constraints: :return: True if the slice is valid. False otherwise. """ d...
c11cc809c1e8547f0ed07fdc761f87f908e7f2d8
3,624,963
def filter_ignore_regions(y_true, y_score): """ Filter ignore regions. """ y_true = np.array(y_true) y_score = np.array(y_score) # with ignore regions, i.e. ignore regions labeled with '2' valid_indices = np.where(y_true <= 1)[0] y_true = y_true[valid_indices] y_score = y_score[valid_i...
1445989d5e6f63c2e0f8df8ded361a148d352808
3,624,964
def uniform_ring(a): """Return the standard uncertainty for a uniform ring :arg float a: the radius Convert the radius of a uniform ring distribution ``a`` to a standard uncertainty See reference: B D Hall, *Metrologia* **48** (2011) 324-332 **Example**:: >>> z = ucompl...
fc5cc3a944db6d827b5ba0d9a91b18d00289712d
3,624,965
import random def sent_to_ids(sent, word2id, tokens, oov): """ sent is a string of chars, return a list of word ids """ if tokens is None: tokens = sent_to_tokens(sent) ids = [] for w in tokens: if w in ['!', '.', ':', '?', '@', '-', '"', "'"]: continue if w in word2id...
438c122b220cecd7a6a74da3f889479f7cc839ca
3,624,966
def _get_valid_filename(string): """Generate a valid filename from a string. Strips all characters which are not alphanumeric or a period (.), dash (-) or underscore (_). Based on https://stackoverflow.com/a/295146/4798943 Args: string (str): String file name to process. Returns: ...
93777a5458c00a0a751f77953d718080cf51088e
3,624,967
import scipy def detrend(flux,centroid): """ Detrend flux against centroid points. Returns normalized flux. """ for f in range(flux.shape[0]): p, cov = scipy.optimize.curve_fit(flatfunc, centroid[f], flux[f]) flux[f] /= flatfunc(centroid[f], *p) flux[f] /= np.median(flux[f]) ...
589f2c7a216a2d50a1f30d5b6d6aa69ac58acb37
3,624,968
from keras import layers def keras_dropout(layer, rate): """ Keras dropout layer. """ input_dim = len(layer.input.shape) if input_dim == 2: return layers.SpatialDropout1D(rate) elif input_dim == 3: return layers.SpatialDropout2D(rate) elif input_dim == 4: return l...
64660103382c9fef7d770c9caa1075ba04e2e790
3,624,969
def save_raster_memory(array, path): """ Save a raster into memory """ example = gdal.Open(path) x_pixels = array.shape[1] # number of pixels in x y_pixels = array.shape[0] # number of pixels in y driver = gdal.GetDriverByName('MEM') dataset = driver.Create('',x_pixels, y_pixels, 1,gdal.GDT_...
2577cbb79aec1cbbcca387daa1f7e0732720c37b
3,624,970
def cleaned_json_data(rs,excludes=['_id']): """清除非json格式化的字段""" for r in rs: keys = [] for k,v in r: if not isinstance(v,(str,unicode,float,int,bool)): keys.append(k) for ex in excludes: keys.append(ex) for k in keys: if r.has_...
29f285dd62d7e45c7e066143360b1c82c50b75db
3,624,971
def seasonal_nll(y, pred_mean, pred_std, time): """ Negative log-likelihood (NLL) for each season. :type y: array_like :param y: The true observation. :type pred: array_like :param pred: The prediction. :type y: array_like :param y: The corresponding time array for the target season. ...
63d1064b9d2d28298cd32e32d1b082d45af78749
3,624,972
def distribution_filter_for(bijector): """Returns filter function f s.t. f(dist)=True => bijector can act on dist.""" if isinstance(bijector, tfb.CholeskyToInvCholesky): def additional_check(dist): return (tensorshape_util.rank(dist.event_shape) == 2 and int(dist.event_shape[0]) == int(dist...
3a5f39bcd11772ca70fb760cc0efbb3485e2c282
3,624,973
def EI(mu, std, **kwargs): """ Expected improvement acquisition function INPUT: - mu: mean of predicted point in grid - std: sigma (square root of variance) of predicted point in grid - fMax: observed or predicted maximum value (depending on noise p.19 Brochu et al. 2010) - epsilon: trade-o...
3c02e5514ab5832c850f6be1b415a8d15c1a01bb
3,624,974
import os def get_raw_html(chunk_id, doc_id): """ Given a chunk_id and doc_id, return the raw html contained in the document If the chunk was not found when generating chunk_map, return None :param chunk_id: string :param doc_id: int :return: dictionary or None """ path = PATH chun...
9349a8c8ac58ce2cd84c49a294dd917c50acf6cc
3,624,975
import subprocess def merge(callgrind_files, srcs): """Calls callgrind_annotate over the set of callgrind output |callgrind_files| using the sources |srcs| and merges the results togsophy.""" out = '' for file in callgrind_files: data = subprocess.check_output(['callgrind_annotate', file] + srcs) ou...
18de163b672328e080dfeb1dc6abe60c6d558bb7
3,624,976
def parse_output(filename): """ This function parses the output of a test run. For each run of the test, the program should print the following: ## ID: result: [OK|FAIL] ## ID: cycles: N_CYCLES ## ID: instructions: N_INSTR ## ID: Key: Value Multiple runs are allowed. ...
e24e961e5222d952e79369d22365723919cc3bfa
3,624,977
def get_username_existence_validation_error(username, api_version='v1'): """Get the built-in validation error message for when the username has an existence conflict. :param username: The proposed username (unicode). :param api_version: registration validation api version :param default: The messag...
078f0df9f107ccc781986e94385a23c997eb654d
3,624,978
def MuellerMatrixThomson(azimuth, polar): """Mueller matrix for Thomson scattering Args: azimuth(num): scattering azimuth (degree) polar(num): scattering angle (degree) Returns: array: Mueller matrix (4x4) """ costh = np.cos(np.radians(polar)) cossq_polar = costh ** 2 ...
dfc0af77cf502be66c9d6a6c2db9a9abe568ccb4
3,624,979
def _create_diagnostics(lang_temp, doc): """Creates diagnostics from TextXError objects.""" return [ Diagnostic(_get_diagnostic_range(err), _get_diagnostic_message(err)) for err in validate(lang_temp, doc.source) ]
fd8d50962661c303515499c0935c650bad30fdf1
3,624,980
def revealed_attrs(proof: dict) -> dict: """ Fetches revealed attributes from input proof, returns dict mapping attribute names to [decoded, encoded] values, for processing as further claims downstream :param: indy-sdk proof as dict (proving exactly one claim) :return: dict mapping revealed attribu...
925fdcc87d99063826dea1defccf70f7745f2fcd
3,624,981
def sample_from_scipy_distribution(dist, size, **kwargs): """ use a given distribution to and extract size samples from it.""" if kwargs: return dist.rvs(**kwargs, size=size) return dist.rvs(size=size)
deefc047d0d8c44d38b055a86fabe7c8fdc73064
3,624,982
def cir_RsTLsQ_fit(params, w): """ Fit Function: -Rs-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance (Q) See more under cir_RsTLsQ() Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params['Rs'] L = params['L'] Ri = pa...
075504d81defff812e6f611802a12f225d60cad3
3,624,983
def calculator(): """ Returns a Calculator instance """ print('calculator fixture') return Calculator()
9de991d76933bcd87a77b4cb2837ce0798593aaa
3,624,984
import six import base64 def http_form_post_message(message, location, relay_state="", typ="SAMLRequest", **kwargs): """The HTTP POST binding defines a mechanism by which SAML protocol messages may be transmitted within the base64-encoded content of a HTML form control. :pa...
f87217b595e0fab9c0f6dac556347f27897393ee
3,624,985
def ensureUser(): """Returns the current user account and associated user object. """ account = accounts.getCurrentAccount() if not account: account = users.User(email='test@example.com') user_properties = { 'key_name': 'test', 'link_id': 'test', 'account': account, 'name': 'Tes...
ecfb72f5b8de24c646ffb2ac5c2efda964b444f7
3,624,986
def get_json(file_name): """ Function for getting JSON data of Object """ global zipname with ZipFile(zipname, 'r') as zip: with zip.open(file_name) as file: data=file.read() data=data.decode('utf-8') data=data.strip('\n') #colorful_data=highlight(data, lexers.JsonLexer(), formatters.Terminal256For...
5a3b2ff473ad9b3c20051c8c9f0353e21de69c00
3,624,987
def _read_eleme(f, label_length): """Read ELEME block data.""" fmt = block_to_format["ELEME"] eleme = {"elements": {}, "elements_order": []} line = f.next() if not label_length: label_length = get_label_length(line[:9]) label_format = "{{:>{}}}".format(label_length) while True: ...
c2d8b518873937bddd1ef18ba9ac228cf37545c0
3,624,988
import sh def compress_errorbar_cxx(v, e, errdigits=2): """Temporary plug-hole measure to get python compress errorbars. Using a small C++ executable to perform the task.""" #perl_lib_dir = sh.getenv("WORK_DIR", "HOME") + "/scripts" return sh.pipe_out((COMPRESS_ERRORBAR_EXE, str(v), str(e), str(errdigits))).s...
819e907b95c89ccc691686ae2201489509968673
3,624,989
def get_make_flags(user_args=None): """ Get compiler and flags from a `make` dry run, and return them. """ # These flags don't make since for general snippet compiling. # The ColrC dir is already taken care of, and -c/-o will be used when # get_gcc_cmd() is called. ignore_flags = {'-c', '-o', '-...
b20c694cf15e291505d4e54bda9404b8cf7d37a0
3,624,990
def additive_weight_decay(weight_decay: float = 0.0) -> GradientTransformation: """Add parameter scaled by `weight_decay`, to all parameters with more than one dim (i.e. exclude ln, bias etc) Args: weight_decay: a scalar weight decay rate. Returns: An (init_fn, update_fn) tuple. """ d...
f10e353b7cbbf44aafea802bfcde3ba21a3f69a9
3,624,991
import torch import tqdm import os def compute_heads_importance( args, model, eval_dataloader, compute_entropy=True, compute_importance=True, head_mask=None, actually_pruned=False ): """ This method shows how to compute: - head attention entropy - head importance scores according to http://arx...
06a00126ddbfa4fff5e86cee2d7b8f713b1ea454
3,624,992
from typing import Callable from typing import Any def partitionwise_layer( func: Callable, name: str, *args: Any, **kwargs: Any, ) -> Blockwise: """Create a partitionwise graph layer. Parameters ---------- func : Callable Function to apply on all partitions. name : str ...
3ed322a487543dd6c4f6aa206b0c980b5c165bda
3,624,993
import os def write(space, fd, w_data): """Write a string to a file descriptor. Return the number of bytes actually written, which may be smaller than len(data).""" data = space.charbuf_w(w_data) while True: try: res = os.write(fd, data) except OSError as e: wrap_o...
e11738186a37daf39e2f94a0f9ecfb9dd1b891e9
3,624,994
def resize(image, label, ratio, image_method='bilinear', label_method='nearest'): """Rescale image and label to the same size by the specified ratio. The aspect ratio is remained the same after rescaling. Args: image: A 2-D/3-D tensor of shape `[height, width, chan...
3b56a22b7435c961ee09bcd8879648b46fab25b0
3,624,995
def get_init_fn(checkpoint_dir, continue_oncheck=False): """Loads the NN""" if checkpoint_dir is None: if continue_oncheck: return None else: raise ValueError('No checkpoint provided, using --checkpoint_dir') checkpoint_path = tf.train.latest_checkpoint(checkpoint_di...
3674d1f23996d7c7f486b72af0c785814b601a84
3,624,996
import sys import time def _genUniqueModuleName(baseModuleName): """The calling code is responsible for concurrency locking. """ if baseModuleName not in sys.modules: finalName = baseModuleName else: finalName = ('cheetah_%s_%s_%s'%(baseModuleName, ...
eef4fb094490f54aced15f998e2303ae02ff6768
3,624,997
def pca(X): """Runs Principal Component Analysis on dataset :param X: Features' dataset :type X: numpy.array :returns: - U - eigenvectors of covariance matrix - S - eigenvalues (on diagonal) of covariance matrix :rtype: - U (:py:class: numpy.array) - S (:py:class: ...
a19aff2b1c92c4f74d1f4625194366bafd377c47
3,624,998
def load_test_data(apiobj): """Pass.""" apiobj.TEST_DATA = getattr(apiobj, "TEST_DATA", {}) if not apiobj.TEST_DATA.get("fields_map"): apiobj.TEST_DATA["fields_map"] = fields_map = apiobj.fields.get() if not apiobj.TEST_DATA.get("assets"): apiobj.TEST_DATA["assets"] = apiobj.get(max_ro...
41786e8a4f8e62e6d051be681068766942214533
3,624,999