content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Iterator from typing import Tuple from typing import Any import itertools def _nonnull_powerset(iterable) -> Iterator[Tuple[Any]]: """Returns powerset of iterable, minus the empty set.""" s = list(iterable) return itertools.chain.from_iterable( itertools.combinations(s, r) for r...
ad02ab8ac02004adb54310bc639c6e2d84f19b02
11,300
import yaml def _parse_obs_status_file(filename): """ Parse a yaml file and return a dictionary. The dictionary will be of the form: {'obs': [], 'bad': [], 'mags: []} :param filename: :return: """ with open(filename) as fh: status = yaml.load(fh, Loader=yaml.SafeLoader) if 'o...
389fc921867367964001e5fc2f56a7fa7defd7c8
11,301
def extract_optional_suffix(r): """ a | a b -> a b? """ modified = False def match_replace_fn(o): if isinstance(o, Antlr4Selection): potential_prefix = None potential_prefix_i = None to_remove = [] for i, c in enumerate(o): if...
a1d4e6702ed1b23e0f94a44e5bea6fae16b47e17
11,302
def _heading_index(config, info, token, stack, level, blockquote_depth): """Get the next heading level, adjusting `stack` as a side effect.""" # Treat chapter titles specially. if level == 1: return tuple(str(i) for i in stack) # Moving up if level > len(stack): if (level > len(stac...
f42dd5c6aae942da687310d7bef81f70bfadad83
11,303
from typing import List def sin_salida_naive(vuelos: Data) -> List[str]: """Retorna una lista de aeropuertos a los cuales hayan llegado vuelos pero no hayan salido vuelos de este. :param vuelos: Información de los vuelos. :vuelos type: Dict[str, Dict[str, Union[str, float]]] :return: Lista de aer...
136b7c1e3428cecee5d3bc7046fac815276288e5
11,304
def converter(doc): """ This is a function for converting various kinds of objects we see inside a graffle document. """ if doc.nodeName == "#text": return str(doc.data) elif doc.nodeName == "string": return str(doc.firstChild.data) elif doc.nodeName == 'integer': return int(doc.firstChi...
8820aa739f4b96251033c191ea405157cfe1e9fb
11,305
def printable_cmd(c): """Converts a `list` of `str`s representing a shell command to a printable `str`.""" return " ".join(map(lambda e: '"' + str(e) + '"', c))
b5e8a68fc535c186fdbadc8a669ed3dec0da3aee
11,306
def details_from_params( params: QueryParams, items_per_page: int, items_per_page_async: int = -1, ) -> common.Details: """Create details from request params.""" try: page = int(params.get('page', 1)) except (ValueError, TypeError): page = 1 try: anchor =...
50e20619bc4f32af6811a3416b2d2f93820ba44a
11,307
import glob import os def run_nuclei_type_stat( pred_dir, true_dir, nuclei_type_dict, type_uid_list=None, exhaustive=True, rad=12, verbose=False ): """ rad = 12 if x40 rad = 6 if x20 """ def _get_type_name(uid, ntd=nuclei_type_dict): for name,v in ntd.items(): if v == uid: ...
9b24343a05c5111b80239c66f1500a934ea3ba33
11,308
from typing import Tuple from typing import Mapping def _signature_pre_process_predict( signature: _SignatureDef) -> Tuple[Text, Mapping[Text, Text]]: """Returns input tensor name and output alias tensor names from signature. Args: signature: SignatureDef Returns: A tuple of input tensor name and ...
a53af746f7cebc7c3baaa316458dd3e7b88c2c38
11,309
def style_95_read_mode(line, patterns): """Style the EAC 95 read mode line.""" # Burst mode doesn't have multiple settings in one line if ',' not in line: return style_setting(line, 'bad') split_line = line.split(':', 1) read_mode = split_line[0].rstrip() line = line.replace(read_mode,...
25c347acb87702f19ebcea85a3b4f0257df101ae
11,310
def trange( client, symbol, timeframe="6m", highcol="high", lowcol="low", closecol="close" ): """This will return a dataframe of true range for the given symbol across the given timeframe Args: client (pyEX.Client): Client symbol (string): Ticker timeframe (string): timeframe to...
94cf95eb86575a66e015e46fd81a5a8085277255
11,311
def ConvolveUsingAlm(map_in, psf_alm): """Convolve a map using a set of pre-computed ALM Parameters ---------- map_in : array_like HEALPix map to be convolved psf_alm : array_like The ALM represenation of the PSF Returns ------- map_out : array_like The smeared ...
0ebfa49c605f57ea2cc59b2686da8995dc01881f
11,312
def load_summary_data(): """ Function to load data param DATA_URL: data_url return: pandas dataframe """ DATA_URL = 'data/summary_df.csv' data = pd.read_csv(DATA_URL) return data
b5f09e845e1379fd00a03fd11b0174e3114eb7d3
11,313
import itertools def _enumerate_trees_w_leaves(n_leaves): """Construct all rooted trees with n leaves.""" def enumtree(*args): n_args = len(args) # trivial cases: if n_args == 0: return [] if n_args == 1: return args # general case of 2 or more args: # build index array idx...
574a2d3ec63d3aeeb06292ec361b83aebba0ff84
11,314
from typing import get_args import sys import re def main(): """Make a jazz noise here""" args = get_args() sub = args.substring word = args.word # Sanity check if sub not in word: sys.exit(f'Substring "{sub}" does not appear in word "{word}"') # Create a pattern that replaces t...
0c2149e1f107967a0bc948fde0e7a25844664f24
11,315
def gen_tfidf(tokens, idf_dict): """ Given a segmented string and idf dict, return a dict of tfidf. """ # tokens = text.split() total = len(tokens) tfidf_dict = {} for w in tokens: tfidf_dict[w] = tfidf_dict.get(w, 0.0) + 1.0 for k in tfidf_dict: tfidf_dict[k] *= idf_dict...
9217867b3661a8070cc1b2d577918c95d1ff7755
11,316
def timestamp_to_seconds(timestamp): """Convert timestamp to python (POSIX) time in seconds. :param timestamp: The timestamp. :return: The python time in float seconds. """ return (timestamp / 2**30) + EPOCH
3d5ca5f5ec93b54e1d1a6c53cefba1d49f8ebac2
11,317
import io import subprocess import time def launch_dpf(ansys_path, ip=LOCALHOST, port=DPF_DEFAULT_PORT, timeout=10, docker_name=None): """Launch Ansys DPF. Parameters ---------- ansys_path : str, optional Root path for the Ansys installation directory. For example, ``"/ansys_inc/v212/"``. ...
6d9d4039b702c3499ed256254f156f28eeb809a6
11,318
def fit_lowmass_mstar_mpeak_relation(mpeak_orig, mstar_orig, mpeak_mstar_fit_low_mpeak=default_mpeak_mstar_fit_low_mpeak, mpeak_mstar_fit_high_mpeak=default_mpeak_mstar_fit_high_mpeak): """ """ mid = 0.5*(mpeak_mstar_fit_low_mpeak + mpeak_mstar_fit_high_mpeak) mask = (mpeak_orig ...
620275ad18173bb00d38f3d468be132d150fc1fa
11,319
def load_ref_system(): """ Returns benzaldehyde as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" C 0.3179 1.0449 -0.0067 C 1.6965 0.8596 -0.0102 C 2.2283 -0.4253 -0...
518ca10a84befa07fefa3c2f646e40095318d63c
11,320
def get_department_level_grade_data_completed(request_ctx, account_id, **request_kwargs): """ Returns the distribution of grades for students in courses in the department. Each data point is one student's current grade in one course; if a student is in multiple courses, he contributes one value per cou...
8dd40c7b7c7a734aa66d4f808224424c0c0df81d
11,321
def allocate_samples_to_bins(n_samples, ideal_bin_count=100): """goal is as best as possible pick a number of bins and per bin samples to a achieve a given number of samples. Parameters ---------- Returns ---------- number of bins, list of samples per bin """ if n_samples <= i...
66d5fe32a89478b543818d63c65f2745fe242b33
11,322
from typing import Any def create_algo(name: str, discrete: bool, **params: Any) -> AlgoBase: """Returns algorithm object from its name. Args: name (str): algorithm name in snake_case. discrete (bool): flag to use discrete action-space algorithm. params (any): arguments for algorithm....
4fab0f5581eb6036efba6074ab6e3b232bcf5679
11,323
def tf_inv(T): """ Invert 4x4 homogeneous transform """ assert T.shape == (4, 4) return np.linalg.inv(T)
5bf7d54456198c25029956a7aebe118d7ee4fa87
11,324
def send_reset_password_email(token, to, username): """ send email to user for reset password :param token: token :param to: email address :param username: user.username :return: """ url_to = current_app.config["WEB_BASE_URL"] + "/auth/reset-password?token=" + token response = _send...
dddcb66425de79a1a736bbbcc5cbc3f5855e7db9
11,325
def part1(data): """Solve part 1""" countIncreased = 0 prevItem = None for row in data: if prevItem == None: prevItem = row continue if prevItem < row: countIncreased += 1; prevItem = row return countIncreased
e01b5edc9d9ac63a31189160d09b5e6e0f11e522
11,326
def yzrotation(theta = np.pi*3/20.0): """ Returns a simple planar rotation matrix that rotates vectors around the x-axis. args: theta: The angle by which we will perform the rotation. """ r = np.eye(3) r[1,1] = np.cos(theta) r[1,2] = -np.sin(theta) r[2,1] = np.sin(theta) ...
59a2a251f8e8aa77548f749f49871536de29b0bb
11,327
def is_compiled_release(data): """ Returns whether the data is a compiled release (embedded or linked). """ return 'tag' in data and isinstance(data['tag'], list) and 'compiled' in data['tag']
ea8c8ae4f1ccdedbcc145bd57bde3b6040e5cab5
11,328
import numpy def resize_frame( frame: numpy.ndarray, width: int, height: int, mode: str = "RGB" ) -> numpy.ndarray: """ Use PIL to resize an RGB frame to an specified height and width. Args: frame: Target numpy array representing the image that will be resized. width: Width of the res...
941eb73961843e46b4e67d48439a09c0223c2af0
11,329
def get_proxies(host, user, password, database, port=3306, unix_socket=None): """"Connect to a mysql database using pymysql and retrieve proxies for the scraping job. Args: host: The mysql database host user: The mysql user password: The database password port: The mysql port, b...
d4595440c9d4d07a7d5e27740bf7049176dbe432
11,330
def APIRevision(): """Gets the current API revision to use. Returns: str, The revision to use. """ return 'v1beta3'
c748e1917befe76da449e1f435540e10ee433444
11,331
def pretty_string_value_error(value, error, error_digits=2, use_unicode=True): """ Returns a value/error combination of numbers in a scientifically 'pretty' format. Scientific quantities often come as a *value* (the actual quantity) and the *error* (the uncertainty in the value). ...
bd7b1496880e7d1cb4ffd04d23df20d679ac8ade
11,332
def update_resnet(model, debug=False): """ Update a ResNet model to use :class:`EltwiseSum` for the skip connection. Args: model (:class:`torchvision.models.resnet.ResNet`): ResNet model. debug (bool): If True, print debug statements. Returns: model (:class:`torchvision.mod...
a6baf031ff89b82b4e063795555c55885548f61e
11,333
def sameSize(arguments) -> bool: """Checks whether given vectors are the same size or not""" sameLength = True initialSize = len(vectors[arguments[0]]) for vector in arguments: if len(vectors[vector]) != initialSize: sameLength = False return sameLength
0840adcb0f6a84c56ff3b0ce3aa23892e45d942e
11,334
def db_read(src_path, read_type=set, read_int=False): """Read string data from a file into a variable of given type. Read from the file at 'src_path', line by line, skipping certain lines and removing trailing whitespace. If 'read_int' is True, convert the resulting string to int. Return r...
811c6efb83d134d695c6dec2e34d3405818b8a48
11,335
import re def get_config_keys(): """Parses Keys.java to extract keys to be used in configuration files Args: None Returns: list: A list of dict containing the following keys - 'key': A dot separated name of the config key 'description': A list of str """ desc_re =...
8c04fcac2d05579ce47f5436999f0fe86fb1bdbd
11,336
def new(): """Create a new community.""" return render_template('invenio_communities/new.html')
60ee1560f749d94833f57b6a34e2d514e3e04ccb
11,337
import torch def interpolate(results_t, results_tp1, dt, K, c2w, img_wh): """ Interpolate between two results t and t+1 to produce t+dt, dt in (0, 1). For each sample on the ray (the sample points lie on the same distances, so they actually form planes), compute the optical flow on this plane, then us...
d5cdae22a3fb324e9bdfdedabe0b69cb5d40ebdb
11,338
def divisor(baudrate): """Calculate the divisor for generating a given baudrate""" CLOCK_HZ = 50e6 return round(CLOCK_HZ / baudrate)
a09eee716889ee6950f8c5bba0f31cdd2b311ada
11,339
def scm_get_active_branch(*args, **kwargs): """ Get the active named branch of an existing SCM repository. :param str path: Path on the file system where the repository resides. If not specified, it defaults to the current work directory. :return: Name of the activ...
6c18454548732cd8db4ba85b45cdc9a8d9b47fce
11,340
def search_evaluations(campus, **kwargs): """ year (required) term_name (required): Winter|Spring|Summer|Autumn curriculum_abbreviation course_number section_id student_id (student number) """ url = "%s?%s" % (IAS_PREFIX, urlencode(kwargs)) data = get_resource_by_campus(url, cam...
d7069c2e9135b350141b0053e3ec1202650b7c28
11,341
from typing import Optional import select async def get_user(username: str, session: AsyncSession) -> Optional[User]: """ Returns a user with the given username """ return ( (await session.execute(select(User).where(User.name == username))) .scalars() .first() )
0975c069d76414fbf57f4b8f7370d0ada40e39f5
11,342
import os import time import stat from datetime import datetime def convert_modtime_to_date(path): """ Formats last modification date of a file into m/d/y form. Params: path (file path): the file to be documented Example: convert_modtime_to_date(/users/.../last_minute_submission.pdf)...
7377e6c46e477a8af9fa1c500517e2a9b2d7df49
11,343
import pandas def compute_balances(flows): """ Balances by currency. :param flows: :return: """ flows = flows.set_index('date') flows_by_asset = flows.pivot(columns='asset', values='amount').apply(pandas.to_numeric) balances = flows_by_asset.fillna(0).cumsum() return balances
98728c2c687df60194eb11b479c08fc90502807a
11,344
import json def unjsonify(json_data): """ Converts the inputted JSON data to Python format. :param json_data | <variant> """ return json.loads(json_data, object_hook=json2py)
93a59f8a2ef96cbe25e89c2970969b0132b1a892
11,345
from typing import Tuple from typing import List def comp_state_dist(table: np.ndarray) -> Tuple[np.ndarray, List[str]]: """Compute the distribution of distinct states/diagnoses from a table of individual diagnoses detailing the patterns of lymphatic progression per patient. Args: table: Rows...
1a2edacd40d4fea3ff3cc5ddd57d76bffc60c7bc
11,346
def polyConvert(coeffs, trans=(0, 1), backward=False): """ Converts polynomial coeffs for x (P = a0 + a1*x + a2*x**2 + ...) in polynomial coeffs for x~:=a+b*x (P~ = a0~ + a1~*x~ + a2~*x~**2 + ...). Therefore, (a,b)=(0,1) makes nothing. If backward, makes the opposite transformation. Note: backw...
1a2607b28046a8dc67315726957a87a5d5c9a435
11,347
import random def uniform(_data, weights): """ Randomly initialize the weights with values between 0 and 1. Parameters ---------- _data: ndarray Data to pick to initialize weights. weights: ndarray Previous weight values. Returns ------- weights: ndarray N...
fbf7e853f11a888ee01dc840c6ffcb214560c5a8
11,348
def ingresar_datos(): """Ingresa los datos de las secciones""" datos = {} while True: codigo = int_input('Ingrese el código de la sección: ') if codigo < 0: break cantidad = int_input( 'Ingrese la cantidad de alumnos: ', min=MIN, max=MAX ) dato...
3bacb0e5d6b234b2f90564c44a25d151a640fd1f
11,349
def fetch_credentials() -> Credentials: """Produces a Credentials object based on the contents of the CONFIG_FILE or, alternatively, interactively. """ if CONFIG_FILE_EXISTS: return parse_config_file(CONFIG_FILE) else: return get_credentials_interactively()
0b882c8c4c8066a1898771c66db6ccbe7cb09c37
11,350
def pool_adjacency_mat_reference_wrapper( adj: sparse.spmatrix, kernel_size=4, stride=2, padding=1 ) -> sparse.spmatrix: """Wraps `pool_adjacency_mat_reference` to provide the same API as `pool_adjacency_mat`""" adj = Variable(to_sparse_tensor(adj).to_dense()) adj_conv = pool_adjacency_mat_reference(adj...
e72cb1e50bf7542d4175b9b3b3989e70a8812373
11,351
def send(socket, obj, flags=0, protocol=-1): """stringify an object, and then send it""" s = str(obj) return socket.send_string(s)
a89165565837ad4a984905d5b5fdd73e398b35fd
11,352
def arraystr(A: Array) -> str: """Pretty print array""" B = np.asarray(A).ravel() if len(B) <= 3: return " ".join([itemstr(v) for v in B]) return " ".join([itemstr(B[0]), itemstr(B[1]), "...", itemstr(B[-1])])
9cceed63c83812a7fd87dba833fc4d5b5a75088c
11,353
def dist2_test(v1, v2, idx1, idx2, len2): """Square of distance equal""" return (v1-v2).mag2() == len2
3a268a3ba704a91f83345766245a952fe5d943dd
11,354
def extract_grid_cells(browser, grid_id): """ Given the ID of a legistar table, returns a list of dictionaries for each row mapping column headers to td elements. """ table = browser.find_element_by_id(grid_id) header_cells = table.find_elements_by_css_selector( 'thead:nth-child(2) ...
bee4265a18cfd428f25e3fdf3202fb5bfad820df
11,355
import ast def gatherAllParameters(a, keep_orig=True): """Gather all parameters in the tree. Names are returned along with their original names (which are used in variable mapping)""" if type(a) == list: allIds = set() for line in a: allIds |= gatherAllVariables(line) return allIds if not isinstance(a, ...
e899e60d818750a4ff1656b039a6dc4413f8f181
11,356
def average_link_euclidian(X,verbose=0): """ Average link clustering based on data matrix. Parameters ---------- X array of shape (nbitem,dim): data matrix from which an Euclidian distance matrix is computed verbose=0, verbosity level Returns ------- t a weightForest structur...
17aae1e7f802f82765bcda8b403598a2c5a9f822
11,357
import functools def cached(func): """Decorator cached makes the function to cache its result and return it in duplicate calls.""" prop_name = '__cached_' + func.__name__ @functools.wraps(func) def _cached_func(self): try: return getattr(self, prop_name) except AttributeEr...
5b23c251c03160ba2c4e87848201be46ba2f34fb
11,358
def SX_inf(*args): """ create a matrix with all inf inf(int nrow, int ncol) -> SX inf((int,int) rc) -> SX inf(Sparsity sp) -> SX """ return _casadi.SX_inf(*args)
b11fba9e9b60eadb983d1203b1dd852abca9a2b7
11,359
def aes_encrypt(mode, aes_key, aes_iv, *data): """ Encrypt data with AES in specified mode. :param aes_key: aes_key to use :param aes_iv: initialization vector """ encryptor = Cipher(algorithms.AES(aes_key), mode(aes_iv), backend=default_backend()).encryptor() result = None for value in...
94a39ddabe3ea186463808e79e86bec171fbaeda
11,360
def _ebpm_gamma_update_a(init, b, plm, step=1, c=0.5, tau=0.5, max_iters=30): """Backtracking line search to select step size for Newton-Raphson update of a""" def loss(a): return -(a * np.log(b) + a * plm - sp.gammaln(a)).sum() obj = loss(init) d = (np.log(b) - sp.digamma(init) + plm).mean() / sp.polygamma...
038fb28824b3429b03887299af7a7feeec16b689
11,361
def edge_distance_mapping(graph : Graph, iterations : int, lrgen : LearningRateGen, verbose : bool = True, reset_locations : bool = True): """ Stochastic Gradient Descent algorithm for performing ...
f5c93cf83a7cd7892936246eb6c90562030ad819
11,362
def strip_extension(name: str) -> str: """ Remove a single extension from a file name, if present. """ last_dot = name.rfind(".") if last_dot > -1: return name[:last_dot] else: return name
9dc1e3a3c9ad3251aba8a1b61f73de9f79f9a8be
11,363
import os def next_joystick_device(): """Finds the next available js device name.""" for i in range(100): dev = "/dev/input/js{0}".format(i) if not os.path.exists(dev): return dev
56e1b859fd26e546e7a63cbf2764b78c2cd41990
11,364
def validatePullRequest(data): """Validate pull request by action.""" if 'action' not in data: raise BadRequest('no event supplied') if 'pull_request' not in data or 'html_url' not in data.get('pull_request'): raise BadRequest('payload.pull_request.html_url missing') return True
a4577a1b719b11f1ea845fff436a78178ca9e370
11,365
def __adjust_data_for_log_scale(dataframe: pd.DataFrame) -> pd.DataFrame: """ This will clean and adjust some of the data so that Altair can plot it using a logarithmic scale. Altair does not allow zero values on the Y axis when plotting with a logarithmic scale, as log(0) is undefined. Args: d...
30d7a73f2f0d564f6e52e1a2fa4b521fa1265c3d
11,366
import torch def predict_sentence(model,vocab,sentence): """Predicts the section value of a given sentence INPUT: Trained model, Model vocab, Sentence to predict OUTPUT: Assigned section to the sentence""" device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') nlp=spacy.load('en_cor...
f8ef02bd92dfc3dfcea0f5a2e9d5da99050fe367
11,367
import spacy import re def ne_offsets_by_sent( text_nest_list=[], model='de_core_news_sm', ): """ extracts offsets of NEs and the NE-type grouped by sents :param text_nest_list: A list of list with following structure:\ [{"text": "Wien ist schön", "ner_dicts": [{"text": "Wien", "ne_type": "LOC"}]...
1e4fdaba07bf562b1d91b5f2376955efa9974c56
11,368
from typing import Optional def clone_repo( url: str, path: str, branch: Optional[str] = None, ) -> bool: """Clone repo from URL (at branch if specified) to given path.""" cmd = ['git', 'clone', url, path] if branch: cmd += ['--branch', branch] return run(cmd)[0].returncode == 0
56bc8641c3418216f1da5f0c87d33478888775c7
11,369
def get_inputtype(name, object_type): """Get an input type based on the object type""" if object_type in _input_registry: return _input_registry[object_type] inputtype = type( name, (graphene.InputObjectType,), _get_input_attrs(object_type), ) _input_registry[object...
aee2a84c8aaf0d66554f022ac0fec0aaef808160
11,370
from src.common import lang import os def res_ex_response(e, original=False): """异常响应,结果必须可以作json序列化 参数: e # 原始错误信息 original # 是否返回原始错误信息,默认flase """ if os.getenv('ENV') != 'UnitTest': current_app.logger.error(e) msg = lang.resp('L_OPER_FAILED') if original: ...
810edae8d2081e208b27e19589d8c9c09d669a72
11,371
def get_engine_status(engine=None): """Return a report of the current engine status""" if engine is None: engine = crawler.engine global_tests = [ "time()-engine.start_time", "engine.is_idle()", "engine.has_capacity()", "engine.scheduler.is_idle()", "len(engi...
0d87692a991965c8b72204d241964a27a9499014
11,372
import tqdm import requests import json def stock_em_jgdy_tj(): """ 东方财富网-数据中心-特色数据-机构调研-机构调研统计 http://data.eastmoney.com/jgdy/tj.html :return: pandas.DataFrame """ url = "http://data.eastmoney.com/DataCenter_V3/jgdy/gsjsdy.ashx" page_num = _get_page_num_tj() temp_df = pd.DataFrame() ...
1841702e6fb5c677245a2d213f489d95a789d68b
11,373
def hpdi(x, prob=0.90, axis=0): """ Computes "highest posterior density interval" (HPDI) which is the narrowest interval with probability mass ``prob``. :param numpy.ndarray x: the input array. :param float prob: the probability mass of samples within the interval. :param int axis: the dimensio...
579515ebb6d28c2a1578c85eab8cbff1b67bd5ee
11,374
def a(n, k): """calculates maximum power of p(n) needed >>> a(0, 20) 4 >>> a(1, 20) 2 >>> a(2, 20) 1 """ return floor(log(k) / log(p(n)))
581e2a23a3dc069fc457ed5a6fe7d5a355353242
11,375
import platform def is_windows(): """ détermine si le système actuel est windows """ return platform.system().lower() == "windows"
fc9e2ca948f7cc5dc6b6cc9afb52ba701222bb7a
11,376
def WTfilt_1d(sig): """ # 使用小波变换对单导联ECG滤波 # 参考:Martis R J, Acharya U R, Min L C. ECG beat classification using PCA, LDA, ICA and discrete wavelet transform[J].Biomedical Signal Processing and Control, 2013, 8(5): 437-448. :param sig: 1-D numpy Array,单导联ECG :return: 1-D numpy Array,滤波后信号 """ ...
8a3c65b35ac347b247a36e7d70705f76f41010d5
11,377
def discount_rewards(r): """ take 1D float array of rewards and compute discounted reward """ gamma = 0.99 discounted_r = np.zeros_like(r) running_add = 0 for t in reversed(range(0, r.size)): running_add = running_add * gamma + r[t] discounted_r[t] = running_add return discounted...
b093c0d82ef82824c08d08ce4da1b840318bd7ed
11,378
def mvn(tensor): """Per row mean-variance normalization.""" epsilon = 1e-6 mean = K.mean(tensor, axis=1, keepdims=True) std = K.std(tensor, axis=1, keepdims=True) mvn = (tensor - mean) / (std + epsilon) return mvn
c205712d3a1a53450de0e0b9af0abe1b9d51f269
11,379
import re def grapheme_to_phoneme(text, g2p, lexicon=None): """Converts grapheme to phoneme""" phones = [] words = filter(None, re.split(r"(['(),:;.\-\?\!\s+])", text)) for w in words: if lexicon is not None and w.lower() in lexicon: phones += lexicon[w.lower()] else: ...
2bb5195a323aa712b2725851fdde64b8e38856f0
11,380
def mean_log_cosh_error(pred, target): """ Determine mean log cosh error. f(y_t, y) = sum(log(cosh(y_t-y)))/n where, y_t = predicted value y = target value n = number of values :param pred: {array}, shape(n_samples,) predicted values. :param targ...
85fd6c3d582e7bc41271e3212d43c5cfea8bcf7e
11,381
def plot_abctraces(pools, surveypath=''): """ Input: a list of pools in the abc format Generates trace plots of the thetas,eps and metrics """ sns.set_style("white") matplotlib.rc("font", size=30) """ Plot Metric-Distances """ distances = np.array([pool.dists for pool in pools]) ...
9fef0b6bf382648d4d9d0cdfc175ce239aaf1aff
11,382
def check_columns(board: list): """ Check column-wise compliance of the board for uniqueness (buildings of unique height) and visibility (top-bottom and vice versa). Same as for horizontal cases, but aggregated in one function for vertical case, i.e. columns. >>> check_columns(['***21**', '412453*...
85fd1f02b392c6b6219ce989f7439ec0140b9fa2
11,383
import numpy import pathlib import tqdm import pandas import warnings def extract_header(mjds, path, keywords, dtypes=None, split_dbs=False, is_range=False): """Returns a `~pandas.DataFrame` with header information. For a list or range of MJDs, collects a series of header keywords for database files and ...
65934d9b5e9c1e6eb639709a16e6e93c145b57e7
11,384
import pytz from datetime import datetime async def get_time(): """获取服务器时间 """ tz = pytz.timezone('Asia/Shanghai') return { 'nowtime': datetime.now(), 'utctime': datetime.utcnow(), 'localtime': datetime.now(tz) }
282eb1136713df8045c6ad5f659042484fe4ec8b
11,385
def health_check(): """Attempt to ping the database and respond with a status code 200. This endpoint is verify that the server is running and that the database is accessible. """ response = {"service": "OK"} try: postgres.session.query(text("1")).from_statement(text("SELECT 1")).all()...
cd47815ada53281f2b13542dd8cad93398be5203
11,386
def find_ad_adapter(bus): """Find the advertising manager interface. :param bus: D-Bus bus object that is searched. """ remote_om = dbus.Interface( bus.get_object(constants.BLUEZ_SERVICE_NAME, '/'), constants.DBUS_OM_IFACE) objects = remote_om.GetManagedObjects() for o, props...
6b5f49a5908948a54f99438a38865293fca51cc7
11,387
def leaky_relu(x, slope=0.2): """Leaky Rectified Linear Unit function. This function is expressed as :math:`f(x) = \max(x, ax)`, where :math:`a` is a configurable slope value. Args: x (~chainer.Variable): Input variable. slope (float): Slope value :math:`a`. Returns: ~chai...
cf7624309543e24c70832249116b74d56c26d1f9
11,388
def GetConfig(user_config): """Decide number of vms needed to run oldisim.""" config = configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) config['vm_groups']['default']['vm_count'] = (FLAGS.oldisim_num_leaves + NUM_DRIVERS + NUM_ROOTS) return config
b04380fe6dbc84ef4c353dd34354581fa69aac89
11,389
import os import shutil def build_tstuser_dir(username): """ Create a directory with files and return its structure in a list. :param username: str :return: tuple """ # md5("foo") = "acbd18db4cc2f85cedef654fccc4a4d8" # md5("bar") = "37b51d194a7513e45b56f6524f2d51f2" # md5("spam") =...
bb6b62a11a778f83cd8161077dbcab5afb40d64c
11,390
import re def gen_answer(question, passages): """由于是MLM模型,所以可以直接argmax解码。 """ all_p_token_ids, token_ids, segment_ids = [], [], [] for passage in passages: passage = re.sub(u' |、|;|,', ',', passage) p_token_ids, _ = tokenizer.encode(passage, maxlen=max_p_len + 1) q_token_ids, _...
536880c1318cc193be19561183e652c7668eb09b
11,391
def compile(function_or_sdfg, *args, **kwargs): """ Obtain a runnable binary from a Python (@dace.program) function. """ if isinstance(function_or_sdfg, dace.frontend.python.parser.DaceProgram): sdfg = dace.frontend.python.parser.parse_from_function( function_or_sdfg, *args, **kwargs) el...
7504344e8e9df5a395e51af1211db286188f3fcb
11,392
import re def is_untweeable(html): """ I'm not sure at the moment what constitutes untweeable HTML, but if we don't find DVIS in tiddlywiki, that is a blocker """ # the same regex used in tiddlywiki divs_re = re.compile( r'<div id="storeArea"(.*)</html>', re.DOTALL ) return bool(divs_re.search(html))
face6c6d30b6e26ffa3344ed8e42ed7d44cf2ea5
11,393
from typing import Optional def create_1m_cnn_model(only_digits: bool = False, seed: Optional[int] = 0): """A CNN model with slightly under 2^20 (roughly 1 million) params. A simple CNN model for the EMNIST character recognition task that is very similar to the default recommended model from `create_conv_dropo...
87353f8bd8e3b3d7602ad3dcd92b717b2590285b
11,394
def _check_index(target_expr, index_expr): """ helper function for making sure that an index is valid :param target_expr: the target tensor :param index_expr: the index :return: the index, wrapped as an expression if necessary """ if issubclass(index_expr.__class__, _Expression): in...
96d5bf6d6d19bfca0de30ea9915a38237cf9c80f
11,395
def create_access_token(user: UserModel, expires_delta: timedelta = None) -> str: """ Create an access token for a user :param user: CTSUser -> The user :param expires_delta: timedelta -> The expiration of the token. If not given a default will be used :return: str -> A token """ load_all_co...
d5ba53f0ecc7e7755988ad2540e4cd4c520b30dd
11,396
def is_async_mode(): """Tests if we're in the async part of the code or not.""" async def f(): """Unasync transforms async functions in sync functions.""" return None obj = f() if obj is None: return False obj.close() # prevent unawaited coroutine warning return True
8e515efc767f75c4b90486089f0d8a7203da59d7
11,397
def remove_arm(frame): """ Removes the human arm portion from the image. """ ##print("Removing arm...") # Cropping 15 pixels from the bottom. height, width = frame.shape[:2] frame = frame[:height - 15, :] ##print("Done!") return frame
99b998da87f1aa2eca0a02b67fc5adc411603ee4
11,398
def cumulative_spread(array, x): """ >>> import numpy as np >>> a = np.array([1., 2., 3., 4.]) >>> cumulative_spread(a, 0.) array([0., 0., 0., 0.]) >>> cumulative_spread(a, 5.) array([1., 2., 2., 0.]) >>> cumulative_spread(a, 6.) array([1., 2., 3., 0.]) >>> cumulative_spread(a, 1...
c6966a97945f30cce6a794325091a31716a36e54
11,399