content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def load_data(file_path, data_format, task_type, label_dict=None):
"""
:param file_path:
:param data_format:
:param task_type:
:param label_dict: map string label to numbers.
only valid for Classification task or ranking task.
For ranking task, better label should have large number
... | 48119f3e194d6514edb6db22819d7fe21639c491 | 77,605 |
import json
def send_email(subject, address, body, data=None):
"""Just sends a quick test email to assure the system is working."""
if address and body:
body = body.decode('UTF-8')
return send_test_email(subject, address, body, json.loads(data))
else:
raise ApiError(code='missing_p... | 8dc42795e888de0fae157ea54876c0955dc58e7b | 77,606 |
def get_csv_url(season, division):
"""Get URL for CSV file from football-data.uk"""
csv_url = BASE_URL
csv_url = csv_url.replace("SEASON",season)
csv_url = csv_url.replace("DIV",division)
return csv_url | ecb4715e0ed2f8747444dfe9ed77db6b0cfb6d5a | 77,607 |
def eval_poses(matched_only, is_relative, pose3d_type, preds_2d_kpt, preds_3d_kpt, keep_matching=False):
"""
Calculates the PCK and AUC. This function is equivalent to ``mpii_mupots_multiperson_eval.m``.
It performs the same gt scaling transformation, uses the same joints for matching and evaluation.
:... | 1f9d50c1a704cfdbcea658408fd8d2d363765bc5 | 77,608 |
import math
def pf_localization(px, pw, z, u):
"""
Localization with Particle filter
"""
for ip in range(NP):
x = np.array([px[:, ip]]).T
w = pw[0, ip]
# Predict with random input sampling
ud1 = u[0, 0] + np.random.randn() * R[0, 0] ** 0.5
ud2 = u[1, 0] + np.... | fca298479e707191448502e1a961a2bb471c4db0 | 77,609 |
from .non_cartesian import NonCartesianFFT
from .non_cartesian import gpunufft_available
def estimate_density_compensation(kspace_loc, volume_shape, num_iterations=10):
""" Utils function to obtain the density compensator for a
given set of kspace locations.
Parameters
----------
kspace_loc: np.n... | d1b0f32b5d875b39846fc01e544b3ec4eeb1c752 | 77,610 |
def get_previous() -> GameStateType:
"""
Get the previous game state
"""
return store.previous_game_state | be7d3375bce57f246c3a2d6da33d0bac2ee0c642 | 77,611 |
import bisect
import itertools
import random
def backport_random_choices(
self, population, weights=None, *, cum_weights=None, k=1
):
"""Return a k sized list of population elements chosen with replacement.
If the relative weights or cumulative weights are not specified,
the selections are made with e... | 785aba10bf33040be51f2ae969c76fac2bfc245e | 77,612 |
def unique_everseen(seq):
"""Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | 900d4e172e3c7e86703f2241ba9abad6fadc20ea | 77,613 |
import pickle
def load_pickle(file_name):
"""
load a pickle object from the given pickle file
:param file_name: path to the pickle file
:return: obj => read pickle object
"""
with open(file_name, "rb") as pick:
obj = pickle.load(pick)
return obj | e50ae7ccd4b72700e5079774c45ec91b240bc88a | 77,614 |
def decodemeta(data):
"""Return string to string dictionary from encoded version."""
d = {}
for l in data.split('\0'):
if l:
key, value = l.split(':')
d[key] = value
return d | 4219675ee3b97e60fe2917b147f87d85c8f446cc | 77,615 |
def exchange(programs, pair):
"""Swap programs on pair positions in programs."""
positions = parse_pair(pair)
swap(programs, positions)
return programs | e6d69784fe79dc59428f9cf69840358601da3b0c | 77,616 |
def fix_labels(origin, add_num):
"""
Fix lebals (teacher vector) to add cass
:param origin: original labels
:param add_num: additional number
:return:
"""
assert (add_num > 0)
return np.c_[origin, np.zeros((origin.shape[0], add_num))] | 79e0e4c7bb50fa428ca233f79ea0bbb4f5dba90e | 77,618 |
import torch
def get_optimizer(model, params):
"""Returns optimizer
:param model: model with his `model.named_parameters()`
:param params: dict with options:
['train.lr']: `lr` for Adam optimizer
['train.weight_decay']: `weight_decay` for Adam optimizer
['train.optimiser_params']:... | f4ce4c97af985fdb13f7ed8ec0ba937a884b5149 | 77,619 |
def find_extremes(content_list):
"""Calculates the smallest and highest values of every position's column of
the positions of features of a wortverbund.
Args:
content_list: list with features of a wortverbund and their positions of
occurrence.
Returns:
... | 75fccb7cd483bfe9e2de0440a93c77a380aef9ad | 77,620 |
def sanitize(input: str) -> str:
"""
Removes all special characters and formatting from
a message.
"""
for c in ['*', '~', '|', '-', '`', '\\']:
input = input.replace('*', f"\\{c}")
input = input.replace('@', f'@{zero_width_space}')
return input | fa39053cebe38d6b9369f848366c9be6c5109268 | 77,621 |
def f_bce_minmax(y_out_min, y_out_max, y_gt):
"""Binary cross entropy (encourages monotonic decreasing).
Use minimum (cumulative from start) to compare against 1.
Use maximum (cumulative till end) to compare against 0.
"""
eps = 1e-5
return -y_gt * tf.log(y_out_min + eps) - (1 - y_gt
... | 9d2206ac67d00b5ad13033f0645194f2093e4329 | 77,622 |
import typing
import asyncio
import itertools
def topic_handler(data: dict, fields: dict) -> typing.Tuple[typing.Dict]:
"""
Handler function to async execute search and aggregate all search request for one topic
:param fields: weighting for fields to search on
:param data: input data dict
:return:... | 825a92d30cb7ce1085acd27e43539491afc17251 | 77,624 |
def handler_cancel(message):
"""
:param message: сообщение от пользователя
:return: None
"""
try:
functions.log(message)
if dataBase.can_accept(message.from_user.id):
dataBase.upd_can_accept(message.from_user.id, 0)
bot.send_message(parse_mode='HTML', chat_id=... | fa54b625af2c156d9aea61449ce3536ac2e3bc28 | 77,625 |
def to_colmap(intrinsics, extrinsics, src_im_size=None, dst_im_size=None):
"""Convert Extrinsics and intrinsics to an empty COLMAP project with no points.
"""
cameras = intrinsics_to_camera(
intrinsics, src_im_size=src_im_size, dst_im_size=dst_im_size
)
images = extrinsics_to_images(extrinsi... | 58ef952533ac6e63cf1991d7cf3caf953f300d3f | 77,626 |
def get_t_epoch(jd):
"""
Get the JD in julian centuries
"""
t = (jd - 2451545.0) / 36525.
return t | 6605018efc72e37b635240180575e31fb08352b1 | 77,627 |
def uni(x, encoding="utf-8"):
"""Convert anything to Unicode, except None."""
if x is None or isinstance(x, unicode): return x
return unicode(str(x), encoding, errors="replace") | 248678856a30e10021980c9a752b950b44e8a95f | 77,628 |
from typing import Sequence
def make_flags(opt_name: CliFlags) -> Sequence[str]:
"""Simple helper to create a list of flags for an
option based on its name"""
return f'-{opt_name.value[0]}', f'--{opt_name.value}' | 9825ca3fb904811dfb7801fb5e902358e634987c | 77,629 |
from typing import List
from typing import Dict
from typing import Union
def format_resources(resources: List[str], resource_param: List[str], kwargs: Dict[str, Union[List[str], str]]):
"""
>>> resources=['hello/{user_name}']
>>> resource_param=['user_name']
>>> kwargs={'user_name': "bob"}
>>> x =... | 9a50c0ee34b07cb228dda781668dd61b94ebaa67 | 77,631 |
def handler500(request):
"""500 error handler."""
response = render_to_response('500.html', {}, request)
response.status_code = 500
return response | be638082ba03aac7f4ac7e306f4f410abfe298ed | 77,632 |
import random
def fft_random(n):
"""
Brainless number crunching just to have a substantial task:
"""
for i in range(n):
x = random.normal(0, 0.1, 2000)
y = fft(x)
if(i%30 == 0):
process_percent = int(100 * float(i) / float(n))
current_task.update_state(s... | 3efcf573d35e38099e656a5a06c20a939338845a | 77,635 |
def icon():
"""
Get addon icon name
"""
return itsme().getAddonInfo("icon") | c6ea225677597e288894e9b97b25b93a692ba4ae | 77,636 |
import warnings
def force_integer(card: BDFCard, ifield: int, fieldname: str) -> int:
"""see ``integer``"""
svalue = card.field(ifield)
if isinstance(svalue, float_types):
warnings.warn('%s = %r (field #%s) on card must be an integer (not a double).\n'
'card=%s' % (fieldname,... | b0042fac21f0290f9215f8001067ac3f5c7d4a2d | 77,637 |
def get_node_agent_for_image(batch_client, config, publisher, offer, sku):
# type: (batch.BatchServiceClient, dict, str, str, str) -> tuple
"""Get node agent for image
:param batch_client: The batch client to use.
:type batch_client: `azure.batch.BatchServiceClient`
:param dict config: configuration... | 1a73a6ae1be3446caf4edb3fc191e6e9e37a2b24 | 77,639 |
def category_selected(intent, session):
""" Sets the color in the session and prepares the speech to reply to the
user.
"""
card_title = "Category Selected"
session_attributes = {}
should_end_session = False
if 'Category' in intent['slots']:
"""favorite_color = intent['sl... | 132fffd92aa1620b3c9dfb164d4c713f74b7b068 | 77,640 |
import six
def _xmldump(obj):
"""Sort of imporved xml creation method.
This converts the dict to xml with following assumptions:
keys starting with _(underscore) are to be used as attributes and not
elements keys starting with @ are to there so that dict can be made.
The keys are not part of any ... | 94f2e41004e980df51230a5b3a28f4c77a5602ae | 77,641 |
def baits(path_to_file, created_baitset_id=None, build='GRCh37'):
"""Reads the bed-file and returns a list of dictionaries
Args:
path_to_file(): path tp temp file
Returns:
bait_dict_list(list): a list of dictionaries with the keys: chromosome, chr_start, chr_stop
"""
bait_dict_list... | 8f05b295a233bd42d1baf40d3ad03477e192e425 | 77,642 |
def _get_filehandle(filepath_or, *args, **kwargs):
"""Open file if `filepath_or` looks like a string/unicode/bytes, else
pass through.
"""
if _is_string_or_bytes(filepath_or):
if h5py.is_hdf5(filepath_or):
fh, own_fh = h5py.File(filepath_or, *args, **kwargs), True
else:
... | 43469472e2cff83c8c16dad6414d4732f3e1f8ee | 77,643 |
def cleanup(args):
"""
Cleanup files after build
:param args: pass type of cleanyp.
:return: 0 on success
"""
if args.clean:
cleanup_type(args, "clean")
if args.generated:
cleanup_type(args, "generated")
if args.all:
cleanup_type(args, "all")
return 0 | 4fa957a2ed5a362403d5ed818245606c51d5acc8 | 77,645 |
import array
def np2array(ndarray, dtype_id):
"""
Helper function to do fast format conversion between numpy array and array.array
used for internal storage of QG8 tensors
args:
ndarray, numpy array of values
dtype_id, target data type as a QG8 constant
"""
typecode = dtype_to_... | e92f633b629722fa6770538bf4c50c30691577df | 77,646 |
def sum_digit_factorials(n: int) -> int:
"""
Return the sum of the factorial of the digits of n.
>>> sum_digit_factorials(145)
145
>>> sum_digit_factorials(45361)
871
>>> sum_digit_factorials(540)
145
"""
if n in CACHE_SUM_DIGIT_FACTORIALS:
return CACHE_SUM_DIGIT_FACTORIA... | bf957b41a6968e27d640a1c192d73846ca8fd719 | 77,647 |
def freq2ind(freqs, srate, nfreq, rfun=None):
"""Returns the index of the first fourier mode with greater than freq
frequency, for each freq in freqs."""
if freqs is None: return freqs
if rfun is None: rfun = np.ceil
return rfun(np.asarray(freqs)/(srate/2.0)*nfreq).astype(int) | 8cfe202e260dc0d52b34476e7ea39e2a25a88358 | 77,648 |
from typing import List
def get_sub_mol(mol: Chem.Mol, sub_atoms: List[int]) -> Chem.Mol:
"""Extract subgraph from molecular graph.
Parameters
----------
mol: Chem.Mol,
RDKit mol object,
sub_atoms: List[int],
List of atom indices in the subgraph.
"""
new_mol = Chem.RWMol()... | 734731e2478237521687361960131a186e5ad08b | 77,649 |
import urllib
def get_user_key(api_key, username, password):
"""Get login key"""
post_url = 'http://localhost:3000/vim'
headers = {}
headers['Content-Type'] = 'application/json'
post_data = urllib.parse.urlencode(
{
'api_dev_key' : api_key,
'api_user_name': username... | e9d88ba3b0b9cba2f60da7c12dca5c24bfd97e04 | 77,650 |
def generate_occurrence_signature (occurrence):
"""Generates the signature for an occurrence.
:param occurrence: the occurrence to generate the signature for
:type occurrence: `Occurrence`
:rtype: tuple
"""
return (_generate_type_signature(occurrence),
_generate_scope_signature(occ... | 63ad090bd97bc401b09ecc56760719051c1d0d39 | 77,651 |
def _prepare_filter_func(target):
"""Create a filter function depending on the type of the given target."""
if isinstance(target, str):
target = target.lower()
def func(atom):
# match: name, type name
return atom.name.lower() == target \
or atom.type_name... | e72a6e1297953892dd52a39df1f4bc422c17a2c9 | 77,654 |
def layer(response, trials=-1):
"""
implementation of the Monitor-Corrector Subspace algorithm
Parameters
----------
result : object
A valid :py:class:`cobea.model.Response` object.
trials: int
Number of different monitor subsets tried for MCS. If set to -1, value is set automat... | 47be2a83311e9ce9bea9fca8244b4cb13c4533b0 | 77,655 |
def buildDesignMatrix(probeTheta, waveNumber):
"""
Build the design matrix (A) from probe positions and the wavenumbers of
interest. Use the design matrix and signal from the probes, x, to solve
for the wavelet coefficients.
<333 T. Harrison 10/2020
Input:
1) probeTheta - angul... | 78d33f09750258a20096451a1d4209b6112d5c94 | 77,656 |
def prepend_domain(link):
"""
Urls are directly combined as given in *args
"""
top_level_domain ='https://www.proff.no'
return top_level_domain + link | 25e599d2744100aeea71556751906dc1a9166428 | 77,657 |
def children(context, root):
"""
Renders all children of root where template matches children_template_name.
"""
queryset = root.get_descendants().filter(template='{}.html'.format(root.categoryextension.children_template_name))
children_per_page = 12
page = context.request.GET.get('page', 1)
... | 131f00e5ac44ac3678e74b42fc7ad69dd2b0c3ff | 77,658 |
import warnings
def get_squid(
direction: Direction,
base_length: float,
anchor: tuple[float, float] = (0, 0),
squid_size: tuple[float, float] = (0.15, 0.15),
squid_pad_size: tuple[float, float] = (6, 8),
xy_distance: tuple[float, float] = (18, 9),
base_layer: i... | bdcabc36af67800cc0951293e9d14ee241ae12ea | 77,659 |
def ref_str_to_tuple(ref):
"""String like ' a : b ' to tuple like ('a', 'b')."""
return tuple(x.strip() for x in ref.split(':')) | fc2e467f054d2b53a580f1d0917d01eda9ba1727 | 77,661 |
def box_area(boxes):
"""
Computes the area of a set of bounding boxes, which are specified by its
(x1, y1, x2, y2) coordinates.
Args:
boxes (Tensor[N, 4]): boxes for which the area will be computed. They
are expected to be in (x1, y1, x2, y2) format
Returns:
area (Tensor[... | bd68c55054a62ef9e58d28dc69f690157d199667 | 77,662 |
def bin_append(a, b, length=None):
"""
Appends number a to the left of b
bin_append(0b1, 0b10) = 0b110
"""
length = length or b.bit_length()
return (a << length) | b | c2d3132532b1d9311d5b6eef94289c0763422665 | 77,663 |
def levenshtein_distance(word_1, word_2):
"""
Calculates the levenshtein distance (= the number of letters to add/
substitute/interchange in order to pass from word_1 to word_2)
"""
array = [[0 for i in range(len(word_2)+1)] for y in range(len(word_1)+1)]
for i in range(len(word_1)+1):
... | ce43e60454b59c3c1323656636f457bc192a2c67 | 77,664 |
import inspect
def get_source_link(obj, page_info):
"""
Returns the link to the source code of an object on GitHub.
"""
package_name = page_info["package_name"]
version = page_info.get("version", "master")
base_link = f"https://github.com/huggingface/{package_name}/blob/{version}/src/"
mod... | 86748f179e44cec37efd88e1b8dc5de0c6268631 | 77,665 |
def concat_environment(env1, env2):
""" Concatenate two environments.
1 - Check duplicated keys and concatenate their values.
2 - Update the concatenated environment.
Parameters
----------
env1: dict (mandatory)
First environment.
env2: dict (mandatory)
Second environment.
... | 25f7aee5a9316ab0604f2e38538a1f67a5333b08 | 77,666 |
def process_article_results(article_results):
"""
"""
article_list = []
for article_item in article_results:
author = article_item.get('author')
title = article_item.get('title')
description = article_item.get('description')
url = article_item.get('url')
picture = article_item.get('urlToIm... | c9aa42f7dc5e22f30491d0ac38dc1eacca7e1318 | 77,667 |
import re
def is_path(source):
"""
check if the supplied source is a valid path
(this does not appear to be part of moments.path module,
but could be relocated there)
** this will not match relative paths **
"""
if re.match('/', source):
return True
else:
return False | 405ff439b2785c54b30877574408e65a4f36e3de | 77,668 |
def green_block(inp, filters, data_format='channels_first', name=None):
"""
green_block(inp, filters, name=None)
------------------------------------
Implementation of the special residual block used in the paper. The block
consists of two (GroupNorm --> ReLu --> 3x3x3 non-strided Convolution)
u... | fa8d26d83b7718549b58cb03e3e6caf564287fcf | 77,670 |
def _convert_to_dataset_class(df, dataset_class, expectations_config=None):
"""
Convert a (pandas) dataframe to a great_expectations dataset, with (optional) expectations_config
"""
if expectations_config is not None:
# Cast the dataframe into the new class, and manually initialize expectations ... | b054bddd563e0f8f68039b7f2d4e7e92f4ded577 | 77,671 |
import itertools
def get_emin_emax(self):
"""
Finds how much the Ek_grid has to be expanded
above the bandwidth D of the leads.
Parameters
----------
self : Approach2vN
Approach2vN object.
self.funcp.emin : float
(Modifies) Minimal energy in the updated Ek_grid.
self.... | 102198b413f190264e231c80f896045fc2eb3f58 | 77,673 |
def _parse_tile_arg(*args):
"""parse the *tile arg of module functions
Parameters
----------
tile : Tile or sequence of int
May be be either an instance of Tile or 3 ints, X, Y, Z.
Returns
-------
Tile
Raises
------
TileArgParsingError
"""
if len(args) == 1:
... | 5b46ce51f5b000e236773daf2f6a86fd70d6b5d8 | 77,674 |
import re
def substitute_pattern_with_char(s, pattern, repl_char='x'):
"""
This is a little different than re.sub(). It replaces all the characters
that match the pattern with an equal number of `repl_char` characters.
The resulting string should be the same length as the starting string.
>>> su... | 98d7f3d642430a5211aa7396a3454d979057ebef | 77,675 |
def map_object_from_java(obj):
"""Converts a JsonObject to a dictionary."""
return map_map_from_java(obj.toMap()) | a7a8acec64e4fe39734d08e21eb2cba7c494f835 | 77,676 |
def rate_limit_exceeded(key="", timeout=1):
"""
:param key: rate limit bin
:param timeout: number of seconds to enforce between requests
:return: True if rate limit has been exceeded (request should be throttled)
The maximum supported rate limit is 1 request/second
Bins should be narrow enough... | ae18f5f39c2f2893fa04ce3ff7615b9c44614b42 | 77,677 |
def rdkit_descriptors(mol):
"""
Get the molecular descriptors by iterating over all possible descriptors.
Parameters
----------
mol : object
An rdkit molecules object.
Returns
-------
dict
Dictionary that contains the molecular descriptor names as keys and their respective values... | f1f69cebe9018c85b4455751af1196358ae4c19c | 77,678 |
import logging
def load_bedcounts(
api_key=None, icubam_host=None,
):
"""Load Bedcount data from ICUBAM API"""
if api_key is None or icubam_host is None:
raise RuntimeError("Provide API key and host to download ICUBAM data")
else:
protocol = "http" if icubam_host.startswith("localhost"... | 5135e7a9c5e0a0e99bd8a2e8298555d8f5043615 | 77,680 |
def get_kolibri_process_info():
"""
Return information on the Kolibri process running in the machine
:returns: tuple of integers containing PID and TCP Port of
the running (if any) Kolibri server in this same machine
"""
kolibri_pid = None
kolibri_port = None
try:
with ... | ea84e100b8cf580e06a0fefe86ffe607ebe0ed28 | 77,681 |
def coach_is_undefeated(list_of_pokemons):
"""Function to know if the Coach is still undefeated.
This function is used in order to know if the Coach is still undefeated.
Syntax
------
[ ] = coach_is_undefeated(list_of_pokemons)
Parameters
----------
[in] list_of_pokemons List of... | 0d74fca6aa03022c40700cc1e6e0accab1c6bb41 | 77,682 |
def extract_table_name(file_name: str) -> str:
"""Extract the table name name from the filename
Assumes the name of the bigquery table the data is being inserted to is the first
word of the filename
Examples:
extract_file_extension(properties/properties_09.csv)
>>> "properties"
"""
re... | 1cac0a58325651abff1399974df52aaefa93585f | 77,683 |
def emr_cost_usage(start_date: str, end_date: str, cluster_name: str):
"""
Get the EMR cost usage mont to date.
Args:
start_date (str): The beginning of the time period that you want the usage and costs for. The start date is inclusive.
end_date (str): The end of the time period that yo... | 0db41e43660d3899da675b33959faeb05f1d5963 | 77,684 |
def calculate_block_ranges(scan, block_size):
"""
:param scans
:type a scan object
:param block_size:
:type block_size: target block size in degrees"""
image_ranges = []
nimages = scan.get_num_images()
osc_range = scan.get_oscillation_range(deg=True)
osc_width = abs(osc_range[1] - ... | 1ea1f8ecb6b7a3a5713a7169effcf0db2d9eac06 | 77,686 |
def get_grid_dim(x):
"""
Transforms x into product of two integers
:param x: int
:return: two ints
:src: https://github.com/grishasergei/conviz/blob/master/utils.py
"""
factors = prime_powers(x)
if len(factors) % 2 == 0:
i = int(len(factors) / 2)
return factors[i], factor... | 2ed0441adf83aee6f33568f4bfa6a826edca797d | 77,687 |
import uuid
def generate_client_token_by_uuid():
"""
The default method to generate the random string for client_token
if the optional parameter client_token is not specified by the user.
:return:
:rtype string
"""
return str(uuid.uuid4()) | 0932936d3f5231cc5aefcdafd317dcf23fab96c0 | 77,688 |
def get_geonames_remote_file(scope: str = "allCountries") -> TextIOWrapper:
"""
retrieve zip file from https://download.geonames.org/export/dump/
:param scope: ISO-3166 alpha2 country abbreviation, e.g. `FR` or `allCountries`
"""
zip_file = download_zip_file(PLACE_DATA_URL.format(scope=scope))
... | 3019b51a8ae06caf1ff84e9e96460399f74247ba | 77,689 |
def solve_tactical_problem(lVehDataFormat):
"""
Create a dictionary indicating the trigger time as a key
"""
SAFETY = 0 # Put on 0 for flow maximization
# Find Xm, Tm
lArrivalTimes = [(-x['abs']/x['vit'], x['id'],
0.0,
float(x['ti'])-x['abs... | 01d51f00654e419e550ea54a74782630528bfecd | 77,690 |
from pathlib import Path
def read_list_file(filename: str, list_type: str, dir_features: Path) -> DataFrame:
"""
Parameters
----------
filename
Returns
-------
"""
# read in probe list (table)
df = pd.read_csv(filename)
if list_type == "probes":
# add column for file... | 518963609744f62f48f3e48e81f35c8cbdc7c16b | 77,691 |
def project_mean_velocity(vmean, position):
"""
Project vmean at `position` and get predicted proper motions
vmean : quantity (v_x, v_y, v_z)
in cartesian equatorial coordinates, km/s
position :
Returns (pmra, pmdec) in units of mas/yr
"""
if isinstance(position, pd.DataFrame):
... | dbf23c523e45c2741714741f81f58630e98a7679 | 77,693 |
import random
def _randbytes(n: int) -> bytes:
"""Polyfill for random.randbytes in Python < 3.9"""
return bytes(random.choices(range(256), k=n)) | 5d6b0a734774dc28d45d53cc2dfeedc8a986a8a5 | 77,694 |
def histogram_stack(*histograms):
"""Creates a THStack object with a unique identifier from the specified
histograms.
This method is useful due to THStack freaking out if a new THStack is
created with the same name.
Args:
histograms: Each argument of this function after plot may be a singl... | 0fdfa6f00363ec12b4b839d9b4619e24eb97d7ca | 77,695 |
def duel(Player, CPU):
"""
flag = 0 --> HAI PERSO
flag = 1 --> PAREGGIO
flag = 2 --> HAI VINTO
"""
flag = 0 # Initialize the flag
if(CPU.cpu == Player.p_value):
flag = 1
else:
if(CPU.cpu == "sasso"):
if(Player.p_value == "carta"): flag = 2
if(Pla... | 9248d86e14ae0783f87dcee42e0fd9a8299f0150 | 77,696 |
def avg(arr):
"""Count average."""
return sum(arr) / float(len(arr)) | 0da964cdb1d14154b4569d010b4caa710a30fd84 | 77,697 |
def users(username):
"""Generate the webpage that displays the user posts"""
db = COMP249Db()
uname = session_user(db) # retrieve user session information from the database
loginString = ""
private = "#private" # string that makes the post private
list = interface.post_list(db, usernick=username... | b717da3b6e40df868bcbe597414bc0bb6211117b | 77,699 |
def convert_to_camel(data):
"""
Convert snake case (foo_bar_bat) to camel case (fooBarBat).
This is not pythonic, but needed for certain situations
"""
components = data.split('_')
return components[0] + "".join(x.title() for x in components[1:]) | cd3e162f02172d5d3d83c1e77d82d65816150278 | 77,700 |
def createAugmentedData(training_data, training_labels):
"""
This is creates the augmented data.
Args:
training_data(numpy arrays): This is the numpy array of the training data.
training_labels(numpy arrays): This is the numpy array of the training labels.
Returns:
complete_t... | e80a2e9689fc282350670f5178f51829d8e9749d | 77,701 |
def add_player(nickname) -> PlayerHuman:
"""Add human player to game.
This function adds human player(s) to the game by taking
the chosen nickname for the player and returning a
Playerhuman instance with the chosen name.
Args:
nickname : str
Takes nickname of player as argument... | febbec9d7aca4a6b1abe1dfdbc4cc6ff94b5eaa3 | 77,703 |
def low_dword(x: IntVar) -> UInt32:
"""Implementation for `LODWORD`."""
return dword_n(x, low_ind(x, UInt32)) | 7270bd37b0343f110d3a8e50b759d17400d805a6 | 77,704 |
def total_review_average(obj, normalize_to=1):
"""Returns the average for all reviews of the given object."""
ctype = ContentType.objects.get_for_model(obj)
total_average = 0
reviews = models.Review.objects.filter(
content_type=ctype, object_id=obj.id)
for review in reviews:
total_av... | df91385bf2552a56ffa9bdc8c8d6fd399c5618a9 | 77,705 |
import typing
async def create_serial_slave(modbus_type: common.ModbusType,
port: str,
read_cb: typing.Optional[ReadCb] = None,
write_cb: typing.Optional[WriteCb] = None,
write_mask_cb: typing.Optio... | a2c22c2d68f32a132f9fd5ccd0565fc67f0fdb8c | 77,706 |
import struct
def create_pedal_command_msg(accelCommand, enable, idx, pedalcan):
"""Create GAS_COMMAND (0x551) message to comma pedal"""
msg_id = 0x551
msg_len = 6
msg = create_string_buffer(msg_len)
m1 = 0.050796813
m2 = 0.101593626
d = -22.85856576
if enable == 1:
int_accelCo... | d018d40526d4df24e9af1b8a3d441f61349614d5 | 77,707 |
def canonicalize_json(value):
"""
Decode all bytes in the ``value`` JSON value.
This clones the input JSON value, replacing all bytes with the
corresponding strings, assuming UTF-8 encoding.
"""
if isinstance(value, (int, bool)):
return value
elif isinstance(value, str):
ret... | f3bb0a83a3a4a230d425a7503ab9026797a2c097 | 77,708 |
def diffquery(*queries):
"""
Factory for relative complement of results for queries A \ B \ ...
Or A minus anything matching any of the subsequent queries.
"""
if len(queries) == 0:
raise ValueError('empty query arguments')
if len(queries) == 1:
return queries[0]
return query... | 2f01abdd9d3e3f8937f13c3f28f1eafb858c234f | 77,709 |
def from_roi(msg):
"""
Convert a `sensor_msgs/RegionOfInterest` ROS message into a list with the
two corners of the ROI.
Parameters
----------
msg: sensor_msgs/RegionOfInterest
The ROS message to be converted
Returns
-------
result: list
The resulting list
"""
t... | ad5b6115d0e22326ba19ad62386d133d813c0b6d | 77,710 |
def read_overall_stats(filename):
"""Reads csv file and returns it as a pandas data frame"""
pandas_df = pandas.read_csv(".\\stats\\" + filename, parse_dates=['DATE'])
print pandas_df
return pandas_df | 46c91e6f6a5c260156b95d9b762123ffcfc05436 | 77,711 |
def rguard(rel_guard, **kwargs):
"""
Converts first and only positional argument to a RelGuard object.
By using rguard you guarantee that `rel_guard` is a correctly defined relguard function.
"""
return guard(RelGuard(rel_guard), **kwargs) | cc0d046330a4581ca85178155222a03441576a43 | 77,712 |
def get_color(fg=None, bg=None, style=None):
"""
Get the ANSI color based on params
:param str|int|tuple fg: Foreground color specification.
:param str|int|tuple bg: Background color specification.
:param str style: Style names, separated by '+'
:returns: ANSI color code
:rtype: str
"""... | 40551afd65cbd8b93483d9a24dc5834766069340 | 77,713 |
def gcr(i, mu, pi):
"""Compute the gray code rank of i given the mask mu.
Algorithm 4 in [TR]"""
r = 0
for k in range(N-1, -1, -1):
if bit_component(mu, k):
r = (r << 1) | bit_component(i, k)
return r | 591b8e43b0687adb99cfd858682e74223b93aadc | 77,714 |
def plot_loss_landscape(loss_landscape, mode='surface', proc_fn=np.log,
clip=(-3,10), elevation=40, angle=45, levels=None, figsize=(10,10),
label=False, cmap='viridis', **pyplot_kwds):
"""Plot the loss landscape as either a surface or contour plot.
Use the outputs... | b7f8ef67e1005097936772b8a044b3db0a168165 | 77,716 |
def get_access_token():
"""获取非用户态access_token"""
return get_client_access_token() | b01136df7b8ba5de9e9988e1a5a7e0e9834d89b5 | 77,717 |
from typing import Tuple
def l_faces(n1: int, n2: int, xform,
dim1: Tuple[float, float, float, float],
dim2: Tuple[float, float, float, float]):
"""
^y
|
0-----5 ^ hall
| | | |
| | | |
| | | |
|... | 829f815c689d52d4e56b3512870e0dfad25b5bab | 77,718 |
import numpy as np
def get_time_course_for_columns( time_course_data_set, col_indices=None ):
"""
Pick out a set of columns
:param time_course_data_set:
:param col_indices:
:return:
"""
if col_indices is None or None in col_indices:
return None
data = np.ndarray( shape=(len... | 1ec4570f37ad7eff10e201a934e05accea7aecbc | 77,719 |
from typing import Tuple
def unbalanced_tree(v: np.ndarray, phase_style: str = PhaseStyle.TOP, error_mean_std: Tuple[float, float] = (0., 0.),
loss_mean_std: Tuple[float, float] = (0., 0.)):
"""Linear chain that analyzes a vector :code:`v`.
Args:
v: Vector unit
phase_style... | fe8ff0cfc0ebeb4045e4d64072ce08b759b57693 | 77,722 |
def lowPassFilter(imgarray, apix=1.0, bin=1, radius=0.0, msg=True):
"""
low pass filter image to radius resolution
"""
if radius is None or radius == 0:
if msg is True:
apDisplay.printMsg("skipping low pass filter")
return(imgarray)
sigma=float(radius/apix/float(bin))
return ndimage.gaussian_filter(imgarra... | 2f7dcbf30718e6e9f613b2b4f9139d07fb63d19c | 77,723 |
def restart_sampler(sample_results, lnprobf, sps, niter,
nthreads=1, pool=None):
"""Restart a sampler from its last position and run it for a specified
number of iterations. The sampler chain and the model object should be
given in the sample_results dictionary. Note that lnprobfn and ... | c0fe71c0c02a4ccbe0cf6e1b1145cb62b4eb295e | 77,724 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.