content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 |
def from_array(flwdir, _mv=_mv, dtype=np.intp):
"""convert 2D LDD data to 1D next downstream indices"""
nrow, ncol = flwdir.shape
flwdir_flat = flwdir.ravel()
# get downsteam indices
pits_lst = []
idxs_ds = np.full(flwdir.size, core._mv, dtype=dtype)
n = 0
for idx0 in range(flwdir.size):... | 039c2255c2ee7b03299ca9f91e11160da68643d2 | 53,000 |
def get_checks_by_status(api_key, status='new'):
"""
Возвращает JsonResponse с чеками соответствующего статуса status.
:param api_key: str: Ключ доступа API
:param status: str: Статус получаемых чеков
:return: :class:`Response <Response>` serialized to JSON
:rtype: http.JsonResponse"""
try... | 5f7a78ddb30c67e6a5310b80a47a7b36f325c1ec | 53,001 |
from datetime import datetime
def current_time():
""" Current UTC datetime """
return datetime.datetime.utcnow() | 2eb04fd6843c9d2f75c27a86e0d8b4f31c5e2194 | 53,002 |
def value_and_multigrad(fun, argnums=[0]):
"""Returns a function that returns both value and gradients wrt multiple
arguments simultaneously."""
def combined_arg_fun(multi_arg, *args, **kwargs):
extra_args_list = list(args)
for argnum_ix, arg_ix in enumerate(argnums):
extra_args_... | fe0c305cf1ef038c856a23e0151e3d69fa3386d1 | 53,004 |
from datetime import datetime
def day_of_year(t=None):
"""Returns the day of year."""
SECONDS_IN_DAY = 60 * 60 * 24.0
time = parse_time(t)
time_diff = parse_time(t) - datetime(time.year, 1, 1, 0, 0, 0)
result = time_diff.days + time_diff.seconds / SECONDS_IN_DAY
return result | c68923603a58719b762415ba46ccd43ff52af383 | 53,005 |
def show_object_id_by_date(
move_data: 'PandasMoveDataFrame' | 'DaskMoveDataFrame',
kind: list | None = None,
figsize: tuple[float, float] = (21, 9),
return_fig: bool = False,
save_fig: bool = False,
name: str = 'shot_points_by_date.png',
) -> figure | None:
"""
Generates four visualizat... | 4e128c517745472d0033815099aa5cbd2634e18f | 53,006 |
from typing import Optional
from typing import Tuple
from pathlib import Path
def retrieve_experiment_name_and_path(experiment_name: Optional[str]) -> Tuple[Path, str]:
"""
Retrieve the experiment_path and experiment_name from the cwd and parameters given.
"""
path = Path.cwd()
if experiment_name ... | f37b57bc0abcfe3dbbb358309819a1d7b4043ddb | 53,007 |
from typing import List
import requests
def option_sse_list_sina(symbol: str = "50ETF", exchange: str = "null") -> List[str]:
"""
新浪财经-期权-上交所-50ETF-合约到期月份列表
https://stock.finance.sina.com.cn/option/quotes.html
:param symbol: 50ETF or 300ETF
:type symbol: str
:param exchange: null
:type exc... | e6ef3b22f8f02c938063b7b5a786248a046a8318 | 53,008 |
async def login(user_data: UserLoginIn):
"""Login Users
Endpoint for users login
Args:
- user_data (UserLoginIn): user_data with fields email and password. This user_data
corresponds a UserLoginIn schema
Returns:
string: Returns jwt token wich the user can navigate for anothers endpoints (i... | 6a857f3d317a20dcc2819090ff003ada3267d20b | 53,009 |
def S_stat(data, data_label, refdata, refdata_label, obj_prop=True,
lsmask=None):
"""
Function to calculate the structure component (S). The basic idea is to
compare the volume of the normalized precipitation objects. This property
captures information of the geometrical characteristics (siz... | fc1f902d9431f59307ad71f619829116cd66c099 | 53,010 |
import re
def fix_bad_next_statements(vba_code):
"""
Change things like "Next x,y" to "Next x\nNext y"
"""
uni_vba_code = None
try:
uni_vba_code = vba_code.decode("utf-8")
except UnicodeDecodeError:
# Punt.
return vba_code
pat = "Next +(?:\w+ *, *)+\w+ *\n"
... | e27bdc733094fbc05268e7dd6dd6c830f1afe4d6 | 53,011 |
import json
def copy_metrics_and_parameters(report_file=REPORT_FILE):
"""
Returns Parameters and Metrics from the report_file.
:param report_file:
"""
metrics = {}
parameters = {}
with open(report_file) as f_in:
result_json = json.load(f_in)
if 'Metrics' in result_json:
... | c816a5098df50e5c0d7395b2a5d4630bf92aacae | 53,013 |
def MnistLI2(list_x,list_y, n_sec=20):
"""
Linear interpolation function for up sampling
"""
FinerArray = np.array([]).reshape(0,2)
for i in range(len(list_x)-1):
if list_x[i]<list_x[i+1]:
xvals = np.linspace(list_x[i], list_x[i+1], n_sec)
xvals = np.delete(xvals, 0)
... | a19b8b909623e76ed1f55809a4acb73ce604c22e | 53,014 |
def log_prior(theta):
"""
Priors, limit the values to a range but otherwise flat.
"""
#limit the values to 0 < theta < 256
if (all(theta > 0) and all(theta < 256)):
return 0
else:
return -np.inf | 4d921dbe9dc39078338c44c2efc065ec6551d6d2 | 53,015 |
def cdf(x, mean=0.0, stdev=1.0):
""" Returns the cumulative distribution function at x.
"""
return min(1.0, 0.5 * erfc((-x + mean) / (stdev * 2**0.5))) | 5a52c23872716fb5cafe4ba0873280f824367488 | 53,016 |
def binarize(img_gray,
diameter=10,
sigmaColor=150,
sigmaSpace=150,
a_thresh_type=2,
a_thresh_blocksize=20,
a_thresh_offset=0,
a_thresh_offset2=0):
"""Binarize an image
Binarize an image using OpenCV library
Args:
... | 6badad6ead77147dc8a00677df1aea273fd69d5f | 53,017 |
def random_SBM(n_nodes, block_sizes, p_in_min, p_out_max):
"""
Full random SBM
"""
nb_communities = len(block_sizes)
outmat = np.random.uniform(low=0, high=p_out_max, size=(nb_communities,nb_communities))
W = 0.5 * (outmat + outmat.T)
inmat = np.random.uniform(low=p_in_min, high=1, size=(nb_... | d1162d5bed9eca674bdf1d9a3b286df3df41a84d | 53,018 |
def add_meta(match):
"""return a dict from the match"""
attr_name, attr_value = match.groups()
return {attr_name: strip_quotes(attr_value)} | 5fa3642a9dbd768d3495fc6517e527a5f4351422 | 53,019 |
def remap_labels(labels, mappings):
"""
:param labels:
:param mappings:
:return:
"""
for source, target in mappings.items():
labels[labels == int(source)] = target
return labels | df418b76c7831ac315e095cd9bf75b7596b04a91 | 53,020 |
def mean_absolute_deviation(array):
"""
Calculate the mean_absolute_deviation on EEG data
input:
array: numpy array. The temporal signal for feature extraction. 1d or with multiple dimensions
return
de: int or numpy array, depends on the input shape
"""
def cal_mad(s):
r... | 8fd013614dd3459d18c3a08683fe60570c31154d | 53,021 |
def render(context, file='index.html', template_name='aquarius'):
"""Render a template in a string, by file.
A webloft template is often much more than a file. Each file is a
django template. Rendering all the files in the template directory
gives a full render of the website.
The template name is... | 234273ad21e11d29cc1d2a62caa61e60125308bf | 53,023 |
def get_data(symbols, dates):
"""Read stock data (adjusted close) for given symbols from CSV files."""
get_csv(symbols)
df = pd.DataFrame(index=dates)
if 'SPY' not in symbols: #add SPY for reference, if absent
symbols.insert(0,'SPY')
for symbol in symbols:
get_csv(symbol)
df_temp = pd.read_csv(symbol_to_pat... | 25c2d47dc097a9950e3bf9407d94aada74fc149d | 53,024 |
def load_network(path, weighted=False, directed=False):
"""
Load the edgelist as a networkx.Graph() object.
Input:
path::string: path to the edgelist
weighted::bool: whether the network has edge weights
directed::bool: whether the network is directed
Return:
::networkx.... | 0a2e4f2789583f70c9b1598c5a4cbb78cacc8b27 | 53,025 |
from . import sill
from clawpack.pyclaw.util import check_diff
import numpy as np
from clawpack.pyclaw.util import gen_variants
from itertools import chain
def test_1d_sill():
"""test_1d_sill
tests against expected classic solution of shallow water equations over
a sill."""
def verify_expected(expe... | 5190b75a4f3dcfc47f019023d450d5e568a2df5e | 53,026 |
def integrations_create(response):
"""Creates an integration. Link"""
return validate_response(response) | d4a119fd8c51c4a2b815dc41dfdccd5a5381a181 | 53,027 |
def select_from_multiple_candidates(transcripts, refseqscan, appris_principal, selected, missing, log, hgncid, build, cartseries, cartidx):
"""Select from multiple transcript candidates"""
if not all_have_same_cds(transcripts):
to_missing_list(missing, log, hgncid, 'coding_mismatch', 'Not all of these ... | f6a73b91162eca742bca73d06ed3d92ceb8b06b0 | 53,028 |
from datetime import datetime
import time
import pytz
def str_date(dt):
"""datetime to ISO 8601 str"""
if not dt or not isinstance(dt, (datetime, date, time)):
raise TypeError('dt should be date object, and not a %s' % type(dt))
if not dt.tzinfo:
# update dt with utc zone
dt = pytz... | 4e4455dc5d30df6fc303b4fa9977f9838f5206cb | 53,029 |
def get_bprop_l2_loss(self):
"""Grad definition for `L2Loss` operation."""
def bprop(x, out, dout):
dx = x * dout
return (dx,)
return bprop | 6f52c07d9133939f5a7dc6d12a2416169f32147e | 53,031 |
def change_dimension_shape_resolution(changed_dimension_shape_conflict):
"""Create a resolution for a changed shape prior"""
return changed_dimension_shape_conflict.ChangeDimensionResolution(
changed_dimension_shape_conflict
) | c6f93f080ed14876a4724924dc848fb835364c33 | 53,032 |
def process_atbat(atbat_elem, atbat):
"""
Call process_pitch for every pitch in that atbat
"""
balls = 0
strikes = 0
pitches = []
for pitch_elem in atbat_elem:
if pitch_elem.tag == 'pitch':
pitch = process_pitch(pitch_elem, atbat, balls, strikes)
pitches.app... | a7c0d37336c375a75aca313b8085fecdcb488b38 | 53,033 |
def extract_tracklist_begin_num(content):
"""Return list of track names extracted from messy web content.
The name of a track is defined as a line which begins with a number
(excluding whitespace).
"""
tracklist = []
for line in content.splitlines():
# Empty line
if not line:
... | 7d860fb0ea444ae0d9bd536a4644fa6b1c11a826 | 53,034 |
import logging
def post_image(conn, image, image_name, description=None, dataset_id=None,
source_image_id=None, channel_list=None):
"""Create a new OMERO image from numpy array.
Parameters
----------
conn : ``omero.gateway.BlitzGateway`` object
OMERO connection.
image : ``n... | 465fca773a9d66ef1e013a6acc0f4c6e0db60258 | 53,036 |
def save_to_mongo(data, mongo_db, mongo_db_coll, **mongo_conn_kw):
"""Saves data to Mongo"""
client = pymongo.MongoClient(**mongo_conn_kw)
db = client[mongo_db]
coll = db[mongo_db_coll]
return coll.insert(data) | 10cd2bfda0f7165ff2dd68e34d44fbdb0375a483 | 53,037 |
from typing import List
def _append_autopep8_lint_command_if_module_updated(
lint_commands: List[LintCommand],
module_paths: List[str]) -> List[str]:
"""
Append the autopep8 lint command to the list if the
modules have been updated.
Parameters
----------
lint_commands : list o... | f6361b5f8f97376295535ff0efea96e0117c8325 | 53,038 |
def rgb2hsv(rgb:np.ndarray):
"""Compute luminance of an RGB image.
Args:
rgb (tensor): rgb image (shape:(H,W,C))
Returns:
gray(tensor): gray-scale image(shape:(H,W))
Examples:
>>> import cv2
>>> from skimage import color
>>> img=cv2.cvtColor(cv2.imread('../../... | 195ef06973b3c01f594e0c0ad515925a51ce6910 | 53,039 |
def net_solar_radiation(rs, albedo=0.23):
"""
Calculate the fraction of the solar radiation that is not reflected from
the surface (Allen et al. 1998).
Parameters
----------
rs : float
Solar radiation (MJ m-2 day-1).
albedo : float, optional
Albedo (-), default is 0.23 (valu... | 41a8930966db4a658d1c3ec31e754987bc9ed387 | 53,040 |
from typing import Callable
from typing import Dict
from typing import Any
from typing import Collection
def resolve_nodes(fn: Callable, config: Dict[str, Any]) -> Collection[node.Node]:
"""Gets a list of nodes from a function. This is meant to be an abstraction between the node
and the function that it imple... | 4e573e027467fef4452c9faf35744c062156498c | 53,041 |
def request_from_dict(d, processor=None):
"""Create Request object from a dict.
If a spider is given, it will try to resolve the callbacks looking at the
spider for methods with the same name.
"""
cb = d['callback']
if cb and processor:
cb = _get_method(processor, cb)
eb = d['errbac... | 5e84e7261cfeea997daa6b974e629aec45e094dc | 53,042 |
def text_color(message='{}', color_code='\033[0;37m'):
"""Set text to a color, default color is White"""
no_color = '\033[0m'
return f'{color_code}{message}{no_color}' | bede08b771b33ce26bbb0ee4fd42f3712d224cc1 | 53,043 |
import torch
def masked_max(
vector: torch.Tensor,
mask: torch.BoolTensor,
dim: int,
keepdim: bool = False,
) -> torch.Tensor:
"""
To calculate max along certain dimensions on masked values
# Parameters
vector : `torch.Tensor`
The vector to calculate max, assume unmasked part... | b37b2007939df46c8963770c12f031cc347144ae | 53,044 |
def get_max_elements_in_row(row: list) -> int:
"""
Loops through the dataset and gets the max elements in a list if
one is found in the list or 1 if all strings.
"""
max_array_count = 0
# get the max height of the cells.
for item in row:
if isinstance(item, list) and len(item) > max... | 0f8573bbabe95c03e3eda5949ff9c1c209b0f5fa | 53,046 |
def coord_type_from_ctype(ctype):
"""
Determine whether a particular WCS ctype corresponds to an angle or scalar
coordinate.
"""
if ctype[:4] == 'RA--':
return 'longitude', u.hourangle, None
elif ctype[:4] == 'HPLN':
return 'longitude', u.arcsec, 180.
elif ctype[:4] == 'HPLT'... | d7f26f5268f4b06e6dceae571516937e85543dee | 53,047 |
def swac()->(int,str):
"""run an analysis on a signle word based on a corpus"""
print('Available corpora:')
for c in corpora:
print(c)
while True:
corpus = input("Please enter an available corpus to refrence by index number: ")
try:
corpus = int(corpus)
if... | a10cd6a4dff6b2fc16d8ecb02024bc1d90ebbdc1 | 53,048 |
def get_adventure(): # noqa: E501
"""Get all adventures
# noqa: E501
:rtype: List[Adventure]
"""
return "do some magic!" | 8ca2cb6b8e0aa004ca7fa54ec35f907c3351cab8 | 53,049 |
def return_pkl_files(pkl_dirs):
"""return pkl filenames"""
pkl_list = []
pkl_filenames = []
for pkl in pkl_dirs:
pkl_list.append(dataparser.load_pkl_file(pkl))
pkl_filenames.append(dataparser.get_filename(pkl))
return pkl_list, pkl_filenames | e8653006d98734e284ffcd0ee908514bb5d51a81 | 53,050 |
def get_control_flow_graph(program):
"""Get a ControlFlowGraph for the provided AST node.
Args:
program: Either an AST node, source string, or a function.
Returns:
A ControlFlowGraph.
"""
control_flow_visitor = ControlFlowVisitor()
node = program_utils.program_to_ast(program)
control_flow_visitor... | 946e39fe4d793bdf591f3934e49943c3bb79f6e5 | 53,051 |
def rebuild_schemas(index):
"""
Resets the schema for all checkpoints to the latest version based off the
current document structure. Returns the number of checkpoints updated.
"""
db = ExportSchema.get_db()
all_checkpoints = ExportSchema.get_all_checkpoints(index)
config = ExportConfigurati... | b89b4460cf1081f22ab193bada1fc77477e2104a | 53,052 |
def warp_occupancy(info, cc, smem_config=None):
"""Returns a dictionary of {threadperblock: occupancy, factor}
Only threadperblock of multiple of warpsize is used.
Only threadperblock of non-zero occupancy is returned.
"""
ret = {}
try:
limits = PHYSICAL_LIMITS[cc]
except KeyError:
... | 1eb7f4ec40a73615cb51fc05dc20c4225cb6b16d | 53,053 |
def cst_efield_2freq_cut_healpix(cst_efield_2freq_cut_healpix_main):
"""Make function level cut down HEALPix 2-freq efield beam."""
return cst_efield_2freq_cut_healpix_main.copy() | b7b2388efbe4f6ca1e22c08e46ec70d391c68ce8 | 53,054 |
import collections
import typing
def is_an_iterable_type_hint(rel_type_hint) -> bool:
"""Check if typing.Iterable wraps the relationship type hint.
###### Parameters ######
* `rel_type_hint`: type hint to check
For a given class `C`, all following expressions are evaluated to `True`:
```python... | a77c80ea5f3a0fa546c4280d1f2b3e1c5f04ae57 | 53,055 |
def shift_chord(chord, shift):
"""Shift chord"""
if chord < 12:
new_chord = (chord + shift) % 12
elif chord < 24:
new_chord = (chord - 12 + shift) % 12 + 12
else:
new_chord = chord
return new_chord | bc72df71282d8ae7d15e591bb2a46e5d00f1cd30 | 53,057 |
def register_new_user(access, username, password):
""" Register a new user & handle duplicate detection """
if access.user_data(username) is not None:
raise ValueError("User '%s' already exists!" % username)
if username in access.pending_users():
raise ValueError("User '%s' has already regis... | 25b98c4def9da81d71176aed196f61b2e71d64c5 | 53,058 |
def main():
"""
This function is called from the main block. The purpose of this function is to contain all the calls to
business logic functions
:return: int - Return 0 or 1, which is used as the exist code, depending on successful or erroneous flow
"""
# Wrap in a try block so ... | f243787ae86cbf77c5ccae44a68e171618c89c1d | 53,061 |
def report_3ware(line, log, controller):
"""Report findings in 3ware pipeline, return BOOL of health check."""
success = True
progress = None
data_type = None
if line[0] == "u":
data_type = "Unit"
status = line.split()[2]
if status == "REBUILDING":
progress = li... | cdb14dabe67614cae111020cced19752babca4cb | 53,062 |
import yaml
def load_properties():
"""
Load yaml file containing program's properties. Check the ReadMe.md file of the directory for a complete list of
the possible configuration properties and their values.
Returns:
dict: the properties dictionary
"""
properties_folder = join(app_dir... | 0e38e3bb9c420e823f911530165b5c5592ff29fa | 53,063 |
def cdf_to_pdf(cdf):
"""Compute a pdf (probability distribution function) from its cdf (cumulative distribution function)."""
pdf = deepcopy(cdf)
pdf[1:] -= pdf[:-1].copy()
return pdf | 5d9af93ba75d94c08c992474dd0302766aaa9210 | 53,064 |
def normalize_code(code):
"""
归一化证券代码
:param code 如000001
:return 证券代码的全称 如000001.XSHE
"""
return JQDataClient.instance().normalize_code(**locals()) | e87717aa55ea614db614fa662f9ce1580961e601 | 53,066 |
def get_not_constant_species(model):
"""
get species of the model that are not constant
@param model: libsbml.model
@type model: libsbml.model
@return: list of species
@rtype: list[libsbml.species]
"""
def not_const(s): return not( s.getConstant() or s.getBoundaryCondition() )
return... | abb376899405fa1623ec5ca646d0399e067fd5cc | 53,067 |
def remap_document_keys(document, key_map, inplace=True):
"""Remap keys in given JSON document.
>>> remap_keys({'foo': 1}, {'foo': 'bar'})
{'bar': 1}
"""
assert isinstance(document, dict)
if inplace:
# modify given document
for key in document.keys():
new_key = key_m... | feaafecc2e64ab2bd5f7cf5438bfa60897a4f334 | 53,068 |
def clientcompressionsupport(proto):
"""Returns a list of compression methods supported by the client.
Returns a list of the compression methods supported by the client
according to the protocol capabilities. If no such capability has
been announced, fallback to the default of zlib and uncompressed.
... | ac690e20a17bbf535c9f41ee5846cb408cfbda4c | 53,069 |
def preprocess_pbt_df(df: pd.DataFrame, x_tag: str) -> pd.DataFrame:
"""Align the x_tag index used in plot_progress before plotting.
Args:
----
df (pd.DataFrame): Dataframe of the progress.csv file
x_tag (str): Desired tag in df to use as index of plot
Return:
------
df (pd... | d669383bba44983e949cbfdf5103ae3f1f97de42 | 53,070 |
from typing import List
import math
def standard_deviation(xs: List[float]) -> float:
"""The standard deviation is the square root of the variance"""
return math.sqrt(variance(xs)) | 9287f9ba4bec6bf5ffc28ebeb7e2aae1265b5d22 | 53,071 |
from ...data import COCODetection
def ssd_512_resnet50_v1_coco(pretrained=False, pretrained_base=True, **kwargs):
"""SSD architecture with ResNet v1 50 layers for COCO.
Parameters
----------
pretrained : bool or str
Boolean value controls whether to load the default pretrained weights for mod... | 7740e92aabe168be02266a2ca421e9cb79480557 | 53,072 |
def filter_otsu_threshold(np_img):
"""
Compute Otsu threshold on image as a NumPy array and return binary image based on pixels above threshold.
Args:
np_img: Image as a NumPy array.
output_type: Type of array to return (bool, float, or uint8).
Returns:
NumPy array (bool, float, ... | 9402a2bf695bb19cb4b0e1524364b9e34c44e9e9 | 53,073 |
def get_default_build_presets(default_run_config):
""" Read the build presets from the config """
return dict(default_run_config[ue4_constants.UNREAL_BUILD_SETTINGS_STRUCTURE]) | 1f2c2364dc14ce146ffba4f55ec327fed946e21a | 53,074 |
from math import floor
from typing import Tuple
from typing import Union
def conv_output_shape(
h_w: Tuple[int, int],
kernel_size: Union[int, Tuple[int, int]] = 1,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
) -> Tuple[int, int]:
"""
Calculates the output shape (height and width)... | ea757a413a3b38ea024b85dd6987beda8a3b9aeb | 53,076 |
from ._vector import Vector
def reflection_matrix(v):
"""Generate reflection matrix that represents reflection of points \
in a mirror plane defined by normal `Vector` `v`.
Parameters
----------
v : :class:`~sknano.core.math.Vector`
Returns
-------
:class:`~numpy:numpy.ndarray`
... | 91498c87a02fc58f7138651f667c9837ea54fc52 | 53,077 |
from typing import Optional
async def normalize_postcode_middleware(request, handler):
"""
If there is a postcode in the url it validates and normalizes it.
"""
postcode: Optional[str] = request.match_info.get('postcode', None)
if postcode is None or postcode == "random":
return await han... | 552c02f05be604a16be93d6b7c8c09f30a3302a0 | 53,078 |
def normalize_v(x):
"""
normalize a vector
:param x: input
:return: normalized vector
"""
mn = np.min(x)
mx = np.max(x)
for i in range(len(x)):
x[i] = (x[i] - mn) / mx - mn
return x | 7487216a9b56b29823c759f85a13aeb04c3ec960 | 53,079 |
def checkout(request, template_name="order/checkout.html"):
"""
Displays the customer info form for checkout
"""
loginform = LoginForm()
addressform = AddressForm()
if request.method == 'POST':
addressform = AddressForm(request.user, request.POST)
if addressform.is_valid():
... | da6abc6712acc72a8c03b81f37987d610f249150 | 53,080 |
def extract(s):
"""Return a list of each individual emoji in the string."""
return EMOJI.findall(s) | 6c4d0681c5a69fa2d00cc0fabe17a36ba7bd6ba9 | 53,081 |
def fixture_grid_result():
"""
Load the expected grdproject grid result.
"""
return xr.DataArray(
data=[
[427.85062, 431.05698, 452.34268],
[563.92957, 540.5212, 501.46896],
[740.80133, 679.1116, 554.78534],
[794.233, 829.4449, 764.12225],
... | 9f3c9d43cd1eef64d6683940498142d18aab52bb | 53,082 |
from typing import List
def all_scalars(fields: List[Field]) -> bool:
"""Checks if all fields are scalars."""
boolean = True
for f in fields:
boolean = boolean and f.is_boson
return boolean | 4dcadd50a7db4efa4a0e99a399f2fc1b54c2d5c2 | 53,083 |
def sum_all(grid_values):
"""
Calculates the sum of all grid values.
Results in scores from
:param grid_values: values of grid
:return: metrics score
"""
score = sum(grid_values)
return score | a7741961c240cb8edbff050566b7f9341a203af7 | 53,084 |
def _ec_helper_native():
"""Loads the ec_helper_native library.
Returns:
The ctypes ec_helper_native library.
"""
cdll.LoadLibrary(find_library('crypto'))
cdll.LoadLibrary(find_library('ssl'))
return cdll.LoadLibrary('./ec_helper_native.so') | 5fc6ddf931e061bf4a3f11669b8112016266f7d0 | 53,085 |
import re
def formulate_condition(analyses_pattern: str, analyses_list: str) -> str:
""" formulate WHERE SQL condition from analyses_pattern """
condition = ''
if analyses_pattern:
a_range = re.match(r'(\d+)\.\.(\d+)', analyses_pattern)
if a_range:
condition = " WHERE analysis_... | 3504c233a4168295ceb39307898f2aa81ef95f29 | 53,086 |
def lossNet(input_shape=(256, 256, 3),
styleLayers=["block1_conv2", "block2_conv2", "block3_conv3", "block4_conv3"],
contentLayers=["block3_conv3"]):
"""Creates the network to compute the style loss.
This network outputs a dictionary with outputs values for style and content, based on a ... | badb39bfe3454ad395dac9aae5a512c680d45f8d | 53,087 |
def _path(from_object, to_object):
"""
Calculates the 'path' of objects starting from 'from_object'
to 'to_object', along with the index of the first common
ancestor in the tree.
Returns (index, list) tuple.
"""
if from_object._root != to_object._root:
raise ValueError('No connecti... | 0ccfe54d36832b8dce3c55168f02abb3c79261ef | 53,088 |
from rfpipe import search, state, metadata
import time
def initialize_worker():
""" Function called to initialize python on workers
"""
t0 = time.Time.now().mjd
search.set_wisdom(512)
st = state.State(inmeta=metadata.mock_metadata(t0, t0+0.001, 27, 16, 16*32, 4, 5e4, datasource='sim'))
return... | 3fc07d291e6b44b9fdc5ddb537c81cf2b59687b7 | 53,089 |
def parse_filter(components, kind):
"""
Parese any filter
"""
filters = []
pieces = kind.split('_')
parenthsis =0
is_in_quotes = False
start_tracking = False
# loop the the data
for ii, s in enumerate(components):
#print('where - ' + s)
# find the end of the columns
(p, is_in_quotes) = track_parenth... | d3c262de47254864e3f5688154c50e5742050377 | 53,090 |
def getATT(file):
"""use Ohlbergs code to read in attitude data from file
and creates a dictionary for easy insertation
into a postgresdatabase.
"""
ap = attitude.AttitudeParser([file])
# sorting attitudes
tbl = ap.table
keys = tbl.keys()
if not keys:
return
keys.sort()
... | f79344830f28803209a8c98c8787ba1340e08527 | 53,091 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.