content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _get_password(email): """ gets the password from the keychain """ return keyring.get_password('mspass', email)
c6deaf235bbfb5fadabc4dc31b667c58d0ede1fd
80,519
import math def millify(n): """ Return a human readable number. """ n = float(n) millidx = max( 0, min( len(millnames) - 1, int(math.floor(0 if n == 0 else math.log10(abs(n)) / 3)), ), ) return '{:.0f}{}'.format(n / 10**(3 * millidx), millna...
7ae535df908a71caa25dabc499eb17bba0707590
80,520
def load_token(token): """ Flask-Login token_loader callback. The token_loader function asks this function to take the token that was stored on the users computer process it to check if its valid and then return a User Object if its valid or None if its not valid. """ # The Token itself was...
e4d5ced16d6f6cf68f030d5eacb337e3f1279361
80,521
def get_minutes_remain(minutes: int) -> int: """ Returns minutes remaining after converting to hours :param minutes: Total minutes before converting to hours :return: minutes after converting to hours """ return minutes % 60
abf025a83804a03d2c41b88eaac35606a5eddc4c
80,522
def critSC3(theta, z_c, jet_type='quark', alpha=alpha_fixed): """A soft-collinear piece of the critical, running coupling radiator, as a function of theta. Kicks in at low theta, theta < 2 MU_NP """ sc = (-(2.*alpha*beta_0)*np.log(2.*z_c) * np.log(2.*MU_NP/theta) / (1....
1c9953b69b455b74d8fe87a137800e9bd535d48c
80,523
from datetime import datetime def last_x_days(days=5): """Return the last X days as string names YYMMDD in a list""" dt = datetime.now() dates = [dt + timedelta(days=-x) for x in xrange(1, days)] + [dt] return [d.strftime("%y%m%d") for d in dates]
85bcc05c4b20831df62684f53d201c8962497ad3
80,524
def get_primes(size, bit_size, count): """Generate a list of probably prime numbers with at least a constant factor difference between the numbers. Args: size: polynomail modulus value. bit_size: bit lengths of the prime no's to be generated. count: No's of prime numbers required. ...
9ac0d5d0e1c7a8341e632abdac6a2663da2a1435
80,525
def fmripop_save_imgdata(args, out_img, params_dict, output_tag=''): """ Saves the output 4D image """ # Output filename output_filename, _ = args.niipath.split(".nii.gz") # NOTE: this line is not general enough, but it'll do for now output_tag = '_confounds-removed' + output_tag + '.nii....
2426c8a08740a0aa243091f5b62f60c1c0ab467e
80,526
def measureBitsEntropy(const): """Use heuristics to measure the "entropy" of the given numeric value. Args: const (int): numeric constant to be measured Return Value: Overall "entropy" score of the given numeric constant """ # we only work on unsigned values if const < 0: ...
75ac80ea1afc1335949fc84e766757d81be23f10
80,527
def get_pubchemcompounds_of_user_entity_ids(cursor, unification_table, user_entity_ids): """ Get the pubchemcompounds using their BIANA user entity ids """ query_pubchemcompound = ("""SELECT PC.value FROM externalEntityPubChemCompound PC, {} U WHERE ...
4085fc3620db3edfb926a4abc89fbe2e70f7b42c
80,528
def diffheaders(t1, t2): """ Return the difference between the headers of the two tables as a pair of sets. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar', 'baz'], ... ['a', 1, .3]] >>> table2 = [['baz', 'bar', 'quux'], ... ['a', 1, .3]...
bb3d6cf8dac9c5ac05ba6d566e9f42ede2d0a029
80,529
def parse_slack_output(slack_rtm_output): """ The Slack Real Time Messaging API is an events firehose. this parsing function returns None unless a message is directed at the Bot, based on its ID. """ output_list = slack_rtm_output if output_list and len(output_list) > 0: ...
bb5c0880933a9861adee4dcea9cd0fa2c632f6d7
80,530
def home(request): """ 首页 """ client = get_client_by_request(request) inner_host_info = get_inner_host_info(request) new_host_list = [] exist_host_list = [] update_host_list = [] for host in inner_host_info: ip = host['ip'] os_type = host['os_type'] hostname =...
6649677cfe3fbcee6460b7a2c4036155351d14e2
80,531
def _has_delta_prefix(name): """Check if name starts with any of two allowed delta prefixes.""" return name and (name.startswith(DeltaCounter.DELTA_PREFIX) or name.startswith(DeltaCounter.ALT_DELTA_PREFIX))
fecc2430e3cf4143a2c264dd2cc0e42c9d1bbd2c
80,532
def get_Q_j(region, j): """断熱性能の区分jの熱損失係数 Q_j (W/m2K) Args: region(int): j(int): 断熱性能の区分 Returns: float: 断熱性能の区分jの熱損失係数 Q_j (W/m2K) """ return get_table_e_5()[j][region - 1]
8792ab56b4390956fc32e8be6e690847452c9224
80,533
def format_text_to_tspans(text, keywordFormats): """ keywordFormats looks like this: { 'Stamina': {'style': "font-weight:bold", 'dx': '3.0' }, 'Harm': {'style': "font-weight:bold", 'dx': '4.0' }, } """ allTspans = [] currentTspan = etree.fromstring('<tspan></tspan>') for w...
c4a025b3ae7b38370f7d53823de86c12e19864af
80,534
def rb_join_arg(li=[], identif="default", pos=0): """Construct url argument with identifier and li as list.""" if li == []: return "" if pos == 0: letter = "?" else: letter = "&" return "{letter}{ident}={arg}".format(letter=letter, ident=identif, arg=','.join(li))
fefb80814ded2fd53ccf99c92a6ec9b538d85a28
80,535
def get_topics(bag): """ Get an alphabetical list of all the unique topics in the bag. @return: sorted list of topics @rtype: list of str """ return sorted(set([c.topic for c in bag._get_connections()]))
863faf144cef064324bb0dff41a9ac70464837ee
80,536
def has_elem(elem_ref): """ Has element? :param elem_ref: :return: """ if not is_elem_ref(elem_ref): return False elif elem_ref[0] == ElemRefObj: return hasattr(elem_ref[1], elem_ref[2]) elif elem_ref[0] == ElemRefArr: return elem_ref[2] in elem_ref[1]
a950e2315002e31fdba9faa8507f1ed3e06bb902
80,537
def get_vlan_brief_rpc(self, vlan_id=None, last_rcvd_vlan_id=None, api_timeout=''): """ This is an auto-generated method for the PySwitchLib. **Supported Versions**: * NOS: 6.0.2f, 7.2.0 * SLXOS: 17r.1.01a, 17r.2.00, 17s.1.02 **Instance Argument(s)**: :type vlan_id: long ...
abf032824e9ba23fb1f2dd6f3d6b4e1a9362487c
80,538
def run_python(env_prefix, args, cwd=None): """ Execute a platform independent python command. :param env_prefix: Python executable prefix to use to run the command. :param args: Optional python arguments. :param cwd: The current working directory. :return: The re...
7cdd731b08706cae6d4e7df83924aa7be35b6097
80,539
from typing import Optional from typing import Union def random_walk_timeseries( mean: float = 0.0, std: float = 1.0, start: Optional[Union[pd.Timestamp, int]] = pd.Timestamp("2000-01-01"), end: Optional[Union[pd.Timestamp, int]] = None, length: Optional[int] = None, freq: str = "D", colum...
79cec1decc5a8648d11d227c6e60e6389001f96d
80,540
import itertools def unroll_example(example, normalized_length=5500, labels=None): """Unroll one example and build labels for the unrolled example. Unroll one example with shape (L, d) to a pd.Series with shape (L * d,) Labels for the input example are an array with shape (d, ), e.g.: ['usr', 'sy...
7aeccaa7a2dc80b467908ed4d139a4f8dc15d600
80,541
import requests from bs4 import BeautifulSoup def get_product_urls(page_lim=10): """ Get urls of products from product listed web page """ urls = [] for i in range(page_lim): url = 'http://www.cosme.net/item/item_id/1064/products/page/{0}'.format(i) r = requests.get(url) html = r....
2199c00a0e38280dd5bfdc84c583aaaf9897b316
80,542
from typing import Optional def format_ipfs_cid(path: str) -> Optional[str]: """Format IPFS CID properly.""" if path.startswith('Qm'): return path elif path.startswith('ipfs://'): return path.replace('ipfs://', '')
eca4a79bc2ba4151495831b51bbd50df68f73025
80,543
def standard_pars_x(x, A=A_def, p=p_def, r=r_def): """returns magnetic parameters based on value received from find_x""" return 2 * A * r * x, A * x**p, (1 - x**p) / (r * x)
4480ea14e242a3ad44176a23480606ece24e328e
80,545
def obter_vetor(tab, vet): """ obter_vetor: tabuleiro x string -> tuplo de pecas Esta funcao devolve todas as pecas da linha ou coluna especificada pelo seu argumento. """ if vet in ('1', '2', '3'): return tuple(tab[int(vet)-1]) else: coluna_num = coluna_para_num(vet) - 1 ...
8689ae1dd1466b351012ebb3bd78269e46cbe5c3
80,546
def _constraints_from_gpu_info(info_str): """Parse the contents of a /proc/driver/nvidia/gpus/*/information to get the gpu model type. Args: info_str (str): The contents of the file. Returns: (str) The full model name. """ if info_str is None: return {} lines = info_str...
f5064b9de8be4918e6fe17b6ba24433c7cd9230b
80,547
import scipy def reliability(data): """ Computes upper and lower boundaries of data reliability :Args: data (np.ndarray) N samples x M features :Returns: (floor, ceiling) """ zdata = scipy.stats.zscore(data, axis=1) # remove data with no variance in it # se...
ff62687c99cb7b69c841d18bc752171e2c7d5222
80,548
import sqlite3 def get_1D_tiles(db_file, zoom, tile_x_pos, num_tiles=1): """ Retrieve a contiguous set of tiles from a db tile file. Parameters ---------- db_file: str The filename of the sqlite db file zoom: int The zoom level tile_x_pos: int The position of the f...
e9d3244720dc3e624a53870ba17fdae91c59d93b
80,549
def turn_coherence(behaviors, n_steps): """ Computes the probability of keeping a turn direction, ignoring intervening stay and straight bouts :param behaviors: Array of consecutive behaviors - 0-stay, 1-straight, 2-left, 3-right :param n_steps: The number of steps over which to compute probalities ...
bb130662f9b46265902a8ace79f6fe87201f3b5f
80,550
def get_transcript(uri): """ Get transcript for a audio WAVE file stored in GCS bucket @param: uri - File location in the google cloud storage bucket """ # create speech client client = speech.SpeechClient() # actual audio file to recognize audio = speech.RecognitionAudio(uri=uri) ...
69f1feabceffc42f8fae9c2c0a6cf546cffe50ca
80,551
def openUnicode(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): """ Unicode auto-detection by BOM. :return: Returns open() with the correct encoding and with the missing first character, if it is BOM. """ detect = False if "r" i...
c7af92a9acde80e5f1a14a304cb135b075b71d7b
80,552
def meters_to_meters2d(meters: Meters) -> np.ndarray: """ Cast for meters to 2D meters. Will make the second dimension 0. :param meters: The input, as meters. :return: The raw value to use for the Meters2D instance. """ return np.append(meters.raw, 0)
b938a75d3aa52f85cbd2ed4666ad266509c4447e
80,553
from typing import Tuple from typing import Union from typing import Iterable def microservice_api_grpc_seldon_message(method: str = "predict", microservice_endpoint: str = "localhost:5000", shape: Tuple = (1, 1), data: object = None, p...
69be6aa059c090becb1838a1e2c6c41684a94189
80,554
def calculate_level(score): """Get the level associated with a given score.""" return score//LINES_PER_LEVEL+1
a09300433eff736b4423647c25e351a398bbaa89
80,555
def breadcrumb_url(parser, token): """ Same as breadcrumb but instead of url context variable takes in all the arguments URL tag takes. {% breadcrumb "Title of breadcrumb" person_detail person.id %} {% breadcrumb person.name person_detail person.id %} """ bits = token.split_cont...
d220fb2c29b5d6a2ecc25fa28128ac5358d34c6a
80,556
def search(public_ip): """ Search for the ``public_ip`` in the ~/.ssh/known_hosts file, returning any occurrences found. """ result = local("ssh-keygen -H -F {0}".format(public_ip), capture=True) return bool(result)
9d64e12a3c69558f050a7e5004581ec083cfbdbe
80,557
def simulation(N=N, G=None, initial_infected_num=INITIAL_INFECTED_NUM, prob_infect=PROB_INFECT, incubation_duration_mean=INCUBATION_DURATION_MEAN, incubation_duration_std=INCUBATION_DURATION_STD, prob_asymptomatic=PROB_ASYMPTOMATI...
86e82be91116dbf5961385fb8fba7ac47b8a7409
80,558
def import_sunpy_map(): """ Import SunPy maps with directory importer. """ caption = "Select a directory containing SunPy Map files." directory = pick_directory(caption) wi = QtSunpyMapImporter(directory) wi.exec_() return wi.datasets
ab55c76f7e918d7f53ee79a23ec60ed5fcbc60fd
80,559
def solve_EEC(self): """Compute the parameters dict for the analytical equivalent electrical circuit cf "Influence of the Number of Pole Pairs on the Audible Noise of Inverter-Fed Induction Motors: Radial Force Waves and Mechanical Resonances" I. P. Tsoumas, H. Tischmacher, B. Eichinger Paramet...
7b8069cf9174c05de277b1b1c625f9259271aa61
80,560
def downgrade(sql_connection, version): """ Downgrade the database's current migration level :param sql_connection: sqlalchemy connection string :param version: version to downgrade to :retval version number """ db_version(sql_connection) # Ensure db is under migration control repo_pat...
6a3ffeaa87ca34fcdb1150bc0c1f590210a0a96b
80,561
def insertion_sort(integers): """Iterate over the list of integers. With each iteration, place the new element into its sorted position by shifting over elements to the left of the pointer until the correct location is found for the new element. Sorts the list in place. O(n^2) running time, O(1) spa...
ee7aa8920406f7c74870e346e486f29486894df1
80,563
def generator(*, domain, name, version): """Decorator that registers a generator function to `ACTIVITY_FUNCTIONS` """ def function_wrapper(func): identifier = '{}:{}:{}'.format(name, version, domain) ACTIVITY_FUNCTIONS[identifier] = check_type_generator_output(func) return function_wrap...
45410bbe0c34c6a5761c23308d551b3bc3e89f02
80,564
def _load_file (filename, env): """_load_file() Given a file name, and an environment, load the file, and extend/modify the environment with information about the current file to be processed.""" with (open(filename)) as fileobj: text = fileobj.read() env["filename"] = filename env["...
f901d6295478b1bbbc8f1bf5b109e4fc0ec778aa
80,565
import curses def init_screen(args): """ Set ncurses screen and returns the screen object """ screen = curses.initscr() curses.curs_set(0) curses.start_color() curses.init_pair(1, 1, args.background) curses.init_pair(2, 2, args.background) curses.init_pair(3, 3, args.background) curs...
e46a5a3bee5f498219fbbf2b8b4df50abffa07fe
80,566
def get_settings(): """ Returns some nice default settings for matplotlib to be used with `matplotlib.pyplot.rc_context`. """ return {'axes.labelsize': 32, 'xtick.major.size': 10, 'xtick.major.width': 1.5, 'xtick.labelsize': 24, 'ytick.major.size': 10, ...
7864c0bcb3b7ab427f6046b3358ee81f70646dd5
80,568
def patron_pid_minter(record_uuid, data): """Dummy patron minter.""" return None
c4ab8008467d54326911634bb51335f3b86cc96e
80,569
from javax.swing.event import UndoableEditListener def addUndoableEditListener(target, listener, *args, **kwargs): """ Shortcut for addEventListener(target, UndoableEditListener, 'undoableEditHappened', listener). """ return addEventListener(target, UndoableEditListener, ...
63bc28fb07f564fba4f59585723937a941f899f7
80,570
from typing import Optional def doolittle(matrix: np.ndarray) -> Optional[np.ndarray]: """ Doolittle 法 LU 分解 :param matrix: 系数矩阵 :return: 分解后的矩阵,下半为 L,上半为 U """ row, col = matrix.shape if row == col: u = np.zeros((row, row)) # init for j in range(0, row): ...
64da71138127a3735e864e0822493ba5c5c6195d
80,571
def plot_background(rgb_bg_data, title=None): """ Plot the RGB backgrounds from `Background2d` objects. Args: rgb_bg_data (list[photutils.Background2D]): The RGB background data as returned by calling `panoptes.utils.images.bayer.get_rgb_background` with `return_separate=True`. ...
18a68f396c717da2c30c1bd7f092eae08a4ff7cf
80,572
def find_class_from_command_name(command_name): """Find the Python class for a specific command name. Parameters: command_name (str) The command name, which should be used to find the class. Returns (sublime_plugin.Command) The python class, which belongs to the command name, o...
a43dee13bfa0987005c83d82962384eb921a0086
80,574
def get_dict_map(dict_code): """ 获取字典映射 :param dict_code: :return: dict """ if dict_code: dicts = DictItem.query.filter_by(dict_code=dict_code, is_valid=IS_VALID_Y).all() return {it.item_code: it.item_name for it in dicts} else: return {}
e0390f3126847b87951598db352c213cafbcfad1
80,575
from scipy.spatial import Voronoi def VoronoiNeighbors( tree, xy, k=100, **kd_kwds ): """ Return Neighbors on a Voronoi diagram (excuding xy) Arguments --------- tree : scipy.stats.cKDtree must implement the query method and the data attribute. xy : coordinates dimensions(...
3ac7e8201c9b1a650d603a18bd7dfb8859d982a1
80,576
def parse_poly(lines): """ Parse an Osmosis polygon filter file. Accept a sequence of lines from a polygon file, return a django.contrib.gis.geos.MultiPolygon object. Adapted Python 2 code from http://wiki.openstreetmap.org/wiki/Osmosis/Polygon_Filter_File_Python_Parsing_Geodjango for ...
7d99d30ae7e968f7f5500476ae310a77a4cd0646
80,579
def calc_weight(team_a, team_b, team_a_ind, team_b_ind, team_a_opt, team_b_opt, team_a_opt_ind, team_b_opt_ind): """ Calculate the penalty for a given pairing Args: team_a - the firs...
7b31b4e71b075f2fd32571e69b7c08a38834826e
80,580
def printing(slab, I, Is, ea): """ print output """ print "\nNumber of slabs to be Integrated: ", slab print "Simpson's Integral value: ", Is print "Analytic Integral value: ", I print "Absolute error: ", ea return 0
b691d08dbe28a8271c035a977f250e6fb5700fdc
80,582
import pickle import random def predict(day, sites, chimeres_day, geops_day, meteo_day, concentrations_day, model=None): """ day: day of the year (1-365) sites : Dataframe with columns "idPolair","nom_station","coord_x_l93","coord_y_l93","X_lamb2","Y_lamb2", "LON" ,"LAT", "Département","Zone_EPCI","typol...
a2db455385639095d8b049825ed2522ec7068277
80,583
def add_asset(data): """Create asset from provided data dictionary.""" client = _algod_client() params = client.suggested_params() unsigned_txn = AssetConfigTxn( sp=params, sender=data.get("creator"), asset_name=data.get("name"), unit_name=data.get("unit"), total=...
63543d5151b1830576a46023a3565c59d9530408
80,584
import timeit def log_com(image): """Doing log compression and count the time for processing Args: image: input image data (should be ndarray) returns: img_str: image after log compression time_process: time for doing the processing """ start = timeit.default_timer() ...
a1db7ec6d0f51e8b2515ca4f6138beb8ffd31c74
80,585
from typing import List def _ext_oracle( src: List[str], ref: str, sim_fn, max_sent: int = 3, max_len: int = -1, threshold: int = -1, ): """ A functionality of generating the extractive oracle for a sample in the summarization dataset src: source documents ref: reference s...
df8989c6d7d6103a6a212ea9cba4578f50a6beda
80,586
def TrainingWeights(y, Pout, lev, weight_precip, weight_shallow): """Set up weights for training examples""" wp = np.ones(y.shape[0]) ws = np.ones(y.shape[0]) if weight_precip: wp = Pout + 1 if weight_shallow: # 0.8 is near the level of maximum shallow convective activity sha...
4b0eaabd5c017972b524321f1f148960e79d4e33
80,587
def build_full_record_to(path_to_full_record_file): """structure of full record: {commitID: {'build-time': time, files: {filename: {record}, filename: {record}}}} """ full_record = build_full_record() if DO_PRINT_RECORDS: f = open(path_to_full_record_file, 'w') try: f.wri...
cbde1306227d9e210a2f2a9a2d1c93ffc9522cee
80,588
import random def neighbor_test(nr_points, dim, bucket_size, radius): """Test all fixed radius neighbor search. Test all fixed radius neighbor search using the KD tree C module. Arguments: - nr_points: number of points used in test - dim: dimension of coords - bucket_size: nr of point...
1542a40d9827dd5e40d92f86a233ec43dc58fb63
80,589
def send_source_data(appsrc_id, tensor, stream_name, stream_manager): """ Construct the input of the stream, send inputs data to a specified stream based on streamName. Returns: bool: send data success or not """ tensor_package_list = MxpiDataType.MxpiTensorPackageList() tensor_pack...
879b48ee938d1b2bfc3092346094f9f991310e78
80,591
def population_counts( boundaries: BoundariesLayer, population: PopulationLayer ) -> pd.Series: """Count population in each boundary. Parameters ---------- boundaries : BoundariesLayer Input boundaries vector layer. population : PopulationLayer Input population raster layer (pop...
64f5a7b387524bf080d2ef8263b1b3e4585c9fb2
80,593
def solvationData(request, solute_adjlist, solvent=''): """ Returns an entry with the solute data for a given molecule when the solute_adjlist is provided. If solvent is provided, the interaction solvation quantities are also displayed. The solvation data is estimated by RMG. """ #from rmgp...
02fe79d860a2878e7265757207ec043a43e17d1c
80,594
import json def load_all_skillets(refresh=False) -> list: """ Returns a list of skillet dictionaries :param refresh: Boolean flag whether to use the cache or force a cache refresh :return: skillet dictionaries """ if refresh is False: cached_skillets = cnc_utils.get_long_term_cached_va...
7e79d4810241544019f45ce7533b18e05fb94803
80,595
def get_shorting_trading_value_and_volume_by_ticker(date: str, market: str, include: list) -> DataFrame: """[32001] 개별종목 공매도 거래 Args: date (str): 조회 시작 일자 (YYYYMMDD) market (str): 검색 시장 (KRX/KOSPI/KOSDAQ) include (str): 증권 구분 (주식/ETF/ETN/ELW/신주인수권및증권/수익증권) Returns: Data...
c0bb66b69076c18404be306136eba6893ad82030
80,596
def merge_scored_dfs(scored_coding_df, scored_non_coding_df): """Merges the scored dataframes by changing some names around""" # for every non-coding TransMap metric, copy it to the other name for m in ['Coverage', 'Identity', 'Goodness']: scored_non_coding_df['Aln' + m + '_mRNA'] = scored_non_codin...
5e5d33edaf6e10bd5d927447b8d042e207cef594
80,597
from typing import List def primary() -> List[str]: """Primary color scheme.""" return ["#00A58D", "#008A8B", "#9FCD91", "#09505D", "#00587C"]
8527c8a649e554e077a57172dfb0d529fff4036a
80,598
def cross_channel_normalization_bc01(bc01, alpha=1e-4, k=2, beta=0.75, n=5): """ BC01 format (batch, channels, rows, cols) version of Cross Channel Normalization. See "ImageNet Classification with Deep Convolutional Neural Networks" Alex Krizhevsky, Ilya Sutskever, and Geoffrey E. Hinton NIPS 2012 ...
22172c5a799f402b7d355e556563ff6c26b47071
80,599
def draw_bbox(img_path: str, bbox: namedtuple, line_width=10): """ Draw a bbox around the object. :param str image_path: an image containing an object :param namedtuple bbox: x0, y0, x1, y1 :param int line_width: a width of bbox side :return draw: image object with bbox drawed. """ im ...
62b8556301d2fc1186d50a1b72be9221f4072b32
80,600
import warnings def pull_halo_output(h5file, clusterID, apertureID, dataset): """ Function to extract a dataset from a Bahamas snapshot output. :param h5file: The h5py File object to extract the data from :param clusterID: The number of cluster in the order imposed by FoF :param apertureID: int(0-22) The index o...
d389af763c7dc7a3c6e54a1f61f4906c7fa4dc0e
80,603
def rt_delta(maxdiff, precision=5): # type: (float, int) -> float """Return the delta tolerance for the given retention time. Keyword Arguments: maxdiff -- maximum time difference between a feature edge and an adjacent frame to be considered part of the same ...
ad04d4f0405544d1cf137b7b3c8aa25ac670365f
80,604
from typing import List def yara_rules_names(yara_rules_string: str) -> List[str]: """Get the name(s) of the given yara_rule(s).""" yara_rules_data = yara_rules_parse(yara_rules_string) all_rule_names = [] for rule in yara_rules_data: if rule.get('rule_name'): rule_name = rule['ru...
6487f4a57b3b01028542aa86800ee8bee17aea0b
80,605
import pkg_resources import logging def get_tango_server_class(device_name): """Build and return the Tango device class for DishMaster :param device_name: str The Tango device name :return DishMaster: tango.server.Device The Tango device class for dishmaster """ data_descr_files =...
3f2dd05aba57b453da6f894f5ccd864890372c7f
80,606
def check_converged( new_transport: dict, old_transport: dict, properties: tuple[str, ...] = _CONVERGENCE_PROPERTIES, tolerance: float = 0.1, ) -> bool: """ Check if all transport properties (averaged) are converged within the tol. Parameters ---------- new_transport : dict ...
45ec62bc180c924267892fb57ce836bb9d7cce68
80,607
def ratio_specials(s): """ Returns the ratio special characters to all characters in s. The default special character list is "~`!@#$%^&*()_={}[]:>;',</?*-+" :param s: Domain (string) """ return analyse.get_ratio_special_2ld(s)
1fdd478e03742f3e5462893d65f9192826f8c4f0
80,608
from typing import List def boxes_from_mask(mask: np.ndarray) -> List[np.ndarray]: """ Args: mask: (1, h, w) 0~1 Returns: """ height, width = mask.shape[1:] _, thresh = cv2.threshold((mask.transpose(1, 2, 0) * 255).astype(np.uint8), 127, 255, 0) contours, _ = cv2.findContours(th...
7b8a2efdc00247f045f82deabcb42653c291549a
80,609
async def ensemble_forecast(): """Execute ensemble forecast and represent as dataframe.""" # Assemble data used as input for simulations ###################################### timer_wfc = Timer( text="Overall duration for preparing weather forecasts: {:.2f} seconds", logger=logger.success, ...
92daece08abac5e3a7007c7e7f630cc83354d815
80,610
def simple_impute( adata: AnnData, var_names: list[str] | None = None, strategy: str = "mean", copy: bool = False ) -> AnnData: """Impute AnnData object using mean/median/most frequent imputation. This works for numerical data only. Args: adata: The AnnData object to use mean Imputation on ...
24216bdb2aa50ad18afa0efed82384ab1be1c084
80,611
def positive_negative_basic_reward_function(causal_prefetch_item): """ Consistent positive reward based on something being used within 128 steps (1, -1) rewards """ if causal_prefetch_item is None: return -1 return 1
beaefcaebe806329d17ec8fa584e2a0f102b978c
80,613
from typing import Union def constant_schedule( value: Union[float, int] ) -> base.Schedule: """Constructs a constant schedule. Args: value: value to be held constant throughout. Returns: schedule: A function that maps step counts to values. """ return lambda count: value
8e20eb79a151b8dbeab914dc81aa71515a29aa5d
80,614
def login(): """ 管理员登录页面 """ form = LoginForm() return render_template('/admin/login.html', form=form)
de8c69d658fcd6494967dde8678c37a85f0d66cf
80,615
def create_template_dict(dbs): """ Generate a Template which will be returned by Executor Classes """ return {db: {'keys': [], 'tables_not_found': []} for db in dbs}
01dbd3733ec77fef0323eea35bc67064b19093c9
80,616
def header_case(s: str): """ Transform into a dash separated string of capitalized words. Parameters ---------- s : str Original string to transform. Returns ------- Transformed string. """ return _change_case(s, '-', str.capitalize)
d0ebceceac702b01c535d7ab0d6091df9f4e3ebf
80,618
def _calc_height2area_ratio(lw, chain, ta=-1.0, tb=-1.0 ): """ We know the value of the full width half max line width in Hz that we have in our data, and want to find the Ta and Tb values that yield this. This function uses the minf_parabolic_info routine to optimze Ta and Tb to values betwee...
517d842d698bb705cfdd448b3f34261e736d051f
80,619
def frame_multi_factory(buf, preface=False): """ Attempt to parse one or more Frame's out of buf Args: buf: string containing HTTP/2 frames. May have an incomplete frame at the end. preface: expect an HTTP/2 preface at the beginning of the buffer. Returns: [Frame] int, ...
f80f42c07c1354af7b9100b342f2e36421074395
80,620
def is_camel_case(string): """ Checks if a string is formatted as camel case. A string is considered camel case when: - it starts with a lower case letter - it's composed only by letters ([a-zA-Z]) and optionally numbers ([0-9]) - it contains both lowercase and uppercase letters or just lowercas...
ecd1f520bca8d4f6e1f54cb1dddea27db51eb302
80,621
def find_nearest_center(a, centers): """ return the nearest center :param a: each pixel [r,g,b] :param centers: a 9*3 R,G,B array :return: """ mid_d = np.inf r = 0 for i in range(len(centers)): distance = np.linalg.norm(a - centers[i]) if distance < mid_d: ...
fd27bb3ce902d0c80d1c3b653375361c881be3e4
80,622
def NodalPlanes_Cast(*args): """ Cast(BaseObject o) -> NodalPlanes NodalPlanes_Cast(Seiscomp::Core::BaseObjectPtr o) -> NodalPlanes """ return _DataModel.NodalPlanes_Cast(*args)
7acaca0ff31257cb2a98fbaafd3e19fc76d983d7
80,623
import numpy def write_gif(dataset, filename, fps=10, loop_times=0): """Write a NumPy array to GIF 89a format. Or write a list of NumPy arrays to an animation (GIF 89a format). - Positional arguments:: :param dataset: A NumPy arrayor list of arrays with shape rgb x rows ...
cf22b9526681158f6bb111e0c7be44da6ccb13e8
80,624
def new_constant(name, py_conversion=None, default_value=None, validation=None, widget_type=None, str_conversion=None, base_class=Constant, compute=None, query_compute=None): """new_constant(name: str, py_conversion: callable, ...
9d6e452e9e85a30f20264612e9912eb8ffc3d828
80,625
from pathlib import Path def get_git_data(): """Assemble some Git metadata.""" repo = Repo(Path(Path(__file__).resolve().parent.parent)) timestamp = repo.head.object.authored_datetime.isoformat() timestamp = timestamp.split("+")[0].replace("T", " ") repo_url = f"https://github.com/{GITHUB_REPO}"...
670e883a986220a6cfb9bda0d3c35128ac49c2d8
80,626
from typing import Any def create_model_group( *, db: Session = Depends(deps.get_db), current_user: models.User = Depends(deps.get_current_active_user), obj_in: schemas.ModelGroupCreate, controller_client: ControllerClient = Depends(deps.get_controller_client), ) -> Any: """ Create model g...
e1c4d5c27e9fc8af0034dfc33186a9b9ba403e57
80,627
def doc2vec_vectorizer(vectorizer): """ Doc2vec interface for text similarity using Encoder model. Parameters ---------- vectorizer : object encoder interface object, BERT, XLNET. should have `vectorize` method. Returns ------- result: malaya.similarity.VectorizerSimila...
9f78f907229097be292a3ebeac335e2944a76da7
80,628
from typing import Union from typing import Optional def calc_terms_marg_probs( phi: Union[ndarray, DataFrame], word_id: Optional[int] = None) -> Union[ndarray, Series]: """Calculate marginal terms probabilities. Parameters ---------- phi : Union[ndarray, DataFrame] Words vs t...
b710a4b25b921b9d09804b4fd4c1e34b3257ecd6
80,629
def get_metadata(user, dataset_name): """Gets the metadata of the specific upload. Checks datastore for an the latest entity that matches the name of the user and dataset name. Args: user: Name of the user that uploaded the file. dataset_name: Name of the dataset ...
da821288b70a72225578baa2492da746dde836f1
80,630
from typing import Mapping from typing import Union def _( _data: TibbleGrouped, _names_sep: str = None, **cols: Mapping[str, Union[str, int]], ) -> TibbleGrouped: """Nesting grouped dataframe""" if not cols: cols = { "data": regcall(setdiff, _data.columns, regcall(group_vars, ...
17fcb0f53d410ed4615bb3b44a73e04640ffa234
80,631