content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List from typing import Set def knapsack_with_budget(vals: List[float], weights: List[int], budget: int, cap: int) -> Set[int]: """ Solves the knapsack problem (with budget) of the items with the given values and weights, with the given budget and capacity, in a...
3d91f18f8be7b82f17ebcda9dbfa419eadeec0ea
3,655,800
import functools def _basemap_redirect(func): """ Docorator that calls the basemap version of the function of the same name. This must be applied as the innermost decorator. """ name = func.__name__ @functools.wraps(func) def wrapper(self, *args, **kwargs): if getattr(self, 'name'...
f3cee9113a6f8044255d3013e357742e231ea98e
3,655,801
def embedding_lookup(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings"): """Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, s...
2f66d05ab70f4fb38d990e66ec5829cb62fdc934
3,655,802
import re def find_version(infile): """ Given an open file (or some other iterator of lines) holding a configure.ac file, find the current version line. """ for line in infile: m = re.search(r'AC_INIT\(\[tor\],\s*\[([^\]]*)\]\)', line) if m: return m.group(1) retur...
35ac18757ee1156f046bbd9ffa68ed4898bc317a
3,655,803
import math def linear_warmup_decay(warmup_steps, total_steps, cosine=True, linear=False): """ Linear warmup for warmup_steps, optionally with cosine annealing or linear decay to 0 at total_steps """ # check if both decays are not True at the same time assert not (linear and cosine) def f...
9326622a07be677cb82744a30850674ca3c5f789
3,655,804
def query_anumbers(bbox,bbox2,bounds2): """ Queries anumbers of the reports within region defined Args: `bbox`= bounds of the region defined Returns: `anumberscode`=list of anumbers """ try: collars_file='http://geo.loop-gis.org/geoserver/loop/wfs?service=WFS&version=1.0....
91a31ba05df1a88f1c665f7d4dbb1c2d26bb2cc9
3,655,805
def Parse(spec_name, arg_r): # type: (str, args.Reader) -> args._Attributes """Parse argv using a given FlagSpec.""" spec = FLAG_SPEC[spec_name] return args.Parse(spec, arg_r)
9dc2de95e8f9001eff82f16de6e14f51f768306f
3,655,806
def get_path_url(path: PathOrString) -> str: """Covert local path to URL Arguments: path {str} -- path to file Returns: str -- URL to file """ path_obj, path_str = get_path_forms(path) if is_supported_scheme(path_str): return build_request(path_str) return path_ob...
812471da77d59cc0f331b5a031282abb5847f054
3,655,807
def process_keyqueue(codes, more_available): """ codes -- list of key codes more_available -- if True then raise MoreInputRequired when in the middle of a character sequence (escape/utf8/wide) and caller will attempt to send more key codes on the next call. returns (list of input, list ...
8a49f55ca760853176c319487936c8e93911535e
3,655,808
from typing import Dict from typing import List from typing import Tuple def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]: """ Given labels and a constraint type, returns the allowed transitions. It will additionally include transitions for the start and end s...
173dd26c17156ecd73ba1181022183b68f158331
3,655,809
import argparse def get_args(**kwargs): """ """ cfg = deepcopy(kwargs) parser = argparse.ArgumentParser( description="Train the Model on CINC2019", formatter_class=argparse.ArgumentDefaultsHelpFormatter) # parser.add_argument( # "-l", "--learning-rate", # metavar="L...
07411949f0219d4c20351c8cefbdc161cafc6ed4
3,655,810
import time from datetime import datetime import os def initialize(cfg, args): """ purpose: load information and add to config """ if cfg.sessionId in (None, '') or cfg.useSessionTimestamp is True: cfg.useSessionTimestamp = True cfg.sessionId = utils.dateStr30(time.localtime()) else: ...
dac199c20c02a5467ba240d592085a7ac8df40c0
3,655,811
def simple_linear(parent = None, element_count=16, element_pitch=7e-3): """1D line of elements, starting at xyz=0, along y, with given element_pitch Parameters ---------- parent : handybeam.world.World the world to give to this array as parent element_count : int count of ...
7cb7a2f5de6ea4ecbe0a67ca8f383bae2bd0f5b0
3,655,812
def for_all_methods(decorator, exclude_methods=None): """ Class decorator """ if exclude_methods is None: exclude_methods = [] def decorate(cls): for attr in cls.__dict__: if ( callable(getattr(cls, attr)) and attr not in DO_NOT_DECORATE_M...
6a24961ebd512a20f3b0cad9c3657fa6ff5997ea
3,655,813
import os def download_if_not_there(file, url, path, force=False, local_file=None): """Downloads a file from the given url if and only if the file doesn't already exist in the provided path or ``force=True`` Args: file (str): File name url (str): Url where the file can be found (without t...
4b470aeb3fb45e4f10784c2074d14209026dbdbd
3,655,814
def _kuramoto_sivashinsky_old(dimensions, system_size, dt, time_steps): """ This function INCORRECTLY simulates the Kuramoto–Sivashinsky PDE It is kept here only for historical reasons. DO NOT USE UNLESS YOU WANT INCORRECT RESULTS Even though it doesn't use the RK4 algorithm, it is bundled with the ot...
3c0158946b1220e0fa56bea201e2ee31d6df51e5
3,655,815
def get_geneids_of_user_entity_ids(cursor, unification_table, user_entity_ids): """ Get the Entrez Gene IDs of targets using their BIANA user entity ids """ query_geneid = ("""SELECT G.value, G.type FROM externalEntityGeneID G, {} U WHERE U.externalEntityID...
bf192c192352da64716ecab6b4523b50fea5cd0f
3,655,816
import sys def alpha_015(enddate, index='all'): """ Inputs: enddate: 必选参数,计算哪一天的因子 index: 默认参数,股票指数,默认为所有股票'all' Outputs: Series:index 为成分股代码,values为对应的因子值 公式: (-1\*sum(rank(correlation(rank(high), rank(volume), 3)), 3)) """ enddate = to_date_str(enddate) ...
2c1c56b9184c46c04b2f05d2ce317e4129a92e07
3,655,817
import os def get_path(root, path): """ Shortcut for ``os.path.join(os.path.dirname(root), path)``. :param root: root path :param path: path to file or folder :returns: path to file or folder relative to root """ return os.path.join(os.path.dirname(root), path)
73974d6d54210615b51d3765d1e5dd0d715080f1
3,655,818
def int_array_to_hex(iv_array): """ Converts an integer array to a hex string. """ iv_hex = '' for b in iv_array: iv_hex += '{:02x}'.format(b) return iv_hex
f3332b7672a266ad9cae9fc52bc8e1152bcee58b
3,655,819
from io import StringIO import logging import tempfile def minimal_sphinx_app( configuration=None, sourcedir=None, with_builder=False, raise_on_warning=False ): """Create a minimal Sphinx environment; loading sphinx roles, directives, etc.""" class MockSphinx(Sphinx): """Minimal sphinx init to lo...
55c911a16748e61ff3461833e82661314c5ffdca
3,655,820
def calc_Mo_from_M(M, C=C): """ Calculate seismic moment (Mo) from moment magnitude (M) given a scaling law. C is a scaling constant; should be set at 6, but is defined elsewhere in the module so that all functions using it share a value. """ term1 = 3/2. * C * (np.log(2) + np.log(5) ) ...
f72033100829126a353d7682f449d0ff4cd3efa8
3,655,821
import sys from sys import path def resource_path(*args): """ Get absolute path to resource, works for dev and for PyInstaller """ base_path = getattr(sys, '_MEIPASS', path.dirname(path.abspath(__file__))) return path.join(base_path, *args)
b6094b28f6a0cb1be5f4e4c05349971dbd559863
3,655,822
import pathlib def _file_format_from_filename(filename): """Determine file format from its name.""" filename = pathlib.Path(filename).name return _file_formats[filename] if filename in _file_formats else ""
25f90333696491ddd7b522ca2ac24c84a09e8d07
3,655,823
def r2k(value): """ converts temperature in R(degrees Rankine) to K(Kelvins) :param value: temperature in R(degrees Rankine) :return: temperature in K(Kelvins) """ return const.convert_temperature(value, 'R', 'K')
93c3a7ead8b6b15fc141cd6339acedc044dd2c61
3,655,824
import select def add_version(project, publication_id): """ Takes "title", "filename", "published", "sort_order", "type" as JSON data "type" denotes version type, 1=base text, 2=other variant Returns "msg" and "version_id" on success, otherwise 40x """ request_data = request.get_json() if ...
b6887e5d09e54827ed4f5ad50f1c3e404d55e821
3,655,825
import functools def to_decorator(wrapped_func): """ Encapsulates the decorator logic for most common use cases. Expects a wrapped function with compatible type signature to: wrapped_func(func, args, kwargs, *outer_args, **outer_kwargs) Example: @to_decorator def foo(func, args, kwargs...
d7c9d0e759e59c26b7c5f7b098e15b78314c8860
3,655,826
def _get_unit(my_str): """ Get unit label from suffix """ # matches = [my_str.endswith(suffix) for suffix in _known_units] # check to see if unit makes sense if not any(matches): raise KeyError('Unit unit not recognized <{}>!'.format(my_str)) # pick unit that matches, with prefix ...
86cbb00dbd95025fde265461963e45d457d68470
3,655,827
import random def spec_augment(spectrogram, time_mask_para=70, freq_mask_para=20, time_mask_num=2, freq_mask_num=2): """ Provides Augmentation for audio Args: spectrogram, time_mask_para, freq_mask_para, time_mask_num, freq_mask_num spectrogram (torch.Tensor): spectrum time_mask_para (int...
a2f1c669253250a581a555a531db79fb756b91bb
3,655,828
def scale(a: tuple, scalar: float) -> tuple: """Scales the point.""" return a[0] * scalar, a[1] * scalar
9638b8cfbd792c2deb35da304c5c375e0402404e
3,655,829
def parse_env(env): """Parse the given environment and return useful information about it, such as whether it is continuous or not and the size of the action space. """ # Determine whether input is continuous or discrete. Generally, for # discrete actions, we will take the softmax of the output ...
4f5c97e71b7c1e8a319c28c4c1c26a1b758c731b
3,655,830
def encode_dataset(dataset, tester, mode="gate"): """ dataset: object from the `word-embeddings-benchmarks` repo dataset.X: a list of lists of pairs of word dataset.y: similarity between these pairs tester: tester implemented in my `tester.py`""" words_1 = [x[0] for x in dataset["X"]] ...
726aed93e3cef49f014d44f62e5ff73eae47da43
3,655,831
import io import os def _RunSetupTools(package_root, setup_py_path, output_dir): """Executes the setuptools `sdist` command. Specifically, runs `python setup.py sdist` (with the full path to `setup.py` given by setup_py_path) with arguments to put the final output in output_dir and all possible temporary fil...
6638cc2f08f6e588cb469c37ea7e31b40d8cddf8
3,655,832
from metadataStore.userapi.commands import search def default_search_func(search_dict): """ Defaults to calling the data broker's search function Parameters ---------- search_dict : dict The search_dict gets unpacked into the databroker's search function Returns ------- searc...
b6eefe27a757051d9bbb40b21164a6f2702eeffb
3,655,833
import csv def readData(filename): """ Read in our data from a CSV file and create a dictionary of records, where the key is a unique record ID and each value is dict """ data_d = {} with open(filename) as f: reader = csv.DictReader(f) for row in reader: clean_row =...
193901c98966f4c0bd2b0e326711b962197ef4da
3,655,834
from datetime import datetime import os def share(request, token): """ Serve a shared file. This view does not require login, but requires a token. """ share = get_object_or_404( Share, Q(expires__isnull=True) | Q(expires__gt=datetime.datetime.now()), token=token) # ...
15d75300784104a165aa31f7b71c0c9099b46622
3,655,835
def update_roi_mask(roi_mask1, roi_mask2): """Y.G. Dec 31, 2016 Update qval_dict1 with qval_dict2 Input: roi_mask1, 2d-array, label array, same shape as xpcs frame, roi_mask2, 2d-array, label array, same shape as xpcs frame, Output: roi_mask, 2d-array, label array, same shape ...
211d6db69438866ff64c1944fa513ab847d9e641
3,655,836
import os def get_latest_recipes(recipe_folder, config, package="*"): """ Generator of recipes. Finds (possibly nested) directories containing a `meta.yaml` file and returns the latest version of each recipe. Parameters ---------- recipe_folder : str Top-level dir of the recipes ...
9441f0fcfce93f094ca50a2b510e4e5c2afb6c1b
3,655,837
from typing import List from typing import Tuple from typing import Dict from typing import Any def training_loop( train_sequences: List[Tuple[pd.DataFrame, float]], val_sequences: List[Tuple[pd.DataFrame, float]], test_sequences: List[Tuple[pd.DataFrame, float]], parameters: Dict[str, Any], dir_...
27b02630173d972a83c82140e0d2c6c957266fa4
3,655,838
def nmi(X, y): """ Normalized mutual information between X and y. :param X: :param y: """ mi = mutual_info_regression(X, y) return mi / mi.max()
5da09b9395883f9b197b2c2add7850d0e1870c44
3,655,839
from typing import Optional import re def attribute_as_str(path: str, name: str) -> Optional[str]: """Return the two numbers found behind --[A-Z] in path. If several matches are found, the last one is returned. Parameters ---------- path : string String with path of file/folder to get at...
257fec03ca911c703e5e06994477cf0b3b75a2ae
3,655,840
def racket_module(value): """ a very minimal racket -> python interpreter """ _awaiting = object() _provide_expect = object() def car(tup): return tup[0] def cdr(tup): return tup[1:] def eval(env, tup): last = None for value in tup: if isinstance(value, tuple): ...
c7fc0937b70bb71143af630cb93699632081ece8
3,655,841
def validate_inputs(input_data: pd.DataFrame) -> pd.DataFrame: """Check model for unprocessable values.""" valudated_data = input_data.copy() # check for numerical variables with NA not seen during training return validated_data
65087650e9a5e85c3a362a5e27f82bf5f27a1f59
3,655,842
def index(): """ Check if user is authenticated and render index page Or login page """ if current_user.is_authenticated: user_id = current_user._uid return render_template('index.html', score=get_score(user_id), username=get_username(user_id)) else: return redirect(url_f...
edb8ad552ab34640fc030250659ebd05027712fa
3,655,843
from typing import Iterable from typing import Callable from typing import Optional def pick( seq: Iterable[_T], func: Callable[[_T], float], maxobj: Optional[_T] = None ) -> Optional[_T]: """Picks the object obj where func(obj) has the highest value.""" maxscore = None for obj in seq: score =...
7f29c3aef5086957a1b1bd97f086a6ba6fb22cfd
3,655,844
def rsync_public_key(server_list): """ 推送PublicKey :return: 只返回推送成功的,失败的直接写错误日志 """ # server_list = [('47.100.231.147', 22, 'root', '-----BEGIN RSA PRIVATE KEYxxxxxEND RSA PRIVATE KEY-----', 'false')] ins_log.read_log('info', 'rsync public key to server') rsync_error_list = [] rsync_suce...
94c9941e3f63caf15b0df8c19dc91ee54d002316
3,655,845
import re from bs4 import BeautifulSoup def create_one(url, alias=None): """ Shortens a URL using the TinyURL API. """ if url != '' and url is not None: regex = re.compile(pattern) searchres = regex.search(url) if searchres is not None: if alias is not None: ...
a543c23bc694fe09bae3bb4d59802fa6a5c3897d
3,655,846
def duplicate_each_element(vector: tf.Tensor, repeat: int): """This method takes a vector and duplicates each element the number of times supplied.""" height = tf.shape(vector)[0] exp_vector = tf.expand_dims(vector, 1) tiled_states = tf.tile(exp_vector, [1, repeat]) mod_vector = tf.reshape(tiled_st...
5b8ea4307d5779929def59805bc5210d8e948a4d
3,655,847
def apk(actual, predicted, k=3): """ Computes the average precision at k. This function computes the average precision at k for single predictions. Parameters ---------- actual : int The true label predicted : list A list of predicted elements (order does matter)...
27c8d1d03f5fe571f89378d1beb60cde9d82f27e
3,655,848
def make_predictor(model): """ Factory to build predictor based on model type provided Args: model (DeployedModel): model to use when instantiating a predictor Returns: BasePredictor Child: instantiated predictor object """ verify = False if model.example == '' else True ...
87a89d179c28e971a3c29946e94105542686510e
3,655,849
def get(identifier: str) -> RewardScheme: """Gets the `RewardScheme` that matches with the identifier. Arguments: identifier: The identifier for the `RewardScheme` Raises: KeyError: if identifier is not associated with any `RewardScheme` """ if identifier not in _registry.keys(): ...
574126cab1a1c1bd10ca2ada1fe626ba66910b11
3,655,850
def add_query_params(url: str, query_params: dict) -> str: """Add query params dict to a given url (which can already contain some query parameters).""" path_result = parse.urlsplit(url) base_url = path_result.path # parse existing query parameters if any existing_query_params = dict(parse.parse_q...
8ea28c2492343e0f7af3bac5d44751827dd6b7aa
3,655,851
import ast import torch def tokenize_lexicon_str(vocab, lexicon_str, pad_max_length, device): """ #todo add documentation :param lexicon_str: :return: a tensor of ids from vocabulary for each . shape=(batch_size,max_length?) """ out_tensor = [] out_mask = [] for row in lexicon_str: ...
a316b4cba9f9ca729de4a49c17dc718ad004f56c
3,655,852
def try_get_mark(obj, mark_name): """Tries getting a specific mark by name from an object, returning None if no such mark is found """ marks = get_marks(obj) if marks is None: return None return marks.get(mark_name, None)
1dd8b9635d836bbce16e795900d7ea9d154e5876
3,655,853
def timedelta_to_seconds(ts): """ Convert the TimedeltaIndex of a pandas.Series into a numpy array of seconds. """ seconds = ts.index.values.astype(float) seconds -= seconds[-1] seconds /= 1e9 return seconds
4565d7a691e8ac004d9d529568db0d032a56d088
3,655,854
def parse_gage(s): """Parse a streamgage key-value pair. Parse a streamgage key-value pair, separated by '='; that's the reverse of ShellArgs. On the command line (argparse) a declaration will typically look like:: foo=hello or foo="hello world" :param s: str :rtype: tuple(key, value) ...
299b47f3a4757c924620bdc05e74f195a4cb7967
3,655,855
from typing import Mapping def get_attribute(instance, attrs): """ Similar to Python's built in `getattr(instance, attr)`, but takes a list of nested attributes, instead of a single attribute. Also accepts either attribute lookup on objects or dictionary lookups. """ for attr in attrs: ...
121ef8d4b0b6b69fda1591e2f372a4cf9ec60129
3,655,856
import traceback def pull_cv_project(request, project_id): """pull_cv_project. Delete the local project, parts and images. Pull the remote project from Custom Vision. Args: request: project_id: """ # FIXME: open a Thread/Task logger.info("Pulling CustomVision Project") ...
c21ad6a15c9eafba723cd20b1bafbcc4a36dfc38
3,655,857
from datetime import datetime def get_log_line_components(s_line): """ given a log line, returns its datetime as a datetime object and its log level as a string and the message itself as another string - those three are returned as a tuple. the log level is returned as a single character (first c...
3ec7e5418f39a579ce8b71f3c51a8e1356cb5291
3,655,858
def is_eligible_for_bulletpoint_vote(recipient, voter): """ Returns True if the recipient is eligible to receive an award. Checks to ensure recipient is not also the voter. """ if voter is None: return True return (recipient != voter) and is_eligible_user(recipient)
20d34076c92b7fd9474a7cf4edf7ca38ad3ffba5
3,655,859
def _get_in_collection_filter_directive(input_filter_name): """Create a @filter directive with in_collecion operation and the desired variable name.""" return DirectiveNode( name=NameNode(value=FilterDirective.name), arguments=[ ArgumentNode( name=NameNode(value="op_n...
3c8b18314aa415d6dbec14b63a956e5fdf73aa9d
3,655,860
def load_labelmap(path): """Loads label map proto. Args: path: path to StringIntLabelMap proto text file. Returns: a StringIntLabelMapProto """ with tf.gfile.GFile(path, 'r') as fid: label_map_string = fid.read() label_map = string_int_label_map_pb2.StringIntLabelMap() try: text_for...
3ec29d2dc8fc4bacde5f0dfa49465676f5e8c44c
3,655,861
def calc_internal_hours(entries): """ Calculates internal utilizable hours from an array of entry dictionaries """ internal_hours = 0.0 for entry in entries: if entry['project_name'][:22] == "TTS Acq / Internal Acq" and not entry['billable']: internal_hours = internal_hours + flo...
0962ee49f60ac296668294e6d2f075ce981cbc55
3,655,862
def format_str_strip(form_data, key): """ """ if key not in form_data: return '' return form_data[key].strip()
44c5aaf8c5e11bfee05971d2961e5dcaf4cd8d9f
3,655,863
def get_element(element_path: str): """ For base extension to get main window's widget,event and function,\n pay attention,you must be sure the element's path grammar: element's path (father>attribute>attribute...) like UI_WIDGETS>textViewer """ try: listed_element_path = element_path.s...
041ec89a700018ce5a6883a80a1998d7179c7041
3,655,864
import urllib def gravatar_for_email(email, size=None, rating=None): """ Generates a Gravatar URL for the given email address. Syntax:: {% gravatar_for_email <email> [size] [rating] %} Example:: {% gravatar_for_email someone@example.com 48 pg %} """ gravatar_url = "%savatar...
73f3eed5ea073cd4bf6e4a978983c4ed12cedcd6
3,655,865
def decmin_to_decdeg(pos, decimals=4): """Convert degrees and decimal minutes into decimal degrees.""" pos = float(pos) output = np.floor(pos / 100.) + (pos % 100) / 60. return round_value(output, nr_decimals=decimals)
de6490ce5278090b90f87adab57fe8b912307e2c
3,655,866
def get_selector(selector_list, identifiers, specified_workflow=None): """ Determine the correct workflow selector from a list of selectors, series of identifiers and user specified workflow if defined. Parameters ---------- selector_list list List of dictionaries, where the value of all di...
f458a82d2d0e81070eefabd490127567a1b67bbb
3,655,867
import functools import inspect import re def register_pth_hook(fname, func=None): """ :: # Add a pth hook. @setup.register_pth_hook("hook_name.pth") def _hook(): '''hook contents.''' """ if func is None: return functools.partial(register_pth_hook, fname) ...
1090d4601e0d51ec4c7761bb070318f906c23f87
3,655,868
def callable_or_raise(obj): """Check that an object is callable, else raise a :exc:`ValueError`. """ if not callable(obj): raise ValueError('Object {0!r} is not callable.'.format(obj)) return obj
cb6dd8c03ea41bb94a8357553b3f3998ffcc0d65
3,655,869
def extractLandMarks(fm_results): """TODO: add preprocessing/normalization step here""" x = [] y = [] z = [] for i in range(468): x.append(fm_results.multi_face_landmarks[0].landmark[i].x) y.append(fm_results.multi_face_landmarks[0].landmark[i].y) z.append(fm_results.multi_fa...
04370c6e0a3a8a4a68b914e0b7c002b829d0a042
3,655,870
def conv_coef(posture="standing", va=0.1, ta=28.8, tsk=34.0,): """ Calculate convective heat transfer coefficient (hc) [W/K.m2] Parameters ---------- posture : str, optional Select posture from standing, sitting or lying. The default is "standing". va : float or iter, option...
d351b82d2ffb81396b4e0ce2f05b429cb79ac28c
3,655,871
def _one_formula(lex, fmt, varname, nvars): """Return one DIMACS SAT formula.""" f = _sat_formula(lex, fmt, varname, nvars) _expect_token(lex, {RPAREN}) return f
166c73c6214a0f6e3e6267804d2dd5c16b43a652
3,655,872
def _split_variables(variables): """Split variables into always passed (std) and specified (file). We always pass some variables to each step but need to explicitly define file and algorithm variables so they can be linked in as needed. """ file_vs = [] std_vs = [] for v in variables: ...
2b297bf99153256769d42c3669f3f8f29da95b70
3,655,873
import numpy def percentiles_fn(data, columns, values=[0.0, 0.25, 0.5, 0.75, 1.0], remove_missing=False): """ Task: Get the data values corresponding to the percentile chosen at the "values" (array of percentiles) after sorting the data. return -1 if no data was found :param da...
cfacd575e3e1f8183b1e82512859198a973a1f85
3,655,874
def base_checkout_total( subtotal: TaxedMoney, shipping_price: TaxedMoney, discount: Money, currency: str, ) -> TaxedMoney: """Return the total cost of the checkout.""" zero = zero_taxed_money(currency) total = subtotal + shipping_price - discount # Discount is subtracted from both gross...
04017f67249b2415779b8a7bbfa854653ec6c285
3,655,875
def if_statement(lhs='x', op='is', rhs=0, _then=None, _else=None): """Celery Script if statement. Kind: _if Arguments: lhs (left-hand side) op (operator) rhs (right-hand side) _then (id of sequence to execute on `then`) _else (id of sequence to execute on `el...
c42baa0933be08e89049894acfd3c003832331db
3,655,876
def add_next_open(df, col='next_open'): """ 找出下根K线的开盘价 """ df[col] = df[CANDLE_OPEN_COLUMN].shift(-1) df[col].fillna(value=df[CANDLE_CLOSE_COLUMN], inplace=True) return df
185fdd87b437546be63548506adef7bb56c4aa5d
3,655,877
def seasons_used(parameters): """ Get a list of the seasons used for this set of parameters. """ seasons_used = set([s for p in parameters for s in p.seasons]) # Make sure this list is ordered by SEASONS. return [season for season in SEASONS if season in seasons_used]
641e0b4dd01bd30bf9129a9302ad5935a614588f
3,655,878
def get_polyphyletic(cons): """get polyphyletic groups and a representative tip""" tips, taxonstrings = unzip(cons.items()) tree, lookup = make_consensus_tree(taxonstrings, False, tips=tips) cache_tipnames(tree) names = {} for n in tree.non_tips(): if n.name is None: continu...
b53a50170b3546f8228aa82013545148918155b7
3,655,879
from typing import Tuple from typing import cast def find_closest_integer_in_ref_arr(query_int: int, ref_arr: NDArrayInt) -> Tuple[int, int]: """Find the closest integer to any integer inside a reference array, and the corresponding difference. In our use case, the query integer represents a nanosecond-discr...
9d0e43d869b94008fb51b1281041538a85d48d7e
3,655,880
def saver_for_file(filename): """ Returns a Saver that can load the specified file, based on the file extension. None if failed to determine. :param filename: the filename to get the saver for :type filename: str :return: the associated saver instance or None if none found :rtype: Saver """...
0838a46be5a282849fdf48584e9a8e971b7ef966
3,655,881
def make(context, name): """Create an object in a registered table class. This function will be stored in that object, so that the new table object is able to create new table objects in its class. !!! hint This is needed when the user wants to insert new records in the table. Parameters ...
2b87aa461f97c1d1e1c6ff9a8c6d4128d8eccbb3
3,655,882
def cofilter(function, iterator): """ Return items in iterator for which `function(item)` returns True. """ results = [] def checkFilter(notfiltered, item): if notfiltered == True: results.append(item) def dofilter(item): d = maybeDeferred(function, item) d....
0c14ce3310e1f1a2984b1faf5be21c552ca65b43
3,655,883
def download_dataset(dataset_name='mnist'): """ Load MNIST dataset using keras convenience function Args: dataset_name (str): which of the keras datasets to download dtype (np.dtype): Type of numpy array Returns tuple[np.array[float]]: (train images, train labels), (test images...
c4bda5981acaf1907d46724f217012bf9349e9da
3,655,884
from typing import Callable from datetime import datetime def __listen_for_requests_events(node_id, success, measurement: str = 'locust_requests') -> Callable: """ Persist request information to influxdb. :param node_id: The id of the node reporting the event. :param measurement: The measurement wher...
de7aef12f2caf77242a863076a2cd8241e611b94
3,655,885
from typing import Type from textwrap import dedent def create_trigger_function_sql( *, audit_logged_model: Type[Model], context_model: Type[Model], log_entry_model: Type[Model], ) -> str: """ Generate the SQL to create the function to log the SQL. """ trigger_function_name = f"{ audi...
696443cee7752b74542d259d4a223f419462d18f
3,655,886
def reorder_by_first(*arrays): """ Applies the same permutation to all passed arrays, permutation sorts the first passed array """ arrays = check_arrays(*arrays) order = np.argsort(arrays[0]) return [arr[order] for arr in arrays]
bd9e60cadba4644b06ae55396c7dcae33f1fa1d0
3,655,887
def embedding_weights(mesh, vocab_dim, output_dim, variable_dtype, name="embedding", ensemble_dim=None, initializer=None): """Embedding weights.""" if not ensemble_dim: ensemble_di...
b89d5a411757d704c57baff6e4a74b7a5807c381
3,655,888
def generiraj_emso(zenska): """Funkcija generira emso stevilko""" rojstvo = random_date_generator(julijana_zakrajsek) # Odstranim prvo števko leta emso_stevke = rojstvo[:4] + rojstvo[5:] if zenska: # Malce pretirana poenostavitev zadnjih treh cifer, lahko se zgodi da pridejo iste + zanemarja...
89734021fd0d6f863a309b5c23c0a4ee6d385edf
3,655,889
def pdf_markov2(x, y, y_offset=1, nlevels=3): """ Compute the empirical joint PDF for two processes of Markov order 2. This version is a bit quicker than the more general pdf() function. See the docstring for pdf for more info. """ y_offset = np.bool(y_offset) # out = np.ones((nlevels,)*6...
6d789d1ef9ff88c27f610e9904bdbc27fbe10e5b
3,655,890
import typing from typing import Union def cvt_dotted_as_name(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base: """dotted_as_name: dotted_name ['as' NAME]""" assert ctx.is_REF, [node] dotted_name = xcast(ast_cooked.DottedNameNode, cvt(node.children[0], ctx.to_BARE())) if len(node.children) == 1: ...
5edf3f7c17db85ca43dcf263e30b127fba7f37fc
3,655,891
import os def train( model, data, epochs=10, batch_size=100, lr=0.001, lr_decay_mul=0.9, lam_recon=0.392, save_dir=None, weights_save_dir=None, save_freq=100, ): """Train a given Capsule Network model. Args: model: The CapsuleNet model to train. data: T...
4cb8b8555c3fd1c62d2cf5741471cbf757029054
3,655,892
def check_if_recipe_skippable(recipe, channels, repodata_dict, actualname_to_idname): """ check_if_recipe_skippable ========================= Method used to check if a recipe should be skipped or not. Skip criteria include: - If the version of the recipe in the channel repodata is greater t...
604fdcf86ec45826f53fd837d165b234e9d11d91
3,655,893
import types def ensure_csv_detections_file( folder: types.GirderModel, detection_item: Item, user: types.GirderUserModel ) -> types.GirderModel: """ Ensures that the detection item has a file which is a csv. Attach the newly created .csv to the existing detection_item. :returns: the file document...
1b9b9a3dff8eedd51193db023b71948118e0fd79
3,655,894
def hello(name=None): """Assuming that name is a String and it checks for user typos to return a name with a first capital letter (Xxxx). Args: name (str): A persons name. Returns: str: "Hello, Name!" to a given name, or says Hello, World! if name is not given (or passed as an empty String...
f1aafbebd49507fd5417d8752f98ae7d0af8ec33
3,655,895
def computePCA(inputMatrix, n_components=None): """Compute Principle Component Analysis (PCA) on feature space. n_components specifies the number of dimensions in the transformed basis to keep.""" pca_ = PCA(n_components) pca_.fit(inputMatrix) return pca_
4061f998bfca9ed294b312ae746a63ea0eef8438
3,655,896
def tag(repo, subset, x): """The specified tag by name, or all tagged revisions if no name is given. Pattern matching is supported for `name`. See :hg:`help revisions.patterns`. """ # i18n: "tag" is a keyword args = getargs(x, 0, 1, _("tag takes one or no arguments")) cl = repo.changelog ...
d4ceadb7ef03ae6ed950c60c7bbf06b4d26f8671
3,655,897
def _embed_json(service, targetid): """ Returns oEmbed JSON for a given URL and service """ return d.http_get(_OEMBED_MAP[service] % (urlquote(targetid),)).json()
347d38e2b4f69c853e8085308e334b7cc778d4ad
3,655,898
import re def is_blank(s): """Returns True if string contains only space characters.""" return re.search(reNonSpace, s) is None
40b4ec62a2882d100b80fd951c6b9e4d31220581
3,655,899