content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def apply_voigt1d(fid, pks, snorms, a0, b0, a, b, zp, bw, flo=None, up=True, link_gg=True, link_ll=True, dx_snr=None, dx_snr_mode='outside', f_cutoff=0., ftype='voigt', outfile=''): """ Apply Voigt-1D window function, fit the spectrum, and return the treated SnR & FWHM :argu...
4e869225bf976138ab3631d3d0def5b7e3e0cc06
3,636,100
from typing import Optional def parse_options(dict_in: Optional[dict], defaults: Optional[dict] = None): """ Utility function to be used for e.g. kwargs 1) creates a copy of dict_in, such that it is safe to change its entries 2) converts None to an empty dictionary (this is useful, since empty diction...
d679539ba29f4acab11f5db59c324473a2e24cc6
3,636,101
import copy def build_optimizer(model, optimizer_cfg): """Build optimizer from configs. Args: model (:obj:`nn.Module`): The model with parameters to be optimized. optimizer_cfg (dict): The config dict of the optimizer. Positional fields are: - type: class name of t...
43d211d57972274de337725a38ae7c08ff7b4e8c
3,636,102
def test_normal_sw(data): """Shapiro-Wilk""" norm_data = (data - np.mean(data))/(np.std(data)/np.sqrt(len(data))) return st.shapiro(norm_data)
e0b547e0b585a1cb5bf88ef818c3e6e1caf9c16a
3,636,103
from typing import Dict from typing import Any def dict_to_namespace(cfg_dict: Dict[str, Any]) -> 'Namespace': """Converts a nested dictionary into a nested namespace.""" cfg_dict = deepcopy(cfg_dict) def expand_dict(cfg): for k, v in cfg.items(): if isinstance(v, dict) and all(isinsta...
492e629815f477d3263121fcd19afea7d3ec9f6f
3,636,104
import click def country_currency(code, country_name): """Gives information about the currency of a country""" _data = return_country(currency_data, country_name) if _data: _, currency_name, the_code, symbol = _data else: return click.secho('Country does not exist. Perhaps, write the...
e576a5a1b6d06ef180c4cb648aecf54005501bc8
3,636,105
import numpy import math def decompose_matrix(matrix): """Return sequence of transformations from transformation matrix. matrix : array_like Non-degenerative homogeneous transformation matrix Return tuple of: scale : vector of 3 scaling factors shear : list of shear factors for x...
c4ec66342720f91c1ec4dbe24c2a89d0b9e7e3f7
3,636,106
def GetMaxHarmonic( efit ): """Determine highest-order of harmonic amplitudes in an ellipse-fit object""" # We assume that columns named "ai3_err", "ai4_err", "ai5_err", etc. # exist, up to "aiM_err", where M is the maximum harmonic number momentNums = [int(cname.rstrip("_err")[2:]) for cname in efit.colNames ...
e11645efa40ce3995788a05c8955d0d5a8804955
3,636,107
import math def quaternary_tournament(population, scores, next_gen_number, random_seed=42): """Selects next generation using quaternary tournament selection for single objective. This function implements quaternary tournament selection to select a specific number of members for the next generation. ...
e59311977358be3a28baeedc8a2e91e8f979eeeb
3,636,108
def empty_list(): """An empty list""" return []
9d803d40be4c7aa7a6a07e94c19495582ab96154
3,636,109
def snapshot(): """Creates a default initialized startup snapshot. deno_core requires this, although it does not document this outside of a few random mentions in issues. """ return Runtime(will_snapshot=True).snapshot()
4a9b4be37b5f31c87897e7c3daa9e4cc6884584c
3,636,110
def sample_user(email='riti2874@gmail.com', password='Riti#2807'): """Createing a smaple user""" return get_user_model().objects.create_user(email, password)
6bf20a2566070cd724bfac66b4591c45b858aef3
3,636,111
def is_chinese_prior_leap_month(m_prime, m): """Return True if there is a Chinese leap month on or after lunar month starting on fixed day, m_prime and at or before lunar month starting at fixed date, m.""" return ((m >= m_prime) and (is_chinese_no_major_solar_term(m) or is_chin...
c196a5135e79b9f3efa6cfcefa5b5f9b1dd175f5
3,636,112
import yaml import json def read_config_file(fname): """Reads a JSON or YAML file. """ if fname.endswith(".yaml") or fname.endswith(".yml"): try: rfunc = partial(yaml.load, Loader=yaml.FullLoader) except AttributeError: rfunc = yaml.load elif fname.endswith(".js...
b86d61ee6d0d8027e325a9e436a031f9e171959d
3,636,113
def plot_wo(wo, legend=True, **plot_kwargs): """Plot a water observation bit flag image. Parameters ---------- wo : xr.DataArray A DataArray containing water observation bit flags. legend : bool Whether to plot a legend. Default True. plot_kwargs : dict Keyword argum...
5c756248d0bcc4dfb42e69a0a4e50c6321ed7023
3,636,114
from thedonald import tweets import os import json def _get_tweets(db_path="tweets.json"): """Get Trump's tweets, caching after first use.""" global TWEETS # Cache tweets if they haven't been fetched yet if TWEETS is None: # Try to read from a saved file if os.path.exists(db_path): ...
3dbed40d88cac84c6a9d4c9595d181a10551432d
3,636,115
def int_list_data(): """Item data with an in list. [1, 2, 3, 4, 5, 6]""" return easymodel.ListItemData([1, 2, 3, 4, 5, 6])
3306a7694d22e2ae9d8de64f3e1a01c27789d818
3,636,116
from typing import Dict from typing import Any from typing import Optional def check_transaction_threw(receipt: Dict[str, Any]) -> Optional[Dict[str, Any]]: """Check if the transaction threw/reverted or if it executed properly by reading the transaction receipt. Returns None in case of success and t...
b79300c45fdb3c598d450cdf42ce2758e2cf8451
3,636,117
from typing import Callable from typing import Coroutine import functools def button(style: ButtonStyle, label: str, **kwargs) -> Callable[..., Button]: """A decorator used to create buttons. This should be decorating the buttons callback. Parameters ---------- style: :class:`.ButtonStyle` ...
6f5877f32aabcb921f835ecbe6158bd9cc4964d3
3,636,118
def AuxSource_Cast(*args): """ Cast(BaseObject o) -> AuxSource AuxSource_Cast(Seiscomp::Core::BaseObjectPtr o) -> AuxSource """ return _DataModel.AuxSource_Cast(*args)
10e149a342e9181636371f11152dc05e3942bd08
3,636,119
def to_byte_array(int_value): """Creates a list of bytes out of an integer representing data that is CODESIZE bytes wide.""" byte_array = [0] * CODESIZE for i in range(CODESIZE): byte_array[i] = int_value & 0xff int_value = int_value >> 8 if BIG_ENDIAN: byte_array.reverse() ...
a44f952acd2d0525eed3dbe36b86ae1b305f6c37
3,636,120
def no_op(loss_tensors): """no op on input""" return loss_tensors
317474aa2ed41668781042a22fb43834dc672bf2
3,636,121
def get_example_two_cube(session, varcodes, selected_year=None): """ Create 2D cube of flight routes per selector variable description, per date selector. """ cubes_api = aa.CubesApi(session.api_client) # If no selected year, no underlying base query if selected_year is None: query = create_que...
5c01f5d48910953fd6238fb987f284a3bfe4fad4
3,636,122
def svd_reduce(imgs, n_jobs): """Reduce data using svd. Work done in parallel across subjects. Parameters ---------- imgs : array of str, shape=[n_subjects, n_sessions] Element i, j of the array is a path to the data of subject i collected during session j. Data are loaded ...
b8aaf939487a183bc0cb8498c6fa41ebc5c3b131
3,636,123
from typing import Tuple from typing import List def parse_project(record: Record, add_info: dict) -> Tuple[Pair, List[Pair], List[Pair]]: """Parse the project record in airtable to Billinge group format. Return a key-value pair of the project and a list of key-value pairs of the people doc and institution d...
a999bd2d5ecc8742739f0143f8df939ff5906a04
3,636,124
def forbidden_handler_exc(message): """More flexible handling of 403-like errors. Used by raising ForbiddenError. Args: message (str) - Custom message to display """ return render_template('errors/403.html', message=message), 403
7a9d6280ac129496c4b50241453aba259812f10e
3,636,125
import unittest def run_test(): """Runs the unit tests without test coverage.""" tests = unittest.TestLoader().discover('./tests', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
ae567c1821a83cde68f23c1bb51325ea02dcc15b
3,636,126
def resnet34(num_classes: int = 1000, class_type: str = "single") -> ResNet: """ Standard ResNet 34 implementation; expected input shape is (B, 3, 224, 224) :param num_classes: the number of classes to classify :param class_type: one of [single, multi] to support multi class training; defau...
e0006ac140dd2969f140bcddebe7fd80b9609766
3,636,127
def linspace(start, stop, num=50): """ Linspace with additional points """ grid = list(np.linspace(start, stop, num)) step = (stop - start) / (num - 1) grid.extend([0.1 * step, 0.5 * step, stop - 0.1 * step, stop - 0.5 * step]) return sorted(grid)
f416f3b86f062fca09b3be669a1651351621ad8a
3,636,128
def strip_html(markdown): """ Strip HTML tags from a markdown string. Entities present in the markdown will be escaped. Parameters: markdown: A :term:`native string` to be stripped and escaped. Returns: An escaped, stripped :term:`native string`. """ class Parser(HTMLParse...
4d8c913a362f9e377b2dcd4172adadf378ffbff3
3,636,129
def find_character_occurences(processed_txt): """ Return a list of actors from `doc` with corresponding occurences. """ total_len = len(processed_text) characters = Counter() index = 0 for ent in processed_txt.ents: if ent.label_ == 'PERSON': characters[ent.lemma_] +...
e3407d1ae5055eb1e43438cde0e467b9f3cc48e1
3,636,130
import random def parents_similarity(subject1, subject2, values): """ This function creates two new subjects by comparing the bits of the binary encoded provided subjects (the parents). If both parents have the same bit in a certain location, the offspring have a very high probability of having the sa...
6fe49a5bb31b37abf49255534d6f6ae9a8301a59
3,636,131
import torch def generic_fftshift(x,axis=[-2,-1],inverse=False): """ Fourier shift to center the low frequency components Parameters ---------- x : torch Tensor Input array inverse : bool whether the shift is for fft or ifft Returns ------- shifted array """ ...
8b5f84f0ed2931a3c1afac7c5632e2b1955b1cd5
3,636,132
def eval_ner(gold, sen, labels): """ evaluate NER """ if len(gold) != len(sen): print(len(gold), len(sen)) raise "lenghts not equal" tp = 0 #tn = 0 fp = 0 fn = 0 list_en = ["LOC", "MISC", "ORG", "PER"] for en in list_en: g = list_entities(gold, labels["...
78daab9ca81466f4f66e5bb542abc9d7a747a44a
3,636,133
def generate_data(m: int = 1000, n: int = 30, sigma: int = 40): """Generates data for regression. To experiment with your own data, just replace the contents of this function with code that loads your dataset. Args ---- m : int The number of examples. n : int The number of ...
10763c3da63874b35a3173a5473f468edc6ff159
3,636,134
import logging def read_datafile(path: str): """ read a flight data file and unpack it """ with open(path, 'rb') as fp: data = fp.read() if len(data) != altacc_format.size: logging.warning(f"invalid data file length, {len(data)} bytes!") fields = altacc_format.unpack(data) fligh...
5683db563d2ece768c6efc66aab60d2cbe84b4aa
3,636,135
def get_compiler_option(): """ Determines the compiler that will be used to build extension modules. Returns ------- compiler : str The compiler option specificied for the build, build_ext, or build_clib command; or the default compiler for the platform if none was specified. ...
944f4352255a83552164bf42dbcd9a976d43d1a8
3,636,136
def create_output_from_files(data_file_path:str, sheet_name:str, yaml_file_path:str, wikifier_filepath:str, output_filepath:str =None, output_format:str ="json"): """A convenience function for creating output from files and saving to an output file. Equivalent to calling KnowledgeGraph.generate_from_files follo...
6be2fb0ea1c57fd10c9a487756ed97615a76675d
3,636,137
def make_new_images(dataset, imgs_train, imgs_val): """ Split the annotations in dataset into two files train and val according to the img ids in imgs_train, imgs_val. """ table_imgs = {x['id']:x for x in dataset['images']} table_anns = {x['image_id']:x for x in dataset['annotations']} keys...
d5851974ad63caaadd390f91bdf395a4a6f1514d
3,636,138
def test_similarity_sample_multiprocess(pk_target): """Test similarity cutoff filter""" def weight(T): return T ** 4 _filter = SimilaritySamplingFilter(sample_size=10, weight=weight) pk_target.react_targets = True pk_target.filters.append(_filter) pk_target.transform_all(processes=2, g...
41c6f370480a83c40598adbe3d3660fd4e09878f
3,636,139
def compute_maximum_ts_map(ts_map_results): """ Compute maximum TS map across a list of given ts maps. Parameters ---------- ts_map_results : list List of `~gammapy.image.SkyImageCollection` objects. Returns ------- images : `~gammapy.image.SkyImageCollection` Images (t...
c1ab40286d1db40f9d1b3a015871ac88dc7b5198
3,636,140
import gc def compute_dist(array1, array2, type='euclidean'): """Compute the euclidean or cosine distance of all pairs. Args: array1: numpy array with shape [m1, n] array2: numpy array with shape [m2, n] type: one of ['cosine', 'euclidean'] Returns: numpy array with shape [m1, m2] ...
a1bc531a5d640598f8eeb097b91daf66ec64b0df
3,636,141
def timer(step, callback, *args): """定时器""" s = internet.TimerService(step, callback, *args) s.startService() return s
b32ad6064e59937f46424ea4672d4ad86e5fcfcb
3,636,142
import tkinter as tk from tkinter import filedialog def select_file(title: str) -> str: """Opens a file select window and return the path to selected file""" root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename(title=title) return file_path
59fdb7945389c2ba75d27e1fe20b596c4497bac1
3,636,143
import ctypes def drdpgr(body, lon, lat, alt, re, f): """ This routine computes the Jacobian matrix of the transformation from planetographic to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdpgr_c.html :param body: Body with which coordinate system is associ...
2224edb6413b9d7b3e56b748c1390299e7cea338
3,636,144
def data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_cost_characteristiccost_name_get(uuid, node_uuid, node_rule_group_uuid, inter_rule_group_uuid, cost_name): # noqa: E501 """data_context_topology_context_topologyuuid_nodenode_uuid_...
34ac66f8d0317770df96a35b698cbb24551996ab
3,636,145
from typing import List async def joinUserChannel(cls:"PhaazebotTwitch", Message:twitch_irc.Message, Context:TwitchCommandContext) -> None: """ allowed user and admin to like phaaze to a channel """ alternative_target:str = "" UserPerm:TwitchPermission = TwitchPermission(Message, None) if UserPerm.rank >= Twit...
072d14e3c2254b1d40f97261e4c22d9559896e52
3,636,146
def budget_balanced_ascending_auction( market:Market, ps_recipes: list)->TradeWithMultipleRecipes: """ Calculate the trade and prices using generalized-ascending-auction. Allows multiple recipes, but only of the following kind: [ [1,0,0,x], [0,1,0,y], [0,0,1,z] ] (i.e., there are n-1 buyer c...
9891beb8077d87236d1ba5d99df70fddb76b62c7
3,636,147
import traceback def copy_inputs(paths, file_list): """.. Create copies to inputs from list of files containing copying instructions. Create copies using instructions contained in files of list ``file_list``. Instructions are `string formatted <https://docs.python.org/3.4/library/string.html...
c638e5c09490667f6aa376dbcc2668d152aafabe
3,636,148
from typing import Tuple from typing import List def agaricus_lepiota() -> Tuple[np.ndarray, np.ndarray, np.ndarray, List[ALFeature]]: """ Source: https://archive.ics.uci.edu/ml/datasets/Mushroom The function requires the file 'agaricus-lepiota.data' to be in the current folder. Retu...
35afd833171846eb2f6bf1424c12c63e3d9576b2
3,636,149
import random import requests import logging def receiveVoteFromLowLevel(): """ input -> params which is received from lower level in the hierarchy return -> 200, 400 params = { string: int "candidate_id_1": num_votes, "candidate_id...
9e3f03040d51d8535294fb455833ae9aeeac4679
3,636,150
def patch286() -> PatchDiscriminator: """ Patch Discriminator from pix2pix """ return PatchDiscriminator([64, 128, 256, 512, 512, 512])
5a563d5fa1976ab24831c16846bc5ea91d78f581
3,636,151
def prefix(m): """Given a NFA `m`, construct a new NFA that accepts all prefixes of strings accepted by `m`. """ if not m.is_finite(): raise ValueError('m must be a finite automaton') f = set(m.get_accept_states()) size = None while len(f) != size: size = len(f) for t...
dc0cba3a5060ea4dbf5a3d51fa42db2ca20383fc
3,636,152
def _predict_k_neighbors(estimator, X): """Predict using a k-nearest neighbors estimator.""" X = estimator._validate_data(X, reset=False) neigh_dist, neigh_ind = estimator.kneighbors(X) neigh_Y = estimator._y[neigh_ind] neigh_weights = _get_weights(neigh_Y, neigh_dist, estimator.weights) retu...
b705c0c84cb3ebf5f3faf0db4e053dfb295527ea
3,636,153
def _loop_over(var): """ Checks if a variable is in the form of an iterable (list/tuple) and if not, returns it as a list. Useful for allowing argument inputs to be either lists (e.g. [1, 3, 4]) or single-valued (e.g. 3). Parameters ---------- var : int or float or list Variable to che...
254143646416af441d3858140b951b7854a0241c
3,636,154
def _get_servings_rest(): """ Makes a REST request to Hopsworks to get a list of all servings in the current project Returns: JSON response parsed as a python dict Raises: :RestAPIError: if there was an error with the REST call to Hopsworks """ method = constants.HTTP_CONFIG.H...
215c425ed0b2dd95e897de48ed5aed629f6eaa4f
3,636,155
from typing import Any from typing import List from typing import Dict def transform_database_account_resources( account_id: Any, name: Any, resource_group: Any, resources: List[Dict], ) -> List[Dict]: """ Transform the SQL Database/Cassandra Keyspace/MongoDB Database/Table Resource response for neo4j...
dac566a1e09e1e395ff6fb78d6f8931a2bca58cb
3,636,156
def jacsim(doc1, doc2, docsAsShingleSets,sign_matrix): """ Jaccard Similarity. :param doc1: First doc to be compared :param doc2: Second doc to be comapred :param docsAsShingleSets: Document wise shingles :param sign_matrix: The Signature matrix :return: The jaccard similarity value """ ...
78871ce8c2bf6fe0f975bc399c3a7baa74ef3b32
3,636,157
def train(model, loss_function, optimizer, train_loader, val_loader=None, max_epochs=100, verbose=False, debug=False): """ Helper method for training a model. Args: model: PyTorch model. loss_function: Loss function. optimizer: Loss function. train_loader: pytorch DataLoader...
988ee7192a2b469a76b595fddc99b5e89088c0de
3,636,158
import os def recent_stream(model_name=None, filter=None): """ return a dict, key the model name of the most recent stream, with stage and date model_name : str | None the full name of the model, e.g. P302_8years/uw8000. If None, use the current folder path """ if model_name is None: model_na...
c9b088f7fdb5581c172a6d71dcdb96dd908f9244
3,636,159
import os import subprocess def batch_tile_redshifts(tileid, exptable, group, spectrographs=None, submit=False, queue='realtime', reservation=None, dependency=None, system_name=None, run_zmtl=False, noafterburners=False): """ Generate ...
b6367abf02f81c534db9df670261d033e53f46e5
3,636,160
def symplot(b, max_m = 20, max_n = 20, ymin = None, sqrts = False, log = True, B0 = True, helical_detail = False, legend_args = {"loc":"best"}, **kwargs): """ Plot the radial variation of all the Fourier ...
7d6b65f9cb3a95ea3b660b4181c76affc0b35a3b
3,636,161
import gc def get_holistic_keypoints( frames, holistic=mp_holistic.Holistic(static_image_mode=False, model_complexity=2) ): """ For videos, it's optimal to create with `static_image_mode=False` for each video. https://google.github.io/mediapipe/solutions/holistic.html#static_image_mode """ ke...
a5a534a7827a800642a96960191977766cbe8452
3,636,162
import struct def get_arp_info(pkt): """ Break the ARP packet into its components. """ if len(pkt) < 8: raise ARPError("ARP header too short") ar_hrd, ar_pro, ar_hln, ar_pln, ar_op = struct.unpack("!HHBBH", pkt[0:8]) pkt_len = 8+(2*ar_hln)+(2*ar_pln) if len(pkt) < pkt_len: ...
d45a64fc2a78c64a2cf730f1c605461f7f31a806
3,636,163
def update_ref_point(ref_point, fy): """ Update the reference point by an offspring parameter ---------- ref_point: 1D-Array the position of original reference point fy: 1D-Array the fitness values of the offspring return ---------- 1D-Array the position of the up...
d821c765992a3d4474dec09b837be99c00d22be3
3,636,164
from typing import Any def parse(grm: util.PathLike, datum: str, **kwargs: Any) -> interface.Response: """ Parse sentence *datum* with ACE using grammar *grm*. Args: grm (str): path to a compiled grammar image datum (str): the sentence to parse **kwargs: additi...
37d004cb82c7b5b0a26b69402ad269636927862c
3,636,165
def EVLAPolCal(uv, InsCals, err, InsCalPoln=None, \ doCalib=2, gainUse=0, doBand=1, BPVer=0, flagVer=-1, \ solType=" ", fixPoln=False, avgIF=False, \ solInt=0.0, refAnt=0, ChInc=1, ChWid=1, \ doFitRL=False, doFitOri=True, check=False, debug =...
6d42b151ed8fdff466b73798638f245b16570080
3,636,166
import os import subprocess import shlex def check_and_store(codechecker_cfg, test_project_name, test_project_path, clean_project=True): """ Check a test project and store the results into the database. :checkers parameter should be a list of enabled or disabled checkers Example: ...
b10e3a222415362463eba26c643b8f02095f97a7
3,636,167
import re def ansyArticle(data): """分析错误日志""" ids=[] with open(data,'r') as fp: i=0 for line in fp.readlines(): i+=1 if i%5==1: m=re.search('view_(\d+)\.aspx',line) ids.append(m.group(1)) else: continue return ids
5c32ca500a4f94f5ab6b38ebc9ca8ab4521f8d8d
3,636,168
def climb_stairs(n): """ Number of paths to climb n stairs if each move comprises of climbing 1 or 2 steps. Args: n integer Returns: integer Preconditions: n >= 0 """ return fib(n)
f54645e53d5ed001e023ba368f9e0c0c72d090d3
3,636,169
def randomInt(bit_length, seed): """Returns a random integer.""" s = randomHexString((bit_length + 3) / 4, seed) return int(s, 16) % (1 << bit_length)
9e226d189114ef6809b119f50f416fe3fd16beae
3,636,170
import tqdm import warnings def best_fit_distribution(data, bins=200, ax=None): """Find the best fitting distribution to the data""" # Get histogram of original data y, x = np.histogram(data, bins=bins, density=True) x = (x + np.roll(x, -1))[:-1] / 2.0 # Distributions to check DISTRIBUTIONS =...
c13525e36b2ccd2e74fb4d3e3c5393ae3a623e72
3,636,171
def cumulative_completion_rate(completion_times, inc, top): """ Gets the cumulative completion rate data from an array of completion times. Starting from zero, time is incremented by `inc` until `top` is reached (inclusive) and the number of timestamps in `completion_times` under the current time is...
e12659c30e4edca1e852f626c6eb54d2a5d95120
3,636,172
def fitPeak(stack, slices, width, startingfit, **kwargs): """ Method to fit a peak through the stack. The method will track the peak through the stack, assuming that moves are relatively small from one slice to the next Parameters ---------- slices : iterator an iterator which dict...
e3b769e6004b263514a937ade8ff114b8c2e8453
3,636,173
def sbol_empty_space (ax, type, num, start, end, prev_end, scale, linewidth, opts): """ Built-in empty space renderer. """ # Default options zorder_add = 0.0 x_extent = 12.0 # Reset defaults if provided if opts != None: if 'zorder_add' in list(opts.keys()): zorder_add = o...
81574119b6ecb1ece556ad02c9e78a6096a2dad5
3,636,174
def find_max_1(array: list) -> int: """ O(n^2) :param array: list of integers :return: integer """ overallmax = array[0] for i in array: is_greatest = True for j in array: if j > i: is_greatest = False if is_greatest: overallm...
9bab28c3d72062af75ac5c2e19c1e9d87e6fc468
3,636,175
def radec2xy(hdr,ra,dec): """Transforms sky coordinates (RA and Dec) to pixel coordinates (x and y). Input: - hdr: FITS image header - ra <float> : Right ascension value in degrees - dec <float>: Declination value in degrees Output: - (x,y) <tuple>: pixel coordinates """ wcs = wcs.WCS(hdr) skycrd = n...
af829688cbbe72429042c5cb6c5e64f1efb47e57
3,636,176
def getStepsBySerialNoAndProcessID(SerialNo, ProcessID): """ 根据流水号和表单ID获取该表单的所有的步骤 :param SerialNo:流水号 :param ProcessID:表单ID :return:返回{"name":步骤名称,"value":步骤ID,"state":步骤状态} """ raw = Raw_sql() raw.sql = "SELECT a.StepID as value, b.StepName as name, Finished as state FROM RMI_TASK_PROCESS_STEP a WITH(NOLOCK) ...
5b6c31a9ff1225db20e8423add9804941bf15f73
3,636,177
def _split_train_dataset(y, tx, jet_num_idx=22): """Split the given training dataset into three distinct datasets. Datasets are split depending on the value of the 'PRI_jet_num' column, since this column dictates the -999 values for all the columns containing the latter (except for the 'DER_mass_MMC' c...
b5ab9efff0655f03290c345d14a6f9bd5263a116
3,636,178
def bear( transitions=None, # Common settings discount_factor=0.99, # Adam optimizer settings lr_q=1e-3, lr_pi=1e-3, lr_enc=1e-3, lr_dec=1e-3, # Training settings minibatch_size=100, polyak_rate=0.005, # BEAR settings ...
24a0ec3e0d8a2ce7074c019d93dcd424b5d967a8
3,636,179
def benchmark(setup=None, number=10, repeat=3, warmup=5): """A parametrized decorator to benchmark the test. Setting up the bench can happen in the normal setUp, which is applied to all benches identically, and additionally the setup parameter, which is bench-specific. Parameters ---------- ...
9ae9cbd0053e1485209881f4cac36241c33fe9d6
3,636,180
def make_dummy_protein_sequence( n_supporting_variant_reads, n_supporting_variant_sequences, n_supporting_reference_transcripts, n_total_variant_sequences=None, n_total_variant_reads=None, n_total_reference_transcripts=None, gene=["TP53"], amino_acids="MKH...
8836afe5a4724779a58e78c5ba064ef63248f20f
3,636,181
import yaml from yaml import YAMLError import sys def parse_file(file): """Parses a YAML file containing the bingo board configuration""" with open(file=file, mode="r", encoding='UTF-8') as stream: try: config = yaml.safe_load(stream) except YAMLError as err: sys.exit("...
ca81beb4fa855bd176b10e17525e82360e246347
3,636,182
import collections import os def process_dataset(path): """Maps entities and relations to ids and saves corresponding pickle arrays. Args: path: Path to dataset directory. Returns: examples: Dictionary mapping splits to with Numpy array contatining corresponding KG triples. filters: ...
d91593ee7869ad4d401bc9836dc789c747a2883c
3,636,183
from pathlib import Path import random import os def prepare_data(): """Data processing and data partitioning""" prapare_ner = PrepareNer() # entity samples_statistics samples_statistics = defaultdict(int) dataset = [] for file_ann in Path(Config.annotation_data_dir).rglob("*.ann"): fi...
1212896b774d000d6ccf6d22b1ff95e0d8ed89e2
3,636,184
from typing import Optional from typing import Tuple def InlineEditor(item: Item, view, pos: Optional[Tuple[int, int]] = None) -> bool: """Show a small editor popup in the diagram. Makes for easy editing without resorting to the Element editor. In case of a mouse press event, the mouse position (relative...
f810e6721acb91bbe8f64a71bdab2442dd5b696f
3,636,185
def getMetrics(trueLabels, predictedLabels): """Takes as input true labels, predictions, and prediction confidence scores and computes all metrics""" MSE = sklearn.metrics.mean_squared_error(trueLabels, predictedLabels, squared = True) MAE = sklearn.metrics.mean_absolute_error(trueLabels, predictedLabels) ...
141ccca0342bea1ef5a69851b1514fc8bfeda091
3,636,186
from datetime import datetime def create_data(feed_slug): """Post Data Post a data point to a feed --- tags: - "Data Points" parameters: - name: feed_slug in: path type: string required: true - name: value in: body schema: ...
99d8d8cc9ba6762ea3767d91204604282b1a10ce
3,636,187
from typing import Optional async def get_hitokoto(*, c: Optional[str] = None) -> Result.TextResult: """获取一言""" url = 'https://v1.hitokoto.cn' params = { 'encode': 'json', 'charset': 'utf-8' } if c is not None: params.update({'c': c}) headers = HttpFetcher.DEFAULT_HEAD...
00a5c498e1a27b96c35b0ec239e2d4e776edfda7
3,636,188
def img_unnormalize(src): """ Unnormalize a RGB image. :param src: Image to unnormalize. Must be RGB order. :return: Unnormalized Image. """ img = src.copy() img *= NORMALIZE_VARIANCE img += NORMALIZE_MEAN return img.astype(np.uint8)
2194a7c9c5cce225d61845093d51ad46d2ffc771
3,636,189
def upilab5_9_6() : """5.9.6. Exercice UpyLaB 5.26 - Parcours bleu rouge Une matrice M = \{m_{ij}\} de taille {n}\times{n} est dite antisymétrique lorsque, pour toute paire d’indices i, j, on a m_{ij} = - m_{ji}. Écrire une fonction booléenne antisymetrique(M) qui teste si la matrice M reçue est antisymétrique. Exe...
0e082a94ae5c4c88ea5340679368ff07e3b30a56
3,636,190
def info(request): """provide readable information for *request*.""" qs = request.get('QUERY_STRING') aia = IAdditionalInfo(request, None) ai = aia and str(aia) return (request.get('PATH_INFO', '') + (qs and '?' + qs or '') + (ai and (' [%s] ' % ai) or '') )
03ed0981ac758b090545225d3b6b4adfdce6c691
3,636,191
def put(entity_pb, **options): """Store an entity in datastore. The entity can be a new entity to be saved for the first time or an existing entity that has been updated. Args: entity_pb (datastore_v1.types.Entity): The entity to be stored. options (Dict[str, Any]): Options for this re...
f7b6c9e7599f43d316999120fe49d22b57dfc5ea
3,636,192
def get_country_flag(country): """Returns the corresponding flag of a provided country.""" with nation_flag_info as flag_path_info: # Validate the provided nation string. if country.title().replace('_', ' ') not in flag_path_info.keys() and \ country.title().replace(' ', '_') not in flag_path...
21a2b4ed69e5963eb57e7de3f393cd6344184a1b
3,636,193
def create_graph_to_decode_and_normalize_image(): """See file docstring. Returns: input: The placeholder to feed the raw bytes of an encoded image. y: A Tensor (the decoded, normalized image) to be fed to the graph. """ image = tf.placeholder(tf.string, shape=(), name='encoded_image_bytes') with tf.n...
e7b72a4ff17db70248b6c08ca1a6565938935d99
3,636,194
def bilinear_upsample(x, scale=2): """Bilinear upsample. Caffe bilinear upsample forked from https://github.com/ppwwyyxx/tensorpack Deterministic bilinearly-upsample the input images. Args: x (tf.Tensor): a NHWC tensor scale (int): the upsample factor Returns: tf.Tenso...
b7b04ef1d6caf957ba96ad36b27e1efb96129db7
3,636,195
from typing import OrderedDict def _generate_simplifiers_and_detailers(): """Generate simplifiers, forced full simplifiers and detailers.""" simplifiers = OrderedDict() forced_full_simplifiers = OrderedDict() detailers = [] def _add_simplifier_and_detailer(curr_type, simplifier, detailer, forced=...
cd26bd70e0030077cfec9d60592b1848b50bcb09
3,636,196
def read_machine_def(): """ Reads the machine definition file. """ return read_yaml_file(machine_def_file)
35f55ee4d05337de656788724254626bea1706f8
3,636,197
import array import scipy def read_libsvm_format(file_path: str) -> 'tuple[list[list[int]], sparse.csr_matrix]': """Read multi-label LIBSVM-format data. Args: file_path (str): Path to file. Returns: tuple[list[list[int]], sparse.csr_matrix]: A tuple of labels and features. """ de...
3c960b1ae2cbb56791c4d17164c7d491e2e47acf
3,636,198
def cristal_load_motor(datafile, root, actuator_name, field_name): """ Try to load the CRISTAL dataset at the defined entry and returns it. Patterns keep changing at CRISTAL. :param datafile: h5py File object of CRISTAL .nxs scan file :param root: string, path of the data up to the last subfolder ...
9815c44965dce0a58de02a4d34b1fed7177baa57
3,636,199