content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def get_img_full_path(path): """ Checks if file can be found by path specified in the input. Returns the same as input if can find, otherwise joins current directory full path with path from input and returns it. :param path: Relative of full path to the image. :return: Relative of full path...
d549cd09035ebd6213f1b31c1c2eee4e64dcdce8
3,654,200
def max_pool_2x2(input_): """ Perform max pool with 2x2 kelner""" return tf.nn.max_pool(input_, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
b85ccfaafbdcf5d703dffab65e188ffab52ebce9
3,654,201
import tqdm def remove_numerals(df, remove_mixed_strings=True): """Removes rows from an ngram table with words that are numerals. This does not include 4-digit numbers which are interpreted as years. Arguments: df {Pandas dataframe} -- A dataframe of with columns 'word', 'count'. Keyword ...
4c3d0468456e08b1a0579a8b73a21221cae17676
3,654,202
def generate_json(args, df, num_changes, start_dt, finish_dt, projects, projects_map, not_found_proj, group=None, groups=[]): """ Returns json report from a dataframe for a specific project """ log.debug('Generating %s report for %s', args.report_format, group) lo...
1f90e73ad26f87cea0052f157ac3167f54f8b027
3,654,203
def b32_ntop(*args): """LDNS buffer.""" return _ldns.b32_ntop(*args)
b43bc9b1b112f7815ec3c280d055676e7255adcc
3,654,204
import logging import sys import os def get_logger(filename, logger_name=None): """set logging file and format Args: filename: str, full path of the logger file to write logger_name: str, the logger name, e.g., 'master_logger', 'local_logger' Return: logger: python logger """ ...
e549cdd7198961662f28390e09480d05f5ad14b4
3,654,205
from typing import Callable from typing import Dict import torch def infer_feature_extraction_pytorch( model: PreTrainedModel, run_on_cuda: bool ) -> Callable[[Dict[str, torch.Tensor]], torch.Tensor]: """ Perform Pytorch inference for feature extraction task :param model: Pytorch model (sentence-trans...
18f935607c824c2122f68ea1ec9a7bcb50604ac8
3,654,206
def editRole(userSource, oldName, newName): """Renames a role in the specified user source. When altering the Gateway System User Source, the Allow User Admin setting must be enabled. Args: userSource (str): The user source in which the role is found. Blank will use the default use...
f72796de14ff5f8c4314a5d31fe4fcf42cb883ec
3,654,207
def compute_bspline_dot_product_derivatives(basis_features, basis_dimension): """ Compute dot products of B-splines and their derivatives. Input: - basis_features: dict Contain information on the basis for each state - basis_dimension: dict Give the number of basis f...
a8ba13b23bb009eb81d57792abeced6fb8715b07
3,654,208
import os def validate_table(config, table): """Run VALVE validation on a table. :param config: valve config dictionary :param table: path to table :return: list of errors """ errors = [] table_name = os.path.splitext(os.path.basename(table))[0] table_details = config["table_details"]...
3b8a1517219d4b8b0db5042200f1c62700cabe94
3,654,209
def beam_hardening_correction(mat, q, n, opt=True): """ Correct the grayscale values of a normalized image using a non-linear function. Parameters ---------- mat : array_like Normalized projection image or sinogram image. q : float Positive number. Recommended range [0.005, ...
d113ff33c2d688f460cf2bac62cdd8a26b890ce5
3,654,210
def cargar_recursos_vectores_transpuestos(): """ Se carga la informacion para poder calcular los vectores transpuestos """ # Se crea el df filename = 'csv/' + conf.data['env']['path'] + '/vectores_transpuestos.csv' recursos_v_transpuestos = pd.read_csv(filename) # Se cambia el nombre de los ...
f982fd22bbdfd2d7d389787bf7f923feb9abf66f
3,654,211
def read_pdb(file_name, exclude=('SOL',), ignh=False, modelidx=1): """ Parse a PDB file to create a molecule. Parameters ---------- filename: str The file to read. exclude: collections.abc.Container[str] Atoms that have one of these residue names will not be included. ignh: ...
d7412b96adef5505676a80e5cdf3fe5e63a3b096
3,654,212
def sao_isomorficas(texto1: str, texto2: str) -> bool: """ >>> sao_isomorficas('egg', 'add') True >>> sao_isomorficas('foo', 'bar') False >>> sao_isomorficas('eggs', 'add') False """ # Algoritmo O(n) em tempo e memória letras_encontradas = {} if len(texto1) != len(texto2): ...
a1f2c00a50b69cb18c32a299d50cbd3a35dcbe5e
3,654,213
def _is_no_args(fn): """Check if function has no arguments. """ return getargspec(fn).args == []
29cb096323c69dd067bf4759a557734443a82ed5
3,654,214
def failure(parsed_args): """ :param :py:class:`argparse.Namespace` parsed_args: :return: Nowcast system message type :rtype: str """ logger.critical( f"{parsed_args.model_config} {parsed_args.run_type} FVCOM VH-FR run for " f'{parsed_args.run_date.format("YYYY-MM-DD")} ' ...
e6744bfd61458497b5a70d7d28712385a8488a98
3,654,215
def good_AP_finder(time,voltage): """ This function takes the following input: time - vector where each element is a time in seconds voltage - vector where each element is a voltage at a different time We are assuming that the two vectors are in correspondance (meaning t...
c13897b7bf5335cae20f65db853e7a214ec570c5
3,654,216
from typing import Dict from typing import Any import tqdm def parse(excel_sheets: Dict[Any, pd.DataFrame], dictionary: Dict[str, Any], verbose: bool = False) -> pd.DataFrame: """Parse sheets of an excel file according to instructions in `dictionary`. """ redux_dict = recursive_traver...
88028fef19eda993680e89c58954c04a215a2fdd
3,654,217
def build_LAMP(prob,T,shrink,untied): """ Builds a LAMP network to infer x from prob.y_ = matmul(prob.A,x) + AWGN return a list of layer info (name,xhat_,newvars) name : description, e.g. 'LISTA T=1' xhat_ : that which approximates x_ at some point in the algorithm newvars : a tuple of layer-...
392050992846aeb1a16e70fe6e43c386e11915e5
3,654,218
def coeffVar(X, precision=3): """ Coefficient of variation of the given data (population) Argument: X: data points, a list of int, do not mix negative and positive numbers precision (optional): digits precision after the comma, default=3 Returns: float, the cv (measure of dispers...
e92505e79c4d10a5d56ec35cd2b543872f6be59c
3,654,219
def tostring(node): """ Generates a string representation of the tree, in a format determined by the user. @ In, node, InputNode or InputTree, item to turn into a string @ Out, tostring, string, full tree in string form """ if isinstance(node,InputNode) or isinstance(node,InputTree): return node.p...
8e6cab92b898bd99b5c738b26fc9f8d79aef0750
3,654,220
from typing import Dict import random def pick_char_from_dict(char: str, dictionary: Dict[str, str]) -> str: """ Picks a random format for the givin letter in the dictionary """ return random.choice(dictionary[char])
c593166ef7cb8c960b8c4be8fa0f8a20ec616f00
3,654,221
from typing import List def bmeow_to_bilou(tags: List[str]) -> List[str]: """Convert BMEOW tags to the BILOU format. Args: tags: The BMEOW tags we are converting Raises: ValueError: If there were errors in the BMEOW formatting of the input. Returns: Tags that produce the sam...
0081b7691a743fe3e28118cbb571708809fbd485
3,654,222
def site_sold_per_category(items): """For every category, a (site, count) pair with the number of items sold by the site in that category. """ return [(site, [(cat, total_sold(cat_items)) for cat, cat_items in categories]) for site, categories in categ...
7b224f3e0a786aef497fad99359e525896eb8441
3,654,223
from typing import List import ctypes def swig_py_object_2_list_int(object, size : int) -> List[int]: """ Converts SwigPyObject to List[float] """ y = (ctypes.c_float * size).from_address(int(object)) new_object = [] for i in range(size): new_object += [int(y[i])] return new_ob...
064a9a1e43884a9f989bec0b31d6d19705764b64
3,654,224
def ParseAttributesFromData(attributes_data, expected_param_names): """Parses a list of ResourceParameterAttributeConfig from yaml data. Args: attributes_data: dict, the attributes data defined in command_lib/resources.yaml file. expected_param_names: [str], the names of the API parameters that the A...
73cfc67dddd4d1385bebd0297bd84233c9546dd4
3,654,225
from typing import Tuple from typing import Union async def reactionFromRaw(payload: RawReactionActionEvent) -> Tuple[Message, Union[User, Member], emojis.BasedEmoji]: """Retrieve complete Reaction and user info from a RawReactionActionEvent payload. :param RawReactionActionEvent payload: Payload describing ...
36ae16e2b1ffb3df1d5c68ae903b95556446138f
3,654,226
import array def poisson2d(N,dtype='d',format=None): """ Return a sparse matrix for the 2d poisson problem with standard 5-point finite difference stencil on a square N-by-N grid. """ if N == 1: diags = asarray( [[4]],dtype=dtype) return dia_matrix((diags,[0]), shape=(1,1)).a...
089088f468e84dce865bbb26707714617e16f3f6
3,654,227
import random def get_factory(): """随机获取一个工厂类""" return random.choice([BasicCourseFactory, ProjectCourseFactory])()
c71401a2092618701966e5214f85c67a6520b1c9
3,654,228
def delay_class_factory(motor_class): """ Create a subclass of DelayBase that controls a motor of class motor_class. Used in delay_instace_factory (DelayMotor), may be useful for one-line declarations inside ophyd Devices. """ try: cls = delay_classes[motor_class] except KeyError: ...
264d68f7d3db164c5c133e68f943b789db52fc8b
3,654,229
import os def check_and_makedir(folder_name): """ Does a directory exist? if not create it. """ if not os.path.isdir(folder_name): os.mkdir(folder_name) return False else: return True
2f2632fc245c04add6a680fa755932d3a082168b
3,654,230
import os import fnmatch def _get_all_files_in_directory(dir_path, excluded_glob_patterns): """Recursively collects all files in directory and subdirectories of specified path. Args: dir_path: str. Path to the folder to be linted. excluded_glob_patterns: set(str). Set of all glob patterns...
42a7f1220fd54b08b83dc9d89beef0c63c9d5cd0
3,654,231
def lonlat2px_gt(img, lon, lat, lon_min, lat_min, lon_max, lat_max): """ Converts a pair of lon and lat to its corresponding pixel value in an geotiff image file. Parameters ---------- img : Image File, e.g. PNG, TIFF Input image file lon : float Longitude lat : float ...
39c1aeb63d38fdac383c510913f50f177d274a04
3,654,232
import torch def patchwise_contrastive_metric(image_sequence: torch.Tensor, kpt_sequence: torch.Tensor, method: str = 'norm', time_window: int = 3, patch_size: tuple = (7, 7), ...
8591d9359773a9b0445974da3926b3cade64d830
3,654,233
import scipy def array_wishart_rvs(df, scale, **kwargs): """ Wrapper around scipy.stats.wishart to always return a np.array """ if np.size(scale) == 1: return np.array([[ scipy.stats.wishart(df=df, scale=scale, **kwargs).rvs() ]]) else: return scipy.stats.wishart(df...
d14b26d8f1b05de1ac961499d96c604028fca379
3,654,234
def get_mpl_colors(): """ ================== Colormap reference ================== Reference for colormaps included with Matplotlib. This reference example shows all colormaps included with Matplotlib. Note that any colormap listed here can be reversed by appending "_r" (e.g., "pin...
5926f878b59f3f41282968c67020f611ad928f28
3,654,235
async def async_setup_entry(hass, entry): """Set up Jenkins from a config entry.""" hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) return True
c46912d11630c36effc07eed3273e42325c9b2b8
3,654,236
import math def signal_to_dataset(raw, fsamp, intvs, labels): """Segmentize raw data into list of epochs. returns dataset and label_array : a list of data, each block is 1 second, with fixed size. width is number of channels in certain standard order. Args: raw: EEG signals. Shap...
340bbb91bd6a36d1d3a20d0689e25c29e5b879c5
3,654,237
def project_dynamic_property_graph(graph, v_prop, e_prop, v_prop_type, e_prop_type): """Create project graph operation for nx graph. Args: graph (:class:`nx.Graph`): A nx graph. v_prop (str): The node attribute key to project. e_prop (str): The edge attribute key to project. v_p...
6e54180a4ef257c50a02104cc3a4cbbae107d233
3,654,238
def eqfm_(a, b): """Helper for comparing floats AND style names.""" n1, v1 = a n2, v2 = b if type(v1) is not float: return eq_(a, b) eqf_(v1, v2) eq_(n1, n2)
1ee53203baa6c8772a4baf240f68bb5898a5d516
3,654,239
def flatten_comment(seq): """Flatten a sequence of comment tokens to a human-readable string.""" # "[CommentToken(value='# Extra settings placed in ``[app:main]`` section in generated production.ini.\\n'), CommentToken(value='# Example:\\n'), CommentToken(value='#\\n'), CommentToken(value='# extra_ini_settings...
56104eb6e0109b6c677964cd1873244ff05f27fc
3,654,240
def get_community(community_id): """ Verify that a community with a given id exists. :param community_id: id of test community :return: Community instance :return: 404 error if doesn't exist """ try: return Community.objects.get(pk=community_id) except Community.DoesNotExist: ...
33d16db86c53b7dd68dec8fe80639b560e41f457
3,654,241
import csv import pprint def load_labeled_info(csv4megan_excell, audio_dataset, ignore_files=None): """Read labeled info from spreat sheet and remove samples with no audio file, also files given in ignore_files """ if ignore_files is None: ignore_files = set() with open(csv4megan_excel...
f196b02c8667ebe5e8d2d89a79be78c6eb838afe
3,654,242
def de_dupe_list(input): """de-dupe a list, preserving order. """ sam_fh = [] for x in input: if x not in sam_fh: sam_fh.append(x) return sam_fh
bbf1936f21c19195369e41b635bf0f99704b3210
3,654,243
def donwload_l10ns(): """Download all l10ns in zip archive.""" url = API_PREFIX + 'download/' + FILENAME + KEY_SUFFIX l10ns_file = urllib2.urlopen(url) with open('all.zip','wb') as f: f.write(l10ns_file.read()) return True
26770dfc8f32947c1a32a287f811e95ffe314822
3,654,244
def _constant_velocity_heading_from_kinematics(kinematics_data: KinematicsData, sec_from_now: float, sampled_at: int) -> np.ndarray: """ Computes a constant velocity baseline for given kinematics data, time window ...
2b6781ceb9e012486d3063b8f3cff29164ff8743
3,654,245
def arg_int(name, default=None): """ Fetch a query argument, as an integer. """ try: v = request.args.get(name) return int(v) except (ValueError, TypeError): return default
110088655bc81363e552f31d9bbd8f4fa45abd1b
3,654,246
import os def db(app, request): """Session-wide test database.""" if os.path.exists(os.path.join(INSTANCE_FOLDER_PATH, 'test.sqlite')): os.unlink(os.path.join(INSTANCE_FOLDER_PATH, 'test.sqlite')) def teardown(): _db.drop_all() os.unlink(os.path.join(INSTANCE_FOLDER_PATH, 'test.sq...
c14b929a9fac6978a7dcb5b0815297598c8a94e1
3,654,247
def adapter_rest(request, api_module_rest, api_client_rest): """Pass.""" return { "adapter": request.param, "api_module": api_module_rest, "api_client": api_client_rest, }
8b96313cb190f6f8a97a853e24a5fcfade291d76
3,654,248
import numpy import os import shutil def extract(lon, lat, dep, prop=['rho', 'vp', 'vs'], **kwargs): """ Simple CVM-S extraction lon, lat, dep: Coordinate arrays prop: 'rho', 'vp', or 'vs' nproc: Optional, number of processes Returns: (rho, vp, vs) material arrays """ lon = numpy.asa...
1503faebece8accb380ad47c0e7108a3313a2080
3,654,249
def remove_quotes(string): """Function to remove quotation marks surrounding a string""" string = string.strip() while len(string) >= 3 and string.startswith('\'') and string.endswith('\''): string = string[1:-1] string = quick_clean(string) string = quick_clean(string) return string
c6585c054abaef7248d30c1814fb13b6b9d01852
3,654,250
def compute_list_featuretypes( data, list_featuretypes, fourier_n_largest_frequencies, wavelet_depth, mother_wavelet, ): """ This function lets the user choose which combination of features they want to have computed. list_featuretypes: "Basic" - min, max, mean, kurt ,skew, ...
f1c8fea04a01f6b7a3932434e27aba7ea2e17948
3,654,251
def select(locator): """ Returns an :class:`Expression` for finding selects matching the given locator. The query will match selects that meet at least one of the following criteria: * the element ``id`` exactly matches the locator * the element ``name`` exactly matches the locator * the elemen...
a3cd093a62d6c926fd9f782cdec35eadc34eba67
3,654,252
def send_image(filename): """Route to uploaded-by-client images Returns ------- file Image file on the server (see Flask documentation) """ return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
68b99ca59d6d4b443a77560d3eb1913422407764
3,654,253
def swissPairings(): """Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. Each player is paired with another player with an equal or nearly-equal win record, that is, a playe...
f83a8a108f2d926c948999014f0dbb79a3b1c428
3,654,254
import torch def split(data, batch): """ PyG util code to create graph batches """ node_slice = torch.cumsum(torch.from_numpy(np.bincount(batch)), 0) node_slice = torch.cat([torch.tensor([0]), node_slice]) row, _ = data.edge_index edge_slice = torch.cumsum(torch.from_numpy(np.bincount(batch[row])), 0) edge_...
69af8b969d7f0da28a1f7fda951f64974c238da0
3,654,255
def _get_shadowprice_data(scenario_id): """Gets data necessary for plotting shadow price :param str/int scenario_id: scenario id :return: (*tuple*) -- interconnect as a str, bus data as a data frame, lmp data as a data frame, branch data as a data frame and congestion data as a data frame ...
57488b7ff6984cc292dce3bf76d18d0b2585b7ff
3,654,256
import json def get_city_reviews(city): """ Given a city name, return the data for all reviews. Returns a pandas DataFrame. """ with open(f"{DATA_DIR}/{city}/review.json", "r") as f: review_list = [] for line in f: review = json.loads(line) review_list.appen...
e0723ab90dafc53059677928fb553cf197abecc1
3,654,257
def extract_rows_from_table(dataset, col_names, fill_null=False): """ Extract rows from DB table. :param dataset: :param col_names: :return: """ trans_dataset = transpose_list(dataset) rows = [] if type(col_names).__name__ == 'str': col_names = [col_names] for col_name in col...
91371215f38a88b93d08c467303ccbd45f57b369
3,654,258
def CalculateHydrogenNumber(mol): """ ################################################################# Calculation of Number of Hydrogen in a molecule ---->nhyd Usage: result=CalculateHydrogenNumber(mol) Input: mol is a molecule object. ...
0b9fbad14c8e9f46beab5208ab0f929fef1ab263
3,654,259
def check_update (): """Return the following values: (False, errmsg) - online version could not be determined (True, None) - user has newest version (True, (version, url string)) - update available (True, (version, None)) - current version is newer than online version """ version...
8bba3e7fbe11ce6c242f965450628dc94b6c2c0b
3,654,260
import torch def count_regularization_baos_for_both(z, count_tokens, count_pieces, mask=None): """ Compute regularization loss, based on a given rationale sequence Use Yujia's formulation Inputs: z -- torch variable, "binary" rationale, (batch_size, sequence_length) percentage -- the ...
7925c8621866a20f0c6130cd925afffe144e1c7c
3,654,261
def unsqueeze_samples(x, n): """ """ bn, d = x.shape x = x.reshape(bn//n, n, d) return x
0c7b95e97df07aea72e9c87996782081763664cf
3,654,262
def f_snr(seq): """compute signal to noise rate of a seq Args: seq: input array_like sequence paras: paras array, in this case should be "axis" """ seq = np.array(seq, dtype=np.float64) result = np.mean(seq)/float(np.std(seq)) if np.isinf(result): print "marker" result = 0 return result
b018b5e4c249cfafcc3ce8b485c917bfcdd19ce2
3,654,263
def _lorentzian_pink_beam(p, x): """ @author Saransh Singh, Lawrence Livermore National Lab @date 03/22/2021 SS 1.0 original @details the lorentzian component of the pink beam peak profile obtained by convolution of gaussian with normalized back to back exponentials. more details can be found in...
7de93743da63ab816133e771075a8e8f0386ad35
3,654,264
def get_q_HPU_ave(Q_HPU): """1時間平均のヒートポンプユニットの平均暖房出力 (7) Args: Q_HPU(ndarray): 1時間当たりのヒートポンプユニットの暖房出力 (MJ/h) Returns: ndarray: 1時間平均のヒートポンプユニットの平均暖房出力 (7) """ return Q_HPU * 10 ** 6 / 3600
fdf339d7f8524f69409711d4daefd1e2aaccbc76
3,654,265
def particles(t1cat): """Return a list of the particles in a T1 catalog DataFrame. Use it to find the individual particles involved in a group of events.""" return particles_fromlist(t1cat.particles.tolist())
38f9a077b7bab55b76a19f467f596ddb28e40c60
3,654,266
def interp_coeff_lambda3(i2,dx2,nx): """ NOTE: input and output index from 0 to nx-1 !!! """ i2=i2+1 # TODO, waiting for script to be updated # Find index of other cells i1 = i2 - 1 i3 = i2 + 1 i4 = i2 + 2 # Find normalised distance to other cells dx1 = dx2 + 1.0 dx3 = ...
560125921588e6302da8ab16e2d7394169fdcbea
3,654,267
def prime_list(num): """ This function returns a list of prime numbers less than natural number entered. :param num: natural number :return result: List of primes less than natural number entered """ prime_table = [True for _ in range(num+1)] i = 2 while i ** 2 <= num: if prime_...
c8e05aae2a59c229cfafb997469dd8ccacdda0fc
3,654,268
import time def check_deadline_exceeded_and_store_partial_minimized_testcase( deadline, testcase_id, job_type, input_directory, file_list, file_to_run_data, main_file_path): """Store the partially minimized test and check the deadline.""" testcase = data_handler.get_testcase_by_id(testcase_id) store_min...
443c09a8b5bcd8141f721b8ea90348879bc3b8c5
3,654,269
import ipaddress def _item_to_python_repr(item, definitions): """Converts the given Capirca item into a typed Python object.""" # Capirca comments are just appended to item strings s = item.split("#")[0].strip() # A reference to another network if s in definitions.networks: return s ...
9881e304e923eb2cea8223224273f4c9ef81696b
3,654,270
import numpy def floor_divide(x1, x2, out=None, where=True, **kwargs): """ Return the largest integer smaller or equal to the division of the inputs. It is equivalent to the Python ``//`` operator and pairs with the Python ``%`` (`remainder`), function so that ``a = a % b + b * (a // b)`` up to r...
9269d088c0893b9b6b4c3b27e8dc83c4493ac2c9
3,654,271
from typing import Callable import click def node_args_argument(command: Callable[..., None]) -> Callable[..., None]: """ Decorate a function to allow choosing arguments to run on a node. """ function = click.argument( 'node_args', type=str, nargs=-1, required=True, ...
89365a41b7665cf291f5c15852db81e89aeef9a7
3,654,272
import functools import unittest def _tag_error(func): """Decorates a unittest test function to add failure information to the TestCase.""" @functools.wraps(func) def decorator(self, *args, **kwargs): """Add failure information to `self` when `func` raises an exception.""" self.test_faile...
a2818c63647410abea3fde0b7f4fdae667b558bf
3,654,273
import fnmatch import sys import traceback import logging import os def create_drizzle_products(total_obj_list, custom_limits=None): """ Run astrodrizzle to produce products specified in the total_obj_list. Parameters ---------- total_obj_list: list List of TotalProduct objects, one objec...
838ad7e0f3590e3dab4f7383f33f9c5d5c55e6d7
3,654,274
from datetime import datetime def get_submission_praw(n, sub, n_num): """ Returns a list of results for submission in past: 1st list: current result from n hours ago until now 2nd list: prev result from 2n hours ago until n hours ago """ mid_interval = datetime.today() - timedelta(hours=n) ...
692af49736fac07a2de51d1cd0c4abcfe7bb8ee3
3,654,275
import scipy def memory_kernel_logspace(dt, coeffs, dim_x, noDirac=False): """ Return the value of the estimated memory kernel Parameters ---------- dt: Timestep coeffs : Coefficients for diffusion and friction dim_x: Dimension of visible variables noDirac: Remove the dirac at time ze...
21e6aed08bebd91f359efa216ab1331cf9ace310
3,654,276
def _is_constant(x, atol=1e-7, positive=None): """ True if x is a constant array, within atol """ x = np.asarray(x) return (np.max(np.abs(x - x[0])) < atol and (np.all((x > 0) == positive) if positive is not None else True))
0b272dd843adbd4eaa4ebbe31efe6420de05a6dd
3,654,277
def estimate_M(X, estimator, B, ratio): """Estimating M with Block or incomplete U-statistics estimator :param B: Block size :param ratio: size of incomplete U-statistics estimator """ p = X.shape[1] x_bw = util.meddistance(X, subsample = 1000)**2 kx = kernel.KGauss(x_bw) if estimator ==...
656b83eac9e522b1feb20a4b5b56649b9553ecb0
3,654,278
def query_yes_no(question, default="yes"): """Queries user for confimration""" valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = "...
58e9bba831155ca9f4d4879a5e960949757b0562
3,654,279
import base64 import binascii def decode(password, encoded, notice): """ :type password: str :type encoded: str """ dec = [] try: encoded_bytes = base64.urlsafe_b64decode(encoded.encode()).decode() except binascii.Error: notice("Invalid input '{}'".format(encoded)) ...
5cf82bfbbe7eee458914113f648dadbe7b15dee8
3,654,280
def read_file_unlabelled_data(file_name): """ read_file_unlabelled_data reades from file_name These files are to be in csv-format with one token per line (see the example project). returns text_vector: Ex: [['7_7', 'perhaps', 'there', 'is', 'a_a', 'better', 'way', '._.'], ['2_2', 'Why', 'are', ...
f171ac6c4728aa67ef59b523acc0a006b3b4f16a
3,654,281
from functools import reduce def replace(data, replacements): """ Allows to performs several string substitutions. This function performs several string substitutions on the initial ``data`` string using a list of 2-tuples (old, new) defining substitutions and returns the resulting string. """ r...
37b2ad5b9b6d50d81a8c1bcded9890de3c840722
3,654,282
def fake_kafka() -> FakeKafka: """Fixture for fake kafka.""" return FakeKafka()
35fdcf2030dda1cab2be1820549f67dc246cf88f
3,654,283
from typing import Union import operator def rr20(prec: pd.Series) -> Union[float, int]: """Function for count of heavy precipitation (days where rr greater equal 20mm) Args: prec (list): value array of precipitation Returns: np.nan or number: the count of icing days """ assert ...
4686eccac5be53b4a888d8bf0649c72e65d81bdb
3,654,284
def get_neg_label(cls_label: np.ndarray, num_neg: int) -> np.ndarray: """Generate random negative samples. :param cls_label: Class labels including only positive samples. :param num_neg: Number of negative samples. :return: Label with original positive samples (marked by 1), negative samples (m...
3cd0ad5c1973eff969330f014c405f39092b733b
3,654,285
def G12(x, a): """ Eqs 20, 24, 25 of Khangulyan et al (2014) """ alpha, a, beta, b = a pi26 = np.pi ** 2 / 6.0 G = (pi26 + x) * np.exp(-x) tmp = 1 + b * x ** beta g = 1.0 / (a * x ** alpha / tmp + 1.0) return G * g
6b84d5f5978a9faf8c9d77a2b9351f73f5717f48
3,654,286
def binomial(n, k): """ binomial coefficient """ if k < 0 or k > n: return 0 if k == 0 or k == n: return 1 num = 1 den = 1 for i in range(1, min(k, n - k) + 1): # take advantage of symmetry num *= (n + 1 - i) den *= i c = num // den return c
78910202202f749f8e154b074a55f6a5ddf91f64
3,654,287
def pagination(page): """ Generates the series of links to the pages in a paginated list. """ paginator = page.paginator page_num = page.number #pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page if False: #not pagination_required: page_range = [] e...
60d90adfbeceab9d159652b641e60da8fa995954
3,654,288
def bubbleSort(arr): """ >>> bubbleSort(arr) [11, 12, 23, 25, 34, 54, 90] """ n = len(arr) for i in range(n-1): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr
28bc9d505ef44a4b403c0f91a971cccf74644c5a
3,654,289
def generate_kronik_feats(fn): """Generates features from a Kronik output file""" header = get_tsv_header(fn) return generate_split_tsv_lines(fn, header)
8b98f346ef5d833e0bfb876a7985c8bb3ced905c
3,654,290
import time import sys def regressor_contrast(model1:RegressorMixin, model2:RegressorMixin, test_data:pd.DataFrame, label_data:pd.Series, threshold:int=10)->pd.DataFrame: """Compute 11 metrics to compare a Sckit-learn regress...
18c55de497009555a30ffd9a3a2b5c5a0f1b53ee
3,654,291
def delete_product(uuid: str, db: Session = Depends(auth)): """Delete a registered product.""" if product := repo.get_product_by_uuid(db=db, uuid=uuid): if product.taken: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Cannot delete prod...
97aa45eec0ae98a58984f8ca97d584b5a715cba6
3,654,292
import functools def CreateMnemonicsC(mnemonicsIds): """ Create the opcodes arrays for C header files. """ opsEnum = "typedef enum {\n\tI_UNDEFINED = 0, " pos = 0 l2 = sorted(mnemonicsIds.keys()) for i in l2: s = "I_%s = %d" % (i.replace(" ", "_").replace(",", ""), mnemonicsIds[i]) if i != l2[-1]: s += ",...
a20a01fbefc1175c24144753264edc938258cdca
3,654,293
import math def create_windows(c_main, origin, J=None, I=None, depth=None, width=None): """ Create windows based on contour and windowing parameters. The first window (at arc length = 0) is placed at the spline origin. Note: to define the windows, this function uses pseudo-radial and pseudo-angul...
c5e3989b8f8f0f558cdc057b6f3bb9901c4363cf
3,654,294
from bs4 import BeautifulSoup def extractsms(htmlsms) : """ extractsms -- extract SMS messages from BeautifulSoup tree of Google Voice SMS HTML. Output is a list of dictionaries, one per message. """ msgitems = [] # accum message items here # Extract all conversations by searching ...
e31a66ae5ee56faf4eab131044c395fcd8de3a2a
3,654,295
def load_ch_wubi_dict(dict_path=e2p.E2P_CH_WUBI_PATH): """Load Chinese to Wubi Dictionary. Parameters --------- dict_path : str the absolute path to chinese2wubi dictionary. In default, it's E2P_CH_WUBI_PATH. Returns ------- dict : Dictionary a mapping between Chine...
e9297968b5dc4d1811659084e03ef0b2156c8a00
3,654,296
def middle_flow(middle_inputs: Tensor) -> Tensor: """ Middle flow Implements the second of the three broad parts of the model :param middle_inputs: middle_inputs: Tensor output generate by the Entry Flow, having shape [*, new_rows, new_cols, 728] :return: Out...
80fedffbb6da2f3e0b99a931d66d593bf627bdbe
3,654,297
def feature_extraction(sample_index, labels, baf, lrr, rawcopy_pred, data_shape, margin=10000, pad_val=-2): """ Extract features at sample index :param sample_index: sample index :param labels: break point labels :param baf: b-allele frequency values :param lrr: ...
2b70229d3e4021d4a0cce9bf7dce2222956e299d
3,654,298
def get_filename(file_fullpath): """ Returns the filename without the full path :param file_fullpath: :return: Returns the filename """ filename = file_fullpath.split("/")[-1].split(".")[0] return filename
903cb26c89d1d18c9ebafe1a468c7fa66c51f119
3,654,299