content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from re import T def prod(x, axis=None, keepdims=False): """Multiply the values in a tensor, alongside the specified axis. """ return T.prod(x, axis=axis, keepdims=keepdims)
8478cab6c1041eab415f2db736379f46d98d323f
72,600
from typing import Tuple from typing import Optional def accumulate_output( duration: float, step: float, patch_collar: float = 0.05, ) -> Operator: """Accumulate predictions and audio to infinity: O(N) space complexity. Uses a pre-allocated buffer that doubles its size once full: O(logN) concat o...
a2867737824630fbf69f50e9164ae41e5189716c
72,601
import tempfile def create_tmpdir(): """Create temporary directory where all intermediate files will be placed.""" return tempfile.mkdtemp(prefix='xl-')
7cac5eb979b3d7150084daf68749b30a3986e52b
72,602
def get_sticker_and_id(sticker): """ Gets sticker and it's identifier from the given sticker or of it's identifier. Parameters ---------- sticker : ``Sticker``, `int` The sticker, or it's identifier. Returns ------- sticker : ``Sticker``, `None` The sticker if f...
afeb09e9d44d5326aa3f4a3511d7536cb36d2476
72,603
import scipy def getRelativisticMaxwellJuttnerDistribution(p,T,n): """ Calculates the relativistic Maxwell-Jüttner distribution. :param float p: Momentum in units of m_e*c :param float T: Plasma temperature (eV) :param float n: Plasma density (m^-3) """ mc2inEV = scipy.constants.m_e*scipy...
b5f9e68ef96800bb3894c90b5d0f0d1bf8466feb
72,604
def _save_prediction_results(res: dict, recorder: Recorder, curr_loader: MARSDataLoader, threshold: float, recall_at: float=None) -> int: """use result metrics, recorder, test dataset loader to save results to pred file""" pred_ID = _find_next_pred_ID() # add additional info ...
a9806d810c992290f8d0004a0f5fbe670d9750aa
72,605
import os def _can_read_file(self, filename): """ On many installations, at.allow and at.deny are not readable by non-root users. Assure that they are. """ if not os.access(filename, os.F_OK): # No file there return False if not os.access(filename, os.R_OK): # Can't read file rais...
98aac8f94b7c16a69718510316c726ed193f4e6e
72,606
def breadth_first_search(graph, s): """ Given a graph (an instance of Digraph) and a vertex s in the graph, will return construct a search tree from s using a breadth-first search. That is, a dictionary "reached" will be returned whose keys are all vertices reachable from s and where reached[v] is the pred...
ee18640947ee5244945c022f2ffdad090ffe9225
72,607
def ovs_vsctl_set(table, record, column, key, value): """ This function allows to alter the OVS database. If column is a map, then caller should also set the key, otherwise the key should be left as an empty string. """ if key is None: index = column else: index = "%s:%s" % (...
c3da6e66d9320d05a91da891e6de1020e9d32092
72,608
def get_pg_type(f, type_override=None): """ :param fields._column f: field to get a Postgres type for :param type type_override: use the provided type for dispatching instead of the field's own type :returns: (postgres_identification_type, postgres_type_specification) :rtype: (str, str) """ ...
d5f0674d656a9ea57a73b77640cfb10ec0f4cb09
72,609
import pprint def readField(f, fieldType): """Read palm record from a file f. fieldType -- integer specifying the palm field type """ if readDebug: print '-----------------------------------' print 'READING FIELD' print 'file:',f print 'fieldType:',fieldType retVal...
8e791efc0b40c3bbb6ed26ac48d815fce902efeb
72,610
import re def get_aws_local_file(aws_creds_file): """ Converting aws config and credentials files into dictionaries :param aws_creds_file: string :return: dictionary """ aws_config = {} current_profile = '' input_file = open(aws_creds_file, 'r') for line in input_file.readlines(): ...
3c0b323f8dc61f17953d72f9e8adb74ac3e0e828
72,611
from typing import Optional def build_get_revoc_reg_delta_request( submitter_did: Optional[str], revoc_reg_id: str, from_ts: Optional[int], to_ts: int ) -> Request: """ Builds a GET_REVOC_REG_DELTA request. Request to get the delta of the accumulated state of the revocation registry identified by...
6d2ae8eea455098390ed1b9f9237b1df5532fb5c
72,612
from typing import Union from typing import Sequence def get_shift( reference_array: np.ndarray, shifted_array: np.ndarray, shift_method: str = "modulus", precision: int = 1000, support_threshold: Union[None, float] = None, verbose: bool = True, ) -> Sequence[float]: """ Calculate the ...
4bf2a071f289154e6fffd85d8fe4764a7a087423
72,613
import threading def make_collector(name, sleep_time, decay_time, collector_class, *args): """ other module should use this fn to init a collector, this fn start a thread to run the collector and return an atomic_ref so outside world can get metrics collected by this collector """ atomic_ref, instance...
ab51ad2a65b7f0678d532b85a985b70d4dd8b478
72,614
import collections def _group_by(objs, keys): """Return a dictionary with keys arbitrary concatenations of attributes and values lists of objects (Albums or Items) with those keys. """ counts = collections.defaultdict(list) for obj in objs: values = [getattr(obj, k, None) for k in keys] ...
97c11094cd97dcaf05db74b8db75df127922d833
72,615
def make_quant(param, default_unit): """Convenience function to intialize a parameter as an astropy quantity. Parameters ---------- param : float, or Astropy Quantity Parameter to initialize default_unit : str Astropy unit string, sets as default for param. Returns ------- ...
a6ed42ba9712b235ecbf0062c08601afb3a3a9a4
72,616
def html_escape(text: str) -> str: """Produce entities within text.""" return "".join(html_escape_table.get(c, c) for c in text)
a3cd3eff7698bb0613f4115f2d539521617db06c
72,617
def vit_base_patch32_224(num_classes: int = 1000): """ ViT-Base model (ViT-B/32) from original paper (https://arxiv.org/abs/2010.11929). ImageNet-1k weights @ 224x224, source https://github.com/google-research/vision_transformer. weights ported from official Google JAX impl: 链接: https://pan.baidu.co...
dc8679a1dbf7ab7d97a9ba263403db77b61ecc91
72,618
def validate_base10(number): """Check if a string is a valid BASE10 representation of an AIC.""" number = compact(number) if len(number) != 9: raise InvalidLength() if not isdigits(number): raise InvalidFormat() if number[0] != '0': raise InvalidComponent() if calc_check_...
bc2394cf5b50d4f5e46b4b8089f0aec463ed5242
72,619
def replace_oovs(source_in, target_in, vocabulary, source_out, target_out): """Replaces out-of-vocabulary words in source and target text with <unk-N>, where N in is the position of the word in the source sequence. """ def format_unk(pos): return "<unk-{}>".format(pos) if target_in is None...
c11412cd67399ec88dd36e3120072500fc39aca5
72,620
def _bowtie_args_from_config(data): """Configurable high level options for bowtie. """ config = data['config'] qual_format = config["algorithm"].get("quality_format", "") if qual_format.lower() == "illumina": qual_flags = ["--phred64-quals"] else: qual_flags = [] multi_mapper...
57e86765444657812d0bebc9b1a3c3dcb234d300
72,621
def split_unk(str_, vocab): """ 将所有不在词表中的符号切分开,尽量保留在词表中的符号 """ rstring = "" for c in str_: if c in vocab.keys(): rstring += c else: rstring += " " + c + " " str_ = rstring return str_
c54da92f9e69f32949bba538242ea91cfdb197f9
72,622
def sum_square_numbers(upper: int) -> int: """Calculate the sum of the squares of the integers less than upper.""" n = upper - 1 return n * (2 * n + 1) * (n + 1) // 6
b576ac0a860ea40a3efae2ced2d2c5d449b975dc
72,623
import requests from bs4 import BeautifulSoup def searchAnimation(keyword = None, pageNum = None): """ 通过关键词搜索动画 返回搜索页的soup """ if keyword == None or keyword == "" : keyword = "极影字幕社 鬼灭之刃" page = Formate.pageFormate(pageNum) keyword = Formate.keywordFormat(keyword) keywordURL = Constant.b...
fb69cb3a5b1072d4c1a7d0acd2f7542dd917b191
72,624
def download_preview_file_thumbnail(preview_file, file_path, client=default): """ Download given preview file thumbnail and save it at given location. Args: preview_file (str / dict): The preview file dict or ID. file_path (str): Location on hard drive where to save the file. """ p...
27a1420640af90cc174a479f8d835cee6b2cd34b
72,625
def get_player_df(players,stat_type,stat,playoffs,player_labels): """ Get dataframe from basketball_scraper :param players: list of player names :return: """ if not player_labels: player_labels=players players_df=[] for player,player_label in zip(players,player_labels): ...
d31ae11917aa23545a3210d662f4ffa6427a4fb9
72,626
def nearest_workday(dt): """ If holiday falls on Saturday, use day before (Friday) instead; if holiday falls on Sunday, use day thereafter (Monday) instead. """ if dt.weekday() == 5: return dt - timedelta(1) elif dt.weekday() == 6: return dt + timedelta(1) return dt
f0f3ff6635ca08ec1b8ca4705b52481b2b8f7d7d
72,627
def _manuscript_chapter_data(ms_id, bk, ch): """ Parse the request and return the data required to make the manuscript page and also the correctors json blob """ ms = get_object_or_404(ManuscriptTranscription, pk=ms_id) my_chapter = get_object_or_404(Chapter, num=ch, book__num=bk) hands = Ha...
bd859bb50112864cbc1db024fe055d79149f3bce
72,628
import warnings from datetime import datetime def read_GPM(infile: str, refl_min_thld: float = 0) -> xr.Dataset: """ Read GPM data and organize them into a Dataset. Parameters: ----------- gpmfile: str GPM data file. refl_min_thld: float Minimum threshold applied to GPM reflec...
58965e878402375ab48637c1980e66d7cc1cd055
72,629
import os def setty19( fpath: str = None ): """ A preprocessed dataset of `Setty2019 <https://www.nature.com/articles/s41587-019-0068-4>`_ \ used in our work. This downloads the dataset from `here <http://www.med.osaka-u.ac.jp/pub/rna/ykato/project/capital/>`__. Parameters ---------- ...
aea42285e1408e31acfe054e03fcce24ee703b70
72,630
def _world2fig(ff, x, y): """ Helper function to convert world to figure coordinates. Parameters ---------- ff : `~aplpy.FITSFigure` `~aplpy.FITSFigure` instance. x : ndarray Array of x coordinates. y : ndarray Array of y coordinates. Returns ------- coo...
99df767d948bc1c0807b676e2178de1478a1ac71
72,631
def gauss(t, sigma): """ Take sample from Gaussian function with the given sigma. """ return e ** (-t ** 2 / (2 * sigma ** 2))
ed5bfb690fc0d1e936880276640bf55261ab2764
72,632
import json import os def create_arguments(ddo): """Create the arguments that need to be add to the argo template. Args: ddo (:py:class:`common_utils_py.ddo.ddo.DDO`): The workflow DDO. Returns: list: The list of arguments to be appended to the argo workflow """ args = '' im...
d5c762b454d05c527229480983e59bd61fd63194
72,633
def log_normal_error(weights, z_alpha=1): """Returns the unnormalised errors on the estimation of the probability density using the lognormal method. Parameters ---------- weights: numpy.ndarray Associated weights to the first-passage time data. Must be a one-to-one correspondance b...
43f617d4a44d1271a9cc38f64700f3dcea86baba
72,634
def T(t): """The file name for target ``t`` of the current object.""" return _targetPrefix + _find_object_type() + "/{oid}/" + t
9bffca11c52d60489eda10963b0e253c0708e3a8
72,635
from typing import List async def list_users() -> List[UserOutGet]: """ Get users list. :return: list users """ return await UserOutGet.from_queryset(Users.all())
89fdcab3a5f1dec1c39f76e036f38c2981a26b0b
72,636
def default_for(python_type): """Sets a specified python type's default SQL type. Args: python_type (type): Python type to set the specified sqltype as default for. """ def func(sql_type): _defaults[python_type] = sql_type return sql_type return func
69c0338911df4b9d0e4f25be22f5ab783c3e7c63
72,637
def submit(syncselection_name, now=True, as_object=False, p5_connection=None): """ Syntax: SyncSelection <name> submit [<now>] Description: Submits the sync selection for execution. You can optionally override plan execution times by giving the <now> as one of the strings "1", "t", "true", "True", "...
214d334ed5e1bff2a717bb075e6f6d51cfc96af8
72,638
from typing import Optional from typing import Union def df_count(x: str, df: pd.DataFrame, hue: Optional[str] = None, sort_by_count: bool = True, top_nr: int = 5, x_base: Optional[float] = None, x_min: Optional[float] = None, x_max: Optional[float] = None, other_name: str = 'other', other_t...
c2385380494f5653406e9796e343a110e2fa90fd
72,639
def is_palindrome(number): """ Returns True if `number` is a palindrome, False otherwise. """ num_str = str(number) num_comparisons = len(num_str) // 2 for idx in range(num_comparisons): if num_str[idx] != num_str[-1-idx]: return False return True
391aec57bba8366d7e7ef2c8187fda377f5a786d
72,640
import wincertstore import os def check_pem_file(): """ Convenience USGS only function that checks if the DOI PEM file is stored in the wincertstore and export a local copy for use in the application. Returns ------- None """ try: pem_fname = get_pem_fname() if not os....
9f3dc4ffa6dfad6dc94eac8373c69748124a3dd5
72,641
def _process_images_num_channels(image_arrays, expected_channels): """ Helper function for processing decompressed images with number of expected channels. This is for old API without mapping provided. Use the first n channel, n=expected_channels. """ if expected_channels == 1: # Convert to ...
b016c596412ae5cc3f40cb6cac9e8587d0258587
72,642
from typing import Iterable def flatten_list(li: Iterable): """Flattens a list of lists.""" if isinstance(li, Iterable): return [a for i in li for a in flatten_list(i)] else: return [li]
306536fdadf231b0a0f752bb63d7e01317819674
72,643
def queryString_required(strList): """ An decorator checking whether queryString key is valid or not Args: str: allowed queryString key Returns: if contains invalid queryString key, it will raise exception. """ def _dec(function): @wraps(function) def _wrap(request, *args, **kwargs): for i in strList: ...
34d69213f4f4bab4965af13beae4faf66d63b970
72,644
def listdetail(filename, itemtype, name="", header="default"): """List nodes and metadata in output file.""" obj = SwmmExtract(filename) typenumber = obj.type_check(itemtype) if name: objectlist = [obj.name_check(itemtype, name)[0]] else: objectlist = obj.names[typenumber] propn...
cb49f791a0fd76db9a4c24e75dbe71d2921ba40a
72,645
import json def get_emails(account_id=None): """ Get all email -entries related to account :param account_id: :return: List of dicts """ if account_id is None: raise AttributeError("Provide account_id as parameter") # Get table name logger.info("Create email") db_entry_obj...
c2cd80af15b11918c20c031983cd2f66d92037cb
72,646
def set_reverseXmatrix(): """Reverse X axis using set_strechmatrix(-1.0, 1.0) Returns ------- reverse_X_matrix: matrix """ return set_stretchmatrix(-1.0, 1.0)
7a39df1344cc8fdfd02a4b77d5fb999c01060e6b
72,647
from typing import Tuple def _get_final_vals(spacetime_matrix: np.array, receiver_velocity_mx_mps: np.array, source_velocity_mx_mps: np.array, time_array_s: np.array, receiver_position_vector_initial_xyz_m: np.array, s...
19f832c26c6f3998fb55ce35431d831ecff7ff20
72,648
def dataset_to_datavar( ds: DataSetGAN, n_convs: int, kernel_size: int, stride: int, padding: int, remove_diags: int, add_diags: bool, ) -> DataVarGAN: """Convert a `DataSetGAN` into a `DataVarGAN`.""" # ds = pad_edges(ds, offset=offset) seqs = push_seqs(ds.seqs) adj = ds.adj...
2e2b961bf2b162a2ab224b5836ddebd3bf48a4c4
72,649
def improve_ensemble(energy, positions, ensemble, ensemble_energies, unchanged_iterations): """ Given an energy and positions for a single pose, as well as the same data for a reference ensemble, this function "improves" the quality of the ensemble by identifying poses with the lowest potential energy. ...
ac1dcf2ec104a886b61e2abe4b4e090724d47ce7
72,650
def get_folds(X, y, cv_count: int, split_seed: int, stratify: bool = None): """Cross validationのインデックスを返す。 Args: X: 入力データ。 y: 出力データ。 cv_count: 分割数。 split_seed: 乱数のseed。 stratify: StratifiedKFoldにするならTrue。 Returns: list of tuple(train_indices, val_indices): イ...
aacefdf31188ac99d73fc82ce3b9f164b0daacd9
72,651
def get_static_welcome_message(): """ Get the static welcome page. """ return \ """ <h3>Search Help</h3> <ul><li>The display below the line is an example of the output the browser shows you when you enter a search word. The search word was <b>green</b>.</li> <li>The search result shows for different par...
f630c67ab66069baf8b82b5b4c5fe111b9191a73
72,652
def bisearch(x, profile, epsilon=RT_EPSILON): """Use binary search to find index of equal or next higher x-value.""" idx = 0 hi = len(profile) while idx < hi: mid = (idx + hi) // 2 if x < profile[mid][0] or equals(x, profile[mid][0], epsilon): hi = mid else:...
7c84325bd267e921b3f5d9f79d0f66f41fc52f91
72,653
def cmd_alias_create(module, cmd_path, alias, version, **kwargs): """ gvm alias create <alias> <version> """ result, data = get_alias_list(module, cmd_path, **kwargs) if not result: module.fail_json(**data) if alias in data["aliases"]: if version == data["aliases"][alias]: ...
c8d9e550d82fd9b6b7a86c653dde6b04efac0205
72,654
def format_lines(statements, lines): """Nicely format a list of line numbers. Format a list of line numbers for printing by coalescing groups of lines as long as the lines represent consecutive statements. This will coalesce even if there are gaps between statements. For example, if `statemen...
9e8f3d83df45134c5cd586a9323612b8516acdec
72,655
def _get_raster_srs_str(fp): """Read a raster with GDAL and return its SRS or None.""" try: tmp_ds = gdal.Open(fp, GA_ReadOnly) # Get WKT projection from gdal srs_str = tmp_ds.GetProjection() if not srs_str: raise Exception('GDAL failed to detect any projection.') ...
b45c5282e1727e61f84dbfba1a9d114202f1d072
72,656
import os def convert_file(input_file_name, args_dict): """ Converts a .py file to a .ipynb file. .py file must be written in a specific format to be converter. :type input_file_name: str :type args_dict: dict args_dict: { 'output': 'outfile.ipynb', 'pyversion': '3.8', ...
f4f69ff175658edd13b31a7597839ed7f9dbe55d
72,657
import os import json def get_best_predictions(args, examples, features, bpe_encoder, mode="train"): """ <examples> example = InputExample( qas_id=qas_id, question_text=question_text, paragraph_text=paragraph_text, orig_answer_text=orig_answer_text, start_position=start_position, a...
6dcde58e92726955d43339dc82c9d5a811f083c5
72,658
def cos_zenith(ha, dec, latitude=None): """Calculate cos(zenith) for specified hour angle, DEC and latitude. Combine with :func:`cos_zenith_to_airmass` to calculate airmass. Parameters ---------- ha : astropy.units.Quantity Hour angle(s) to use, with units convertible to angle. dec : a...
00c8d2ca71da833d7769e3b1fb6f8d5ca1664c69
72,659
def format_body(issue, empty_row, width_col): """ Formats the body of an issue """ wrapper = TextWrapper(initial_indent=empty_row, subsequent_indent=empty_row, width=len(empty_row) + width_col, replace_whitespace=False) body = i...
538129479099bca39fdaecf7561ac3ee42a687ef
72,660
def get_single_feature_from_example(example: InputExample, config: Config) -> InputFeatures: """ Transfer an example to a feature. text -> ids list; labels -> label_id list; Add padding if text is too long. Parameters: example: InputExample Returns: feature: InputFeature """ ...
1f0c35ddd1e6b92896ecb0acd8b98a181cc5a8c6
72,661
import sys def main(argv=sys.argv): # pragma: no-cover """Main point of Entry""" return pbparser_runner( argv=argv[1:], parser=_get_parser(), args_runner_func=_args_runner, contract_runner_func=_resolved_tool_contract_runner, alog=log, setup_log_func=setup_log)
7f65c5dac4313156e12603bf29238cf1825ce2b1
72,662
def parse_value(text, spec, max_value=None): """Finds a value embedded in a formatted string (spec) in the form of 'placeholder placeholder2 %v placeholder3' where placeholder text helps locate the desired value denoted by %v""" text = text.replace("|", "") text = text.replace("]", "") text = te...
27c73999ca2483a754b1cf59c9717e85d7b2a458
72,663
import os from datetime import datetime def trainloaderSimCLR(args): """ Load training data through DataLoader """ transform = SimCLRTransform(args.img_size) if args.ssl_dataset == 'CIFAR100': train_dataset = CIFAR100(args.data_dir, train=True, download=True, transform=transform) elif ...
ba8bc0708ca01b3a2c2c8623ff2e75cd07ad4f22
72,664
def _make_history_monotone(df, target_col, direction="minimize"): """Create a monotone Series, i.e. the best so far instead of the current evaluation. Args: df (pandas.Dataframe): must contain ["problem", "algorithm", "n_evaluations"] and the target_col as columns. target_col (str):...
5a7029206d93f615d28e573afb5919374bfa9f4d
72,665
def message_to_message(message_to, message_name, message_from): """Makes a message from another message Shallow copy; supports primitive data types and lists (arrays) Add depth and/or additional datatypes when needed (TODO: add json support)""" for key, value in message_from.ListFields(): if has...
603284047cab9696629dd26b26ac02ced1fcd0b0
72,666
def _build_coords(arg): """Converts one or many lng/lat pair(s) to a comma-separated, pipe delimited string. Coordinates will be rounded to 5 digits. For example: convert.build_coords([(151.2069902,-33.8674869),(2.352315,48.513158)]) # '151.20699,-33.86749|2.35232,48.51316' :param arg: The l...
8f06d98ea50402bb7650af118d7e96f5a049d1eb
72,667
def predict(x_input: np.ndarray, model: np.ndarray, predicts: float = 7): """Model that return just arithmetical average from last few data points. Args: x_input (np.ndarray): Time series data inputting the models. Usually last few data points. Structure depends on X in train function (usua...
0577d2754b1be97f3b3675ee1be8de1386b1ce7a
72,668
def platform_name(project, platform): """"Get the untrusted platform name.""" return project.upper() + '_' + platform.upper()
3f63ab210ef040114a536cac40efbad168631273
72,669
def length(input): """Creates a task that takes one object and returns its size""" task = Task() task.task_type = BASE_LENGTH task.inputs = (input,) return task
4d368f541608bb749bf30fb571a88a77a45e4694
72,670
def _process_stmt(statement: dict) -> BaseStatement: """Receive statement dict and call the proper statement class. The `name` attribute of the class is used to bind the statement type to its class. Parameters ---------- statement : dict Dict from Validation Document representing statem...
3857e74ec92cc983d50c258c0d6805219a3af5c0
72,671
def contact_infectivity_asymptomatic_50x60(): """ Real Name: b'contact infectivity asymptomatic 50x60' Original Eqn: b'contacts per person normal 50x60*infectivity per contact' Units: b'1/Day' Limits: (None, None) Type: component b'' """ return contacts_per_person_normal_50x60() * i...
10c6336aa0f922538ecf7856a0349706f1b9e7dd
72,672
import os, uuid from azure.storage.blob import BlobServiceClient def _create_container_azure(container_name): """ Creates a storage container on Azure Platform. gets the connection string from the environment variables. Example ------- >>> container_client = _create_container_azure(container_nam...
51abb3d009cbba1de7357e76b73513429c4dd913
72,673
from typing import Tuple def parse_item(item: str) -> Tuple[str, int]: """ Returns a pair: bag_color, count """ item_match = ITEM_PATTERN.match(item) if not item_match: raise Exception("Bad item: " + item) return item_match.group(2), int(item_match.group(1))
b933bb7dec450454f3da25ab6d736f3c556dfd77
72,674
def init(mainf): """ initialize and shutsdown minesweeper""" def initf(): setup() mainf() teardown() return initf
b65668643393e5bca3ed17033f4c7efa0af70686
72,675
import numpy def lat2g0(lat): """Calculate surface gravitational acceleration for latitude This function is stolen from atmlab: https://www.sat.ltu.se/trac/rt/browser/atmlab/trunk/geophysics/pt2z.m From the original description: Expression below taken from Wikipedia page "Gravity of Earth", tha...
7c907a8016b6a579dd0a16a1662bf02358778d16
72,676
def specificity(y_true, y_pred): """Gets the specificity of labels and predictions. Parameters ---------- y_true : torch.tensor The true labels. y_pred : torch.tensor The prediction. Returns ------- numpy.ndarray The specificity. """ y_true, y_pred = pr...
93cf3c81504b56613257363dc3f603ce96453d65
72,677
def create_strategy(config): """ Create build strategy and exec strategy. Args: config(dict): config Returns: build_strategy: build strategy exec_strategy: exec strategy """ build_strategy = paddle.static.BuildStrategy() exec_strategy = paddle.static.ExecutionStrate...
f5677fc4b9c7d176d9a22862465f8debda95aa4d
72,678
from typing import Any from typing import Optional def coerce_type(obj: Any, typ: Optional[type]) -> Any: """ Coerce object to the given type. Type must be registered for this function to work. """ if typ is None or typ is type(obj): return obj fn = _coerce_fn.dispatch(typ) resul...
2fb7dce2e2f19a8790f7403b003c85581d393f97
72,679
def brevity_penalty(alpha: float, length: int) -> jnp.ndarray: """Brevity penalty function for beam search penalizing short sequences. Args: alpha: float: brevity-penalty scaling parameter. length: int: length of considered sequence. Returns: Brevity penalty score as jax scalar. """ return jnp.p...
88590e93bf47109bd7b333f6ca09336c0590dd33
72,680
import os from typing import OrderedDict def NDVIpuller(fname, data, region, force=False): """ takes the NDVI data and makes a saveable CSV file args: fame: str the name of the file to be saved data: OD dictionary with dataset infomation returns: dataframe with relevant data """ if (not os.path.is...
9d6fc5dd49c426985671026b06c22b8ea30fde7d
72,681
def _imports(graph: mapry.Graph) -> str: """ Generate the import declaration. :param graph: mapry definition of the object graph :param go: Go settings :return: generated code """ import_set = {'strings', 'fmt'} if mapry.needs_type(a_type=graph, query=mapry.Integer): import_set...
473facecef56897bee7c67e7ecec8a3620597980
72,682
def p_qq(data,pv_index=0,alpha=0.05): """ This function plots all the raw p-values and compares them with a theoretical uniform distribution using a qq plot. This plot is created with a negative log scale, letting us visualize all the p-values, independent of their small magnitudes. The p-values deviate...
d857c54c91c8c4ec3541411b134839d836b9fbf3
72,683
def occlusion_reliability(forward_flow, backward_flow, gamma=1): """ Calculates the flow variation reliability Parameters ---------- forward_flow: numpy array forward flow values backward_flow: numpy array backward flow values gamma: float, optional soft threshold ...
a67ff73a557ca1a3cc984d29218fa9251a869baf
72,684
def leja(a): """ Leja ordering of given numbers: * |a[0]| = max_j |a[j]| * prod_{i=0}^{k-1} |a[k] - a[i]| = max_j prod_{i=0}^{k-1} |a[j] - a[i]| When used as a preprocessing for np.poly it increases its numerical precision. """ n = len(a) c = np.argmax(np.abs(a)) a[[c, 0]] = a[[0, ...
60d989aaf92ac79ced364096701d7da0a4d9853e
72,685
def is_dry_run() -> bool: """ Returns whether or not we are currently doing a preview. """ return bool(SETTINGS.dry_run)
4ae0de410979b25fe94a169e3508e14cd797d02c
72,686
def hockeydata_css(*args): """ hockeydata css tag """ url = get_hd_attr('STATIC', '') if url is None: return mark_safe('Error: No HOCKEYDATA_STATIC in settings provided!') default_css = get_hd_attr('DEFAULT_CSS', '') if default_css is not None: css_links = '<link href="{url}css/?{de...
94eda4e80242fe7ee8dce77fa376c9e915bfcf88
72,687
def Add(left: Expr, right: Expr) -> BinaryExpr: """Add two numbers. Produces left + right. Args: left: Must evaluate to uint64. right: Must evaluate to uint64. """ return BinaryExpr(Op.add, TealType.uint64, TealType.uint64, left, right)
13245e95637841f60cda88e8de2624bdde4e4aa3
72,688
def getArtistCompleter(year, country, label): """ Retrieve all artists of Discogs jazz release data within selected year, country, and label Params: (year) array containing selected year(s) (country) array containing selected country(s) (label) arr...
60a34656d25286a9cd3f59d62e227aae54b4e96d
72,689
def rps(da_cmp, da_ref, bins, over_dims=None, ensemble_dim='ensemble'): """ Returns the ranked probability score Author: Dougie Squire Date: 10/05/2018 Parameters ---------- da_cmp : xarray DataArray Array containing data to be compared to refere...
e6e30c902a3beb954079e1d54f019eeeeab34173
72,690
def m_order(freq,theta,lcandidat,k, id2word): """ Calculate the M-Order Relevance Parameters: ---------- freq : Array containing the frequency of occurrences of each word in the whole corpus theta : Array containing the frequency of occurrences of each word in each topic lcandidat: Array co...
2b57cbb4df82481bb4a6ad82b4ae3de1d4fc5875
72,691
def find_possible_swap_regions(genome, front_arm_sequence, back_arm_sequence, cassette): """ Computes all possible recombined region from arm sequences. """ front_arm_results = blast_genome(genome, 'blastn', front_arm_sequence) back_arm_results = blast_genome(genome, 'blastn', back_arm_sequence) ...
f1a9822f399b15de4f1e16a3c419107901fcc480
72,692
def tpearson(x, y, axis=0): """Tensor-based pearson correlation.""" n = x.shape[axis] xc = x - x.mean(axis=axis, keepdims=True) yc = y - y.mean(axis=axis, keepdims=True) xystd = x.std(axis=axis) * y.std(axis=axis) cov = (xc * yc).sum(axis=axis) / n corr = cov / xystd return corr
37da10d2e21f04296a2cc0b3f8b239e0fcba8957
72,693
def fermisign(projected_states, i, j, sigma, tau=None): """ Gounts how many fermions are sitting between sites i and j with spin sigma in the state defined by stateprojection Note: implicit spin-ordering for Fermi sign: all Up before all Down Args: projected_states - (2xN) list with the ferm...
cfb29337a4cc62fda37e8172d4834a7332fb2842
72,694
def circle_from_points_xy(a, b, c): """Create a circle from three points lying in the XY-plane Parameters ---------- a : [float, float] or [float, float, float] | :class:`compas.geometry.Point` XY(Z) coordinates of a 2D or 3D point (Z will be ignored). b : [float, float] or [float, float, f...
e89f2b0aa937f00688db5162ae86a536fdf246a3
72,695
import unittest def makeTestSuiteV201109(): """Set up test suite using v201109. Returns: TestSuite test suite using v201109. """ suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(ExperimentServiceTestV201109)) return suite
779e276b765c363191fb31386ee915c3ab8a3f43
72,696
def get_entity_friendly_name(entity_id): """Get entity friendly name.""" return hass.states.get(entity_id).attributes["friendly_name"]
e944bdf63ab3292ffd386d21d5ed3d8607a33c16
72,697
from typing import Union from sys import path def _structured_tensor_field_to_prensor( field_value: Union[structured_tensor.StructuredTensor, tf.RaggedTensor, tf.Tensor], default_field_name: path.Step) -> prensor.Prensor: """Creates a ChildNodeTensor from a field in a structured tenso...
e46e43be1b3a20175c19b69c6af247a61e1f4736
72,698
import tqdm import os def create_adjusted_atlases(linear, poly, ids, atlas_indices=None, free_text="", save_to_db=True): """ input: linear_model: instance of class Model with first order model poly_model: instance of class Model with second order model ids: an AnalysisIds object matchi...
9fa76eb43152a337ed858aa6b522a7d399756598
72,699