content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def nu_linear_function(c, x, d): """Wrapper function to calculate linear function. Args: a scaler, a numpy array, another numpy array as bias Return: a numpy array. """ n = x.shape[0] d_c = c d_x = cuda.to_device(x) d_d = cuda.to_device(d) d_out = cuda.device_array(n) blocks = (n...
36d77c7027ed4e85d5fc9b44a176ba08c3417018
3,607,600
def install_command(package): """ 安装命令组合 :param package: 安装包 :return: 返回完整安装命令 """ cmd_ = "pacman -S --noconfirm {0}".format(package) return cmd_
55f8a67a2abebc3204af1f5a1d2e390df69ef999
3,607,601
from typing import Iterable def filter_array(func, arr: Iterable) -> list: """ Filters the arr using the given function. The function must return True or False whether the element should be part of the result or not. """ res = list() for el in arr: if func(el): res.append(...
53e1db35e1876475efa1427aefc4b6728d97087e
3,607,602
def make_aeon_loaders(train_manifest, valid_manifest, batch_size, train_iterations, datadir, random_seed=1, dataset="i1k"): """ datadir is the path for the images train_manifest is the name of tab separated file for AEON for training images valid_manifest is t...
a8c83e5377b1f4c3970245d9166293bc3bd83ae7
3,607,603
def update_query_params(url, **kwargs): """ Updates a URLs query string, inserting or replacing specified parameters. >>> update_query_params('http://example.com', foo=1) 'http://example.com?foo=1' >>> update_query_params('http://example.com?foo=1', foo=2) 'http://example.com?foo=2' >>> upd...
36f161bf44961dcb540afee9f253d01d0a698cd2
3,607,604
def slices(series: str, length: int) -> list: """slices - a.k.a Grouped Slices - :param series: str: :param length: int: :returns: A list of grouped slices of n length from a string """ if length not in range(len(series) + 1): raise ValueError(f'Length {length} not in range for this se...
53a15a0b6322a22b95fc8943fbd7546da4419a77
3,607,605
def s2human(time): """Convert a time in second into an human readable string""" for delay, desc in [(86400,'d'),(3600,'h'),(60,'m')]: if time >= delay: return str(int(time / delay)) + desc return str(int(time)) + "s"
a2d2264fde357534e52444b754de81398eeacea7
3,607,606
def keyInfoNodeWrite(keyInfoNode, key, keyInfoCtx): """ Writes the key into the <dsig:KeyInfo/> element template keyInfoNode. keyInfoNode : the <dsig:KeyInfo/> node. key : the result key object. keyInfoCtx : the <dsig:KeyInfo/> element processing context. Returns : 0 on success or -...
836173858a8fac3bacb661eb920f24e399fbaa73
3,607,607
def create_forward_outright_dataframe(fx_spot_df, fx_forward_df, forward_tenor, price_col_name='MID_PRICE'): """ Calculates forward outright using spot prices and forward points :param fx_spot_df: fx spot dataframe, interval needs to be the same as fx forward dataframe :param fx_forward_df: fx forward dataframe t...
1ebfa271de409265b023f131c7955cb88817812e
3,607,608
import torch def _set_sources(x_s, freq, dt, nt, dtype=None, dpeak_time=0.3): """Create sources with amplitudes that have randomly shifted start times. """ num_shots, num_sources_per_shot = x_s.shape[:2] sources = {} sources['amplitude'] = torch.zeros(nt, num_shots, num_sources_per_shot, ...
00c60b09bab28d86d1601edac5fdbe1a4958c050
3,607,609
def set_customer_filters(request): """Sets customer filters given by passed request. """ customer_filters = request.session.get("customer-filters", {}) if request.POST.get("name", "") != "": customer_filters["name"] = request.POST.get("name") else: if customer_filters.get("name"): ...
4200f9b8a02af35c85721f7e66301347fd49c422
3,607,610
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2), use_l2_regularizer=True): """A block that has a conv layer at shortcut. Note that from stage 3, the second conv layer at main path is with stri...
8c24ace8836e0e9c30aefe158bf7b3e7ae98a326
3,607,611
def norm_sigenh(data, nvols=3): """ Scale each data point by dividing by a 'baseline' value and then subtracting 1 This results in 'signal enhancement' curves, starting at 0 :param data: Numpy array whose last dimension is assumed to be the volume sequence """ data_nvols = dat...
1b53c0de9258c1e330e38fb34209abdbadd5c827
3,607,612
def get_elixier_item_status(id_local): """ .. liefert den Status zu <id_local> oder None """ items = DmsElixierItem.objects.filter(id_local=id_local) if len(items) > 0: return items[0] else: return None
f6b319b5d962ba03669b273c0cefbeafed931dda
3,607,613
def get_short_name(username): """ 根据openid查询展示的uin """ return username
e1062fb0b4d58c052ce60abc9081ec6bb211c006
3,607,614
def dm_nfnet_f3(pretrained=False, **kwargs): """ NFNet-F3 (DeepMind weight compatible) `High-Performance Large-Scale Image Recognition Without Normalization` - https://arxiv.org/abs/2102.06171 """ return _create_normfreenet('dm_nfnet_f3', pretrained=pretrained, **kwargs)
1dc437ee569d58a0e0aacb3686cfcfb4557d754f
3,607,615
def _create_flow(function, bounds): """Create a FlowChart.""" f, b = None, None if function is not None: f = idaapi.get_func(function) if f is None: _log(0, 'Bad func {:#x}', func) return None if bounds is not None: b = (start, end) return idaapi.FlowC...
4e11771c30e38de03e57bd98d5ef0ba4918583ec
3,607,616
from typing import List from typing import Dict def group(answers: List[str]) -> Dict[int, List[str]]: """ group an answers into group-of-word-length :param answers: :return: """ answers.sort() # sort answers_group = {} for item in answers: n = len(item) # define ke...
8ffec0f8e1a1c32d8f28d4364cf9afac6c3e544f
3,607,617
import argparse import typing def _get_operator_and_user_keys(args: argparse.Namespace) -> typing.Tuple[PrivateKey, PublicKey]: """Returns the smart contract operator's private key. """ operator = pycspr.parse_private_key( args.path_to_operator_secret_key, args.type_of_operator_secret_key...
2aa38e332bf795cdce2332786faeeff0f3548718
3,607,618
def ngiaho_stabilization(test, gt, out_path='.', compare_output=1, max_width=640): """ :param test: :param out_path: :param compare_output: :param max_width: :return: """ n, h, w, _ = test.shape # initialize storage prev_to_cur_transform = [] prev...
1386a50cab5764517a1de1c78a07b8e0cd5fb133
3,607,619
import logging def nao_train_model(train_queue, model, optimizer, global_step, arch_pool, arch_pool_prob, criterion, args): """ training model procedure in NAO training search. :param train_queue: :param model: :param optimizer: :param global_step: :param arch_pool: architecture pooling de...
5b39258e56f93266e4ec1fc033ffa056e605e25e
3,607,620
def deep_isinstance(obj, cond): """Checks that items within an arbitrarily nested iterable meet `cond`. Returns a list of bools; to assert that *all* elements meet `cond`, run `all(deep_isinstance())`. """ bools = [] def fn(item, key=None): if isinstance(item, str): bools.app...
4e28a5e254b63a5e0e5b99892fc7945574ada333
3,607,621
def seresunext18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResUNet(BasicBlock, [2, 2, 2, 2], **kwargs) # if pretrained: # model.load_state_dict(model_zoo.load_url(model_urls['res...
3367d44d114140941821e1a05d901eeaa0ab8d3d
3,607,622
def ext_create(cursor, ext, schema, cascade, version): """ Create the extension objects inside the database. Return True if success. Args: cursor (cursor) -- cursor object of psycopg2 library ext (str) -- extension name schema (str) -- target schema for extension objects versio...
33811e88f2f41c1275310a575cce14d4c93008ec
3,607,623
def test_export(): """ to run: kosmos 'j.data.bcdb.test(name="export")' """ namespaces = ["testexport_zdb", "testexport_sqlite"] schema_text = """ @url = farm.1 name** = (S) resource_prices = (LO) !node.resource.price.1 @url = node.resource.price.1 currency = "EUR,USD,TFT,...
5482f3bb32343cfac6929ca234b39cb6a522b246
3,607,624
from sys import version def get_version(): """ Returns current version of this script. The version is an integer number and it must be updated after each modification of the script. Parameters ---------- data : ndarray an array with experiment data config : Object configur...
2dfa42ac9eae9e590b5e6401a78ab8a281b1a454
3,607,625
def get_filled_nc_db(nc, data, symbols, units, comments, z_col, long_names, std_names): """ Check that data written to a netCDF dataset has been stored correctly. """ # Store the data in the netCDF dataset z_len = nc.variables['z'][:].shape nc = ambient.fill_nc_db(nc, ...
f5521766b5ab138da1a40b10af834588592f746a
3,607,626
def plot_ellbow_kmeans(metric, prefix=None, save_path=None): """Plots the sum of squared distances for K-Means to do the ellbow method visually Args: sum_of_squared_distances ([type]): [description] file_name ([type], optional): [description]. Defaults to None. save_path ([type], optio...
543bdbc8e6d6543a91dd005b33f86d00cc7651b8
3,607,627
def state_poly_constraint(sys, A, b): """Create state constraint from polytope Creates a linear constraint on the system state of the form A x <= b that can be used as an optimal control constraint (trajectory or terminal). Parameters ---------- sys : InputOutputSystem I/O system for w...
095617b9b5f4e5315ae192f28095f22fba6c7577
3,607,628
import pandas import numpy def check_matrix_list_format(format, filepath): """ Check format Quality control function to assure that the file format is 'as advertised' :param format: The expected format of the connectivity file (i.e. "Matrix", "Edge List", "Edge List with Type", "Edge List with Time"). S...
2c45affb0d2cf7dfe80ebbaa8238851b17c4fa17
3,607,629
import utool as ut import types import os def is_defined_by_module(item, module, parent=None): """ Check if item is directly defined by a module. This check may be prone to errors. """ flag = False if isinstance(item, types.ModuleType): if not hasattr(item, '__file__'): try...
df49cd1c4ac292ba11295d453fbadb436e2c787e
3,607,630
def user_exists(username): """ Checks if a username is taken. """ df = __get_passwords_table() return (df.username==username).sum() != 0
7eface30766effa3825bb25885b1fc109d5e06a5
3,607,631
def bulk_has_uuid(loc_list: list, product: str) -> list: """Fetch YAML uuid's from S3 using aiobotocore in parallel and check their presence in datacube using bulk_has https://datacube-core.readthedocs.io/en/latest/dev/api/generate/datacube.index._datasets.DatasetResource.bulk_has.html Arguments: ...
699d3851c6df5d2687f0e5927641ff2d0cb71631
3,607,632
from typing import Dict def train_data_discrete_cpds_k2(train_data_discrete) -> Dict[str, np.ndarray]: """Conditional probability distributions of train_data in the train_model""" return create_cpds(train_data_discrete, pc=1)
95b18096e7c84543258690e571cd98f913a6d920
3,607,633
import torch import torchvision def _make_crop(tensor: torch.Tensor, scale_factor: float) -> T_ResizeTransform: """Makes a random crop transform for an input image.""" Hc = int(scale_factor * tensor.shape[2]) Wc = int(scale_factor * tensor.shape[3]) top = torch.randint(tensor.shape[2] - Hc, size=(1,))...
317121f9589320cda2ea72b5273e951f98c0aaf2
3,607,634
import boto3 import logging def find_stacks(fProfile, fRegion, fStackFragment="all", fStatus="active"): """ fprofile is an string holding the name of the profile you're connecting to: fRegion is a string fStackFragment is a string fStatus is a string Returns a dict that looks like this: 'StackId': 'StackNa...
049a9ee90bfcc9efb6dcfdb121d3a4e98a1ff302
3,607,635
def min_edit_distance(word1, word2): """ :type word1: str :type word2: str :rtype: int """ n = len(word1) m = len(word2) # 有一个字符串为空串 if n * m == 0: return n + m # DP 数组 D = [[0] * (m + 1) for _ in range(n + 1)] # 边界状态初始化 for i in range(n + 1): D[i][...
8504dcb903176e745ac24babd05b5e91af9088ca
3,607,636
def createFeatmat(): """ Computes the features of all trips and stores them in a matrix. """ driverFolder = DATA # driver IDs drivers = sorted([int(folderName) for folderName in os.listdir(driverFolder)]) print 'Creating feature matrix...' n_feat = 81 ...
821d0370745d099eb57f94bc6962dafef1835d04
3,607,637
def in_top_countries(country): """Normalize country to be within a top country list. :param country: Column name for "country" :return: set(TOP_COUNTRIES) | "ROW" """ return ( F.when(F.col(country).isin(TOP_COUNTRIES), F.col(country)) .otherwise(F.lit("ROW")) )
9f03d22eb0d8fd62465863fcb6ddccfe8cf35055
3,607,638
import os import subprocess def convertImage(file, maxDim, scale, ext): """Converts the given absolute file path to the given extension, using the icp command from $HFS/bin Args: file (str): The absolute file path of the image to convert. The converted image will have the same path/filename, but with th...
d03158d27ab69374a37e626720b144bd933d96cb
3,607,639
from typing import Counter def aggregate_results(regions_input_file): #generated_sig_merged_element_files = process_cohorts() """ Desired output format: Position #cohorts cohorts(unique) Information from functional mutations (aggregate across all merged cohorts) (RegMuts): - Summary...
2eaceb439e40ff978311f79443612459140dc82d
3,607,640
def Ql_from_Qi_Qe(Qi, Qe): """ 1/Ql = 1/Qi+1/Qe """ Ql = 1/(1/Qi+1/Qe) return Ql
500ea9877d13f70ac8f51bd6add9ffc792ee7de0
3,607,641
def gTranslate(r, src='en', dest='fr', text='translation'): """ To return json dynamic translation response : {translation : 'translated text ...'} @param: src language to translate from (default: 'en') @param: dest language to translate to (default: 'fr') @param: text text to be translated (de...
42da6c5ffae0369db7b2e373806ee198515f96bf
3,607,642
def _depth_to_percentile_normalized_disp(depth): """This performs the same steps as normalize_depth_for_display from the SfMLearner repository, given the default options. This treads every image in the batch separately. """ disp = 1 / (depth + 1e-6) disp_sorted, _ = disp.flatten(1).sort(1) ...
74cf3a7d04e7dbed59860eef4c1abcbc6f27b33b
3,607,643
import re def format_msg(msg: str): """格式化msg并显示在控制台上 本函数允许在写代码时按格式要求进行缩进和排版,但在输出时,这些格式都会被移除;对较长的文本, 按每80个字符为一行进行输出。 如果需要在msg中插入换行或者制表符,使用`\\n`和`\\t`。 args: msg: returns: """ msg = re.sub(r"\n\s+", "", msg) msg = re.sub(r"[\t\n]", "", msg) msg = msg.replace("\\t", "...
5cba99133b66cc1f7820e79a9b2620e07cf39968
3,607,644
import logging def fetch_daily_case(data_home=None, update=True, return_data=False,download = False): """ Download daily case in France per departement Can return dataframe or not Arguments: --------- - data_home: where to save file (default in covid.dataset.data) - update [bool]: if a...
20e09effb2f0db3869c6a5453abb1c3574fc1fc5
3,607,645
def map_get_by_key_index_range_relative( bin_name, value, offset, return_type, count=None, inverted=False): """Create a map get by value rank range relative operation Create map get by key relative to index range operation. Server removes and returns map items with key nearest to value and greater ...
1cbc8163195222bb18a12d8c17b0d9462ac555e7
3,607,646
def final(obj=None): """Decorator marking a CLI handler as final. Everything that follows after it is taken as arguments to the handler. """ return decorate(FINAL, None, None, obj)
61c8ab3ad405aba8a3b2aa7ed7329179ff31367a
3,607,647
def i_priority_node(g, i): """ Returns all nodes of priority i in game graph g. :param g: the game graph. :param i: the requested priority. :return: a list of nodes of priority i in g. """ nodes = g.nodes # Nodes from g # get all node indexes in node tuple (index, (node_player, node_pri...
4d81fab7c7ea7ac75d21dfa36735b1e9a8981444
3,607,648
def get_user_by_username(db: Session, username: str): """get user from table `users` by email Args: - db: Session - username: str Returns: - db query instance """ return db.query(models.User).filter(models.User.username == username).first()
c5438fbf9e77c62a969972e17faaf3d8cfb92410
3,607,649
def installs_series(request, addon, group, start, end, format): """ Generate install counts grouped by ``group`` in ``format``. """ date_range = check_series_params_or_404(group, start, end, format) check_stats_permission(request, addon) series = get_series_line(Installed, group, addon=addon.id...
0e284863de58fe8caac57a2e62b5aa2677c31c37
3,607,650
def svm_classify(newdata, SVM): """SVM classifier. Args: newdata (ndarray): Input test set (of unseen data).\n SVM (dictinary): The trained SVM from 'svm_train'. Yields: prediction (ndarray): The list of predictions . Example: Calculate the distance matrix to itself. ...
2a9d3e49afebd151ea9b24cea95d0d5cde306ea3
3,607,651
def agg_trades(self, symbol: str, **kwargs): """Compressed/Aggregate Trades List GET /api/v3/aggTrades https://binance-docs.github.io/apidocs/spot/en/#compressed-aggregate-trades-list Args: symbol (str): the trading pair Keyword Args: limit (int, optional): limit the results. Defa...
1e4ed6b9b4ab5abafab1007cdefdd9454d8d3d83
3,607,652
import warnings def make_sklearn_compat(op): """This is a deprecated method for backward compatibility and will be removed soon""" warnings.warn( "sklearn_compat.make_sklearn_compat exists for backwards compatibility and will be removed soon", DeprecationWarning, ) return op
da6881d324549258cb185be6cadbcb2e795ea655
3,607,653
def pom_deps(artifacts = []): """Format a set of artifacts for use in a POM dependency. Args: artifacts: List of rendered outputs from `pom_dep`. Returns: Formatted XML POM stanzas, joined together and tabbed in.""" return POM_DEP_CONTAINER_ % ( "\n".join(artifacts) )
3b04450884b1b66957361208ab48d79ef8b10137
3,607,654
def handler(): """Returns the name of the function that is handling the current request, or \ "error" if the current request resulted in an HTTP error, or if the function \ cannot be found.""" # TODO: Update this function when Bottle 0.10 code gets pushed and "the # semantics [of Bottle.match] change" match...
9d55f548479a1a0afd6e6fd44967a7a0290f48ba
3,607,655
def sum_path(G, path): """ Calculate sum of weight in each edges of `path` """ sum_weight = 0 for i in range(len(path)-1): n1, n2 = path[i], path[i+1] sum_weight += G[n1][n2]['weight'] return sum_weight
324c9d99c609da742ab71ad43714ec02d4f4d78c
3,607,656
def login(): """ User login page GET: Displays the login page html POST: If credentials are correct: redirect to the appropriate user page Else display error """ #Check if the user is already logged in if session.get('logged_in'): if session['type'] == 'A...
2c58b95564f577f80c47980d41b70663ac705920
3,607,657
def split_doc(d): """Split sentences in a document and saved the sentences to a list. Args: d: a document final_d: a list of sentences """ d = d.strip().split(".") # split document by "." to sentences final_d = [] for s in d: if s != "": # ignore if the sentenc...
85726c04edbc94ec28e737050c0e508b54b59e5e
3,607,658
import time import requests import json import traceback import sys def fetch_stock_concept_from_eastmoney(stock_bk: str = "BK05666", freq=QA.FREQUENCE.HOUR, ) -> pd.DataFrame: """ 东方财富网 > 行情中心 > 沪深板块 http://quote.eastmoney.com/center/hsbk.html :param stock: 股票代码...
05751795a3eca6f7eb0ddf3c0f682479226e8b91
3,607,659
import re def dict_count(text_list, custom_dict): """Performs dictionary analysis, returning number of dictionary hits found. Removes punctuation and stems the phrase being analyzed. Compatible with multiple-word dictionary elements.""" counts = 0 # number of matches between text_list and c...
992c09edfced50d25ffa22f525204fccde72037c
3,607,660
def insertIntoDb(table, names, values): """Insert into database""" if len(values) != len(names): return None query = 'INSERT INTO %s (%s) VALUES(%s)'%(table, ', '.join(names), ', '.join(values)) rowId = None try: db = get_db() cur = db.cursor() cur = get_db().cur...
77fa39103d7dfc2102e4cdbd4899e0e083720039
3,607,661
import asyncio def retry(times, retry_interval=2): """Decorator that provides backoff retries.""" def func_wrapper(func): """Function wrapper.""" async def wrapper(*args, **kwargs): """The main functionality of backoff retries leaves here.""" for time in range(times): ...
3f055d7aa4dd8b9cbe16d0fd19febfb3ae8f18c7
3,607,662
def login(): """Step 1: Get the user identify for authentication. """ # print("Step 1: User Authorization") github = OAuth2Session(cfg.GITHUB_CLIENT_ID) authorization_url, state = github.authorization_url(cfg.AUTHORIZATION_BASE_URL) # State is used to prevent CSRF. session['oauth_state'] = ...
ee788f163fb8986721e6c472bbab8edb6348367a
3,607,663
def build_history_object(metrics): """ Builds history object """ history = {"batchwise": {}, "epochwise": {}} for matrix in metrics: history["batchwise"][f"training_{matrix}"] = [] history["batchwise"][f"validation_{matrix}"] = [] history["epochwise"][f"training_{matrix}"] =...
1062b05b6ec5fb0126b85eb06270ccbd0cc2d468
3,607,664
def humidity_read(intent, session): """ If we wanted to initialize the session to have some attributes we could add those here """ result = read_table_item("onsemi", "serial", "humidity") #humidity = float("{0:.2f}".format(result)) session_attributes = {} card_title = "Reading Humidity" spe...
ffcec61e906aae1373626523c10bcec3ef087aba
3,607,665
from typing import Mapping from typing import Any from typing import Union from typing import Tuple def _check_namelist_entries(entries_mapper: Mapping[str, Any]): """ Check whether namelist entries follow NEMO convention for names and types Parameters ---------- entries_mapper: Mapping O...
5d19d9210a9286e4da436640d96c2ae11f8f3a40
3,607,666
def atan2(arg1, arg2): """ calculate arc tangent with two arguments """ if isinstance(arg1, (int,float)) and isinstance(arg2, (int,float)): return np.arctan2(arg1,arg2) else: return symbolics.atan2(arg1,arg2)
d7b94c135d4664f2254e24d5777901fde853e3ac
3,607,667
import functools def make_reference_fn(node_vec: np.ndarray, edge_vec: np.ndarray): """Make reference function.""" ref_fn = functools.partial( make_constant_like, node_vec=node_vec, edge_vec=edge_vec) return ref_fn
29f107ba376b043a0b39813a97e703267b8c5ff7
3,607,668
import pathlib def directory_tree(directory: pathlib.Path) -> None: """Return a string that is a printable tree directory of the passed directory""" directory_tree_string = '' # Turn directory into a pathlib.Path object # if not already one if not isinstance(directory, pathlib.Path): direc...
20a655a80f46060515883640049d0d22795ac422
3,607,669
def list_albums(artist_id): """produce list of albums for artist """ album_list = my.Album.objects.filter(artist=artist_id) return [{'id': x.id, 'name': x.name} for x in album_list]
83bd08422a54e8ca2ccd24d8082e7bfdf3eea5c6
3,607,670
import torch def coarse2fine_rendering(model_fine, model_coarse, xyz, ray_o, ray_d, view_d, z, n_fine_points=128, density_noise_std=0, with_noise=False, white_bkgd=True): """ Args: model_fine, model_coarse: nn.Module NeRF MLP for fine and coarse rendering xyz: torch.Tensor ...
957d51e9ec2a55728bcfb7ffe3a5b9d17943d339
3,607,671
import re import platform import subprocess def ssh_copy_id(name): """ Returns True if ssh-copy-id succeded. Else returns exception string. """ def eval_copy_response(copy_response): # todo: add other exceptions when they occur key_exists = re.search(r'WARNING:(.*)', copy_response[1])...
bcd5705cad5789246be2200a84403fb8b1d0fb0a
3,607,672
def allclose(a: xr.DataArray, b: xr.DataArray, *args, **kwargs) -> bool: """Like np.allclose, but converts a to b's units before comparing.""" try: a = a.pint.to(b.pint.units) except pint.DimensionalityError: return False if a.dtype == float: # need to use "allclose" to compare floats ...
0bd7977236c179ddd8e84bad3be1e22623a7a7a5
3,607,673
import torch def evaluate(data_iterator, model, args, timers, verbose=False): """Evaluation.""" # Turn on evaluation mode which disables dropout. model.eval() total_lm_loss = 0 eval_len = args.eval_iters or len(data_iterator) with torch.no_grad(): # stop = False iteration = ...
86c28ae16a2a980ab76a96b8b3654edde0b5f38b
3,607,674
def find_latest_deployment(package_name, app_id, environment): """Find the most recent deployment for a given package in a given environment for the given application ID """ return (Session.query(AppDeployment, Package) .join(Package) .filter(Package.pkg_name==p...
dc90d9264544ee0842acb5bc2725f8a871b4574d
3,607,675
def is_ccw(signed_area): """Returns True when a ring is oriented counterclockwise This is based on the signed area: > 0 for counterclockwise = 0 for none (degenerate) < 0 for clockwise """ if signed_area > 0: return True elif signed_area < 0: return False else: ...
bd0e0d92913dcb1c895c36c6e724e454e3658a6d
3,607,676
import torch def quat_to_rotmat(quat): """Convert quaternion coefficients to rotation matrix. Args: quat: size = [B, 4] 4 <===>(w, x, y, z) Returns: Rotation matrix corresponding to the quaternion -- size = [B, 3, 3] """ norm_quat = quat norm_quat = norm_quat/norm_quat.norm(p=...
c707db69636f0da2f4a0a822e264f0ec4ac7df89
3,607,677
def igv_test_tracks(igv_public_track): """Returns a list with test tracks for igv.js""" return [igv_public_track]
58b1de343f6b9aa4d4274fd9a67fd40021d774ec
3,607,678
def init_operation(mocker): """Fixture to initialize an operation.""" mocker.patch.object(settilecallback.SetTileCallback, "__init__", lambda x, y: None) def _create(): return settilecallback.SetTileCallback(None) return _create
36cec84b3812eeb2b302a26dc64cfc75ba49ce6e
3,607,679
def start_threads(started_thread_for_system, thread_instance_list, same_system, unique_log_verify_list, system_name): """ This function iterates over unique_log_verify_list which consists of unique values gotten from monitor attributes and verify_on attributes If a system_name has a * aga...
8fb6f98a54773d9ba5ece37e8d39fa8e7aca97f9
3,607,680
def args_to_job_params(envs, labels, inputs, inputs_recursive, outputs, outputs_recursive, mounts, input_file_param_util, output_file_param_util, mount_param_util): """Parse env, input, and output parameters into a job parameters and data. Passing arguments on the comm...
bb953f70870beb69ecc4293e0dd06db5c0776cb8
3,607,681
def error_in_assigned_energy(pred_meter, ground_truth_meter, etype = ("power","active")): """ ORIGINAL A) Compute error in assigned energy. OK The difference between the energy within the original energy and the current one. .. math:: error^{(n)} = \\left | \\sum_t y^{(n)}_t - \\sum_t ...
aa826c79073e4e79fa2931ae4518ebe87c6a4e7e
3,607,682
import requests import json def get_json(yuri): """Obtain the json data from directory API.""" jason = cache.get('{0}_api_json'.format(yuri)) if jason is None: # read the json data from URL earl = "{0}{1}/api/json.txt?api_key={2}".format( settings.API_PEOPLE_URL, yuri, settings...
aa842780bd8bd94fd583280fc2414747606f5cb6
3,607,683
def circle_mask(img, dims): """ Create a circular mask. Parameters ---------- img : ndarray Grayscale image to produce circular mask for. dims : tuple or list Circle(s) to base mask on. Note these should be supplied in ((x,y),r) format. Returns ------- mask ...
434060bf2f5898721c032560536ca13f571b740a
3,607,684
import logging import time def database_updater(args, job, wait_time=90): """ Try to update our db for x seconds and handle it nicely if we cant :param args: This needs to be a Dict with the key being the job.method you want to change and the value being the new value. :param job: This is the jo...
51a8e728f5f05a9617d04dad2ffa68e6968de585
3,607,685
def creating_scatter_graph(df, type_, marker_size=50): """ :param df: dataframe :param type_: string :param marker_size: int :return: Plotly Scatter Graph """ # getting grouping data df_ = grouping_types(df=df.copy(), t=type_) # changing numeric column name t = 'avg_' + type_[-3...
868326c751794efbf53e3e57fd6fc3ca3c0631c7
3,607,686
def findinfiles(qtbot): """Set up SearchInComboBox combobox.""" findinfiles_plugin = FindInFiles() qtbot.addWidget(findinfiles_plugin) return findinfiles_plugin
48c469465cd2d032aa6dfbcc7acdbcc53212f601
3,607,687
def _symlink_genrule_for_dir( repository_ctx, src_dir, dest_dir, genrule_name, src_files = [], dest_files = []): """Returns a genrule to symlink(or copy if on Windows) a set of files. If src_dir is passed, files will be read from the given directory; otherwise ...
494ce9c4eb8530f825f449e1a9d5da26d8e2cd0a
3,607,688
from datetime import datetime def create_tmp_token(key_path, server_id): """ This function use JWT protocol to creates a temporary token for user authentication. Focus on the "Server Token (ID Registration Style)" section of the following documents. reference - https://developers...
96a0d35cfe71fdeaa03f3a8fb2d5b3cb36b64739
3,607,689
def update_space_settings(environ, name): """ Read a tiddler named by SPACE_SERVER_SETTINGS in the current space's public bag. Parse each line as a key:value pair which is then injected tiddlyweb.query. The goal here is to allow a space member to force incoming requests to use specific settings,...
e55283ac38ede07e01a4ea0f0b496dbc0b97a3bc
3,607,690
from typing import Tuple def update_n( update_mask: np.ndarray, n: np.ndarray, output_idx: Tuple[int, int] ) -> np.ndarray: """Updates the counts that are stored in 'n' array. Args: update_mask (np.ndarray): a 2d boolean array indicating which indices in the arra...
87c934825185038b9ff84b0386d7a6aedf790790
3,607,691
def matrix_K(le, lp, newElement): """make matrix of stiffness with boundary condition""" size = len(lp) K = np.zeros((size * 3, size * 3)) # определение геометрических параметров for elm in le: """Для стержней""" if len(elm.pnt) == 2: #print('{type = 2, points = {', elm....
64e1d8d495de194ff27eb746b1f4e7153f92f9de
3,607,692
import argparse def parse_args(): """ build arguments :return args: input arguments """ parser = argparse.ArgumentParser(description="Flack to wave arguments.") parser.add_argument("--wav_dir", type=str, default="../../data/LibriSpeech/wav", required=False, help="LibriSpeech wav directory") ...
f3c5e8f3636ce91be3042feae8e385ebd2b25ce0
3,607,693
from datetime import datetime import csv def Cull(max_age=None,masterfile=None,edlfile=None,simulate=False): """ Using the module level MaxAge, remove entries from the EDL, older then the interval. """ global EDLMaster, MaxAge, Columns, AutoSave if masterfile == None: masterfile = EDLMaster if max_age == Non...
9aa74a92cca7c6ed322a376e1c7afbd35766f852
3,607,694
def from_row_num_to_track_id(df, row_num): """ df must have a 'track_id' column """ return df.iloc[row_num].track_id
db34b53be6a74e8a0fa20394f014346dc8d654d0
3,607,695
from re import search as re_search import os def load_files(path, extensions=[], filters=[], read=False): """ Method to load files from path, and filter file names with REs filters and extensions. Args: path (str): string that contains OS path extensions (list): list of strings files' ...
e2c631a3d1f2077c76f6f9ffe9a13b86ba0ea72a
3,607,696
def hyperbolic_clip(x, r=-1., axis=-1): """ Clips points in the ambient space to a hyperbolic CCM of radius `r`, by f orcing the `axis` coordinate of the points to be \(X_{axis} = \sqrt{\sum\limits_{i \neq {axis}} X_{i}^{2} + r^{2}}\). :param x: np.array, coordinates are assumed to be in the last ax...
2ab0c9888c6b6f9d2fb796d82b288b1f4bc4aa54
3,607,697
def age_window_hit(by_predicted, by_truth): """ calculates the window for a given truth and checks if the prediction lies within that window :param by_predicted: the predicted birth year :param by_truth: the true birth year :return: true if by_predicted within m-window of by_truth """ m = -0...
0d5903d21006f2651114affa9179cfc063b25f1d
3,607,698
def ConstraintRandomMinFluxScan(model, cd, lo, hi, n_p, it, IncZeroes=True, reacs=None, exc=[], processes=None): """ same as ConstraintScan except using RWFM rather than FBA pre: cd = sum of reaction fluxes dictionary """ state = model.GetState() rv = matrix.matrix(co...
0ce7817c0350262f44f8d6eb36a4a49025220417
3,607,699