content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List import random from typing import Tuple import itertools def create_trader_inventories() -> None: """Create inventory objects for 75% of traders""" pk_list: List[int] = list(Trader.objects.values_list("id", flat=True)) subset_count = int((len(pk_list) / 4) * 3) random.shuffle(pk...
3435e2f9c98f8b5316dadfed6a8e8c4462668be3
69,600
def v2_serving_handler(context, event, get_body=False): """hook for nuclio handler()""" if not context._server.http_trigger: event.path = "/" # fix the issue that non http returns "Unsupported" return context._server.run(event, context, get_body)
63397eaf6d4d009ea6eff3332ba7c611c2f8202a
69,601
import os import sys def get_gmake(): """ Locate GNU make """ try: GMAKE = os.environ["MAKE"] except KeyError: if "bsd" in sys.platform: GMAKE = "gmake" else: GMAKE = "make" return GMAKE
34d2e46936aafd9406225dde1de32e689ce2a774
69,602
from typing import List def get_euclidean(array: np.ndarray = None, global_neighbors: np.ndarray = None) -> List[List[float]]: """ Pairwise euclidean distance ---------------------------------------- input: numpy array with samples as rows output: pairwise euclidean distance array""" # split numpy...
f860b0191f917000ea31e2a160f7452e9d7751aa
69,603
import unittest def test_fuse(): """ Function to execute unitest associated to fuse virtual folders. """ suite = unittest.TestLoader().loadTestsFromTestCase(TestHTTPExecuteFuse) runtime = unittest.TextTestRunner(verbosity=2).run(suite) return runtime.wasSuccessful()
4e4f9455067b0e00209a4ec350b8bc25d5ff78f9
69,604
import array def hotspotKmerFilter(sd, sa, hotspotPct = 0.1): """Filter out kmers that are not in top fraction of HLA epitope hotspots (False indicates invalid kmers/params)""" binders = _nepitope_distance(sa.results.insertBA,sa.results.btBA,sa.results.params).sum(axis=0) ranki = argrank(binders) mask...
c2f2d4369979c3bbf4eda46db88c6bf4c63db4ce
69,605
from datetime import datetime import random import os def get_sub_tmp_path(): """一時フォルダー配下にさらに一時フォルダーを取得する :return: """ name = "{0}_{1}".format( datetime.datetime.now().strftime('%Y%m%d%H%M%S%f'), random.randint(10000, 99999), ) tmp_path = os.path.join(get_tmp_path(), name) ...
1867eb4d17be51f16c396f1730e278d1f713897e
69,606
def conv_backward_naive(dout, cache): """ A naive implementation of the backward pass for a convolutional layer. Inputs: - dout: Upstream derivatives. - cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive Returns a tuple of: - dx: Gradient with respect to x - dw: Gradient ...
2150bc86395bbe259f5075a457d5244ad41135a7
69,607
from typing import Union from typing import Any from typing import cast def gather_data(seq: pulser.sequence.Sequence) -> dict: """Collects the whole sequence data for plotting. Args: seq (pulser.Sequence): The input sequence of operations on a device. Returns: dict: The data to plot. ...
c638e28d87d775633d9d53639f912abf71c021aa
69,608
def xyz2lonlat(x,y,z, radius=1): """From cartesian geocentric coordinates to 2D geographic coordinates.""" latitude = np.rad2deg(np.arcsin(z / radius)) longitude = np.rad2deg(np.arctan2(y, x)) return longitude, latitude
3277f2155f292b53e6ad5063b8097bd008cd1d02
69,609
from typing import List def crawl(url: str, url_prefix: str, out_path: str, depth: int) -> List[File]: """ Recursively crawl a website and save each HTML page to a local file. """ # We use `check_valid="shallow"` to make resuming a past execution faster. # See task options documentation for more d...
dee0e4cc1f54eb878f347fcf5cded2a664fad95a
69,610
import math def is_matching_bouding_box(source, target, tolerance=0.05): """ Checks if the source and target shape have the same bounding box :param source: source shape node :type source: string :param target: target shape node :type target: string :param tolerance: difference tolerance al...
743b1ce804d69b14beff4ecffaa353801f128b98
69,611
import argparse import os def get_args() -> Args: """ Get command-line arguments """ parser = argparse.ArgumentParser( description='Tetranucleotide frequency', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('dna', metavar='DNA', ...
0007769028d96a03dc548a022d3ebb9f94d033b0
69,612
def linear_search_iterative(elements, key): """ An index, i, where A[i] = k. If there is no such i, then NOT_FOUND. """ for idx, value in enumerate(elements): if key == value: return idx return "Not Found"
2b856762bccd355ecd847ba318d50a678c8aa89a
69,613
def reg_delete_tree(*args): """ reg_delete_tree(name) -> bool Delete a subtree from the registry. @param name (C++: const char *) """ return _ida_registry.reg_delete_tree(*args)
a9cf3fb8c8b1ddbb2e2d3a886f4e0f1cd6ec7303
69,614
def get_static_select_value(input: dict) -> str: """ Get the value selected from a drop-down. """ if 'selected_option' in input: if 'value' in input['selected_option']: return input['selected_option']['value'] return None
562f9c92e6611d497bfe31e59bb31374a67e5e88
69,615
def get_index(parnames, namelist): """ Searches for a particular parname in a list and returns the index of where that parname appears Parameters ---------- parnames : list list of strings containing the names of the parameters in the pyspeckit fit. This will vary depending on t...
d59326b9dd02e9e717631395ac9874e6d949831e
69,616
import hashlib from re import T from re import A def posts(): """ Function accessed by AJAX to handle a Series of Posts """ try: series_id = request.args[0] except: raise HTTP(400) try: recent = request.args[1] except: recent = 5 table = s3db.cms_...
e75bdf5ee55e552ce412f1a881634b17fa6ed494
69,617
def find_longest_consecutive_sequence(root: TreeNode) -> int: """https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/""" max_length = 0 if root is None: return max_length stack = [(root, 1)] while stack: node, current_length = stack.pop() if node.right: ...
a2000ee9803d839e527aaa4799a419a447b25698
69,618
import copy def calc_cv(nr_particles, model_weights, N_BOOTSTR, test_w, transitions, test_X): """ Calculate the Coefficient of Variation. Parameters ---------- nr_particles: int Number of particles to estimate the CV for model_weights: np.ndarray array of model w...
7ee102ff16298abe739949a4ae6d82d02e22d419
69,619
import ctypes from typing import Tuple def sparse_tensor_to_coo_tensor( lib_name: str, sparse_tensor: ctypes.c_void_p, dtype: np.dtype, ) -> Tuple[int, int, np.ndarray, np.ndarray, np.ndarray]: """Converts an MLIR sparse tensor to a COO-flavored format tensor. Args: lib_name: A string for the su...
d62b2a2f9973abae78349b21c52a1b0ed33ab175
69,620
def filter_entries(inputs_map, spec): """Filter inputs entries that are not in the spec""" param_names = [ p["name"] for p in spec["parameters"] \ if "sourced_at_deployment" in p and p["sourced_at_deployment"] ] # Identify any missing parameters from inputs_map missing = list(filter(lambda ...
8617a5d1ce42b24249ee27e62141d40aeab06567
69,621
from datetime import datetime import os def folder_from_datetime(dt: datetime.datetime) -> str: """Determine the folder path to store moved files in.""" # return dt.strftime('%Y' + os.sep + '%Y-%m') return dt.strftime("%Y-%m" + os.sep + "%Y_%m_%d")
89693b8b34796d7d34f3892c918050caec3dcc94
69,622
def snapshot_expval_pre_meas_values(): """SnapshotExpectationValue test circuits reference final probs""" targets = [] for statevec in snapshot_expval_final_statevecs(): values = {} for label, (mat, qubits) in snapshot_expval_params().items(): values[label] = { '0...
d78c9fca51619ca23946801323e44b9e3f785886
69,623
def remainder1_with_denominator(arr: NDArray, denominator: int) -> NDArray: """ return arr (mod 1) """ arr_int = np.around(arr * denominator).astype(int) arr_int_mod = np.remainder(arr_int, denominator) arr_mod = arr_int_mod / denominator return arr_mod
2248c933362a599771b41f0d54e928ef405a97f3
69,624
from typing import Optional def expm1( x: oneflow._oneflow_internal.BlobDesc, name: Optional[str] = None ) -> oneflow._oneflow_internal.BlobDesc: """This operator computes :math:`y=e^x-1`. Args: x (oneflow._oneflow_internal.BlobDesc): A Blob name (Optional[str], optional): The name for th...
750c5be7f586dffec33b7c9e374bdc4636e206ec
69,625
def substr_match(a, b): """ Verify substring matches of two strings. """ if (a is None) or (b is None): return False else: return a in b
9b98d14b6ec5f2ab433eea92d377b5e1477fef64
69,626
from io import StringIO def get_martin_moyce_1(): """Returns t*sqrt(2*g/a), z/a for the case where a = 1.125 inches """ # z/a vs t*np.sqrt(2*g/a) t, z = np.loadtxt(StringIO(mm_data_1), unpack=True) return t, z
7a2caaa4cc8e19ab882746ebf4d41b70ac823e7d
69,627
def replace_negative(l, default_value=0): """ Replaces all negative values with default_value :param l: Original list :param default_value: The value to replace negatives values with. Default is 0. :return: Number of values replaced """ n_replaced = 0 for i in range(len(l)): if l[i] < 0: l[i...
431781a48a36a00329537b92b589cf223b945ca4
69,628
import os import re from pathlib import Path def import_content(source, all_contents={}, drive_dir=None): """ sometimes it's not known if there is a Content object for a given path and sometimes we want there to be one, if there is not already many of these checks need to happen before initializing t...
06a89ec51e7e13387d1f7aa0b2808e1407595101
69,629
import logging import subprocess def push_uuid_tag(project_id: str, image_id: str, force: bool = False) -> str: """Takes a base image and tags it for upload, then pushes it to a remote Google Container Registry. Returns the tag on a successful push. """ image_tag = _image_tag_for_project(project_id, image_...
6b15dc3c2b0949dd24a42693c7cfc0fa86c0662a
69,630
def get_class_pmr_limits(edges=False) -> list: """ Parses the supplied in wltc_data and extracts the part-limits for the specified class-name. :param edges: when `True`, embeds internal limits into (0, len) :return: a list with the pmr-limits (2 numbers) .. note:: For pipe...
40ce0aedac6af1e32191b0dfd658b6cd815ad9df
69,631
def knightCheck(row, column, possibleMoves, positionCheck): """show all possible knight moves""" colour = positionCheck[row][column].colour for i in range(-2, 3): for j in range(-2, 3): """use pythagoras""" if i ** 2 + j ** 2 == 5: if check(row + i, column + j...
625134fec7f7f5e8b82baaa33a8adb155e6eda76
69,632
def nearest(x, x0): """ Find the nearest index of list x to x0. """ return np.argmin(np.abs(x - x0))
5e90d65fc9479d651e052ceaf5ae638c6dedb5a6
69,633
from typing import Union import pathlib import shutil import subprocess def git_commit(path: Union[str, pathlib.Path], error_message: str = 'parent directory is not a repository') -> str: """ Finds the current commit of a git repository. Parameters ---------- path: str or pathlib The path to the git repositor...
94839ba6e4ff6c2a23078468b1a920090470a7e8
69,634
def convert_transcriptions(trans_source, transform=False, in_place=False): """ Args: trans_source : str filepath of a csv with an 'IPA Actual', 'IPA Target' column or both. transform : bool to toggle transforming data into Phon-readable format (not yet implemented). Defau...
213ee274af67e29737ff32628c2791ad500eb334
69,635
def view(id): """Get a Point with a specific ID.""" point = Point().get(id) return render_template("view_point.html", title=point["properties"]["name"], point=point)
dcd8bc604f6b2b03da45d4567ac606fedab93a33
69,636
def get_molecular_formula(smi): """ Return the molecular formula of the molecule corresponding to the smiles """ mol = Chem.AddHs(Chem.MolFromSmiles(smi)) return rdMolDescriptors.CalcMolFormula(mol)
75b9561d72fa2f941a48bc25b466e4e0eedf57ab
69,637
def solution(): """Sum all integers that cannot be written as the sum of two abundant numbers.""" # Calculate all abundant numbers < 28123/2 abundants = [x for x in range(28124) if is_abundant(x)] # Seive out numbers that can be written as sums numbers = {} for i in range(28124): num...
b5690033194a1cde5f3f8f58c85b746639303134
69,638
import torch def gdl_loss(gen_frames, gt_frames): """ Calculates the sum of GDL losses between the predicted and ground truth frames. @param gen_frames: The predicted frames at each scale. @param gt_frames: The ground truth frames at each scale @param alpha: The power to which each gradient term ...
1be985e44bedf684e104dc78a2866fe4d19693f8
69,639
def process_data(df, cols_order_wanted): """Process inspections data.""" # Datetime formatting df["INSPECTION_DATE"] = pd.to_datetime(df["INSPECTION_DATE"]) # Change datatype 1/2 df = df.astype({"MINIMUM_INSPECTIONS_PERYEAR": int}) # Remove commas from column and convert string to float cnam...
ef2ba2d22afd8169a9407e3ee933ab5739561404
69,640
async def fetch( url: UrlType, session, response_attr: str = 'json', callback: FetchCallback = default_callback, handle_exceptions: HandleExceptionType = raise_by_default ): """ Asynchronous get request. Pass handle_exceptions in order to get your desired error handli...
514678489b36c6c697e371b97104a5c2ca77354d
69,641
async def edit_a_timetable(id: int, timetable: Timetable): """Updates the information stored about a timetable.""" edit_timetable = await Timetable.edit(id, timetable) if not edit_timetable: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No timetable with that id was found.") ...
be7b3bd0fecfec37d3c74b3a731119b83cc00959
69,642
import scipy import signal def bandpower(x: object, fs: object, fmin: object, fmax: object, nfft_point: object = 1024) -> object: """ returns the power in a frequency band of a signal :rtype: object :param x: :param fs: :param fmin: low frequency :param fmax: high frequency :param nfft...
6a1feda74978fb18a27e9fba6d448623140da021
69,643
def swap_64b(val): """ Byte swap val (unsigned int64) :param val: 64b value :return: swapped 64b """ tmp = ((val << 8) & 0xFF00FF00FF00FF00) | ((val >> 8) & 0x00FF00FF00FF00FF) tmp = ((tmp << 16) & 0xFFFF0000FFFF0000) | ((tmp >> 16) & 0x0000FFFF0000FFFF) tmp = (tmp << 32) | (tmp >> 32) retur...
5b7fa81d352e94db03f8089f50fedd0ab7a3903e
69,644
from operator import add def linecenter(l): """ return the center of a line""" return scale3(add(l[0],l[1]),0.5)
dd5ec61b4b80cb359382630449d21bb23c2feadf
69,645
def get_gitlab_namespace(response): """Return the gitlab namespace.""" return glom(response, 'project.path_with_namespace', default=False)
1a3484ea0572eec636b49774bb9b75585a1c152f
69,646
def login(request): """user login webpage :request: client request :returns: index page if success, login page if fail """ if request.user.is_authenticated(): return HttpResponseRedirect('/index/') username = request.POST.get('username', '') password = request.POST.get('password',...
39c0fac4877731b69048f9c7eafb77ed2e60d040
69,647
import torch def nms_gpu(boxes, scores, thresh): """Non maximum suppression on GPU. Args: boxes (torch.Tensor): Input boxes with shape (N, 5). scores (torch.Tensor): Scores of predicted boxes with shape (N). thresh (torch.Tensor): Threshold of non maximum suppression. Returns: ...
30d46ec12f95fd04ba0094ecd8dac96dadd8a0ea
69,648
def voronoi_otsu_labeling(image:ImageData, spot_sigma: float = 2, outline_sigma: float = 2, viewer: napari.Viewer = None) -> LabelsData: """ The two sigma parameters allow tuning the segmentation result. The first sigma controls how close detected cells can be (spot_sigma) and the second controls how precis...
1d724c5a8ac8595f917cf048bdd1b9aec86cbfa7
69,649
def strict_conj(a, b): """Strict conjunction Arguments: - `a`: a boolean - `b`: a boolean """ return a & b
59d1a1de721ce8fd8390f8582f8cd4bfc67b073c
69,650
def process(pattern, mer_index): """ calculates metrics. :param pattern: the pattern :param mer_index: the index :return: """ global sequence exact = exact_match_finder(pattern, mer_index) approx = approximate_match_finder(pattern, mer_index) total_occurences = len(list(set(exa...
68a6d6ac48bb73b28c6432637715f008a9a20c1e
69,651
def identifie_cycle_dans_chemin(m, s, marque, chemin): """Retourne le 1er cycle trouvé dans le chemin. m - matrice d'adjacence. s - sommet à visiter. marque - liste de sommets marqués. chemin - chemin jusqu'à s. """ nouveau_chemin = chemin + [s] # Si un cycle est identifié dans le ...
c2da1312c41de84093d5d1d2c0d5a8058fc9a21f
69,652
def varlen_sparse_feature_process(x): """序列特征的处理""" res = [] try: items = eval(x) for item in items: if item is np.nan: continue if item not in res: res.append(item) if len(res) != 0: return res else: ...
2a6b2d2c6d51b09647d55029ee46c53397ee52d9
69,653
from symgp.superexpressions import SuperDiagMat, SuperBlockDiagMat def get_num_symbols(expr): """ Returns the number of MatrixSyms in the expression """ numSyms = 0 stack = [{expr: 0}] while len(stack) > 0: sub_expr, level = list(stack.pop()...
17f748e177c9f4ac971c9c6b68150e64dacec8b8
69,654
def get_crossover_of_binary(crossover_type:str = "UNI"): """ バイナリ記号列を遺伝子型とする場合の交叉のアルゴリズムを呼び出す ONEなら一点交差 TWOなら二点交差 UNIなら一様交差 のアルゴリズムを流す関数を返す """ index_to_func = {} index_to_func["ONE"] = one_point_crossover index_to_func["TWO"] = two_point_crossover index_to_func["UNI"] = unif...
2966b1faf87a3c357b7a6ecca1cb3476074141b2
69,655
def signed_varint(i): """Zig-zag encodes a signed integer into a varint. """ if i >= 0: return varint(i << 1) return varint((i << 1) ^ (~0))
15ae5d2158113fecddb2cadca71b669d9d5949c2
69,656
def update_needed(path, package_version): """Determines if a file needs to be updated""" current_version = get_file_version(path) if(current_version is not None): needed = current_version != package_version else: needed = True print "Update to '%s' needed == %s"%(path, str(needed)) ...
d596a92685a766c4b79111c7ea05b0bce435ad11
69,657
def convert_to_readable_mac( eth_src ) : """ converts eth.src and eth.dst to readable mac address """ mac_addr = hexlify(eth_src) """This function accepts a 12 hex digit string and converts it to a colon separated string""" s = list() for i in range(12/2) : # mac_addr should always be ...
dfca1b477e056289905c3571cf20000823bb15a1
69,658
def getClassAttendance(moduleCode): """ Will take in the module code and use the code to open the file of the specified module and read it to created the list of names, presents, absents and excuses. To be return for future use :param moduleCode: :return: (list) """ classData = open(f"{modul...
a618b90bd6be84fbe23c28ab8d71a57c108b76dc
69,659
def compose_password_update(user_id: str, old_password: str, password: str) -> dict: """ Compose an update dict for self-changing a users account password. This will disable forced reset and won't invalidate current sessions, unlike a password change by an administrator. :param user_id: the id of the u...
0f1a8ea71f23b6b87cb8220b3453076e66d26b76
69,660
from sage.plot.graphics import Graphics from sage.plot.line import line def plot_phase_trajectories(func, inits, xbound, ybound, tbound=(0, 10, 100), use_sage=False, axis=None, f_kwargs={}, odeint_kwargs={}, plt_kwargs={'color': 'blue'}): """function for plo...
712cb5f1b457ffb6bb0a4b5e2d0dde957e8ee20e
69,661
def main(): """Run Maximum path sum I.""" path = max_value_path_sum(get_tree_from_doc()) return (sum(path), path,)
b931f38c2e1b43595e7489242c6100846edc9634
69,662
import re def extract_bag_of_words_features( ngram_lengths_to_start_positions, thresholds=(1,), **kwargs ): """Returns a bag-of-words feature extractor. Args: ngram_lengths_to_start_positions (dict) thresholds (int): Cut off value to include word in n-gram vocab Returns: (fun...
ce1bcc9f190e97df9e196e867a3a4fe486cf8685
69,663
def load_results(conn, df, table_name): """Get the extracted data and insert into a postgres table. Parameters: ----------- conn: connection to the database. df: Dataframe to insert into the database. table_name: table to insert the dataframe. """ # Create a list of tup...
fa0f11fc99493d43a8bfb13cd9f4a57f5a6ff523
69,664
def calc_time_equivalence( time_step, time_limiting, window_height, window_width, window_open_fraction, room_breadth, room_depth, room_height, room_wall_thermal_inertia, fire_load_density, fire_hrr_density, fire_spread_speed...
2f931a3881694d501a522ee30e3bfd5ff2522ff3
69,665
def layer_function2(x): """ lambda function """ return x[0] + x[1]
62a0ab30432fecad48afa18ecaf7d946ffb0d83b
69,666
def zoom_box(ax, xlim, ylim, zoom = 2, loc = "lower left", borderpad = 1): """ Puts a zoomed inset axis on the associated x and y limits with the specified zoom scale on a matplotlib subplot. Parameters ========== ax :: subplot The matplotlib axis object to put the zoomed axes on xlim :: list The desired x...
8a68d1b1b58533a1823bc167f2f75211d6930e52
69,667
def test(match=lambda document:False, documents=[]): """ Returns an (accuracy, precision, recall, F1-score)-tuple. """ TP, TN, FP, FN = confusion_matrix(match, documents) a = float(TP+TN) / ((TP+TN+FP+FN) or 1) p = float(TP) / ((TP+FP) or 1) r = float(TP) / ((TP+FN) or 1) f = 2 * p * r / ((p...
92ceba859b82c9374a5cffd3185b78888bee3365
69,668
def average_wdirs(wdirs, wspds=None): """ Average wind directions together using vector averaging. This works for a list, array, np.array, pd.Series or pd.DataFrame. If a list, array, np.array or pd.Series of wind directions are sent, it will average all the wind speeds in that array together retur...
a2d97dd1c74a53656ad22d0bc09119b0bfdc57e8
69,669
def make_valid_data_iter(valid_dataset, opt): """ This returns user-defined validate data iterator for the trainer to iterate over during each validate epoch. We implement simple ordered iterator strategy here, but more sophisticated strategy is ok too. """ # Sort batch by decreasing lengths...
4bc0968c1dff9c63e37caeae2041036ecd4aa125
69,670
def task_handler(): """Log the request payload.""" t = HelloTask.load(request.get_data(as_text=True)) print('Received task with payload: {}'.format(t.message)) return 'Printed task payload: {}'.format(t.message)
f0ce693fa5407424e7087653c318cb2c23f4cc60
69,671
import dill def load_cookie(website): """ For adding Fantia cookie into the webdriver. Will return True or False depending on whether the cookie has been loaded successfully or not. Requires one argument to be defined: - The website which is either "pixiv" or "fantia" (string) """ cookie...
9fc30cc9fb86ce09f170bbf68a823e4af5532d6d
69,672
def get_radzones(): """ Constuct a list of complete radiation zones using kadi events """ radzones = events.rad_zones.filter(start=DateTime() - 5, stop=None) return [(x.start, x.stop) for x in radzones]
17ecbf030928e7f73f91887645481ad72c962284
69,673
import yaml def get_config(config): """Loads a yaml configuration file.""" with open(config, 'r') as stream: return yaml.load(stream, Loader=yaml.FullLoader)
58937acf5984b08193c78877fbb94c07c6d779df
69,674
def is_rgb(image): """ Return True if image is RGB (ie 3 channels) for pixels in WxH grid """ return len(image.shape) == 3 and image.shape[-1] == 3
f0452fc5f9b6eb69917f8b5de76329eb2e4f03b2
69,675
import yaml from io import StringIO def ash_to_dat(fn_yni,fn_mix,isStringIO=True): """ Convert allowable shift start time inputs into GMPL dat form. Inputs: fn_yni - filename of yaml ini scenario file fn_mix - filename of yaml tour type mix file isstringio - true to return StringIO...
a16e16a55d861df0001e95a035d9d15bf935f8fc
69,676
def get_u(ll): """ function to get limb darkening coefficient u (Allen 1973) based on wavelength value Parameters ---------- ll: float wavelength Returns ------- ul: float coefficient u based on wavelength """ pll = np.array([1.0, ll, ll ** 2, ll ** 3, ll ** 4...
99dd3c4c00c5539955c472c109cc8e3f54173700
69,677
def _class_get_controller_g(cls, request): """ Retrieves the controller instance that is currently set in the current environment (request) falling back to an invalid (unset) value in case no controller was found for the current environment. This is the global method equivalent to the instance...
9a0097ab5cc7411f0f58e6e503d8338da80ac687
69,678
import math def dampedOscillation( u, v, t): """Calculation of a R2 -> R1 function at position u,v at curr_time t. A t-dependent cosine function is multiplied with a 2D gaussian. Both functions depend on the distance of (u,v) to the origin.""" distSq = u * u + v * v; dist = math.pi * 4 * math.sqrt( distSq ); ...
6bd367348d4cac0ed3f584ef0866c1e5222835cd
69,679
from datetime import datetime def time_stamp() -> str: """UTC time stamps for logging :return: UTC time as a formatted string """ return datetime.datetime.utcnow().strftime("%Y%m%d_%H:%M:%S")
7dba1afcec52135d5a51125200e054df1141bf0c
69,680
def _make_dataset_feature_statistics_list_proto( stats_proto ): """Constructs a DatasetFeatureStatisticsList proto. Args: stats_proto: The input DatasetFeatureStatistics proto. Returns: The DatasetFeatureStatisticsList proto containing the input stats proto. """ # Create a new DatasetFeatureStat...
0154ff2bd4ec1c19a88584924161e9f81e7a1996
69,681
def absolute_error(residuals): """ :param residuals: a numpy array of the difference between target and model. THIS ARRAY IS MODIFIED IN PLACE :return: AE """ np.absolute(residuals, out=residuals) return np.sum(residuals)
d2190f7aeac7a62f66a7c68798e62e67cccd622a
69,682
def read( model_name, dat, let, fdir=None, fname=None, varname='uindex', nt=0, ): """ Reading variable array from SHEMAT-Suite vtk-file. Parameters ---------- model_name : string String of model name. dat : string String w...
d9f034f4bc3297b0f19116bb5e9f22141be6b759
69,683
def isAffine(expr, include_div = True, include_modulo = False): """ Function to determine if an expression is affine or not. The input is a binary expression tree. It recursively checks if the left and right sub expressions are affine. Determines if the entire expression is affine using the followin...
a37bb4ea00b39fecf0984d0ca9c9cb11c213e5c4
69,684
import logging def evaluation( model: RegressorMixin, x_test: pd.DataFrame, y_test: pd.Series ) -> Output(r2_score=float, rmse=float): """ Args: model: RegressorMixin x_test: pd.DataFrame y_test: pd.Series Returns: r2_score: float rmse: float """ try: ...
99672febfaedd747c3dd194f09f34fe5d1cb89f8
69,685
def get_method_args_as_dict(locals, should_remove_none=False): """ Use inside a class method to get all method arguments as a dictionary.\n Must pass locals() in at top of method\n """ locals.pop("self") if should_remove_none: for k, v in locals.items(): if v is None: ...
e9903eb6216b81cb95fbeecaada8f3e34db864ee
69,686
def upsample(layer, scale, mode="repeat"): """ Upsampling by repetition or bilinear upsampling """ if mode in ["repeat", "dilate"]: return Upscale2DLayer(layer, scale, mode=mode) elif mode in ["bilinear"]: nb_kernels = nn.layers.get_output_shape(layer)[1] return upsample_bilinear...
8c913a3bb54436b7924660fb9a6e4458d59d9e8f
69,687
def sample_recipe(user, **params): # the ** means that any extra key-word arguments passed in other than user will be passed into a dict called params """Create and return a sample recipe""" defaults = { 'title': 'Sample recipe', 'time_minutes': 10, 'price': 5.00, } defaults.upda...
67164cd0ab94e890407c3302a01d091493376b24
69,688
def rank_multiple_queries(predictions, qptr, max_documents=None, inverted=False, n_results=None): """ Given predicted scores for queries rankings are generated and returned. """ max_value = np.max(predictions) # vector with lenght of each doclist n = qptr[1:]-qptr[:-1] if not max_documents:...
1753b3235434ea5f61dbc454037eb74e5c4b2c0d
69,689
def intersection_in_2orders(orders_pd, other_orders_pd, same_rule=EOrderSameRule.ORDER_SAME_BSPD): """ 交集: 分析因子或者参数问题时使用,debug策略问题时筛选出两个orders_pd中相同的交易, 即结果为交集:orders_pd & cmp_orders_pd或orders_pd.intersection(cmp_orders_pd) :param orders_pd: 回测结果生成的交易订单构成的pd.DataFrame对象 :param other_orders_pd: 回测结果生...
c2fd5a45b016308b375dabacdb206732abdea357
69,690
from typing import Dict def fraud_watch_brands_list_command(client: Client, args: Dict) -> CommandResults: """ Gets a list of brands from FraudWatch service: - Limit: Total number of brands in a page. The default limit is 20, minimum number is also 20 and the maximum number is 100. - Page...
a814872debdcf162efd39f96b9ce2e447b5633be
69,691
import sod def analyticSolution(*args, **kwargs): """ A wrapper for sod.solve(). Requires the sod-shocktube package, available at https://github.com/ibackus/sod-shocktube See sod.solve() for documentation """ try: except ImportError: print "sod-shocktube package must be installed....
b159768e17e5c8cddce4e89c23790edd9045fd1a
69,692
import os import glob from typing import OrderedDict import importlib def get_all_main_functions(): """Get a dict with all scripts (used for testing). """ # Could this work? # http://stackoverflow.com/questions/1707709/list-all-the-modules-that-are-part-of-a-python-package # import pkgutil # p...
d6cb18b67380e500f78c3ddda5d7832871ec6a35
69,693
def clean_artists(df): """ Filter irrelevant playlists.""" # Remove artists with same name. df = df.drop_duplicates(subset='name', keep='first') # Remove artists from other countries foreign_countries_re = 'argentin|chile|colombia|mexic|peru|uruguay' df = df[~df.genres.astype(str).str.contains...
c0f5f6fbe4a2e2307a728112c304d660e307f929
69,694
def sample_user(email='test@gmail.com', password='testpass'): """Create a sample user""" return get_user_model().objects.create_user(email=email, password=password)
c894bad826f6b6d6bdb1afde0928f4216be7eb20
69,695
import json def send_all_provider_balances(): """ Send all the funds to all the providers """ transaction = payment_manager_contract.send_all_provider_balances() if transaction is not None: return json.dumps({'Response': '200 - OK', 'Transaction': transaction}) else: return jso...
19d182ae338be54c39df85aa3510945284b3fccd
69,696
from datetime import datetime from pathlib import Path def job_scatter(account, target, d_from, d_to='', d_from_drop='', out_name='', out_path='', plot_jobstack=True, plot_insta=True, plot_cumu=True, plot_mem_delta=False, plot_start_wait=False): """Accepts an account name and quer...
8e4456b06ba08905d6b389af92a51d7e51d57413
69,697
def disabled(syncplan_name, p5_connection=None): """ Syntax: SyncPlan <name> disabled Description: Queries the plan Disabled status Return Values: -On Success: the string "1" (the plan is disabled) or "0" (not disabled) """ method_name = "disabled" return exec_nsdchat([module_name, syn...
b4fa8d60ec9ce25762f25e07e694596230695892
69,698
from datetime import datetime def _parse_datetime_string(val): """ Attempts to parse a string representation of a date or datetime value, and returns a datetime if successful. If not, a InvalidDateTimeString exception will be raised. """ dt = None lenval = len(val) fmt = {19: "%Y-%m-%d...
3a9fa6b2829d4fce9f495ea290b8d42327738c89
69,699