content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def substitute_variables(model_params_variables, model_data_raw): """ :param model_params_variables: :param model_data_raw: :return: """ model_data_list = [] for argument_raw in model_data_raw: argument_split_raw = argument_raw.split(",") argument_split = [] for par...
bb34bc44f9f4c633d5396fde31bf8ece5cd163c6
3,630,800
def getFirstDay(curDate, curWeek): """get first day of the first week""" assert(curWeek >= 1) curDate -= timedelta(weeks=curWeek-1) curDate -= timedelta(days=curDate.weekday()) return curDate
b9b2de6040cc655aa309a763046300cd88d92ab1
3,630,801
from typing import List from re import T from typing import Callable from typing import Optional import click def select_from_list(data: List[T], name: Callable[[T], str], prompt: str) -> Optional[T]: """Interactively selects named entity from given list""" names: List[str] = list(map(name, data)) prompt ...
cb76336780d5efb6b3f2d6d71cc210c5743c2bb6
3,630,802
def gram_matrix(features, normalize=True): """ Compute the Gram matrix from features. Inputs: - features: Tensor of shape (1, H, W, C) giving features for a single image. - normalize: optional, whether to normalize the Gram matrix If True, divide the Gram matrix by the number of n...
094dcdf8e3ee65fcc9ec19d226062fbb9ac01781
3,630,803
import os def project_path(*relative_paths): """Full path corresponding to 'relative_paths' components""" return os.path.join(MetaDefs.project_dir, *relative_paths)
19027b20a31ed976b115d209795d4a123dfea66f
3,630,804
import tempfile import subprocess def get_html_docker(url: str) -> str: """Returns the rendered HTML at *url* as a string""" cmd = ['docker', 'container', 'run', '--rm', 'zenika/alpine-chrome', '--no-sandbox', '--dump-dom', str(url) ...
2980e35337f572daca7a16f2694620ca5c02aa90
3,630,805
def convert_from_pj_fat_choice(py_json): """ Convert the given py_json into a PlayerFeedVegetarian :param py_json: the PyJSON to convert :type py_json: PyJSON :return: the equivalent PlayerFeedVegetarian :rtype: PlayerFeedVegetarian """ [species_index, fat_to_store] = py_json if not ...
198914610dbe0b0810ebad1bcb1dcc1db1e78938
3,630,806
from typing import OrderedDict def marshal(data, fields, envelope=None): """Takes raw data (in the form of a dict, list, object) and a dict of fields to output and filters the data based on those fields. :param data: the actual object(s) from which the fields are taken from :param fields: a dict of wh...
502fb7b91ff701f3390aae8db5a9463ad792f6ba
3,630,807
def _generator2(path): """ Args: path: path of the dataframe Returns: yield outputs of X and Y pairs """ args = init_args() catalog = load_catalog(path) def preprocess(x): zero = False if not np.any(x): zero = True img = (x - avg_x) / std_...
86d87ce4b53fa6c0d57a2f144542484803447625
3,630,808
import requests from bs4 import BeautifulSoup from datetime import datetime from typing import Counter def main(): """ Get the urls from receita website (to see structure of dict -- see tests) :return: dict with urls from files as well as last modified date and size in bytes """ # get page conten...
a998b014f08fbe4912c1178cd1c2412b3adf2d9c
3,630,809
def dropDuplicatedResponses(dfResponses, dupIdColumns=None, returnDups=False): """ Take a parsed response data frame, returns a data frame after dropping duplications :param dfResponses: data frame with responses :param dupIdColumns: a list of column names to keep track when we identify duplications. ...
15428b6d8938bbd1d3d3dc9e1002206b10a902f6
3,630,810
def load(model_name): """Loads and returns pickle File """ return load_file(model_name)
d8e162104294252494c07335373353ec2bcbc2f0
3,630,811
def get_policy_acc(graph, values): """ compute the accuracy of policy predictions (per graph averaged manner) :param graph: dgl.graph; possibly batched :param values: (predicted) state values :return: """ policy = get_policy(graph, values) with graph.local_scope(): graph.ndata['corre...
fd2cb9741982b6478c34cbeb9b7c305371533974
3,630,812
def domain_domain_pair_association(domain_type_dict, opposite_type_dict={'T': 'AT', 'AT': 'T'}): """ Compute domain domain association. domain_type_dict is a {domain_name:{T:[gene_ids], AT:[gene_ids]} ... } """ domain_domain_dict = {} for domain, type2genes in domain_type_dict.items(): ...
1dea69154132af8e39b4119a307e38bde8269160
3,630,813
def pull_jhu_data(base_url: str, metric: str, pop_df: pd.DataFrame) -> pd.DataFrame: """Pulls the latest Johns Hopkins CSSE data, and conforms it into a dataset The output dataset has: - Each row corresponds to (County, Date), denoted (FIPS, timestamp) - Each row additionally has a column `new_counts`...
b11d852498df4efdebaf15dba2f56f06666a0928
3,630,814
def dict_from_graph_attr(graph, attr, array_values=False): """ Parameters ---------- graph : networkx.Graph attr : str, iterable, or dict If str, then it specifies the an attribute of the graph's nodes. If iterable of strings, then multiple attributes of the graph's nodes ar...
3d097842d92670d8c0217a8ec179cf5e61c83780
3,630,815
from scipy.signal import freqz def _filter_attenuation(h, frequencies, gains): """ Compute minimum attenuation at stop frequency. Args: h (array): Filter coefficients. frequencies (list): Transition frequencies normalized. gains (array): Filter gain at frequency sampling points. ...
e412d987ae83e5f6ae4bae5f550d1cb22590bd41
3,630,816
def about1(): """ Name : about1 function Module : routes Description : This function loads about1.html page. Parameters: None Returns : This function returns the About-us tab of the Web app. Written By : Abhishek Mestry ,Ninad Kadam ,Viresh Dhuri Version : 1.0.0 ...
0e4ab7ea15e0f54c35eb746b41944fba065c8d2e
3,630,817
import os def execute_barrbap(organism, dna_file, con): """determines the 16sRNA sequences using barrnap tool""" # barrnap output file name e.g. barrnap.NC_000913 barrnap_out = cwd + "/barrnap." + organism # > /dev/null 2>&1 is to disable stdout from displaying on terminal barrnap_cmd = "barrnap "...
15b68e3268c9bbfe913fcc6e795ed26320b5499a
3,630,818
from operator import and_ from operator import lt from operator import ge from operator import eq from typing import cast def local_adv_sub1_adv_inc_sub1(fgraph, node): """Optimize the possible AdvSub1(AdvSetSub1(...), ...). AdvancedSubtensor1(AdvancedSetSubtensor1(x, y, idx), idx) -> y Notes ----- ...
f69b7be639457b0147dcb5836a86028277bfa939
3,630,819
import asyncio def mock_coro(return_value=None, exception=None): """Return a coro that returns a value or raise an exception.""" fut = asyncio.Future() if exception is not None: fut.set_exception(exception) else: fut.set_result(return_value) return fut
d06d037bab143e288534e3e7e98da259f7c1cefc
3,630,820
from typing import Tuple def convert_to_classes(data: MoleculeDataset, num_bins: int = 20) -> Tuple[MoleculeDataset, np.ndarray, MoleculeDataset]: """ Converts ...
f8ff21234c94315387fc2669e0ff02d3c3d68fb6
3,630,821
def construct_lambda_schedule(num_windows): """Generate a length-num_windows list of lambda values from 0.0 up to 1.0 Notes ----- manually optimized by YTZ """ A = int(.35 * num_windows) B = int(.30 * num_windows) C = num_windows - A - B # Empirically, we see the largest variance ...
af9104ad7c5f8a529a3098d495c3fbfb38ca5df2
3,630,822
import torch def compute_face_normals_and_areas(vertices: torch.Tensor, faces: torch.Tensor): """ :params vertices (B,N,3) faces (B,F,3) :return face_normals (B,F,3) face_areas (B,F) """ ndim = vertices.ndimension() if vertices.ndimension() == 2...
c586b621d8621aedd4a19d0da11d97e705fe2a06
3,630,823
def der_Cquat_by_v(q,v): """ Being C=C(quat) the rotational matrix depending on the quaternion q and defined as C=quat2rotation(q), the function returns the derivative, w.r.t. the quanternion components, of the vector dot(C,v), where v is a constant vector. The elements of the resulting derivat...
a4ade85551921a96bc371fc2d99793490637a561
3,630,824
def calc_BMDs(Tcpl,BMR=dict(E=[10,20,30],Z=[1,2,3]), ret='dict',add_info=False, dbg=False): """ Calculate benchmark doses corresponding to bmrs:- E: fractional efficacy (top) Z: number of standard deviations (assumes response is in units of Z) """ BF = Tcpl['bes...
478f7b5a811ef0996a3f7db847fe8c9a8aa1b23b
3,630,825
import requests import json def request_records(request_params): """ Download utility rate records from USURDB given a set of request parameters. :param request_params: dictionary with request parameter names as keys and the parameter values :return: """ records = requests.get( ...
7323657186cc87a291e47c3a71cd2e81b4ec8a73
3,630,826
def _handle_sort_key(model_name, sort_key=None): """Generate sort keys according to the passed in sort key from user. :param model_name: Database model name be query.(alarm, meter, etc.) :param sort_key: sort key passed from user. return: sort keys list """ sort_keys_extra = {'alarm': ['name', ...
aef2d996d9d18593ec129c4a37bf8150b3e9c0fe
3,630,827
def view_clear_pages_cache(self, request, form): """ Clears the pages cache. """ layout = DefaultLayout(self, request) if form.submitted(request): request.app.pages_cache.flush() request.message(_("Cache cleared."), 'success') return redirect(layout.manage_link) return { ...
3cad0b2ab565b558c575131e38530c6f548a9f25
3,630,828
def cyan_on_red(string, *funcs, **additional): """Text color - cyan on background color - red. (see sgr_combiner()).""" return sgr_combiner(string, ansi.CYAN, *funcs, attributes=(ansi.BG_RED,))
80072a9df6e8f0c13154d8f563c04d36cfdbc6e1
3,630,829
def calc_glass_constants(nd, nF, nC, *partials): """Given central, blue and red refractive indices, calculate Vd and PFd. Args: nd, nF, nC: refractive indices at central, short and long wavelengths partials (tuple): if present, 2 ref indxs, n4 and n5, wl4 < wl5 Returns: ...
f347b6caf167c19451bb2f03e88b5846c6873250
3,630,830
import subprocess import click def git_status_check(cwd): """check whether there are uncommited changes in current dir Parameters ---------- cwd : str current working directory to check git status Returns ------- bool indicating whether there are uncommited changes ""...
11960967a2e0461ee21861a8aaa856233b0275d9
3,630,831
def light_rgb_schema(gateway, child, value_type_name): """Return a validation schema for V_RGB.""" schema = {"V_RGB": cv.string, "V_STATUS": cv.string} return get_child_schema(gateway, child, value_type_name, schema)
da6b262b8e0c0cc8461e0184e67c6b2bc6c9bee4
3,630,832
from datetime import datetime def macro_timedelta(start_date, years=0, months=0, days=0): """Since datetime doesn't provide timedeltas at the year or month level, this function generates timedeltas of the appropriate sizes. """ delta = datetime.timedelta(days=days) new_month = start_date.month + ...
ee2df42abc74d14951a03827d9c5de67f10cac38
3,630,833
import re def chomp_keep_single_spaces(string): """This chomp cleans up all white-space, not just at the ends""" string = str(string) result = string.replace("\n", " ") # Convert line ends to spaces result = re.sub(" [ ]*", " ", result) # Truncate multiple spaces to single space result = result....
e72a3e416dbbeb97d3984f7f3883a91b0ab13877
3,630,834
def index(): """Displays the main page""" user = get_user() # XXX return redirect('/login') # Render template render = render_template('main.html', lang=lang, user=user) return make_response(render)
0548c072d7eb0def56e444beab39937933fa12c6
3,630,835
import os from pathlib import Path from datetime import datetime def update_ssh_config(sshurl, user, dryrun=False): """ Add a new entry to the SSH config file (``~/.ssh/config``). It sets the default user login to the SSH special remote. Parameters ----------- sshurl : str SSH URL of...
50feb2753eb5095090be7b440bb60a7a0478204b
3,630,836
import re def _unhumanize(human_time_interval): """Converts human_time_interval (e.g. 'an hour ago') into a datetime.timedelta. """ munged = human_time_interval.strip() for needle in _SINGULARS: munged = munged.replace(needle, '1 ') interval_re = '|'.join(_DELTAS.keys()) sre = re....
c70ba342cfb7721517365fed0596a312d35179a1
3,630,837
import re def parase_pbs_script(filename = "emtojob.pbs"): """ Parse the exe part of pbs file Parameter filename: str (filename-like) The filename of the pbs script Return param_dict: dict The dict of parameters. """ s = {"-q": "queue", "-A": "account",...
7c1aed9c08a21b123d70e1697d3cf72fcd418a5e
3,630,838
async def handle_errors(request: Request, exception: Exception): """ Handles exceptions raised by the API. Parameters ---------- exception : Exception Returns ------- str """ return JSONResponse( status_code=exception.code, content={"message": exception.message}...
13a5240d5790f5edbd359c24a990c7adada8a3cc
3,630,839
def immortal(): """ Make target (if 400+) or self (if 399-) immortal. """ av = spellbook.getTarget() if spellbook.getInvokerAccess() >= 400 else spellbook.getInvoker() av.setImmortalMode(not av.immortalMode) return 'Toggled immortal mode %s for %s' % ('ON' if av.immortalMode else 'OFF', av.getName())
ad10c3ff62e583e55ba55bc09c4214a2f670d3aa
3,630,840
import math def read_command_line_branch(input_path=None, output_path=None): """ Read arguments from commandline and return all values in a dictionary. If input_path and output_path are not None, then do not parse command line, but only return default values. Args: input_path (str): Input...
b838e60a78cd6840d2802a879d6d64cf29bf4e6c
3,630,841
def predict_fr(dst_path, ref_path): """ 用于FR的预测函数 :param dst_path: :param ref_path: :return: """ assert ref_path is not None if utils.is_img(dst_path): img_dst = cv2.imread(dst_path) img_dst = utils.transform(img_dst, config.input_process)[np.newaxis, ...] img_ref...
2eeb4e123d09136d5da037b2955cf5f331ed8e6c
3,630,842
def disk_example(): """Create an example of disk element. This function returns an instance of a simple disk. The purpose is to make available a simple model so that doctest can be written using it. Returns ------- disk : ross.DiskElement An instance of a disk object. Examples ...
b02c25a59f52ca47c84c5fffa29414fc622555c1
3,630,843
def build_optim( model, optim="adam", lr=0.002, max_grad_norm=0, beta1=0.9, beta2=0.999, decay_method="noam", warmup_steps=8000, ): """ Build optimizer """ optim = Optimizer( optim, lr, max_grad_norm, beta1=beta1, beta2=beta2, decay...
eaa1b32098d7eb8f58d0c1ac41906badb56a37c6
3,630,844
def bst(height=4): """Generate a random binary search tree and return its root. :param height: the height of the tree (default: 4) :return: the root of the generated binary search tree """ values = _generate_values(height) root = _new_node(values[0]) for index in range(1, len(values)): ...
301f0776f67bbcd3ce90fa1109bcee80180a6fd1
3,630,845
from typing import Optional def get_model_info(model: str, repo: str = "onnx/models:master", opset: Optional[int] = None) -> ModelInfo: """ Get the model info matching the given name and opset. @param model: The name of the onnx model in the manifest. This field is case-sensitive @param repo: The loc...
63e94ff122066d26fcf173f49c6f63662443acc0
3,630,846
def byprotocolobj(protocolobj): """ Returns the Session for an instance of :class:`Protocol` given as *protocolobj*. Keys will match when *protocolobj* is an instance of the respective key class. """ for key in sessions.keys(): if isinstance(protocolobj, key): return sessions[key] ...
9d683caec6da167b815fdcc60d02ad1fef002647
3,630,847
from typing import Callable from typing import Dict def trace_numpy_function( function_to_trace: Callable, function_parameters: Dict[str, BaseValue] ) -> OPGraph: """Trace a numpy function. Args: function_to_trace (Callable): The function you want to trace function_parameters (Dict[str, B...
38454e0251bcc3bde4b9d49c86fd76bf6b4cd278
3,630,848
def random_crop(arr, new_h=224, new_w=224): """Crop an image of shape (dim, dim, channels) to (new_h, new_w, channels).""" height = len(arr) width = len(arr[0]) assert height >= new_h assert width >= new_w if height > new_h or width > new_w: height_sample_pt = np.random.randint(height-ne...
55984b293e66064a919d38a203270134dd5d6b0d
3,630,849
def bilingual(obj, field, attr=None): """ This is a quick and dirty way to define bilingual content in a single field. """ field_locale = '%s_%s' % (field, get_language()) value = None try: value = getattr(obj, field_locale) except AttributeError: pass if not value: tr...
1c4c7b5b3ec650f9e30749d6188b99f3b858fc5c
3,630,850
def get_available_quantity(variant: "ProductVariant", country_code: str) -> int: """Return available quantity for given product in given country.""" try: stock = Stock.objects.get_variant_stock_for_country(country_code, variant) except Stock.DoesNotExist: return 0 return stock.quantity_a...
f3cac101a2079564e35c07542b63c2217c4c9aae
3,630,851
def in_range(x, a1, a2): """Check if (modulo 360) x is in the range a1...a2. a1 must be < a2.""" a1 %= 360. a2 %= 360. if a1 <= a2: # "normal" range (not including 0) return a1 <= x <= a2 # "jumping" range (around 0) return a1 <= x or x <= a2
8855ea29e44c546d55122c7c6e4878b44a3bc272
3,630,852
def _dark_parse_accept_lang_header(accept): """ The use of 'zh-cn' for 'Simplified Chinese' and 'zh-tw' for 'Traditional Chinese' are now deprecated, as discussed here: https://code.djangoproject.com/ticket/18419. The new language codes 'zh-hans' and 'zh-hant' are now used since django 1.7. Although...
03f4b15dba30f569eb4bb853426e5ceeafa6f2a5
3,630,853
def trip_direction(trip_original_stops, direction_stops): """ Guess the trip direction_id based on trip_original_stops, and a direction_stops which should be a dictionary with 2 keys: "0" and "1" - corresponding values should be sets of stops encountered in given dir """ # Stops for each directi...
a418c90775039b1d52b09cb2057d71f97361e0d9
3,630,854
def unf_pb_Valko_MPaa(rsb_m3m3, gamma_oil=0.86, gamma_gas=0.6, t_K=350): """ bubble point pressure calculation according to Valko McCain (2002) correlation :param rsb_m3m3: solution ration at bubble point, must be given, m3/m3 :param gamma_oil: specific oil density (by water) :param gamma_gas: ...
3879fe70af6116251cc08dfc14934f623e23b57f
3,630,855
def disasm(file, objdump_or_gdb, symbol, start, finish): """ Disassemble binary file. """ if objdump_or_gdb: out = _run(['objdump', '-d', file]) elif symbol is not None: out = _run(['gdb', '-batch', '-ex', f'disassemble {symbol}', file]) else: out = _run(['gdb', '-batch',...
ec5af11fa6d73698907e48fae58b041027a94160
3,630,856
def gaussian_on_simplex(mu, sigma, npoints): """ This function provides npoints i.i.d. points on the simplex, normally distributed according to sigma around :math:`mu`. Parameters ---------- mu : 1D-numpy-array expectation value on the simplex sigma : 2D-numpy-array covarian...
d7b0ef0d897cd3493b8333d528128a2fc68bd359
3,630,857
def add_common_arguments(parser): """Populate the given argparse.ArgumentParser with arguments. This function can be used to make the definition these argparse arguments reusable in other modules and avoid the duplication of these definitions among the executable scripts. The following arguments a...
c8e3eba16c33f0fcf12caf3a31b281dcee858648
3,630,858
import os def is_valid_path_and_ext(fname, wanted_ext=None): """ Validates the path exists and the extension is one wanted. Parameters ---------- fname : str Input file name. wanted_ext : List of str, optional Extensions to check Return ------ bool """ if ...
fea067c87a2f867703c234c2fdab418c7e0ab862
3,630,859
def circuit(params, a, m1, m2, cutoff): """Runs the constrained variational circuit with specified parameters, returning the output fidelity to the requested ON state, as well as the post-selection probability. Args: params (list): list of gate parameters for the constrained variati...
fb210648ab05aa99c3644ecce74a175951eb1cb3
3,630,860
def attr_names(obj): """ Determine the names of user-defined attributes of the given SimpleNamespace object. Source: https://stackoverflow.com/a/27532110 :return: A list of strings. """ return sorted(obj.__dict__)
ecbc0321d0796925341731df303c48ea911fcf57
3,630,861
from typing import Optional from typing import List from datetime import datetime from textwrap import dedent def get_scada_range( network: Optional[NetworkSchema] = None, networks: Optional[List[NetworkSchema]] = None, network_region: Optional[str] = None, facilities: Optional[List[str]] = None, ...
7307b826171abfc9d712c640fd0a0618b8576892
3,630,862
def treetable(childreds, parents, arg3=None, nodename_colname=None): """ 输入childres子结点id列表,和parents父结点id列表 两个列表长度必须相等 文档:http://note.youdao.com/noteshare?id=126200f45d301fcb4364d06a0cae8376 有两种调用形式 >> treetable(childreds, parents) --> DataFrame (新建df) >> treetable(df, child_colname, parent_c...
e5daaa2839a6fdc0cefa444872a38a99e31ce6cb
3,630,863
def plot_drawdown_periods(returns, top=10, k=None, ax=None, **kwargs): """ Plots cumulative returns highlighting top drawdown periods. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. ...
258a12f3bb96b727e2486f5ca2c67bec06649e6c
3,630,864
def redirect_back(endpoint='index', **values): """ 跳转(优先next, 其次endpoint) :param endpoint: :param values: :return: """ target = request.args.get('next') if not target or not is_safe_url(target): target = url_for(endpoint, **values) return redirect(target)
3fd0185d1f0af70f59d6d7b75343ff759cb8f979
3,630,865
import joblib def load( tag: t.Union[str, Tag], model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> t.Union["BaseEstimator", "Pipeline"]: """ Load a model from BentoML local modelstore with given name. Args: tag (:code:`Union[str, Tag]`): Tag of a saved mod...
892f7c280f097732f97af7054b7e41be9552fdf2
3,630,866
def tag_to_python(tag): """ Convert a stream tag to a Python-readable object """ newtag = PythonTag() newtag.offset = tag.offset newtag.key = pmt.to_python(tag.key) newtag.value = pmt.to_python(tag.value) newtag.srcid = pmt.to_python(tag.srcid) return newtag
29687b1322709b953e69089d2f398ba83235dc22
3,630,867
def corrections(word_in, dictionary, keyboard_cm, ed=2): """ @input: word_in - input word dictionary - dictionary/lexicon keyboard_cm - confusion matrix for keyboard in question """ assert isinstance(dictionary, Dictionary) candidates = oridam_generate_patterns(word_in, keyboard_cm...
ac6031edef0ef03af6b871425eb9ed60a914fbf2
3,630,868
def read_polyglot_embeddings(filename): """ Read vocabulary and embeddings from a file from polyglot. """ with open(filename, 'rb') as f: data = cPickle.load(f) # first four words are UNK, <s>, </s> and padding # we discard <s> and </s> words = data[0] matrix = data[1].astyp...
1351e2f3f50df6b192e06201f1989ffb30b0d6fd
3,630,869
def exp_by_squaring(x, n): """Assumes n>=0 See: https://en.wikipedia.org/wiki/Exponentiation_by_squaring """ if n == 0: return 1 if n % 2 == 0: return exp_by_squaring(x * x, n // 2) else: return x * exp_by_squaring(x * x, (n - 1) / 2)
57eab07b123c72dbeeaa6f5f08d18b4abad5c497
3,630,870
from dagster.config.field import resolve_to_config_type def dagster_type_materializer(config_schema, required_resource_keys=None): """Create an output materialization hydration config that configurably materializes a runtime value. The decorated function should take the execution context, the parsed conf...
feb39a8b745ebc81a761903b76c13edd1670b1da
3,630,871
from typing import Union from typing import List def get_models(deploy_cfg: Union[str, mmcv.Config], model_cfg: Union[str, mmcv.Config], work_dir: str) -> List: """Get the output model informantion for deploy.json. Args: deploy_cfg (mmcv.Config): Deploy config dict. model_cfg (...
a8259f52918f41d5142a892f445c1ae30829ce66
3,630,872
import random def weighted_choice(choices): """ Pick a weighted value off :param list choices: Each item is a tuple of choice and weight :return: """ total = sum(weight for choice, weight in choices) selection = random.uniform(0, total) counter = 0 for choice, weight in choices: ...
c32ff27b9892bb88db2928ec22c4ede644f6792c
3,630,873
def css_s(property, value): """Creates a stringified CSSString proto with the given values""" return proto_to_str(make_cssstyle_proto(property, value))
212abbe578d337b39a9ea109f2a7910e1ad3be09
3,630,874
import argparse def parse_args(args): """ Parse the arguments. """ parser = argparse.ArgumentParser(description='Simple training script for training a RetinaNet network.') parser.add_argument('--data-path', help='Data for prediction', type=str, required=True) parser.add_argument('--target-pat...
1071d2fdeb2eec7a7b149b295d504e4796dd3aa7
3,630,875
from datetime import datetime import json async def get_expired_members(request): """ Returns a list of all members that should have finished their degree, calculated by current semester and normed time for each members associated study programme. :param request: :return: List of all expired memb...
7de1cbf72b30e8dba7548c4ceb17b8c53efe7f7e
3,630,876
def sim_hawkes(dims, adjacency, decays, baseline, kernel_support, max_points, run_time, phi_inv, plot=False, seed=None, track_intensity=False): """Simulate point process using Ogata razor. Input - S: Settings dictionary - plot: Indication of whether to plot events and intensities - seed: Seed for r...
9c412324b24426239a152336777cccdcb2b02204
3,630,877
def ADD(sum, augend, addend): """ args: sum: the register where the addition result is stored. augend: the left operand of the addition. addend: the right operand of the addition. function: Performs basic addition. """ return TacInstruction(instructions.ADD, sum, aug...
c51b6d98c88f6d6d8bb2bde8b20fddb531409f10
3,630,878
import io def __convert__(filename): """Convert a python script so that it can be called by slave. The converted file is named by appending '_converted' to the filename.""" with open(filename,'r') as f: script = f.read() if '#main' not in script: raise SlaveError('Could not find #main ...
dc98d0c4046daed743c6b99673e1c39414707e64
3,630,879
import json def parse_value(str_val, type): """ Parse the string representation of a value (e.g., for use with an attribute of an XML object) Args: str_val (:obj:`str`): string representation of the value type (:obj:`ValueType`): type Returns: :obj:`object`: Python representation...
61a96db11d8bccfb05bf85f2ab022f3ba441092e
3,630,880
def _ls_emr_step_logs(fs, log_dir_stream, step_id=None): """Yield matching step logs, optionally filtering by *step_id*. Yields dicts with the keys: path: path/URI of step file step_id: step_id in *path* (must match *step_id* if set) """ matches = _ls_logs(fs, log_dir_stream, _match_emr_step_lo...
95162a0a24d3d9e7bb58224ee6f636636aa0a26f
3,630,881
def propeller_icon(icon, **kwargs): """ Render an icon **Tag name**: propeller_icon **Parameters**: icon Icon name. See the `Propeller docs <http://propeller.in/style/icons.php>`_ for all icons. size Size of the icon. Must be one of 'xs', 'sm', 'md', ...
2e043741ca1cbd1a4feab0c59eb4a31b4c2314fd
3,630,882
def sbasis(i, n): """Standard basis vector e_i of dimension n.""" arr = np.zeros(n) arr[i] = 1.0 return arr
9afd8f56c52e13ba59baf8f9c458fe3428e8826b
3,630,883
def get_users(): """return users in admin.""" current_app.logger.debug(u'Get all users in admin.') return render_template('admin/users/list.html')
29f4fa6e23bccc6da3af7d6f167178d9a181aa25
3,630,884
import struct def decrypt(text): """ :param str text: :rtype: str """ plain = [] for i in range(0, len(text), 2): num, = struct.unpack('!B', text[i]) plain.append(decrypt_bets.get(num)) return ''.join(plain)
e3379909732ff0bb6dbed771cd859d460e6b2964
3,630,885
def LF_warning_signs_hypothetical(c): """ Check if candidate is in a list of warning signs e.g. preceded by 'Warning Signs:' :param c: pain-anatomy candidate :return: -1 if True, 0 otherwise """ sent_spans = get_sent_candidate_spans(c) sent = '' for span in sent_spans: word...
3c03548e66ebb6c8146ec43ee9f63d3337f093d8
3,630,886
def render_upcoming_events(event_amount=5, category=None): """Template tag to render a list of upcoming events.""" return { 'occurrences': _get_upcoming_events( amount=event_amount, category=category), }
015454a6c4a97c1a964eb540892ef1b37ff4dd68
3,630,887
from typing import List from typing import Dict def aggregate_collate_fn(insts: List) -> Dict[str, List[str]]: """aggragate the instance to the max seq length in batch. Args: insts: list of sample Returns: """ snts, golds = [], [] for inst in insts: snts.append(inst['snt']) ...
8d986d508fd2e5a5c91947563aec2b862ab13361
3,630,888
def isBetween(p1, p2, p, epsilon=1e-5): """ test if p is between p1 and p2 Parameters ---------- p1 : np.array p2 : np.array p : np.array epsilon : float tolerance default 1e-5 Returns ------- boolean Examples -------- >>> p1 = np.array([0,0]) >>> p2...
5a19f6903dfefa7340895a622c8a2a8c7d33b2f4
3,630,889
import functools def load_val_data(batch_size, dataset_name): """Load Patch Camelyon val data""" val_dataset = tfds.load( name=dataset_name, split='validation', as_supervised=True) val_dataset = val_dataset.map( functools.partial(preprocess_data, is_training=False)) val_dataset = val_dataset.batch...
5df6916721f588db3553c7bc05e7b40f0edf6b19
3,630,890
def dictfetchall(cursor): """ Return all rows from a cursor as a dict. :param cursor: a database cursor. :return: the results from the cursor as a dictionary. """ columns = [col[0] for col in cursor.description] return [dict(zip(columns, row)) for row in cursor.fetchall()]
e8c4d3d53a4d204d2f7ac95fefb08c5a77fa5e5f
3,630,891
def dev_login(request): """docstring""" if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request,...
b0f4d2b1b3eb2bdefc361d85b62cadc802a15b54
3,630,892
def CheckBackwardsCompatibility(new_universe, old_universe): """Checks that non-abstract types are not removed or changed in new configs. Method expects types in passed universe to have inherited_fields_expanded. Method has the side effect of setting is_changed field on everything in this universe that has cha...
a1ec6de3062926c0e08789d4d937c3b132b9aacc
3,630,893
def pgram(N, years, fname): """ Calculate periodograms of LSST light curves. """ ps = np.linspace(2, 100, 1000) # the period array (in days) print("Computing periodograms") # Now compute LS pgrams for a set of LSST light curves & save highest peak ids = np.arange(N) periods = np.zeros_...
cfbaef2650f025a50b3735d3db39d638242a6175
3,630,894
import requests def check_version(version, server_url, client='cli'): """ Check if the current version of the client software is supported by the One Codex backend. Returns a tuple with two values: - True if the user *must* upgrade their software, otherwise False - An error message if the ...
98aa8ba12a26609610c705a735a962c474c1321e
3,630,895
def get_layout(data, width_limit): """A row of a chart can be dissected as four components below: 1. Label region ('label1'): fixed length (set to max label length + 1) 2. Intermediate region (' | '): 3 characters 3. Bar region ('▇ or '): variable length This function first calculates the width of...
dbb8bfa2c537f3b05713bf3abdc106ec74bc7ac9
3,630,896
import os def get_wordlist(seed): """ Takes a seed value from possible_seeds and generates a wordlist from the thesaurus files. Args: seed - a string, one of possible_seeds Returns: a list of words for flag values """ word_list = [] tmp_list = [] word_string = "" with open (os.path.join...
776d2760aeeb0e9efb74126e4864d34ed6d4268a
3,630,897
def add_stats(all_data, yesterday_date_str, rows, key): """ Given the entire registration report, augment a particular slice of the data with male/female/total counts and label for each row. The input rows are dictionaries with entries containing male and female registrations by date, and total registr...
b49154bce300a601d27e2f7d9fa54899da858472
3,630,898
import nose import re def assert_raises_regex(exception_class, expected_regexp, callable_obj=None, *args, **kwargs): """ Fail unless an exception of class exception_class and with message that matches expected_regexp is thrown by callable when invoked with arguments args and ke...
f61a5145c62b10d17db3fe4dc380935fb2c1395e
3,630,899