content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def random(): """Return a random parameter set for the model.""" fractal_dim = np.random.uniform(0, 6) surface_portion = np.random.uniform(0, 1) fractal_dim_surf = fractal_dim*surface_portion fractal_dim_mass = fractal_dim - fractal_dim_surf rg_cluster = 10**np.random.uniform(1, 5) rg_primar...
47c85b745af4cecd2104bb667c52baaeb0b463fb
59,872
import requests import html import re def snopes(text): """snopes <topic> -- Searches snopes for an urban legend about <topic>.""" try: params = {'sp_q': text, 'sp_c': "1"} request = requests.get(search_url, params=params) request.raise_for_status() except (requests.exceptions.HTT...
eebec93f70ce00ee2a13d58b37b775810046ba2d
59,873
def log(bot, message): """ 记录聊天记录. """ logging = Log(qq=message.qq, type=type(message).__name__) if isinstance(message, RcvdGroupMessage): logging.group = message.group elif isinstance(message, RcvdDiscussMessage): logging.discuss = message.discuss logging.save() retur...
8e67b8c16fd5d969c68e6839900186a3d28eb2c2
59,874
def apology(message, code=400): """ Render message as an apology to user """ return render_template('apology.html', code=code, message=message), code
90962de02c3e43f7561cd380f05aaade2bf3eb72
59,875
def SetDocEndTime(doc:NexDoc, endtime): """Sets the length (in seconds) of experimental session for the document.""" return NexRun("SetDocEndTime", locals())
5daa4905c059fff5ffee91abb5db428ef9f360fa
59,876
def now(): """Returns the current timestamp in ms Returns: int -- current ms """ return rospy.Time.now().to_nsec()
00c57a01055d3516f34be2ca5d94a4ff4129f76c
59,877
def find_parent( child: str, parent_of: dict, recursive=False): """ Find the parent or great-great-...-great-parent of a child Required Parameters ------------------- child: str If this is already the greatest-parent, will return itself otherwise, raise KeyE...
429f91160f6abc8710ced71b07e5e2e5c0a97cfc
59,878
def process_immediate(immediate): """ Returns a integer object from a string object. """ if not isinstance(immediate, str): raise TypeError('Immediate must be a String object.') if immediate.startswith("0x"): return int(immediate, 16) else: return int(immediate)
b6665563663731337df2b7a31defaca0ae3de24f
59,880
from typing import Any import lzma import json def get_gist_json_file(db_url: str, file_name: str) -> Any: """ Grab the contents from a gist file :param db_url: Database URL :param file_name: File to open from Gist :return: File content """ LOGGER.info("Cloning gist database") git_sh =...
600db080b792da554780b93250eee1e71a713226
59,881
def get_all_records_by_country(instance): """ Collect all confirmed, recovered and deaths for all the countries :param instance: class instance :return: dict """ result = dict() for _action in instance._actions_files.keys(): reader = instance.get_reader(_action) # Dict reade...
79d0ddac0f2dbfbbc56ad06117c1bcf7bde17bd9
59,882
def zeros(shape, typecode='l', savespace=0, dtype=None): """zeros(shape, dtype=int) returns an array of the given dimensions which is initialized to all zeros """ dtype = convtypecode(typecode,dtype) return mu.zeros(shape, dtype)
53c8b96caa0ff70dee4c59037cfc2b9fd33b65ee
59,883
def successors_query(var_name, node_id, node_label, edge_label, successor_label=None, undirected=False): """Generate query for getting the ids of all the successors of a node. Parameters ---------- var_name Name of the variable corresponding to the node...
7ad64a3d535e575af3db4e5f6719ce0d0b702a97
59,886
def sub_menu(request, page_id): """Render the children of the requested page with the sub_menu template.""" page = Page.objects.get(id=page_id) pages = page.children.all() page_languages = settings.PAGE_LANGUAGES return render(request, "admin/pages/page/sub_menu.html", { 'can_publish': r...
0f180268ed126e0e1c7db7ac6ee17897db7db8b0
59,887
def handle_fs_errors(function): """Method decorator to report FS errors in the appropriate way. This decorator catches all FS errors and translates them into an equivalent OSError, then returns the negated error number. It also makes the function return zero instead of None as an indication of successful executi...
833724326db34a01b45ea7222cbae0057aa496fd
59,888
def _TimeToString(datetime): """Converts a datetime object into a string adapted from M-LOOP: mloop.utilities Args: datetime (datetime): datetime object (e.g. datetime.datetime.now()) Returns: str: date time as 'yyyy-mm-dd_hh-mm' """ return datetime.strftime("%Y-%m-%d_%H-%M")
3f778b8b15f19bdfe5238799cb248316772380b4
59,889
import tokenize def is_media(user): """ Is twitter user a member of the media """ if user['screen_name'] in KNOWN_MEDIA: return True name_tokens = [] description_tokens = [] for token in tokenize(user['name']): for t in token.split('-'): name_tokens.append(t.low...
ad125107c0018e9d9319505a6b1e71ddff46ab4f
59,892
def matching_files(directory, suffix=None, prepend=False): """Get a list of files that start with a specific prefix, optionally removing any files that end in `_001`. Args: directory (str): The directory containing files. suffix (str): A suffix (file extension) to match filenames against. ...
c9105ee73c6a25598c2afe4a216016b4a5b197ed
59,893
def event_names(lang="en"): """This resource returns an unordered list of the localized event names for the specified language. :param lang: The language to query the names for. :return: A dictionary where the key is the event id and the value is the name of the event in the specified lang...
8fb2e3fd82d438bfb652eb3c0f46d2bd2d34a03f
59,894
def generate_tiny_dataset(n_samples, language="english", seed=None, **kwarg): """Generate a dataset of 8x8 resolution in gray scale with scale of 1 and minimal variations. """ fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_...
92818f77ccfc2b48457b6bf520a5c356f7229b09
59,896
def array(string): """Converts string to a list, split on whitespace :param: string(str): The string to split :return string.split()(list): The string split into a list on the white space.""" return string.split()
c48c35d321848f3e997931c5ab9f9357842b9228
59,897
def count_nans_by_period( df: pd.DataFrame, config: cconconf.Config, period: str, top_n: int = 10, ) -> pd.DataFrame: """ Count NaNs by period. :param df: data :param period: time period, e.g. "D" - to group by day :param top_n: display top N counts :return: table with NaN count...
6860604095a438aa29dcfc31bcf20b5eec384eff
59,898
import re def to_numpy(t): """ return numpy datetime64 scalar corresponding to the given comma time string >>> import numpy as np >>> from comma.csv.time import to_numpy >>> to_numpy('20150102T123456') == np.datetime64('2015-01-02T12:34:56.000000', 'us') True >>> to_numpy('20150102T123456...
9f859a64378231572f66916893f39ce3a0e6d772
59,900
def _migrate_db_sync(engine, abs_path, version=None, init_version=0): """Upgrade or downgrade a database. Function runs the upgrade() or downgrade() functions in change scripts. :param engine: SQLAlchemy engine instance for a given database :param abs_path: Absolute path to migrate repository. :pa...
1d2eb159354c9a026abc805b2706dd4252619776
59,901
def run_diag(parameter: "CoreParameter") -> "CoreParameter": """Runs the aerosol aeronet diagnostic. :param parameter: Parameters for the run :type parameter: CoreParameter :raises ValueError: Invalid run type :return: Parameters for the run :rtype: CoreParameter """ variables = paramet...
69836d585a7f1c53c48923aba48482a32083b5ff
59,902
import io import re def parse_msa_file(infile): """Read sequences from a multiple sequence alignment (MSA) file. Parameters ---------- infile : str file path to input MSA file in A3M format (like FASTA format, but lowercase letters will be dropped) Returns ------- skbio T...
bcb4bd5ad22a79d31e18c0470830ab72b5106aaf
59,903
def cadastro(request): """Cadastra um novo usuário no sistema""" if request.method == 'POST': nome = request.POST['nome'] email = request.POST['email'] senha = request.POST['password'] senha2 = request.POST['password2'] if campo_vazio(nome): messages.error(req...
7c8e2c049d6f70a1f3ae9b850f6737757915f697
59,904
def parser_summaries(gold_corpus, annotated_corpus): """Computes parser evaluation summaries for gold and annotated sentences.""" pos, uas, las = calculate_parse_metrics(gold_corpus, annotated_corpus) return {'POS': pos, 'LAS': las, 'UAS': uas, 'eval_metric': las}
beddd90bfb940434f60f7099ceca3fd5d20f4b85
59,905
import json def json_files_serializer(objs, status=None): """JSON Files Serializer. :parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion` instances. :param status: A HTTP Status. (Default: ``None``) :returns: A Flask response with JSON data. :rtype: :py:class:`flask.Respo...
830ddc8c8c9b55a75ee0abb4f3b7a4398fd46f76
59,906
def TensorBoardConfig(argument_parser): """ Set CLI arguments :param argument_parser: argument parser :type argument_parser: ```ArgumentParser``` :returns: argument_parser :rtype: ```ArgumentParser``` """ argument_parser.description = """Enable visualizations for TensorBoard. TensorBo...
22abff24eb0d0ca64d32db7a8de57623d51a3c00
59,908
def delta_prob(variants, tx, clf1, clf2, model='cterm', is_sum=True): """Calculate the difference between a position specific model and a "bag of words" model""" # fetch c-terminal sequence term_seq, vars_considered = utils.process_var_seq(variants, model=model, is_sum=is_sum) # return None if no v...
d4f7e222286c4fd262ebcc26a74b1f4724742722
59,910
import builtins import functools def install_import_hook(): """Installs __import__ hook.""" saved_import = builtins.__import__ @functools.wraps(saved_import) def import_hook(name, *args, **kwargs): if name == 'end': process_import() end return saved_import(name, *ar...
b78799448becd79ab1a1001a07b1eb4445da5780
59,911
def draw_square_support(data, h, c1, c2, t, r): """ "Support", "Cuboid" :param (h, c1, c2): position :param (r, t): shape """ data[cut(16 + h):cut(16 + h + t), cut(16 + c1 - r):cut(16 + c1 + r), cut(16 + c2 - r):cut(16 + c2 + r)] = 1 step = np.asarray([7, h, c1, c2, t, r]) return data, s...
094b4d722e0d5afa2642d10eac72399e60ebf577
59,912
def read_or_skip(file): """This function is to supress imageio exception if file doesn't exist""" try: img = skimage.io.imread(img_folder + file) img = skimage.transform.resize(img, (img_width, img_height), mode='reflect') return img[:,:,:img_channels] except: #print('Skippin...
cbcae49d0fa18dc441f1e154d6a4034ca4883b61
59,913
def read_zero_mode(zero_mode, L1, L2): """Read the \alpha_i, \beta_j parameters from the 2D zero mode Operator. """ if isinstance(zero_mode, qy.Operator): alphas = np.zeros((L1,L2)) betas = np.zeros((L1,L2)) for (coeff, os) in zero_mode: if len(os.orbital_operators...
be01b3f27c61341f7bc213f4eba98b8d41435af7
59,914
def worm_like_chain_1p(x, L_0, L_p=50e-9, T=298): """ An improved worm-like chain model. Petrosyan, R. "Improved approximations for some polymer extension models". Rehol Acta. 2016. doi:10.1007/s00397-016-0977-9 Parameters ---------- x : float Extension (m) L_0 : float ...
38ce0482241870d215751228505d59bbc3c49f28
59,915
def label_mapper(raw_labels, new_labels): """Map some raw labels into new labels. When dealing with GEO DataSets it is very common that each GSM sample has a different phenotye (e.g. 'Brain - 001', 'Brain - 002', ...). This function maps these raw labels into new homogeneous labels. Parameters ...
67aaa329374169f61414032b0949344437d16022
59,916
import time import logging def detect_scenes(cap, scene_manager, start_frame = 0, end_frame = 0, duration_frames = 0): """Performs scene detection based on passed video and scene detectors. Args: cap: An open cv2.VideoCapture object that is assumed to be at the first frame. Frames are r...
59a0ef88df005309cfa3a8cb9037d1fde2d9d85e
59,917
def pad_1d_tensor(inputs): """ Pad 1d tensor to fixed size. """ max_len = hp.character_max_length padded = np.pad(inputs, (0, max_len - inputs.shape[0])) return padded
728d8c8d1558c16489c4571bfa1d372b6e8cb409
59,918
def get_apispec(app): """ Формируем объект APISpec. :param app: объект Flask приложения """ spec = APISpec( title="ustMock", version="1.0.0", openapi_version="3.0.3", info={'description': "ustMock api based from marshmallow models"}, plugins=[FlaskPlugin(), DocPlu...
800e87b001fd880ca3b9b17cba24d18488ec88c6
59,919
from typing import MutableSequence def lookup_func(arg, ctx): """ Runs an ansible lookup plugin. Usage: .. code-block:: YAML lookup: lookupFunctionName: 'arg' or ['arg1', 'arg2'] kw1: value kw2: value """ arg = map_value(arg, ctx) assert_form(arg, test=arg...
75db3924e9cfebae28b0b18c9db8699edf5e4435
59,920
def text2entity(text): """Convert HTML/XML special chars to entity references """ return ESCAPE.get(text, text)
ded63af8e8e5d1d097c67301ca4433382fef3c73
59,921
from pathlib import Path from typing import Dict def register( manager: TaskManager, project: str, cwd: Path, substitutions: Dict[str, str], ) -> bool: """Register static-analysis tasks to the manager.""" manager.register(Phony("python-sa"), ["python-lint-mypy"]) # Register a target so t...
6b326ecfc1713045f934e006670d8a0d3f52f463
59,922
def transform_all(calendar, listings, reviews, save_results=False): """ Transforms all the columns. """ calendar, listings, reviews = transform_prices(calendar, listings, reviews) calendar, listings, reviews = transform_booleans(calendar, listings, review...
b9e337a970570b47b2e543285ca673bd26bb4481
59,923
from typing import Optional def validate_self_discharge(self_discharge: Optional[float]) -> Optional[float]: """ Validates the self discharge of an object. Self discharge is always optional. :param self_discharge: The self discharge of the object. :return: The validated self discharge. """ ...
4d1d6c3ddb6530fc6fc6e03809a4320b0b50033f
59,924
import collections def shrink_nd(a, trim_spec, assume_sorted=False): """Perform multidimensional shrink. Args: a: ndarray The grid to shrink. trim_spec: sequence of tuples Iterates over tuples (bins, low, high, axis) assume_sorted: bool, optional If...
895c547371ec37df6bc73e9fc8df4003b583c3e4
59,926
import base64 def hash_b64(s): """ hash the string using sha256 and produce a base64 output removes the trailing "=" """ hasher = SHA256.new(s.encode('utf-8')) result = base64.b64encode(hasher.digest())[:-1].decode('ascii') return result
81770cc9a5ac7fdbd29fa1e6d10d9a580aec0196
59,927
def all_builtins(): """Helper function to return an iterator over all builtin plugins.""" return (p for p in plugin.plugins.itervalues() if p.builtin)
ead7e176af58bc38772b5b5bfc4dc8b25082ca5b
59,929
def parse_type_arg(type_arg_string): """Parse typed individual argument strings This is the base function to parse an individual argument string with type information. It identifies the type and calls the appropriate parsing function from the parsing function dict. Args: type_arg_string(st...
401f181a21d2745ded0db2f2e8f417e6186fe6e8
59,930
import pickle import base64 def unbp(data): """Un-(Base64-Pickle).""" return pickle.loads(base64.b64decode(data))
d1338e2d877ac84c78cd67e2b5b425c173011331
59,932
def check_in_field(pos, field_config): """ Return flag to indicate whether the object is in the field """ k1 = field_config['borderline'][0] k2 = field_config['borderline'][1] b = field_config['borderline'][2] flag = k1 * pos[0] + k2 * pos[1] + b > 0 return flag
1a0020bf9a0a6baad6cb465092864899bba7324a
59,934
from operator import inv from re import I def xrecover(y): """ Return y given x such that (x,y) is on the curve """ xx = (y * y - 1) * inv(d * y * y + 1) x = expmod(xx, (q + 3) / 8, q) if (x * x - xx) % q != 0: x = (x * I) % q if x % 2 != 0: x = q - x return x
909367253a6f990aa9866a42a88a25bb1d482a02
59,935
def ocs_iso_to_mjd(iso_string=''): """ :param iso_string: input ISO-8660 date :return: string representation of date_string as MJD """ if not isinstance(iso_string, str) or iso_string == '': return '' else: return '{0:23.17f}'.format(Time(str(iso_string)).mjd)
e08492f29b149ad15b120f805e60d2977a5bc358
59,936
def random_vec(n, type="stdnorm"): """ input: n : vector size output: random vector that follows rademacher distribution & std normal distribution example: "randmacher" : [1,1,-1,1,-1,-1,-1,1,-1,1] """ if type == "stdnorm": return np.random.standard_normal(n) ...
42048fac4d61bdab1512b02fa862a10c417d6aad
59,937
def add_hard_linked_production_volumes(data): """Add information to target datasets about subtracted production volume. Production volumes from hard (activity) links are subtracted from the total production volume of transforming or market activities. The amount to subtract is added to a new field in the produ...
2e34304acda4b764dcd377603b1617ed78daf87b
59,938
def location_get(table_name): """ Gets data from table. Args: table_name: Name of table in DB. Returns: All data in table |table_name|. """ db = get_db() select_stmt = "SELECT * FROM " + table_name cur = db.execute(select_stmt) result = {"result": cur.fetchall()} p...
aa55184f2854408148d7d784c3d1adbffd51496e
59,941
import inspect import ray def create_backend_worker(func_or_class): """Creates a worker class wrapping the provided function or class.""" if inspect.isfunction(func_or_class): is_function = True elif inspect.isclass(func_or_class): is_function = False else: assert False, "func...
47fe7fac5ad154b0a567cf82205492e085c24535
59,942
def local_structure_tensor(img: np.ndarray, si: float = 0.8, so: float = 1.6, slope_method: str = 'eigen', grad_method: str = None, f: float = 1) -> [np.ndarray, np.ndarray, np.ndarray]...
6553fe2fe15c046226ea67d15247a457b945fc30
59,943
def v1_find_users_by_name(request: WSGIRequest) -> JsonResponse: """ Find users by a string their name contains. Return the found users in JSON formatted as a select2 result. """ name_contains = request.GET.get('name_contains') if name_contains is None or len(name_contains) < 2: # Nothin...
7c1cff476684b2fd61c8826482d177d1d187503d
59,944
def inline_callback(): """Filters callback_query done in messages posted through inline query. Assumes update_type is callback_query. :return: True or False """ if context.update.type is not UpdateType.callback_query: return False if context.update.callback_query.inline_message_id is ...
3e07b8549a626800510ca9a1b7fbddcda7183e2f
59,945
def clearBlinkCache(): """ clearBlinkCache() -> None Clear the Blink cache for all devices. """ return None
d518a45b96fc7193a6a28952aee2500b0bb470b1
59,947
def compute_I_ux(model, t1=None, t2=None): """Compute the :math:`I_{ux}` integral. Args: model (:class:`.gpcm.GPCM`): Model. t1 (tensor, optional): First time input. Defaults to zero. t2 (tensor, optional): Second time input. Defaults to zero. Returns: tensor: Value of :mat...
558a9ef603cec235dd39db5021ce8c5970e37b1a
59,948
async def translations( query: str, src: LANGUAGE_CODE, dst: LANGUAGE_CODE, response: Response, guess_direction: bool = False, ): """ Translate the query between src and dst language. The response contains the list of lemma objects matching the query in the source language. Each of ...
28d464beba4082f22cc1ba13eacc1b5c19b775c3
59,950
import requests def md_to_rst(from_file): """ 将markdown格式转换为rst格式 @param from_file: {str} markdown文件的路径 @param to_file: {str} rst文件的路径 """ response = requests.post( url='http://c.docverter.com/convert', data={'to': 'rst', 'from': 'markdown'}, files={'input_files[]': ope...
5001a37634b08857747f58de1f7591c34a5d4fa2
59,952
def parse_charge(charge_str): """ Parses a SMILES charge specification. Parameters ---------- charge_str : str The charge specification to parse. Returns ------- int The charge. """ if not charge_str: return 0 signs = {'-': -1, '+': 1} sign = signs...
0b605a00dd12903c834c83a27d7e42078acdb456
59,953
def accuracy(y_true, y_score): """Compute accuracy using one-hot representaitons.""" if isinstance(y_true, list) and isinstance(y_score, list): # Online scenario if y_true[0].ndim == 2 and y_score[0].ndim == 2: # Flatten to single (very long prediction) y_true = np.concat...
dcb49e25a019638e6f3a5bf7bb0e7dfc87f49ed0
59,954
import torch def sample_boxes(mean, var, num_samples, eps=1e-4, angular_dim=6): """ Sample boxes from distributions Args: mean [torch.Tensor(..., D)]: Bounding box parameter means var [torch.Tensor(..., D)]: Bounding box parameter variances num_samples [int]: Number of samples (M) ...
c41a3ba8afa100811735091c45f2fb1eef1b7235
59,956
def flag_abuse_for_comment(request, course_id, comment_id): """ given a course and comment id, flag comment for abuse ajax only """ course_key = CourseKey.from_string(course_id) user = cc.User.from_django_user(request.user) comment = cc.Comment.find(comment_id) comment.flagAbuse(user, co...
bd135c4248c784b14a5fd560d753441af8a9ed80
59,957
from typing import Dict def _get_all_aliases(sql, example: NLToSQLExample) -> Dict[str, DatabaseTable]: """Returns a dictionary of aliases for the tables.""" root = sql while True: if root.parent is None: break root = root.parent aliases = {} for item in _iterate_sql(r...
5d5196e1191109bdbceb6f38fbbf8749fd15c062
59,958
import math def filter_green_channel(img, green_thresh=200, avoid_overmask=True, overmask_thresh=90, dtype="bool"): """ Create a mask to filter out pixels with a green channel value greater than a particular th...
57f81d904b5482995737429955561f72d5ce8e51
59,959
def user_can_delete_model_nodegroups(user, resource): """ returns a list of graphs of which a user can edit resource instances Arguments: user -- the user to check resource -- an instance of a model """ return user_has_resource_model_permissions(user, ["models.delete_nodegroup"], resource...
1a4cb4e6d1185387a63a8b3ade725f18a9231576
59,960
def l_min(s, m): """ Minimum allowed value of l for a given s, m. The formula is l_min = max(\|m\|,\|s\|). Parameters ---------- s: int Spin-weight of interest m: int Magnetic quantum number Returns ------- int l_min """ return max(abs(s), abs(m))
9eec996df3b8e026c8b58649fddbbbcc05c38372
59,961
import attr def query_and(draw, stattrs=st.lists(st.sampled_from(_supported_attr_types()), min_size=1, unique=True)): """ Generate a AttrAnd query. """ attr_types = draw(stattrs) query_attrs = list(map(draw, map(st.from_type, attr_types))) assume(not(len(qu...
57e8f522f4e3b6b579d55012189896546911cf74
59,962
def discrete_sample(p, n_samples=1): """ Samples from a discrete distribution. :param p: a distribution with N elements :param n_samples: number of samples :return: vector of samples """ # check distribution #assert isdistribution(p), 'Probabilities must be non-negative and sum to one.'...
1dccafc919a85a58efcd481275be129ebe0362ae
59,963
def my_get_matrix(opt): """Return which distance matrix to use Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions Returns which distance matrix to use Ca/Cb/... -- distance matrix function """ if opt.matrix == 'Ca': retu...
f6ea4e4e0c0850efa5a63da245f398d4f88b4af1
59,964
def load_cifar(labels='cifar10', channels_last=False, flatten=False, dtype=None, normalize=False): """ Load the CIFAR dataset. Args: labels ({"cifar10", "cifar100"}): Specify the labels to load. channels_last (bool): If True, will place the channels in the last di...
ccf93d9ede78578949c9a8fb221304e34d4be1e9
59,965
def to_mp3( audio_content: bytes, sample_rate: str, src_sample_rate: str = "22050", src_fmt: str = "s16le", ) -> bytes: """Convert audio to MP3 (using ffmpeg) Args: audio_content Any audio content (with headers) that the available ffmpeg binary can decode sampl...
2049b4f733ae2d6f53b23d3c7898fedc98e804c7
59,966
import torch def indices_to_dense_vector(indices, size, indices_value=1., default_value=0, dtype=np.float32): """Creates dense vector with indices set to specific value and rest to zeros. This func...
ce3de9751b8d97a0ced2760bad9b2bef52484d2f
59,967
def lastrow_calc_player_velocities(team, smoothing=True, filter_='Savitzky-Golay', window=7, polyorder=1, maxspeed = 12): """ calc_player_velocities( tracking_data ) Calculate player velocities in x & y direciton, and total player speed at each timestamp of the tracking data Parameters -------...
d4ff6a7594d9a9f79ddfb2643ac5ec3b51f7a30e
59,968
from django_wireguard.models import WireguardPeer def purge_private_keys() -> int: """Purge all Private Key from database. :return: Removed keys count. """ peers = WireguardPeer.objects.filter(private_key__isnull=False) if peers.exists(): peers.update(private_key=None) return peers....
9ab704de807a4057d7afb0c3353a4033fa173957
59,969
from typing import Any from typing import Union def _strat_commutes_from_commutes(left_val: Any, right_val: Any, *, atol: Union[int, float] = 1e-8 ) -> Union[bool, NotImplementedType,...
040cc5060b653c68ce63141b2d971349458a591b
59,970
def request_elevations(locations): """Request elevations for a list of (lat,lon) coordinates. Args: locations: list of (lat,lon) Returns: a list of elevation responses in the deserialized Elevation API response format in order of input locations """ elevations_response = GMAPS.elevation(locations...
98ccf44cfb96a9136eb6ff40fe3853e598da5fbd
59,971
def get_rand_token(bits=256): """Generate a random number of specified length and return its hex string. Default is to generate 256 bits = 32 bytes, resulting in a 64 characters token to be generated (since a byte needs 2 hex chars). """ return hex(getrandbits(bits))[2:-1]
fe5afd3edb7ba0d69f589904964f3b6255bbe4fc
59,972
def synch_parallel_process(proc1, proc2): """ Return the step function of process proc1||proc2. :param proc1: a process :param proc2: a process :return: synchronous parallel composition of proc1 and proc2 """ return lambda pdef, d: synch_parallel_combine(proc1(pdef, d), proc2(pdef, d))
32475548423ed2ccc93a29d00ed2b40ead3a51cd
59,973
import time def native_sort_implementation(array): """Implement native python sort method.""" begin = time.time() nat_sortedarray = sorted(array.getData()) end = time.time() time_native = end - begin print('Native sort', f'{time_native =}') return nat_sortedarray
7b964644fdb2b11e8c50303ac0c7f4d4d76d6842
59,974
def haversine(lat1: float, long1: float, lat2: float, long2: float) -> float: """Determines the distance between two coordinates. We take r as the average radius of the Earth: 6378 km. >>> import math >>> bahen = (43.65983570963418, -79.39694225927128) >>> margad = (43.668387110900944, -79.39244320...
402b3786ee47ae5b6c54d857685b783e28b7cbe2
59,975
from pathlib import Path from typing import List def add_paths(df: pd.DataFrame, feature_dir: Path, label_dir: Path) -> pd.DataFrame: """ Given dataframe with a column for chip_id, returns a dataframe with a column added indicating the path to each band's TIF image as "{band}_path", eg "B02_path". A c...
ce5c71e9b02f5f45819a60aac850bcd4d1d81778
59,976
def _figure_layout( layout, width, height, labels, xaxis, yaxis, sign, orientation, zero_vals ): """ Sets up figure and axis layouts, and adds leaf labels. """ if len(labels) > 0: if orientation in ["left", "right"]: axis_key_labels = yaxis else: ...
a231a88eb911ba2b60fd329f71aa98c734a20519
59,977
def threshold_means(df, thresh_name, thresholds, comp_df=None, error_fac=1.0, use_percents=True): """Computes the means (and standard deviations) along a set of threshold values. This is handy for doing the Threshold v.s. Robustness plots when in comparison to DREA. Args: ...
99f7855f457a2aec71a1454ac08fb656745f84d1
59,978
import pickle def unpack_apply_message(bufs, g=None, copy=True): """unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs""" bufs = list(bufs) # allow us to pop assert len(bufs) >= 2, "not enough buffers!" pf = buffer_to_bytes_py2(bufs.pop(0)) f = unc...
77004594532a06c2fabe806663db68d77b8528e6
59,980
def find_ram_base(u_boot_console): """Find the running U-Boot's RAM location. Probe the running U-Boot to determine the address of the first bank of RAM. This is useful for tests that test reading/writing RAM, or load/save files that aren't associated with some standard address typically represente...
ae550229a493ac88819cecfcc983a5ee84c995b3
59,981
def my_name(): """ The pmap axis of this processor. Returns: i: The axis. """ return jax.lax.axis_index(axis_name=AXIS_NAME)
cd813f2abf3fe47952af51f61919f2d6e0ea2bb0
59,982
import urllib import re def _get_query_params(args): """ creates dictionary of search params for displaying on search result page :param args: request.args :return: dictionary with all params of query """ result_dict = {} for key in args: if key == 'provinz' and args['provinz']...
80ac3542a0b5e2a1f52e9d183cc6307d302781c4
59,983
def vecHomography(H: np.ndarray, p: int, q: int): """ Input: H -- 3x3 homography matrix p -- first column index q -- second column index Output: v -- 1x6 vector containing components of H based on the indices p and q which represent columns of the homography H ...
1c1c5a1fd2b187bef7a5347bf90eede2b6990069
59,984
from typing import Iterable from typing import List def sort_terms(naf: KafNafParser, terms: Iterable[Cterm]) -> List[Cterm]: """Sort terms by natural order (sent, offset)""" def get_offset(term: Cterm): tokens = [naf.get_token(tid) for tid in naf.get_dict_tokens_for_termid(term.get_id())] tok...
e41806e5fd3619d83dbd9eeacad5899e8e687e29
59,985
import urllib import yaml import requests def _fetch_global_config(config_url, github_release_url, gh_token, file_name): """ Fetch the index_runner_spec configuration file from the Github release using either the direct URL to the file or by querying the repo's release info using the GITHUB API. "...
d5321fd255a6a3e748dff423161ffd6751d31ee9
59,987
def batch_jdbc(conf: BlockConfig) -> DataFrame: """Batch save data with jdbc driver. :param str Mode: the mode to write with such as append or overwrite :param str Driver: the driver :param str ConnUrl: the connection url :param str Table: table to write to :param str User: username to database...
1ac129ca5e26ee021b4ec3684bc684e27f4190a8
59,989
def remove_parents(network, name, **kwargs): """ removes all parents of the given node name, replacing the root node with itself """ def inner(root_node): if network.is_built: graph = network.graph else: graph = treeano.core.graph.TreeanoGraph(root_node) ...
f2600cebdc9a5c4d6b2e0d41a73fd78e1b6c9fc9
59,991
def fetch_messages(chatkit_access_data, room_id, initial_id=None, limit=20, direction="newer"): """ direction in ['newer', 'older'] """ endpoint_parts = ["rooms", room_id, "messages"] query_parameters = {} if(initial_id is not None): query_parameters['initial_id'] = initial_id if(...
9fe484ef236e81699a4f176e960c2a09f8496b2e
59,992
async def test_thread_override_step_and_step(mocker): """ Throw an error if we try to send on an emoji step """ global third_step third_step = False class FirstLogic(BaseStep): name = "first" async def send(self, message, user_id): return message, {"example": 0} ...
28b293e7d20befd8387912eb76e4dd43c0e27761
59,993
from typing import Dict import json def validate_file(file: str, schema: str, fuzz: bool=False, backend: Backend=None, output: Dict=None) -> bool: """validate a spaceTx formatted file with a given schema. Accepts local filepaths or files hosted at http links. Parameters ---------- ...
9a19c0047f976d87113a0bb6a298e5f121563fea
59,994