content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def record_mode(request): """Manage compatibility with DD client libraries.""" mode = os.getenv("RECORD", "false") if mode is not None: if mode == "none": request.config.option.disable_vcr = True else: setattr( request.config.option, ...
a68af5c9449bf300fec18c51168e2f9096038b1f
3,633,700
def get_number_of_engine_threads(): """ Returns the number of engine threads. """ command = 'ps aux | grep "./build/engine" | grep -v "grep" | wc -l' n_threads = int(common.run_local_cmd(command, get_output = True)) return n_threads
843bec78af34d97f73b42447180636b5fe171d17
3,633,701
def metadata_repr_as_list(metadata_list): """ Turn a list of metadata into a list of printable representations """ output = [] for metadata_dict in metadata_list: try: output.append('%s - %s' % (MetadataType.objects.get( pk=metadata_dict['id']), metadata_dict.get(...
ef6cae970f98311b150fde019b7479b5fd35a573
3,633,702
def dip_reconstructor(dataset='ellipses', name=None): """ :param dataset: Can be 'ellipses' or 'lodopab' :return: The Deep Image Prior (DIP) method for the specified dataset """ try: standard_dataset = load_standard_dataset(dataset) params = Params.load('{}_dip'.format(dataset)) ...
dcd34307b9d69ed5ad4cbbf8ee61063c02c8d592
3,633,703
def convert_listofrollouts(paths): """ Take a list of rollout dictionaries and return separate arrays, where each array is a concatenation of that array from across the rollouts """ observations = np.concatenate([path["observation"] for path in paths]) actions = np.concatenate([p...
f3cc52fa56f26985c1cb69c991bc28ff4f19b118
3,633,704
def get_iex_corporate_actions(start=None, **kwargs): """ Top-level function to retrieve IEX Corporate Actions from the ref-data endpoints Parameters ---------- start: datetime.datetime, default None, optional A month to use for retrieval (a datetime object) kwargs: Additional Reques...
c355f70ff84f5be7a808dccad02bd644f21edc5f
3,633,705
import math def mc_generation_costs(df_ren, h2_demand, year_diff, capex_extra, capex_h2, lifetime_hours, electrolyser_efficiency, elec_opex, other_capex_elec, water_cost, capex_wind, opex_wind, capex_solar, opex_factor_solar, ...
6ba407ecda6619293b811c7cab6c71a95284c2bc
3,633,706
def relax(u, f, nu): """ Weighted Jacobi """ n = len(u) Dinv = 1.0 / (2.0 * ((n+1)**2)) omega = 2.0 / 3.0 unew = u.copy() for steps in range(nu): unew = unew + omega * Dinv * residual(unew, f) return unew
5216744a04e93ad5dc22d5f01f47bc3c5c2ccbe1
3,633,707
import requests import sys def doi_to_id(doi, timestamp): """Query translator to convert book DOI to specified schema.""" params = { 'uri': doi, 'filter': f'uri_scheme:{URI_SCHEME}', 'strict': URI_STRICT } headers = {'Authorization': AUTH} if AUTH else {} response = reque...
f260229eeeffe47f3e8d58e4262530476dc1904b
3,633,708
def forward_influence_centrality(graph, weight=None): """Returns the forward influence centrality of the nodes in a network as an array. Parameters ---------- graph : Graph, array A NetworkX graph or numpy/sparse array weight : string or None If you have weighted edges i...
684b6342b96b1807ec5dd841b23a476703813298
3,633,709
import json def try_to_replace_line_json(line, json_type, new_json, json_prefix=""): """Attempts to replace a JSON declaration if it's on the line. Parameters ---------- line: str A line from a JavaScript code file. It's assumed that, if it declares a JSON, this declaration will only ta...
602897349b52be3f10a41cf90d211ad70a6d4cc2
3,633,710
def createInvoice(request): """ Invoice Generator page it will have Functionality to create new invoices, this will be protected view, only admin has the authority to read and make changes here. """ heading_message = 'Formset Demo' if request.method == 'GET': formset = LineItemForms...
e759be0c0f270ab3979d2dc2303f838dee9b58a4
3,633,711
def GetTopLevelParent(*args, **kwargs): """GetTopLevelParent(Window win) -> Window""" return _misc_.GetTopLevelParent(*args, **kwargs)
cf4bdbf694b45935af96f3e6432b38a7da6ca283
3,633,712
def slotnick(x, k): """ Relation between velocity and depth Parameters ---------- x : 1-d ndarray Depth to convert k : scalar velocity gradient Notes ----- typical values of velocity gradient k falls in the range 0.6-1.0s-1 References ---------- .. [1] ...
25b068919edea9226e071ad4ae948463384a71c9
3,633,713
def NodeEvolution(tensor, directed=False): """Temporal evolution of all nodes' input and output communicability or flow. Parameters ---------- tensor : ndarray of rank-3 Temporal evolution of the network's dynamic communicability. A tensor of shape timesteps x n_nodes x n_nodes, where n...
cd05e84d136047997723c92f1e68d84d96c9d023
3,633,714
def transform_symbol(ctx, name): """Transform the symbol NAME using the renaming rules specified with --symbol-transform. Return the transformed symbol name.""" for (pattern, replacement) in ctx.symbol_transforms: newname = pattern.sub(replacement, name) if newname != name: print " symbol '%s' t...
d4dfb7a2875b4ee20b5a9476578c0ae65afb297c
3,633,715
def get_active_resources_in_grid(grid): """Get active resources in grid. :param powersimdata.input.grid.Grid grid: a Grid instance. :return: (*set*) -- name of active resources in grid. """ _check_grid_type(grid) active_resources = set(grid.plant.loc[grid.plant["Pmax"] > 0].type.unique()) r...
b5d621577fb9cf99451efc41d32ee59530e6ecab
3,633,716
def getReflectionandTransmission( sig1, sig2, f, theta_i, eps1=epsilon_0, eps2=epsilon_0, mu1=mu_0, mu2=mu_0, dtype="TE", ): """ Compute reflection and refraction coefficient of plane waves """ theta_i = np.deg2rad(theta_i) omega = 2 * np.pi * f k1 = np.sqrt(...
6b04fc7e90c8baf8c78342d1e1afe2a6c65f489b
3,633,717
import math def tile(lng, lat, zoom, truncate=False): """Get the tile containing a longitude and latitude Parameters ---------- lng, lat : float A longitude and latitude pair in decimal degrees. zoom : int The web mercator zoom level. truncate : bool, optional Whether ...
4c5ad0ee802a61b1fe091a431d6cb53667a68d9c
3,633,718
def read(file_path, lines=False): """Returns contents of file either as a string or list of lines.""" with open(file_path, 'r') as fp: if lines: return fp.readlines() return fp.read()
86b36dbc2792ac70bd9a71c74486643b3cdef690
3,633,719
from typing import Union from typing import Tuple from typing import List def diff(tv: vs.VideoNode, bd: vs.VideoNode, thr: float = 72, height: int = 288, return_array: bool = False, return_frames: bool = False) -> Union[vs.VideoNode, Tuple[vs.VideoNode, List[in...
73509e85f1134179a71170496c64ca17f0239b15
3,633,720
from typing import List import os def extract_wheel(wheel_file: str, extras: List[str]) -> str: """Extracts wheel into given directory and creates a py_library target. Args: wheel_file: the filepath of the .whl extras: a list of extras to add as dependencies for the installed wheel Retur...
79402e433b67b749955d2bd2af426f998838fd19
3,633,721
from typing import List def random_choice(choices: List[float]) -> float: """Selects a random choice within a list.""" return choices[np.random.choice(len(choices), size=1)[0]]
69d1f25b830e295d81666e3c29c7b16bf53e76ba
3,633,722
def UnescapeUnderscores(s: str): """Reverses EscapeWithUnderscores.""" i = 0 r = '' while i < len(s): if s[i] == '_': j = s.find('_', i + 1) if j == -1: raise ValueError('Not a valid string escaped with `_`') ss = s[i + 1:j] if not ...
c793666527b37ee66f832e650e6c6aac47bc8a82
3,633,723
def login(base_config): """ 返回登录后的 :return: """ username = base_config.get("username") password = base_config.get("password") base_url = base_config.get("base_url") company_id = base_config.get("company_id") app_id = base_config.get("app_id") app_secret = base_config.get("app_sec...
d17c9d300ac233a845e7439bd9abd9528a4e9041
3,633,724
def filter_(stream_spec, filter_name, *args, **kwargs): """Alternate name for ``filter``, so as to not collide with the built-in python ``filter`` operator. """ return filter(stream_spec, filter_name, *args, **kwargs)
0e55c8c6093fafed58ced08c757e6a489fcefa17
3,633,725
def angle_normalization_0_2pi(angle): """Automatically normalize angle value(s) to the range of 0-2pi. This function relies on modular arithmetic. Parameters ---------- angle : array_like The angles to be converted Returns ------- normalized_angles : ndarray The angles...
ceef5b57ad18fc01ee7faf71d51c303621170674
3,633,726
def config_resolve_context(cookie, in_context, in_size): """ Auto-generated UCS XML API Method. """ method = ExternalMethod("ConfigResolveContext") method.cookie = cookie method.in_context = str(in_context) method.in_size = str(in_size) xml_request = method.to_xml(option=WriteXmlOption.DIRTY) ...
deea2ff376318f49102d1c0eeceb58a0dfb1e9d8
3,633,727
def bots_endpoint(page=1): """ Return bots from the BotList. Use the url parameters `url` or `username` to perform a search on the BotList. The @-character in usernames can be omitted. :param page: The page to display :return: All bots (paginated) or the search result if url parameters were us...
86686626a46817c85c9cdbc188b27bb4a2e59d6b
3,633,728
import os import sys import shutil import time import math def launch_visit_test(args): """ Runs a single VisIt test. """ idx = args[0] test = args[1] opts = args[2] top_dir = visit_root() test_script = abs_path(test_path(),"visit_test_main.py") test_dir, test_file = os.pat...
13432ce7e37ada6b59ac15a2d69328dcf20a58be
3,633,729
from typing import List from typing import Dict def parse_secrets(raw: List[str]) -> Dict[str, str]: """Parses secrets""" result: Dict[str, str] = {} for raw_secret in raw: keyval = raw_secret.split('=', 1) if len(keyval) != 2: raise ValueError(f'Invalid secret "{raw_secret}"')...
d209c954c75353c17f0bca561c3ad94fc26a9ad0
3,633,730
async def detect_custom(model: str = Form(...), image: UploadFile = File(...)): """ Performs a prediction for a specified image using one of the available models. :param model: Model name or model hash :param image: Image file :return: Model's Bounding boxes """ draw_boxes = False predict_batch = False try: ...
f6a2eefa7ac855899bec9fd86399f8704e24f3d6
3,633,731
def ensure_databases_alive(max_retries: int = 100, retry_timeout: int = 5, exit_on_failure: bool = True) -> bool: """ Checks every database alias in ``settings.DATABASES`` until it becomes available. After ``max_retries`` attempts to reach any backend ar...
e583d3b1cceca43e66c246fa4fea8eb58727ef6c
3,633,732
def __maxCrossingSubArr(seq, low, mid, high): """ 寻找seq[low..high]跨越了中点mid的最大子数组 总循环次数为high-low+1,线性的 """ leftSum = float('-Inf') sumTemp = 0 for i in range(mid, low - 1, -1): sumTemp += seq[i] if sumTemp > leftSum: leftSum = sumTemp maxLeft = i ri...
542f07214438297623518046c51974cf461b3aa5
3,633,733
def transition_matrix(embeddings, word_net=False, first_order=False, sym=False, trans=False, **kwargs): """ Build a probabilistic transition matrix from word embeddings. """ if word_net: L = wordnet_similarity_matrix(embeddings) elif not first_order: L = similarity_matrix(embeddings...
c4181b5ad61f32429d289c207eb9bb5282f8fa99
3,633,734
import os import sys def read_met_data(): """ Reads in the streamflow data and returns them as dataframe. Expects to be in the dir were the data is stored. :return: stream_df: Column names are the stream ids. Index is the date. """ # Set the cwd to the directory of the file os.chdir(os...
f4b106c95f5c70f55fdc45e45a1ed4e68c09ac4b
3,633,735
def gen_review_vecs(reviews, model, num_features): """ Function which generates a m-by-n numpy array from all reviews, where m is len(reviews), and n is num_feature Input: reviews: a list of lists. Inner lists are words from each review. Outer lists...
b8ce4489aaa03f45727e3340c361f185bf2f77dd
3,633,736
def ott(high, low, close, length=None,_shift=None, multiplier=None, **kwargs): """Indicator: Supertrend""" # Validate Arguments high = verify_series(high) low = verify_series(low) close = verify_series(close) length = int(length) if length and length > 0 else 7 shift = int(_shift) if _shift ...
dd9f1010a4db9c45ce8d81d78a562ae656980d10
3,633,737
def lambda_cut_series(x, mfx, n): """ Determines a series of lambda-cuts in a sweep from 0+ to 1.0 in n steps. Parameters ---------- x : 1d array Universe function for fuzzy membership function mfx. mfx : 1d array Fuzzy membership function for x. n : int Number of st...
60d25561b0fb637ab33407a6ea627da6ef553192
3,633,738
def validate_schema(request, schema_instance): """ A decorator function that validates schema againt request payload """ def decorator(func): @wraps(func) def wrapper_function(*args, **kwargs): json_payload = request.get_json() schema_instance.load_json_into_schema(json_...
841e60779887fc076cdf5af4dc1fc054b72799c2
3,633,739
def has_inference_based_loaders(cfg: CfgNode) -> bool: """ Returns True, if at least one inferense-based loader must be instantiated for training """ return len(cfg.BOOTSTRAP_DATASETS) > 0
6a8677edfe2074902a6f0327636cfa177577f862
3,633,740
def get_terrain_for_coord(x, y): """Get the terrain type for a coordinate. :param int x: The x coordinate :param int y: The y coordinate :returns tuple(Terrain, bool): The terrain type and whether it is diverse """ elevation, moisture, temperature, diversity = _render_map_data( 1, 1, (...
0f25ecd3e70d3a1d45b3b4d08a064d40c57e2284
3,633,741
def read_Image8(Object, Channel, iFlags=0): """ read_Image8(Object, Channel, iFlags=0) -> bool read_Image8(Object, Channel) -> bool """ return _Channel.read_Image8(Object, Channel, iFlags)
4a3265d9a3ba0ce486d968156a5a35e6b61ec7de
3,633,742
import math def Linear(in_features, out_features, dropout=0): """Weight-normalized Linear layer (input: N x T x C)""" m = nn.Linear(in_features, out_features) m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features)) m.bias.data.zero_() return nn.utils.weight_norm(m)
de26db37469b6e0d4fbd92545982b1deaef997c6
3,633,743
def get_state(initial, input_value=None): """Get new state, filling initial and optional input_value.""" return { 'last_position': None, 'initial': [initial], 'input': [input_value] if input_value is not None else [], 'output': [], }
7520341debf6b7287a445be1a44e51bd5675472f
3,633,744
import operator def predictkNNLabels(closest_neighbors, y_train): """This function predicts the label of a individual point in X_test based on the labels of the nearest neighbour(s). And sums up the total of appearences of the labels and returns the label that occurs the most """ labelPrediction ...
aa7ce9383253230f2c0535e3e27e2f2442dec043
3,633,745
def fetch_dataset(filename): """ Useful util function for fetching records """ buffer_size = 32 * 1024 * 1024 # 32 MiB per file dataset = tf.data.TFRecordDataset(filename, buffer_size=buffer_size) return dataset
594a2298b6d72cea2982ec91476d6c0f78aaae65
3,633,746
def get_alma_project(ra,de, radius_arcsec=10/3600): """Return ALMA project IDs (if exists) given coordinates.""" # set up connection cnx = db.get_cnx(cfg.mysql['user'], cfg.mysql['passwd'], cfg.mysql['host'], cfg.mysql['db_sdb']) if cnx is None: return cursor = cnx.curs...
8e1ac1b1bd979f5386d388aecef7f85ccff92492
3,633,747
from typing import Optional def read_certification_data(reader: PdfFileReader) -> Optional[DocMDPInfo]: """ Read the certification information for a PDF document, if present. :param reader: Reader representing the input document. :return: A :class:`.DocMDPInfo` object containing the r...
f26f09e7b3c835e5d029d824257053fa4fdcb97d
3,633,748
from re import T def from_independent_matroid(matroid: tuple[set[T], list[set[T]]]) -> list[set[T]]: """Construct circuits from a matroid defined by independent sets. Args: matroid (tuple[set[T], list[set[T]]]): A matroid defined by independent sets. Returns: list[set[T]]: The circuits o...
a5b8a278147b3926904cfc4d0bc23249a1669857
3,633,749
from .ir import ModularIndexing import sympy def join_dimensions(expr: sympy.Expr) -> sympy.Expr: """ ModularIndexing(i0, 1, 32) + 32 * ModularIndexing(i0, 32, 4) becomes ModularIndexing(i0, 1, 128) This type of pattern can come from view operations """ if not isinstance(expr, sympy.Add)...
72528ce5630f5e8ddcfcb42ddbc2b45cc194b9d4
3,633,750
import gzip import time import sys def map_trans_tfrecord(vcf_tfrecord, phenotype_df, covariates_df, interaction_s=None, return_sparse=True, pval_threshold=1e-5, maf_threshold=0.05, batch_size=50000, logger=None): """Run trans-QTL mapping from genotypes in tfrecord""" if logger is None: logger = Simpl...
7ea91bcc708ba4ffb6d5240295359728095a0fe9
3,633,751
def evolve(model, mutator, population, tournament_size=4): """ Performs crossover and mutation and doubles population size :param model: Instance of Model :param mutator: Instance of Mutator :param population: List of points :param tournament_size: Size of tournament :return: List of population + List of ...
0bf6629601ee6f8a3be1a9491d85944fb817bd38
3,633,752
def cell_snippet(x, is_date=False): """create the proper cell snippet depending on the value type""" if type(x) == int: return { 'userEnteredValue': {'numberValue': x}, 'userEnteredFormat': { 'numberFormat': { 'type': 'NUMBER', ...
bc91279e5e9b4e9e6b853badf28081e0e4746549
3,633,753
import io def load_image(image_path: str) -> np.ndarray: """ Read image from disk. :param image_path: Path to input image. :return: uint8 numpy array sized H x W. """ # load image img = io.imread(image_path) # assert img dtype assert img.dtype == 'uint8' return img
f524b5be404541ece8807455f4c0f450a9aa9fc1
3,633,754
def lowerUserList(inputList): """Lowercase user inputLists in case there are misspellings. (e.g. 3-6KB)""" # clean list loweredList = [] for item in inputList: loweredItem = item.lower() loweredList.append(loweredItem) return loweredList
e5d55a39a98b741758c8b1e8306a4ee486c7a29d
3,633,755
def na_cmp(): """Binary operator for comparing NA values. Should return a function of two arguments that returns True if both arguments are (scalar) NA for your type. By default, uses ``operator.or`` """ return lambda x, y: x is None and y is None
27c6324219af507d30d2ef763e731f2f6b525820
3,633,756
def get_list_files(initializer): """ """ # get settings for find roots, listOfExtension, ignoreLists, ignoreLists, ignoreLists = initializer() resultArgv = '' for pathes in roots: for at in listOfExtension: listSlice = list() listSlice.append(at) ...
23b19c3ceb6cb266a5e9bf1f9881917eab319b5b
3,633,757
def constant(name, shape, value, dtype=tf.float32): """ Creates a variable which is initiated to a constant value. :param name: The name of the variable. :param shape: The shape of the variable. :param value: The constant value of the tensor. :param dtype: The data type. :return: A constant-ini...
6878afa7dbd6485dd0373f6cd67fb0377f9957e1
3,633,758
def _cat_blob(repo, obj, bad_ok=False): """Call `git cat-file blob OBJ`. Parameters ---------- repo : GitRepo obj : str Blob object. bad_ok : boolean, optional Don't fail if `obj` doesn't name a known blob. Returns ------- Blob's content (str) or None if `obj` is no...
81a092d85b18106b7acb8c0df951267d56d07e40
3,633,759
import torch def get_disp_samples(max_dis, feature_map, stage_id=0, disprity_map=None, step=1, samp_num=9, sample_spa_size=None) : """function: get the sampled disparities args: max_dis: the maximum disparity; feature map: left or right feature map, N*C*H*W; disprity_map: if it is not ...
d07bc06e69b0015f9604a91fe4455ef61bb3c505
3,633,760
def load_data(database_filepath): """ Load cleaned data from database_filepath INPUT database_filepath --filepath to csv dataset OUTPUT X - message column to predict Y values Y - list of columns to be predicted category_names - name of Y column names """ # load data from ...
a4e4eb2acbbe1bbc7f338b4dcfe1c19ff81dd968
3,633,761
def sigma_clip(array, flags=None, sigma=4.0, axis=0, min_N=4): """ one-iteration robust sigma clipping algorithm. returns clip_flags array. Warning: this function will directly replace flagged and clipped data in array with a np.nan, so as to not make a copy of array. Parameters: ----------- ...
9ce1ec8f261e0b548ae8feb3d6f5769f3994f64f
3,633,762
from genrl.core import get_actor_critic_from_name from genrl.core import get_value_from_name from genrl.core import get_policy_from_name from typing import Union def get_model(type_: str, name_: str) -> Union: """ Utility to get the class of required function :param type_: "ac" for Actor Critic, ...
13e29ab4065425a1c68bfead5c8d6811b24234f3
3,633,763
import os def _preprocess_data(data, data_type, auth=None): """Preprocess input data according to the specified type. Possoble data types are: - "raw" use data as is provided in the request - "json_pgframe" create a PandasPGFrame from the provided JSON repr - "nexus_dataset" download a JSON data...
69ded5d2e39657d7bc68d68edd2ba7b26048b3a5
3,633,764
def short_comment(x): """Ham comments are often short, such as 'cool video!'""" return len(x.text.split()) < 5
f8d91feb4549219275dd5bace104cd8d89b96748
3,633,765
def xxyy_basis_rotation(pairs, clean_xxyy=False): """Generate the measurement circuits.""" all_ops = [] for a, b in pairs: if clean_xxyy: all_ops += [ cirq.rz(-np.pi * 0.25).on(a), cirq.rz(np.pi * 0.25).on(b), cirq.ISWAP.on(a, b)**0.5 ...
4d5e5bfeb0b6ec6276fc8b640c600e3d2b8dc488
3,633,766
def partitions_class_attribute(data_points, attr_index): """Partitions data points using a given class attribute. Data points with the same class label are combined into a partition. :param data_points: List of tuples representing the data points. :param attr_index: Index of the attribute inside the tup...
848cce86bfbe052098caefb83bd0f27ca9703c74
3,633,767
def set_crop_to_volume(volume, bb_min, bb_max, sub_volume): """ set a subregion to an nd image. :param volume: volume image :param bb_min: box region minimum :param bb_max: box region maximum : """ dim = len(bb_min) out = volume if(dim == 2): out[np.ix_(range(bb_min[0], b...
54be20a0f1b9f85187adba68a2f5a9a3dec85d1c
3,633,768
def display_image_grid(bounding_pts,image,skip_dilate=True,size = 2.5): """ construct a grid from the padded images and create the entire grid displays the image returns an image and list of all the digit images """ if not skip_dilate: list_digits = [draw_block(i[0],i[1],image.copy(),ski...
fb539d899410b6c7824ce57fb21292a746abe464
3,633,769
import random import string def generate_random_name(): """Generate a random name to use as a handle for a job.""" return "".join(random.choice(string.ascii_lowercase) for j in range(8))
c793c77289e7813cfd679b23613a9b1cd38af941
3,633,770
import os def _compile_explicit_relpath(verb): """Decline to map any explicit relpath to verb""" assert ("/" in verb) or ("." in verb) if os.path.exists(verb): how = _compile_log_error( "bash.py: warning: {}: No such file or directory in bash path".format(verb) ) ret...
869874a768a85d113904c515e1ccb31747315bf7
3,633,771
import os def get_commands(): """ Returns a list of command names. This works by looking for commands inside crichtoncli.commands. The list is in the format [command_name]. Items from this list can then be used in calls to load_command_class(command_name). The list is cached on the ...
c565edbd43e95de2424cd3f3370c6b1b011f2e51
3,633,772
def import_skymodel_from_hdf5(filename): """Import a Skymodel from HDF5 format :param filename: :return: SkyModel """ with h5py.File(filename, 'r') as f: ncomponents = f.attrs['number_skycomponents'] components = [convert_hdf_to_skycomponent(f['skycomponent%d' % i]) ...
b57e8ce7af13f303e6985690c45d1b99fb3b1755
3,633,773
def _get_initial_ktensor(init, X, rank, random_state, scale_norm=True): """ Parameters ---------- init : str Specifies type of initializations ('randn', 'rand') X : ndarray Tensor that the decomposition is fit to. rank : int Rank of decomposition random_state : Random...
aab154e034465961e3aee336ad615677d353e487
3,633,774
import numpy def grabocka_params_to_shapelet_size_dict(n_ts, ts_sz, n_classes, l, r): """Compute number and length of shapelets. This function uses the heuristic from [1]_. Parameters ---------- n_ts: int Number of time series in the dataset ts_sz: int Length of time series ...
bc1016e57487374762d801de64059c4b5a5acd07
3,633,775
import csv def gslib(FileName, deli=' ', useTab=False, numIgLns=0, pdo=None): """ Description ----------- Reads a GSLIB file format to a vtkTable. The GSLIB file format has headers lines followed by the data as a space delimited ASCI file (this filter is set up to allow you to choose any single charac...
be8259e987627df32254a4231791caf1571c8fad
3,633,776
from typing import List def precision_recall( similarity_melted_df: pd.DataFrame, replicate_groups: List[str], k: int, ) -> pd.DataFrame: """ Determine the precision and recall at k for all unique replicate groups based on a predefined similarity metric (see cytominer_eval.transform.metric_melt) ...
518e667597d3b85683d3b49dd0426a514ef9997f
3,633,777
def validate_index(n: int, ind: int, command: str): """ Simple function to validate existence of index within in the model repository. Args: n (int): length of indices ind (int): selected index command (str): name of command for "tailored" help message """ # ensure index e...
3aef711caef041d2f4aa1dfdf0b5135d9f626b3c
3,633,778
import requests def search_page(request): """Page with search results.""" def _articles_filter(name): """Delete articles in product names Arguments: name {str} -- Name or generic name of product """ exclude = ("de", "des", "au", "aux", 'en', "le", ...
a41143e49cd1e94aa3341f6e30b3dc1d98b22882
3,633,779
def calculate_sa_expected_feature_counts(pi, mdp, epsilon=0.0001): """return dictionary of feature counts associated with each (s,a) pair""" sa_fcounts = dict() #compute feature expectations per state fcounts = calculate_expected_feature_counts(pi, mdp, epsilon) #(s,a) feature expectations are \phi(...
19ebd9da4b722078d1f961da0774573176017742
3,633,780
def xmlToTag(tag): """The opposite of tagToXML()""" if tag == "OS_2": return "OS/2" if len(tag) == 8: return identifierToTag(tag) else: return tag + " " * (4 - len(tag)) return tag
4c6e26f429e273f9b25adc25d262a523fda6467c
3,633,781
def translate(num_list, transl_dict): """ Translates integer list to number word list (no error handling!) Args: num_list: list with interger items. transl_dict: dictionary with integer keys and number word values. Returns: list of strings which are the translated numbers into word...
dec1b25d64acf99dc04885f773ea42a55865bf8d
3,633,782
def _1d_overlap_filter(x, n_h, n_edge, phase, cuda_dict, pad, n_fft): """Do one-dimensional overlap-add FFT FIR filtering.""" # pad to reduce ringing x_ext = _smart_pad(x, (n_edge, n_edge), pad) n_x = len(x_ext) x_filtered = np.zeros_like(x_ext) n_seg = n_fft - n_h + 1 n_segments = int(np.c...
4c6825a2df425415d546e47f0c2ba24166e0bf2c
3,633,783
def LED(state): """this is the arduino function that controls how the LED bulb with respect to what the webserver says""" if state == True: arduino.write(b'1') print('the arduino is in the ON state') return True else: arduino.write(b'0') print('the arduino is in the O...
bcdc9bbc315215631af8ca0ef5bc48eb3b0b3b03
3,633,784
def noise_mean(corr, scale_factor = 1., mode = "corr"): """Computes the scalled mean noise from the correlation data estimator. This is the delta parameter for weighted normalization. Parameters ---------- corr: (ndarray,) Correlation function (or difference function) model. ...
e94f04664888f981131fd406a1f55e404dcb1581
3,633,785
def get_python(uid): """Returns location of virtualenv python binary given UID""" return get_venv_folder(uid) + '/bin/python'
b8e73ff14df2151915a55d11c1aaba9457dac4c3
3,633,786
def login(): """View of login to the backstage""" if current_user.is_authenticated: return redirect(url_for('admin.index')) form = LoginForm() if form.validate_on_submit(): admin = Administrator.query \ .filter_by(name=form.name.data).first() if admin is not None and...
e653f078c9f31477d13cc773db25a9bb2bb16ceb
3,633,787
def vgg_retinanet(num_classes, backbone='vgg16', inputs=None, modifier=None, **kwargs): """ Constructs a retinanet model using a vgg backbone. Args num_classes: Number of classes to predict. backbone: Which backbone to use (one of ('vgg16', 'vgg19')). inputs: The inputs to the network (...
cc1e14f45108ede7bed38c40601bcd35a487fb97
3,633,788
def fetchWorkflowsSpec(config, listOfWfs): """ Fetch the workload of a list of workflows. Filter out only a few usefull keys """ if isinstance(listOfWfs, basestring): listOfWfs = [listOfWfs] wfDBReader = RequestDBReader(config.AnalyticsDataCollector.centralRequestDBURL, ...
77ac4fb477673acc0e08388cc9075c00f7dbbcf5
3,633,789
def rel_error(x, y): """ Returns relative error """ assert x.shape == y.shape, "tensors do not have the same shape. %s != %s" \ % (x.shape, y.shape) return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
34166fe707ad3733c7e798319f634eaac549811d
3,633,790
def wrap_ddp(cls): """Return wrapper class for the torch.DDP and apex. Delegete getattr to the inner module. """ class _Wrap(cls): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __getattr__(self, name): wrapped_module = super().__getat...
d8d4148a4e26e28bca76bbac7ecd0e0cea64b3ba
3,633,791
def mortgage_max(buyer_dsr): """ Calculates maximum loan available to offer based on buyer's proposed downpayment and downpayment percent ... Returns ------- loan : float Returns maximum available loan to be offered """ downpayment_percent = 0 min_downpayment = 0 try: ...
c1fa429d61100dce20b5a4cbeaef365d39ad14af
3,633,792
import jinja2 def generate_newsletter(cal_dict): """ Given a JSON formatted calendar dictionary, make the text for a fascinating newsletter. """ sorted_items = organize_events_by_day( cal_dict['items'], config.NEWSLETTER_MAX_DAYS, ) # pprint.pprint(sorted_items) ...
efc39101c668e7744d95334204778e854747c362
3,633,793
import json def request_api(request, # type: Request path, # type: Str method="GET", # type: Str data=None, # type: Optional[Union[JSON, Str]] headers=None, # type: Optional[HeadersType] cooki...
4d6131ee53b948298652b357be62e52112015854
3,633,794
def unit_vector(vector): """ Returns the unit vector of the vector. """ div = np_norm(vector) if div == 0.0: return vector return vector / div
fbff470eae5bdc6fe43fd883fec83d3ec3e0482e
3,633,795
import uuid import base64 import os def save_files(images): """ Save encoded image to image file on local machine. Image is decoded and saved as JPEG file with UUID name in "imstore" directory. :param images: encoded image string (string) :return: file name of stored image (string) """ f...
ba3e6f99570b540470fe687f69fc13ac803c9a39
3,633,796
import re def _generate_nsa_options(query): """ >>> _generate_nsa_options("NM_000551.3") [('refseq', 'NM_000551.3')] >>> _generate_nsa_options("ENST00000530893.6") [('ensembl', 'ENST00000530893.6')] >>> _generate_nsa_options("gi:123456789") [('gi', '123456789')] >>> _generate_nsa_op...
07f6e9a703464b1c97cac94dfc5806f2ef39f420
3,633,797
def identify_place_type(place_type): """ Identifies the type of the given geoname. It first inferes the type from the metadata file, then identifies using regular expressions. """ if re.search("Lieu", place_type): if re.search("RUE$", place_type): return 11 elif re.search...
edfe5dd42f3ce3e0e1d609a4d73328b2995184ec
3,633,798
def InterferenceDict(data_list): """Creates an interferenceReturns a double dict from a list of lat,lng, interferences.""" if not isinstance(data_list, list): data_list = [data_list] result = {} for lat, lon, data in data_list: if lat not in result: result[lat] = {} result[lat][lon] = data return...
fae34ea1182c6f709691ef1bab72f1796d073a2a
3,633,799