content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def service_unavailable(request,template_name='503.html'): """ Default service unavailable view """ return TemplateResponse(request,template_name,status=503)
e474d5780bff381a6365fe9c8e28416c7a689708
52,900
from datetime import datetime def utcnow_str(): """ Return a new datetime string representing UTC day and time. """ return time2str(datetime.datetime.utcnow())
1008efc7536880a389913f5dd3a03c157323dc2a
52,901
def accuracy(output, target, topk=(1,)): """ Computes the precision@k for the specified values of k Parameters ---------- output : pytorch tensor output, e.g., predicted value target : pytorch tensor label topk : tuple specify top1 and top5 Returns ------- ...
018d19d70084c9e1f4f5269f4cf6c444a41e016b
52,902
def compute_divide(z, w): """ Compute `z` divided by `w`. :param z: MathsComplexNumber object to be divided. :param w: MathsComplexNumber object to divide by. :return: MathsComplexNumber object of `z` divided by `w`. """ # z = a + bj # w = c + dj a, b = z.re, z.im c, d = w.re,...
0740446226dbc52273c7dcdc0e7c1cf1deb8df70
52,903
import six def _build_deeplab(inputs_queue, outputs_to_num_classes, ignore_label): """Builds a clone of DeepLab. Args: inputs_queue: A prefetch queue for images and labels. outputs_to_num_classes: A map from output type to the number of classes. For example, for the task of semantic segmentation wi...
5ff0a26a68355eff7a940534c79a8edcb39fe981
52,904
from datetime import datetime def clean_up(): """Clean up the cache. Finish introspection for timed out nodes. :return: list of timed out node UUID's """ timeout = CONF.timeout if timeout <= 0: return [] threshold = timeutils.utcnow() - datetime.timedelta(seconds=timeout) uui...
d22423d9e9eb8d06e4f9887b9f4ee0a395e9a51d
52,905
from typing import Type from typing import Sequence from textwrap import dedent def create_triggers_sql(*, audit_logged_model: Type[Model]) -> Sequence[str]: """ Create the SQL requried to set up triggers for audit logging to the given audit log entry model. """ # Get the model that we are audit ...
3b5b5e3e236adb06f6f30961adb7ee4da5ad6d30
52,906
def _get_neighbors(loc, image, voxels, thresh, dist_params): """Find all the neighbors above a threshold near a voxel.""" neighbors = set() for axis in range(len(loc)): for i in (-1, 1): next_loc = np.array(loc) next_loc[axis] += i if thresh is not None: ...
e7e1e7e7509609a40803fff0816d30a056824395
52,907
def is_partition(set_of_sets, alphabet): """ Determine whether `set_of_sets` partitions `alphabet`; that is, is every element of `alphabet` represented exactly once in `set_of_sets`? Parameters ---------- set_of_sets : a (frozen)set of (frozen)sets The potential partition. alphabet ...
dab446b6f9beefe4acc5c400f71749352ab81b46
52,908
def OMO( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "2020-06-08", **kwargs ) -> Graph: """Ret...
c9e37f025788e8c1a2630e9ba9b7ee8f542f34dc
52,909
def _render_dimensional_metric_cell(row_data: pd.Series, metric: Metric): """ Renders a table cell in a metric column for pivoted tables where there are two or more dimensions. This function is recursive to traverse multi-dimensional indices. :param row_data: A series containing the value for t...
36dce77d07b6581d0bf120f55f4bc3e1813c3deb
52,910
import tqdm def pca_init_dense(model, mu_dense_layer_name, undense_layer_name, generator, input_len=None, do_vae=True, logvar_dense_layer_name=None, nb_samples=None, tqdm=tqdm, vis=False): """ ini...
4ae2d4248e75d0cee9dd7aa0d9783895d07f31fc
52,911
def allocationsCount(memory): """Return the total number of allocations. """ return np.count_nonzero(memory['allocations'] > 0)
171374eb60cc63f56c54b667eaadaa43cc611b38
52,912
def file_docker_pull_latest(): """#! /usr/bin/env bash SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" source ${SCRIPT_DIR}/docker-environment-vars.sh echo "${SENZING_HORIZONTAL_RULE}" echo "${SENZING_HORIZONTAL_RULE:0:2} Pull ${SENZING_PROJECT_NAME} docker containers for DockerHub....
b71227f2c95cd4a582528b632450cc60c29c4aa2
52,913
import os import tempfile import requests import zipfile import io def load_data(path=None): """Downloads the Mendeley dataset to local storage, if not already downloaded. This will generate 2 csv files (train and test), which contain all the path information. Args: path (str, optional): The ...
79cf58c2686574e8091add87c355ee93548a18de
52,914
def _get_annotation_type(annotation) -> AnnotationType: """ Returns the type of a given annotation. Annotation can be a BinaryBuffer, TypedBuffer or something else """ if isinstance(annotation, list): if len(annotation) == 2: return AnnotationType.BINARY_BUFFER elif len...
1b499a6137d7378661b521bbc94ed574994a3c9d
52,915
import ast def is_obvious_builtin(node, value): # type: (ast.expr, Any) -> bool """ Return True if this node looks like a builtin and it really is (i.e. hasn't been shadowed). """ return ((isinstance(node, ast.Name) and node.id in builtins_dict and builtins_dict[node....
8a404b5cc84a6ea19edf60e3211497002426ede6
52,916
import requests import sys from bs4 import BeautifulSoup import json def extract_problems(cfg, login_reply, filename='kattis'): """ Stores solved prolbems and stats in .json file """ data = {} solved = [] header_url = get_url(cfg, '', 'problems') try: result = submissions(header_url, login...
b3a547cc88503f45e209fd560d783ae7c9eb782e
52,917
def insert_records(conta, data): """ Recebe o objeto e inseri a data no banco de dados. A data são os logs de exibições recebidos do manager. param: conta : Account: data: list of dicts: return: records: int: Quantidade de registros inseridos """ records = 0 i = len(data) - 1 ...
a136fd7bda8d0c32deb45290661574735d9faf2f
52,918
def sample_2d_no_compete(alternatives, choosers, sample_size, capacities=None): """ Samples alternatives in a manner that guarantees that capacities will be respected: the maximum # of times a given alternative can appear in the sample (across choosers) is equal to its capacity. Use this for the la...
d96dd35c7c03ddb39784c91bd8efc989c5226f26
52,919
from typing import Sequence def notch_filter(): """ implements a notch filter with notches at 1/week and 2/week; assuming input signal sampling rate is 1/week""" fs, f0, Q = 1, 1/7, 1 b1, a1 = iirnotch(f0, Q, fs) b2, a2 = iirnotch(2*f0, 2*Q, fs) # Frequency response b = convolve(b1, b2) a ...
1a7162d24124c177e1ec8b76bb0d424a8a3ccbb4
52,920
def monthly_file_name(var, model, rcp): """Function for creating file connections for different variables scenarios and models. Preasently, ensemble member r1i1p1 is assumed, as well as 200601-210012 dime span for the monthly data.""" # e.g. hfls_Amon_CNRM-CM5_rcp85_r1i1p1_200601-210012.nc f = var + "_" + "Amon_...
7aeea6d3724c470e076645ddb96877e9fa15843f
52,921
def extract_sum_of_products(cluster, template, *args): """ Extract sub-expressions in sum-of-product form, and assign them to temporaries. """ make = lambda: Scalar(name=template(), dtype=cluster.dtype).indexify() rule = q_sum_of_product costmodel = lambda e: not (q_leaf(e) or q_terminalop(e)) ...
b5eab74b889dfdf528677170fe0c5b0c5828e4d1
52,922
def minimize(_mol, nsteps, opttol, func, minimizer): """ Minimizes a single molecule Arguments: nstesp -- perform a maximum of nsteps steps opttol -- the maximum rms gradient shall be below this value func -- energy and gradient function minimizer -- a minimizer """ ...
e465c415066c0619a7fbc84656e32eeddf21ac8e
52,923
from re import DEBUG def _init_logger(): """Initialize the Bempp logger.""" _logging.addLevelName(11, "TIMING") logger = _logging.getLogger("bempp") logger.setLevel(DEBUG) logger.addHandler(_logging.NullHandler()) return logger
9cb78a26c88d08b1dd7d7103791769aaf6ed8dfc
52,924
import requests def request(method, url, **kwargs): """ Central place to make any v1 api request. :param (str) method: The request method ('get', 'put', 'delete', ...). :param (str) url: The full api url to make the request to. :param kwargs: These are passed along to requests. :return: (requ...
ca3bc5e5607d1b3dbebcfa92c8532dee9ab2b673
52,925
import tqdm import torch def single_epoch_train(model, data_loader, criteria, optimizer, device, pad_idx, args, epoch=None): """ :param model: :param data_loader: :param criteria: (dict) holding all modules for computing the losses. :param optimizer: :param device: :param pad_idx: (int) ...
8c387fc4ab0bb980b60df2a324d45c6a524c98e1
52,926
from typing import Callable import cloudpickle def default_key_provider(func: Callable, *args, **kwargs) -> str: """ Default cache key function. This uses cloudpickle to hash the function and all arguments. """ return cloudpickle.dumps({"function": func, "args": args, "kwargs": kwargs})
693129568a45270d48c1cedb6995d07abd875715
52,927
import warnings def fips_to_location_id(fips: str) -> str: """Converts a FIPS code to a location_id""" try: return dataset_utils.get_fips_to_location().at[fips] except KeyError: # This happens mostly (entirely?) in unittest data where the first two digits # are not a valid state FI...
d1478f36a39534a22860b8382fc4808cd0deedff
52,928
from datetime import datetime import pytz def check_asset_availability(start=None, end=None): """ Am I within the Asset's availablity window? If "start" is defined, now >= start must be True If "end" is defined, now <= end must be True. Otherwise each condition is presumed TRUE (e.g., n...
12c2480c51c8656f46b905f454620c73c826a6f5
52,929
def calc_distance(l): """Calculates distance between list items in two lists""" # l needs to start from zero, get lowest number and substract it from all numbers min_l = min([x[1] for x in l if x[1] != ''], default=0) l = [[x[0], (x[1] - min_l)] for x in l if x[1] != ''] distance = 0 for id...
57d52eb4bb4b772024d68cb397f2e315825a25df
52,930
def load_archive(task_name: str, hparam_set_name: str): """Load a precomputed archive file for `task_name` and `hparam_set_name`.""" path = get_baseline_archive_path(task_name, hparam_set_name) return read_npz(path)
69cf98f9e7193bb60aa8a5c17e9574289c73e7c4
52,931
import sys import fileinput def use_learned_model(model_file: str, remove_pattern: str = "", replace_pattern_file: str = "") -> pd.DataFrame: """標準入力から読み込んだ文字列に対して学習済みモデルによる推論を実施 :param model_file: :param remove_pattern: :param replace_pattern_file: :returns: :rtype: """ print(...
a9b65f7529ef901688ea9d00037c0e7cb0380c3c
52,932
import torch from typing import Tuple def get_explanation_accuracy(model:torch.nn.Module,loader:torch.utils.data.DataLoader,mem_loader:torch.utils.data.DataLoader,device:torch.device)-> Tuple[float, float, float]: """ Method to compute the explanation accuracy for different settings, as described in the paper...
2c90a5df55925016c85b6c494cee0279cddfdb41
52,933
import locale import warnings def locale_convert(key): """Creates a converter for a locale key.""" def lc_converter(val): try: locale.setlocale(LOCALE_CATS[key], val) val = locale.setlocale(LOCALE_CATS[key]) except (locale.Error, KeyError): msg = 'Failed to ...
54f45d2290c47e9773a269f9cd3e65ebce8a233d
52,934
from datetime import datetime def get_offer_info(soup, offer_id): """get information about a specific offer according to its id information: title, company name, published date, link Parameters ---------- soup: BeautifulSoup html code offer_id: str offer identifier Retur...
516c555a86e40e2b9e45e05a7994e39c5ae9ae23
52,935
def to_csv(raw_data): """Converts a serialized TfStatsDatabase string to CSV.""" tf_stats_db = tf_stats_pb2.TfStatsDatabase() tf_stats_db.ParseFromString(raw_data) return generate_chart_table(tf_stats_db.with_idle, tf_stats_db.device_type).ToCsv()
eecd980878849ec5853662fe647cb9dbe3ec98a3
52,936
def lam(x, lam0, alpha=4.0): """Return classic alpha model lambda value(s) for input value(s).""" return lam0 * ( 1.0 - x**alpha )
37a10d890acc2b983c09300b865e58fe9dc2f7fe
52,937
def Add(left: Expr, right: Expr) -> BinaryExpr: """Add two numbers. Produces left + right. Args: left: Must evaluate to uint64. right: Must evaluate to uint64. """ return BinaryExpr(Op.add, TealType.uint64, TealType.uint64, left, right)
27ba874d66b57669f6ec332e86530f40b022a637
52,938
def reduceCoefficients(polynomial : Polynomial) -> Polynomial: """ Initialize a Polynomial for the Kerner method: Make the leading coefficient 1 """ eq = polynomial.eq() h_coeff = eq.get(max(eq)) return Polynomial([ coefficient / h_coeff for coefficient in polynomial.arr() ...
d31c538801c3a7472eb6e52b17421b783f239a0f
52,939
def count(): """ 查询记录总数 """ return Record.objects.owner().count()
0e4466da6c3a4c1f549bcdbafa0b76233daa4a40
52,940
import os def campbell(caseFile, mainFst, tStart, nPerPeriod, workDir, toolboxDir, matlabExe, fastExe, baseDict=None, generateInputs=True, runFast=True, runMBC=True, prefix='',sortedSuffix=None, ylim=None): """ Wrapper function to perform a Campbell diagram study see: writeFASTLinInputs...
ed6c2779c2d2cc0fd715e817d9f8a075d1be4179
52,941
import os def get_files_time_period(prefix, yr_s, yr_e): """ Get nc files within the time period, with the prefix :param prefix: prefix of file names :param yr_s: start year :param yr_e: end year :return: files in folder, max and min year """ # Get path and folder path = directori...
35e0bb6e223882d11a63b21f6c4302cad7054b2e
52,942
def subset(part, whole): """Test whether `part` is a subset of `whole`. Both must be iterable. Note consumable iterables will be consumed by the test! This is a convenience function. Examples:: assert subset([1, 2, 3], [1, 2, 3, 4, 5]) assert subset({"cat"}, {"cat", "lynx"}) ...
4200ea95e0c9ff03d0b7589812d0313c5d13cfac
52,943
def kl_categorical_uniform(preds): """KL divergence between categorical distribution and uniform prior.""" kl_div = preds * jnp.log(preds + EPS) # Constant term omitted. return kl_div.sum(1)
311cae987a9e43742d036fe9b23f37654987264f
52,944
def remove_proxy_vcs(session, quantity, return_type=None, **kwargs): """ Removes proxy vcs. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type quantity: int :param quantity: The number of vcs to be removed. Required. :type re...
2d5e05f338e0414e0ed5fe6c5eb567aaf8f01f9f
52,945
from pathlib import Path def stem(fname, include_suffix=False): """/blah/my_file.json.gz --> my_file""" path = Path(fname) stem = path.stem # If a filename has multiple suffixes, take them all off. stem = stem[: stem.index(".")] if "." in stem else stem if include_suffix: stem = stem...
9e4c557dff8583f9129215f91f8e123f062ccf52
52,946
def compile(fmt, names=None): """Compile given format string `fmt` and return a compiled format object that can be used to pack and/or unpack data multiple times. Returns a :class:`~bitstruct.CompiledFormat` object if `names` is ``None``, and otherwise a :class:`~bitstruct.CompiledFormatDict` objec...
00c4596739e65295b579002917ddfbaee6a7390b
52,947
import sqlite3 def username_lookup(userName): """ Lookup user from availability.db by unique username """ # connect to db conn = sqlite3.connect("availability.db") # create cursor c = conn.cursor() # check if lookup initiated for specific user or for all users if userName: # quer...
36c0927a79791eca8d69f574799490c716f2fe05
52,948
def allInfoTests(P, inIter=10, outIter=10): """ performs information theoretic tests on a tripartite behaviour """ results = [] # get marginal for X,Y l = len(P.shape) t = tuple(np.arange(2,l)) m = pr.marginal(P, t) # calculate mutual information of the marginal X,Y mutInf =...
ecf3f2a2e2fd2ba29847e6ae5d883aced5a1f8df
52,949
def Insert(head, data): """ >>> head = None >>> node = Insert(head, 4) >>> assert(node.data == 4) >>> head = Node(6) >>> node = Insert(head, 4) >>> assert(node.next.data == 4) >>> head = Node(6, Node(7)) >>> node = Insert(head, 4) >>> assert(node.next.next.data == 4) """ ...
3372a20ba7a9b6e80b07fadedce9bfb12baed4e9
52,950
def important_features(model): """ Get the most important features from some model """ invalid_features = ["count_","tf_idf_","word2vec_"] feat_importances = pd.Series(model.feature_importances_, index=features).to_string() feat_importances = [i for i in feat_importances if not any(feat in i for feat i...
22880b50b83f08c224f1e1bd0cc7032f2b6ccd0b
52,951
def get_backend(config): """ :param app: celery instance :type app: celery.Celery """ klass = config.backend_class kwargs = config.backend_kwargs url = config.backend_url return klass(url, **kwargs)
57d6c82f99888ae992503492a8edfa802315a3cc
52,952
def affine(f, T): """Applies the affine transformation on a given image. ' g(r, c) = f(T^{-1}(r,c)) ' Direct mapping: From image (f) map the values to image (g) - g(T(r,c)) = f((r,c)) , (r,c) in [0,H-1]x[0, W-1] - con: T(r,c) might not fill every pixel of G Indirect Mapping ...
593617f5296361ac7d797e2f804eb12dea347e1c
52,953
def atol(s, base=None): # real signature unknown; restored from __doc__ """ atol(s [,base]) -> long Return the long integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it i...
f39aa403cbad98c448a35305c97c595bc3a77c02
52,954
def open_or_std(file, std, *args, **kwargs): """ Opens the file in the specified mode unless file is STD_IDENTIFIER, in which case it returns std. """ if file == STD_IDENTIFIER: return std return open(file, *args, **kwargs)
dd8b08569ff6ee702864fe453e13d3e8f7497267
52,955
from typing import Tuple from typing import Optional def translate( parsed_symbol_table: parse.SymbolTable, atok: asttokens.ASTTokens, ) -> Tuple[Optional[SymbolTable], Optional[Error]]: """Translate the parsed symbols into intermediate symbols.""" underlying_errors = [] # type: List[Error] def ...
7e293389b51fdc9f05ef047c82bd5a0362cb3c01
52,956
def tokens_to_sovatoms(tokens: float) -> int: """Convert tokens to sovatoms.""" return int(tokens * 100000000)
23f4bc3a1afc4520b5e2416332702d0a594c5039
52,957
def _frame_only(frame, skeleton_data): """ Save only one frame from skeleton data """ result = [] for raw_descriptor in skeleton_data: if raw_descriptor[0] == frame: result.append(raw_descriptor) return result
1581ddc52eedc81dbe2cc71ed66524b6af5f4b3d
52,958
def sort_node_id(a, b): """ @param a, b: node pair to be sorted by id @type treenode, treenode """ if a.id > b.id: return 1 else: return -1
2db33f63f009d4d50c922b4daf45dbac56a60312
52,959
def generate_steps(model_name, new_steps, generator='random(edge_coverage(100))'): """ This is the top level builder for making test steps. Args: model_name (str): The name of the model file - no extension needed. new_steps (bool): Whether to recalculate the model steps. generator (...
c825ea6fe81a9bdfe436a7382b564729fae585d7
52,960
def collect_trajectories(env, policy_fun, num_trajectories=1, policy=env_problem_utils.CATEGORICAL_SAMPLING, max_timestep=None, boundary=20, epsilon=0.1, ...
77af43962dec2ba236ceb7a33fbcbc51b410a9dc
52,961
from datetime import datetime def request_directions(start_location, end_location): """Request directions from start_location to end_location. Args: start_location: tuple of floats (lat, lon) for starting point end_location: tuple of floats (lat, lon) for ending point Returns: a list of directions ...
a4e2208f18fb885d083f28aafcb2e48529b9e3fe
52,962
def __Boundary_outside__(self): """Is the boundary is on the outside of the mesh.""" return self.leftCell() is not None and self.rightCell() is None
cce3ffadc5e2598beae8b320b4d2f5122d6de904
52,963
def create_dataset_lookup(py_obj): """ What type of object are we trying to pickle? This is a python dictionary based equivalent of a case statement. It returns the correct helper function for a given data type. Args: py_obj: python object to look-up what function to use to dump to disk ...
0a36c178c6ceccafe35f1023cbfe6eb293ad0ba3
52,964
def find_anagrams(s): """ :param s: search str :return: a list of anagrams """ print('Searching...') return find_anagrams_helper(s, '', [])
f636200d611d0a38a8cdfc8802f611a0fb6073b1
52,965
from typing import List def follow_directions(start: Cell, directions: List[Direction]) -> Cell: """ Walk the ``directions`` from the ``start``. :return: The final :py:class:`Cell` of the journey """ cursor = start for direction in directions: cursor = next_cell(cell=cursor, direction...
4409a7ba6a2edf53e0f9aaeb2cbf90e96e72c5e5
52,966
def mongo_dump(server, args_array, **kwargs): """Method: mongo_dump Description: Function stub holder for mongo_db_dump.mongo_dump. Arguments: (input) server -> Server instance. (input) args_array -> Dictionary of arguments. """ status = False err_msg = None if server...
895ad2d77282d1d5c65c54940a4f83b64023f92d
52,967
def majority(taxa, th=0.8): """Select taxon from list by majority rule. Parameters ---------- taxa : list of str Input taxon list. th : float, optional Threshold of majority, range = (0.5, 1.0]. Returns ------- str or None Selected taxon. """ for taxon, ...
0828b8704aeb1f7ced1446b563ba4f1f98634ffe
52,968
def version(serial=None): """ Returns version information for MicroPython running on the connected device. If such information is not available or the device is not running MicroPython, raise a ValueError. If any other exception is thrown, the device was running MicroPython but there was a...
b082467669fe00321f50406b1a94cd013d971469
52,969
from .matplotlib import plot_roc_curve as _plot_roc_curve from .plotly import plot_roc_curve as _plot_roc_curve def plot_roc_curve(fpr, tpr, roc_auc=None, backend="plotly", **kwargs): """Plots a receiver operating characteristic (ROC) curve. Args: fpr: an array of false postive rates tpr: an ...
d4bcfe3d37478602a9a80435c5aa979fcb2143cc
52,970
def send(draw, min_value=0, max_value=None): """Generates the send for Blast+6 file format. Arguments: - `min_value`: Minimum value of send to generate. - `max_value`: Maximum value of send to generate. """ return draw(integers(min_value=min_value, max_value=max_value))
6b6cd9d5965cb3e114c61aeff76dca1bc3149d64
52,971
def flow_cell_mode(info_reads): """Return flow cell sequencing mode.""" res = '' if info_reads: read_lens = [ a['num_cycles'] for a in info_reads if not a['is_indexed_read']] if len(read_lens) == 1: res = '1x{}'.format(read_lens[0]) elif len(set(read_lens)) ==...
0563d0c163c2bd42b05d07fb30940669a8ef3513
52,972
def dynamic_module_wrapper(wrapped_module: nn.Module): """ Wrapped module must locate on one single device, but could be moved around. Input device and output device are automatically detected. """ wrapper = NeuralNetworkModule() wrapper.add_module("wrapped_module", wrapped_module) wrapper....
963200ae5abf305deb08b2e3a2b78e58d068ff75
52,973
def fixture_conf2(): """Instance of loaded config_test2.ini.""" return md.FrontMatter("./tests/config_test2.ini")
34b78a4a23fc253dea014152a3f20ec3a1c535ce
52,974
import pycountry import urllib import requests import json def find_best_match(row, scopus_url): """Splits the name and surnames and tries to find some combination of them, that still matches the country.""" # Prepare the parameters csv_name = row['firstName'].replace(",","").replace(" or ", " ") ...
42d9b2cd4a9cc2544337cad3e211a1d9bd3ab6d7
52,975
def _quote_dict_to_embed(quote: dict) -> discord.Embed: """Changes a given quote dict to an embed format Args: quote (dict): The quote in `dict` format Returns: discord.Embed: The embed itself. """ message_link = quote["Message Link"] title = f"***Quote #{quote['Number']}***" ...
18d4cfb36c20dcc016c9692c73bfe5b57928b5a5
52,976
def git_get_tags_by_referred_object(context: RepoContext, obj_name: str) -> list: """ :param context: :param obj_name: :rtype: list of Ref """ commit_tags = git_get_tag_map(context).get(obj_name) return commit_tags if commit_tags is not None else []
59211ed55db6b446caae2c5ecade7bc956c2cb92
52,977
def sortKey(e): """ This sorts the chores based on their start time. e[0] is the start time for all the chores in my array of chores. """ return int(e[0])
00d37751d23fe6210b406485cbd76906075b2578
52,978
def merge_into_dict(original, secondary): """Merge two dictionaries into the first and return it. This is simply a conveinence wrapper around the dictionary update method. In addition to the update it returns the original dict to allow for chaining. Args: original: The dict which will be updated. seco...
899d40396885f0775f2cbaa865702ed0e5706dba
52,979
def drop_cols(dataset: pd.DataFrame, cols: tuple = ('ConnID', 'Repseudonym', 'siteid', 'visdat', 'IDs', "prmdiag")) -> pd.DataFrame: """ Drops the columns which are not needed for further modelling Args: dataset: dataset on which the cols should be dropped...
f3a96d16d3da9c30980f72879142eb9c50736e2f
52,980
def matchXandYbyIndex(clr_x, model_proc_df): """ This fxn drops rows in the design matrix & response vector according to index equivalency. """ # drop all rows in x that don't match to y x_bool = clr_x.index.isin(model_proc_df.index) x_1 = clr_x[x_bool] # drop all values in y that don't...
cf9b78e7e7ffb2ba4a18eca9ee74cca39b44946b
52,981
def conic_sag(c, kappa, rhosq, phi=None): """Sag of a spherical surface. Parameters ---------- c : float surface curvature kappa : float conic constant rhosq : numpy.ndarray radial coordinate squared e.g. for a 15 mm half-diameter optic, rho = 0 .. 15 ...
4de6955ba1f1633ede0008743f95321c38649c93
52,982
def get_nba_player_name(div_name: list, tag_name: str, class_name: str) -> list: """For getting the names of NBA player and return the names as a list Arguments: div_name {list} -- [The div that contain all the players name] tag_name {str} -- [The tag name which contain the name of the Play...
39e4afd86eb8a2d27589953bf5614a4bdb8837bf
52,983
def verify_author(author, connection): """Given an author id, check it.""" database = connection['test'] collection = database['users'] try: post = collection.find_one({"_id" : ObjectId(author)}) except InvalidId: post = None if post is None: return False return T...
35ad43b2c32c90787051766cfe9af02e034084ad
52,984
import math def quatfrom_m43(m): """ Convert the top of an m33 matrix into a quaternion.""" (m0, m1, m2, m3, m4, m5, m6, m7, m8, _, _, _) = m trace = m0 + m4 + m8 + 1 if trace > PRECISION: w = math.sqrt(trace) / 2 x = (m5 - m7) / (4*w) y = (m6 - m2) / (4*w) z = (m1 - m3...
c8eb0d07c9e82c1ad32eb4c036c310f5ab1ce73f
52,985
def simulated_get_actions(seed_value=0, number_created_agents=1): """ Simulates the function which """ #Returns a random actions list for each robot np.random.seed(seed_value) action_list = list(np.random.randint(low=0, high=5, size=number_created_agents)) print(action_list) return action...
a8d46342e1bb807fb51c7c4467b0ae1d572bcfd7
52,986
def readAlignments(filename, name): """ reads alignment from alignment file """ FOUND = False alignment = "" alignments = [] text = [] file = open(filename) # searching for correct protein entry while True: line = file.readline() if line == "": break ...
0e306e9d9009f82e564258e5894e973c72536826
52,987
def get_v_left(g_or_n, v_list): """Return vertices from graph not in v_list""" V, n = get_set_vertices(g_or_n) v_left = [x for x in V if x not in v_list] return v_left
175f47c3d0734d917604b68bfa102a08f947933a
52,988
def normalize_obs(obs_dict, obs_normalization_stats): """ Normalize observations using the provided "mean" and "std" entries for each observation key. The observation dictionary will be modified in-place. Args: obs_dict (dict): dictionary mapping observation key to np.array or ...
c866b6d18df13b9e6903b7d96024d48cde99d2ff
52,989
def get_closest_language(differences): """[summary] Args: differences ([list]): [contains tuples with language and difference score] Returns: [tuple]: [containing 3 closest possible languages to given input] """ # print(differences) differences_sorted = sorted(differences, key=...
55e231e249c8bae5116be0b2feac96d184a6cbee
52,990
from typing import List from typing import Optional from typing import Dict from typing import Union from typing import Any def apply_trace_attribute(log: EventLog, values: List[str], parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> EventLog: """ Filter a log on the trace attribute values ...
e876620f0b4f94521a656f392647b6269c76bee5
52,991
def cross_product(X1, X2): """ Cross product of features in matrices X1 and X2 """ n = np.shape(X1)[0] assert n == np.shape(X2)[0] return (X1.reshape(n,1,-1) * X2.reshape(n,-1,1)).reshape(n,-1)
56590019253d90beb97038b41dc901a5eb56cd40
52,992
def getAtomType(atom, bonds): """ Determine the appropriate atom type for an :class:`Atom` object `atom` with local bond structure `bonds`, a ``dict`` containing atom-bond pairs. """ cython.declare(atomSymbol=str) cython.declare(molFeatureList=cython.list, atomTypeFeatureList=cython.list) ...
fbe5a477d1c1cca11e3011107b08028267b03285
52,993
def impute_rare_titles(df: pd.DataFrame, tresh: int = 100) -> pd.DataFrame: """Substitutes rare titles with closest ones by Elo Parameters: thresh: threshold for title to be considered as rare """ for color in ['White', 'Black']: title_column_name = f'{color}Title' elo_column_name =...
c5c2ee6105b56e0a883f03328f388f00fbe5f64f
52,994
from typing import Dict import pandas from typing import Counter def calculate_most_mistaken_heatmap(label_classifiers: Dict[str, pandas.DataFrame], labels) -> pandas.DataFrame: """ Generates a 2d table describing how many times each column is mistaken for a given index. :param label_classifiers: A numb...
409d089945ebc9150f06152fbce60aa3b907cc2c
52,995
from typing import Tuple from typing import Dict from typing import Any def get_label_metadata( app: App, label: LabelRef, state_machine: StateMachine, ) -> Tuple[Dict[str, Any], bool]: """Get the metadata and whether the label has been deleted.""" return app.session.query(Label.metadata, Label.de...
8fe26e55240b0d8394f7e1d1a3a3041235c8b789
52,996
def copy_of_xml_element(elem): """ This method returns a shallow copy of a XML-Element. This method is for compatibility with Python 2.6 or earlier.. In Python 2.7 you can use 'copyElem = elem.copy()' instead. """ copyElem = ET.Element(elem.tag, elem.attrib) for child in elem: cop...
685c3ba214179a8958db7d1292642dd28796dbff
52,997
def get_arrivals(knots: dict, func=None, *func_args, **func_kwargs) -> list : """ Generate a sequence from a nonhomogeneous Poisson process specified by a piecewise linear function determined from the knots parameter. The knots should specify the (domain, range) of each segment's knot. knots: dictionary where ke...
627079cb9cb984e163c7fb0a5cb1c91147fac393
52,998
import copy def align_trajectory(traj, traj_ref, correct_scale=False, correct_only_scale=False, n=-1, return_parameters=False): """ align a trajectory to a reference using Umeyama alignment :param traj: the trajectory to align :param traj_ref: reference trajectory :param corre...
9e892d9336f8c7c2be9de9e29f2e22352e3f4740
52,999