content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def convert_init_dict(init_dict):
"""Convert an init_dict from an old version of pyleecan to the current one"""
# V 1.0.4 => 1.1.0: New definition for LamSlotMag + SlotMag
if init_dict["__class__"] == "MachineSIPMSM" and "magnet" not in init_dict["rotor"]:
print("Old machine version detected, Updat... | d73718c77b1909b150e254aa1ef4eed7fbf33c35 | 55,000 |
def plot_2D_comparison(
field_direction,
diagnostic,
observable,
experimental_data,
simulation_data,
fig_width=7.5,
fig_height_per_row=1.5,
title_height=1.0,
common_colorbar: bool = True,
experiment_sets_colorbar: bool = False,
diverging: bool = False,
**kwargs,
):
""... | 99132938fd8b962e8fb0b7d17347aad2a1a7d8d2 | 55,001 |
def f_solpos(times, latitude, longitude):
"""
Calculate solar position for lat/long at times.
:param times: Python :class:`datetime.datetime` object.
:type times: list
:param latitude: latitude [degrees]
:type latitude: float
:param longitude: longitude [degrees]
:type longitude: float
... | 0499a8aec045ba27f20de2d0768f95b1c1f3a1bd | 55,002 |
def linear_comb_layer(weights, vectors, size=None, name=None, layer_attr=None):
"""
A layer for weighted sum of vectors takes two inputs.
- Input: size of weights is M
size of vectors is M*N
- Output: a vector of size=N
.. math::
z(i) = \sum_{j=0}^{M-1} x(j) y(i+Nj)
... | e03344d23e3a68344dca214940ca9b489effec50 | 55,003 |
import json
def get_default_conf(device_type: str) -> json.Data:
"""Get default configuration associated with provided device type"""
if device_type == 'orchestrator':
return hat.manager.devices.orchestrator.default_conf
if device_type == 'monitor':
return hat.manager.devices.monitor.def... | 47172d9631a797cafc70c696fa6361822c4bf761 | 55,004 |
import logging
import os
def execute_ccm_remotely(remote_options, ccm_args):
"""
Execute CCM operation(s) remotely
:return A tuple defining the execution of the command
* output - The output of the execution if the output was not displayed
* exit_status - The exit status ... | 8022a63a77c61dfcc7b189ab1350cec7ec0c9077 | 55,005 |
def plot_cartmap(lvc_healpix_file, levels=[0.5, 0.9], angsize=3., tile_ra=None, tile_dec=None, targ_ra=None, targ_dec=None):
"""Plot the GW map with the DESI footprint in a Cartesian projection.
Parameters
----------
lvc_healpix_file : str
Relative or absolute path to LIGO/Virgo HEALPix ang... | ede5746a3fca4d7d341f1cfe957bda3af65ac7c9 | 55,006 |
import requests
def get_task_status(task_id):
"""Queries the task status of an iControl LX task"""
task_url = 'http://localhost:8100/mgmt/shared/iapp/package-management-tasks/' + task_id
response = requests.get(task_url, auth=('admin', ''))
if response.status_code < 400:
response_json = respon... | de1f59e39b56a90390359df44a714fd5e37e445e | 55,007 |
import fnmatch
def check_result_ignore(result, ignore_ranges):
"""
Determines if the result has to be ignored.
Any result will be ignored if its origin matches any bear names and its
SourceRange overlaps with the ignore range.
Note that everything after a space in the origin will be cut away, so... | d7ae057d76c77b6c8e2582e9e929a6aa7ce9f4dc | 55,008 |
def stitchCollections(m_Dbase, c_suffix):
"""This function will take a mongodatabase and cycle through the collections.
Each collection will be parsed for its first and last record id.
Then twitter search api will be queried to find any tweets missed between the last
and the first.
"""
#create a... | 4c47f44e8c400cce6d691e4d3ce661bac942b0e3 | 55,009 |
def ckan_collect_packages(url, memcached_client=None, cache=0):
"""
collect CKAN packages
:param url: the CKAN url, e.g., .../api/3/action/package_list
:param memcached_client: pymemcache client for caching http response
:param cache: cache results
:return: a list of CKAN packages
"""
p... | 3f1ff946a63ce7f775b28ea7381155e5634235d1 | 55,010 |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary) raw structured data to process
Returns:
Dictionary. Structured data with the following schema:
{
"uid": {
"id": integer,
"name... | b97d35b93ea08d6adcd69e0fa84c9b59be8d4419 | 55,011 |
def datasource(name='Alpha', location='https://asource.foo/', id_prefix='A'):
"""
Create a DataSource object
"""
return DataSource(id=name, name=name, id_prefix=id_prefix, location=location) | bf1a3a49bdb70d28f4864961ef8cd4c4483f788d | 55,012 |
def all_protoform(d, var_names, Q = "wiekszosc", desc = 'most', classtoprint="class"):
"""
Funkcja wyznaczajoca stopnie prawdy dla wszystkich
podumowań lingwistycznych (prostych i zlozonych)
"""
pp = [var_names[0] + "_low", var_names[0] + "_medium", var_names[0] + "_high"]
qq = [var_na... | 3611b8a37c2856bccf2fc9402caac2466801d783 | 55,013 |
def get_indexes_async(**kwargs):
"""Asynchronously retrieves the application indexes and their states.
Identical to get_indexes() except returns an asynchronous object. Call
get_result() on the return value to block on the call and get the results.
"""
def extra_hook(indexes):
return [(_index_converter(i... | f9c7f9af1263139c0efe69f2b0d0ff8e9d1b9339 | 55,014 |
def compute_stats(a, cfg, lgth_corr_function):
"""
Computes and returns basic positional, length, coverage and GC info.
This function MUST be run in order to obtain cov, GC & length statistics!
(i.e. mean and SD over all contigs and genes)
Args:
a:
lgth_corr_function:
Returns:
... | cbf274800b2ac32eab4c7b5d3ad756c303ec46a1 | 55,015 |
def unf_deadoilviscosity_Beggs_cP(gamma_oil, t_K):
"""
Correlation for dead oil viscosity
ref1 Beggs, H.D. and Robinson, J.R. “Estimating the Viscosity of Crude Oil Systems.”
Journal of Petroleum Technology. Vol. 27, No. 9 (1975)
return dead oil viscosity,cP
gamma_oil, specific oil de... | 02271d26bfe72d2fc70ec02d17723010c9135e25 | 55,016 |
async def get_active_user(current_user: User = Security(get_current_user)):
"""Проверка активный юзер или нет"""
if not current_user.is_active:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user | 36ece075acfcc77516223add7d80aa847f3828d0 | 55,017 |
def get_tag_type(tagtype, pairs):
"""
Given a list of (word,tag) pairs, return a list of words which are tagged as nouns/verbs/etc
The tagtype could be 'NN', 'JJ', 'VB', etc
"""
return [w for (w, tag) in pairs if tag.startswith(tagtype)] | 383515704788e0fd6bcfd7d7f21e77be18397163 | 55,018 |
from typing import AnyStr
import re
def regexp(pattern: AnyStr, string: AnyStr) -> bool:
"""SQLite REGEXP implementation."""
if pattern is None or string is None:
return False
try:
return re.search(pattern, string) is not None
except re.error:
return False | ed5cc3eca07e153cfd5610e237afb62a0cadcb0a | 55,019 |
import traceback
import sys
def wrapped_extract_events(*args, **kwargs):
"""`extract_events` function wrapped in a try/except that keeps full
traceback information. Use if calling from multiprocessing module."""
try:
extract_events(*args, **kwargs)
except Exception:
traceback.print_exc... | 6e4d1698e4199916745d493dfb3629ff282c3d9d | 55,020 |
def sortable_header(parser, token):
"""
Parses a tag that's supposed to be in this format: {% sortable_header field title %}
"""
bits = [b.strip('"\'') for b in token.split_contents()]
if len(bits) < 2:
raise TemplateSyntaxError, "anchor tag takes at least 1 argument"
try:
ti... | ffe8c76541b638248a0a33069a432da1ae461dae | 55,021 |
import sys
import os
import json
import requests
def main(argv=None) -> int:
"""Main entry point for the CLI
Args:
argv: The command line arguments. These default to None and if so, the function will fall back to use the
command line arguments without the application name used to invoke... | 3db6c71117f64ff01a05b185684c0afade87a41e | 55,022 |
def Sqrt(a):
"""
Square root op.
"""
return np.sqrt(a), | 58bad6cfa02f0da5fe6546a581d58fc201b0194c | 55,023 |
def SinC(x, c):
"""A unified sine and inverse sine function for different signs of curvatures.
This function is used in k-Stereographic model, a unification of constant curvature manifolds.
Please refer to https://arxiv.org/abs/2007.07698 for more details.
First-order expansion is used in order to cal... | b029973a3b71b3de0daababbd8439cac3616c969 | 55,024 |
from functools import reduce
def create_slug(title):
"""
Generates an alias url for the article by its title.
"""
only_latin = translit_text(title.replace(' ', '-'))
is_allowed = lambda ch: ch.isalpha() or ch.isdigit() or ch == '-'
if not only_latin:
return ''
leave_allowed = redu... | 889ae39fbc5a72457dbd4701b44da28928b97238 | 55,025 |
def plotOrbitsMissed(allObjects,
orbits,
testOrbits=None,
columnMapping=Config.COLUMN_MAPPING):
"""
Plots orbits that have been missed (but were findable) in semi-major axis, inclination
and eccentrity space.
Parameters
--------... | 4f8d546a4281e2cf6f6ce7dbea0cfdb7f6aa4b09 | 55,026 |
def sample_parameters(samplers):
"""Samples params [key, val, ...] list based on the samplers."""
params = []
for param, sampler in samplers.items():
val = sampler_types[sampler.TYPE](sampler)
is_composite = is_composite_sampler(sampler.TYPE)
params.extend(val if is_composite else [p... | a6fed6cfd9eef57c9b96e6ced90d7770d69ea051 | 55,027 |
def findCmd(keyword):
# type: (str) -> Optional[Type['Cmd']]
""" Find and return a Cmd subclass for a given keyword.
"""
command_list = getCmdList()
matching_cmds = [cmd for cmd in command_list if keyword in cmd.keywords]
if len(matching_cmds) == 0:
return None
if len(matching_cmds) ... | 7d75f71975745bf6b7a1d3f54c50e125c12e8eea | 55,028 |
def asin(var):
"""
Returns variable representing asin applied to the input variable var
"""
result = Var(np.arcsin(var.val))
result.parents[var] = var.children[result] = 1 / np.sqrt(1 - var.val ** 2)
return result | 8d62c6ff9b7342cae40ecbad870f68616acd1619 | 55,029 |
def accounts_list(svc_rec=None, hostfilter=None, compromised=False):
"""Returns a list of accounts for a service or host
Accepts: Service id, hostfilter, compromised
Returns: [ service_id, ipv4, ipv6, hostname, account info... ]
"""
query = (db.t_accounts.f_services_id==db.t_services.id)
if svc_rec is no... | ad3a2a0191c5a0a5117bdadb2ede37b5c727c440 | 55,030 |
def read_data_from(file_: str) -> list:
"""Read boarding pass data from file."""
with open(file_, "r") as f:
return f.read().splitlines() | 7315c4c284cdd2e9e1b66776c26eccabe13acdb4 | 55,031 |
def warm_t(t, t_ust, Tn):
"""
Уравнение ПП при нагревании, когда температура
двигателя равна температуре окружающей среды.
t - время
t_ust - установившееся значение температуры
Tn - постоянная времени нагревания
"""
return t_ust * (1 - np.exp(-1 * t / Tn)) | 212c3bd5fd60c8a41568ca936e690ee4a078774b | 55,032 |
def make_gaussian_image(shape, table):
"""Make an image of Gaussian sources.
The input table must contain parameters for one Gaussian
source per row with column names matching the
`~photutils.GaussianPSF` parameter names.
Parameters
----------
shape : tuple of int
Output image shap... | b39655c6c5480f9e0af775052cd854a05d7f2dcb | 55,033 |
import torch
def Pocm_Matmul(x, gammas, betas):
"""
:param x: an output feature map of a CNN layer [*, ch, T, F]
:param gamma: [*, ch, ch]
:param beta: [*, ch]
:return: gamma * x + beta
"""
x = x.transpose(-1, -3) # [*, F, T, ch]
gammas = gammas.unsqueeze(-3) # [*, 1, ch, ch]
po... | 325e0318254b008b84c505d1de4c7f5ab61d7099 | 55,034 |
def exportSDFJoint(jointdict, indentation):
"""
Args:
jointdict:
indentation:
Returns:
"""
tagger = xmlTagger(initial=indentation)
# use sdf joint names instead URDF
sdftype = jointmapping[jointdict['type']]
tagger.descend('joint', {'name': jointdict['name'], 'type': sdf... | 148380b0be110ac295ea6bc603116f03d97ddf96 | 55,035 |
def convert_heads_to_classy_model(
state_dict, out_prefix, num_fc_layers, use_bn_head=False, use_bias_head_fc=True
):
"""
Convert an MLP head of 2 kinds:
Type 1: FC only
Type 2: FC -> RELU -> FC
"""
logger.info("Converting head...")
converted_dict = {"block3-2": {"default_head": {}}}
... | 0b8a542dc3395d1983b65599141f45d273d908a9 | 55,036 |
def sigmoid(Z):
"""Applies sigmoid function to an array/value
Arguments
---------
Z: float/int/array_like
Original Value
Returns
-------
A: same shape as input
Value after applying sigmoid function
"""
# return 1/(1+np.power(np.e, -Z))
return 1/(1 + np.exp(-Z) ) | 34d1aa9358397c069619f4fe868222a1bc37b98b | 55,037 |
import urllib
def _unicode_urlencode(params):
"""
A unicode aware version of urllib.urlencode.
Borrowed from pyfacebook :: http://github.com/sciyoshi/pyfacebook/
"""
if isinstance(params, dict):
params = params.items()
return urllib.urlencode([(k, isinstance(v, unicode) and v.encode('u... | 537d969e55aba91390d75f1fb4e59a82b08f8de2 | 55,038 |
import ast
def get_auxiliary_name(node: ast.AST, aux_symbol_id: str) -> str:
"""
Generates a name for auxiliary variables.
:param node: the ast node that originates the auxiliary symbol
:param aux_symbol_id: the id name of the auxiliary symbol
:return: the unique name to the symbol.
"""
r... | d67fc8d70553265a7d5345e97877e07caf36e19a | 55,039 |
import typing
async def patch(
url: URLTypes,
*,
data: RequestData = None,
files: RequestFiles = None,
json: typing.Any = None,
params: QueryParamTypes = None,
headers: HeaderTypes = None,
cookies: CookieTypes = None,
stream: bool = False,
auth: AuthTypes = None,
allow_redi... | 9c65d3b8deba8496dc4412210ebb7191d4157aa1 | 55,040 |
def blob(x):
"""Given an Nx3 matrix of blob positions and size,
create N img_size x img_size images, each with a blob drawn on
them given by the value in each row of x
One row of x = [x,y,radius]."""
y = np.zeros((x.shape[0], img_size, img_size))
for i, particle in enumerate(x):
r... | 8371c49c0e0ad50988925e12575ade4845abf40d | 55,041 |
import zipfile
def fetch_uci_words():
""" Returns UCI vocabulary text. """
data_path = check_fetch_uci_words()
all_data = []
with zipfile.ZipFile(data_path, "r") as f:
for name in f.namelist():
if ".txt" not in name:
# Skip README
continue
... | 8c09098aeb950eceac42ce416a60e3a411265d42 | 55,042 |
def search_for_pod_name(details: dict, operator_id: str):
"""Get operator pod name.
Args:
details (dict): workflow manifest from pipeline runtime
operator_id (str): operator id
Returns:
dict: id and status of pod
"""
try:
if 'nodes' in details['status']:
... | cc5bc532a1875145452fbe71cca54f840257c90d | 55,043 |
def edit_dict_from_dict(
old_embed_dict: dict,
update_embed_dict: dict,
add_attributes: bool = True,
inner_fields: bool = False,
):
"""
Edits the changed attributes of an embed dictionary using another
dictionary
"""
if inner_fields:
if "fields" in old_embed_dict:
... | 12d1314b2dfdbf01809fabf729a1f48732bd57e6 | 55,044 |
def humanize_demarche_names(name: str) -> str:
"""
>>> humanize_demarche_names('argent')
"ARGENT: Crédit immobilier, Impôts, Consommation, Livret A, Assurance, "
"Surendettement…"
:param machine_names:
:return: list of human names and description
"""
demarches = settings.DEMARCHE... | 16b2d163adebc7f1dd6dfb50089c3bf831765a6b | 55,045 |
def get_product_yield(product: reaction_pb2.ProductCompound,
as_measurement: bool = False):
"""Returns the value of a product's yield if it is defined. If multiple
measurements of type YIELD exist, only the first is returned.
Args:
product: ProductCompound message.
as_... | 01c6c7243d8ccd9b2ec25672ed06727d0324ef5f | 55,046 |
def test_for_short_cell(raw_python_source: str) -> bool:
"""
Returns True if the text "# Long" is in the first line of
`raw_python_source`. False otherwise.
"""
first_element = raw_python_source.split("\n")[0]
if "#" in first_element and "short" in first_element.lower():
return True
... | f76c19750afda8851dfe328851662fa3276f3529 | 55,047 |
def cofold_barriers(_name, species,
s_opts=['|', 'pylands_spatch.py'],
s_ener=None,
s_maxn=59000000,
barriers='barriers',
minh=0.001,
maxn=50,
k0=1.0,
temp=37.0... | e3a1441957596bb45d3caef10cfae87835b77840 | 55,048 |
import os
def DrawBoxPlots_multi_eval(data_dir, data_name, save_name='Box_plot'):
"""
The function to draw the statitstics of the data using a Box plot
:param data_dir: The mother directory to call
:param data_name: The data set name
"""
# Predefine name of mse_mat
mse_mat_name = 'mse_mat.... | 9ba9414b8e684f8b316f59c5d5db6bcd8eeed2c1 | 55,049 |
def generate_paths(G, od_pairs, k=10, weight=None):
"""
Generates k shortest paths from origin 'o' to destination 'd'
for all origin destination pairs
Args:
G - graph of network
od_pairs - list of origin-destination pairs
k - max number of paths returned
weight - par... | c7f4ca676bbb068b74cc1ece13b71429ac567a5a | 55,050 |
import math
def area_circle(radius):
"""
Calculate the area of a circle
>> area_circle(20)
1256.6370614359173
"""
return math.pi * radius * radius | 978dc9252c48fd288d348316604910712c5b8b2b | 55,051 |
def sum_missing_formula(base):
"""Define a biomass reaction whose components lack a formula."""
met_a = cobra.Metabolite("lipid_c", "H744")
met_b = cobra.Metabolite("protein_c", "H119")
met_c = cobra.Metabolite("rna_c")
met_d = cobra.Metabolite("dna_c")
met_e = cobra.Metabolite("ash_c", None)
... | a4167ef86be03cf449bb3f4fe902bac5a1f57412 | 55,052 |
import logging
def configure_logger(name, log_file):
"""
Configure a named global logger.
(see also [1])
:param name: Name of global logger.
:param log_file: Path to log file for FileHandler.
[1]: http://stackoverflow.com/a/7622029
"""
logger = logging.getLogger(name) # name is None ... | 359e6168e37dfd3ebe7e723c483c46eccaaa5b60 | 55,053 |
import inspect
def _get_warnings(warnings_instance):
"""
returns a list of the returned value of
all private functions of warnings_instance
"""
# all functions of this class
warning_functions = inspect.getmembers(
warnings_instance.__class__, predicate=inspect.isfunction
)
# al... | 3152273a7eb2c78b612b1e35506163bce6a42f24 | 55,054 |
def make_embed_b(m, msg_type="banned"):
"""Create an embed for bans."""
title = "%s User __%s__ %s" % (msg_icon(msg_type), m.name, msg_type)
embed = discord.Embed(title=title,
description="",
color=msg_color(msg_type))
return embed.set_footer(text="ID... | ca6fa9845fcad617be3f42b9f2042066f99747a2 | 55,055 |
def _get_year_month(file_name):
"""
Extract year and month from file name and concatenate to year-month string
"""
ym = file_name.replace('.csv', '')
year, ita_month = ym.split("_")[-2:]
month = [k for k, v in ITA_MONTHS.items() if v == ita_month][0]
return year + "-" + month | f698529dd72d2455808aa4966f8e50a1c0b04f4a | 55,056 |
import collections
def windowed_slope_sum_function(fitered_bp_vector, window_length):
"""see the mathematical description of this algorithm in:
An Open-source Algorithm to Detect Onset of Arterial Blood Pressure Pulses
"""
# this could be replaced with simple pointer manipulation, but this is easi... | 730431f665589cecf32655e6f4d14a0f9cbb2290 | 55,057 |
import re
def color(string: str) -> Color:
""" Parse color string like a "#007fff"
>>> color('#007fff')
(0, 127, 255)
>>> color('#000000')
(0, 0, 0)
>>> color('#fFfFfF')
(255, 255, 255)
>>> color('#1234567')
Traceback (most recent call last):
...
TypeError: "#1234567" i... | 9fa59b23cc5b1375d549eab046a0ba1a350a00a2 | 55,058 |
def api_upload(request):
"""POST - Upload API."""
upload = Upload(request)
resp, code = upload.upload_api()
return make_api_response(resp, code) | baade870b77f6aa401b0fd6d3d654f90f3b4735e | 55,059 |
def filter_count_df(count_df, min_read_mean, outdir_path):
"""
:return: filtered count dataframe
"""
check_sparse = stats.Density(count_df)
filtering = MeanFiltering(count_df, threshold=min_read_mean)
count_df = filtering.filtered_df
filtered_stats = stats.Descriptive(count_df, outdir_path)
... | 0130046812c8746e8cd75d031ecf77edb46860bc | 55,060 |
import codecs
def load_dataset(dataset_file):
"""
Loads a dataset file
:param dataset_file: the file path
:return: a list of dataset instances, (x, y, relation)
"""
with codecs.open(dataset_file, 'r', 'utf-8') as f_in:
dataset = [tuple(line.strip().split('\t')) for line in f_in]
... | 3f19a367b27c6dd123498e8cf73dee5d54454a2b | 55,061 |
def get_vm_identifiers(wireserver_connection):
"""Get the ContainerId and InstanceId from the Wireserver."""
wireserver_connection.request(
'GET',
'/machine?comp=goalstate',
headers={'x-ms-version': '2012-11-30'}
)
resp = wireserver_connection.getresponse()
wireserver_goal... | e1629b4e87c106e71437273ef742cb43f5e275f8 | 55,062 |
import string
import random
def generate_random_name(seed_name: str):
"""
Function responsible for generating random names using Markov chain
Args:
seed_name (str): name of the seed file contained in name_generator directory
Returns:
random_name (str): string generated procedurally ba... | 1f3ada644a9bea27a3b908a6fb857f43b3d2349b | 55,063 |
def check_updates(version: str, user: str, repository: str) -> (bool, str):
"""
Checks if a newer version exists for a program at the given version, on github
:param version: current program version
:param user: the user who owns the repository
:param repository: the repository where the code is hos... | f4c669b7050e66b877371480ca01786535c72a68 | 55,064 |
def readxmol(ifile,elem,xyz):
"""
read xmol file
"""
lines = ifile.readlines()
nat = int(lines[0])
title = lines[1]
for l in lines[2:]:
type, x, y, z = l.split()
xyz.append([float(x),float(y),float(z)])
elem.append(type)
# xyz.append(l)
return nat | 62be4300fcf30f3b2dee329418352230639ef7a1 | 55,065 |
import subprocess
import sys
def run_command(cmd, dry_run=False, verbose=False):
"""
Run a command directly
"""
if dry_run or verbose:
print_stderr("[cmd] " + " ".join(cmd))
if dry_run:
return
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PI... | a19ad3b361d3f4a06edaf17e762c1d2bf07fa370 | 55,066 |
def euro_implied_vol_76(option_type, fs, x, t, r, cp):
"""Implied volatility calculator for European commodity options.
Args:
option_type (str): Type of the option. "p" for put and "c" for call options.
fs (float): Price of underlying asset.
x (float): Strike price.
t (float): T... | fc1ab11f41d08cacedde466d9e1775488b48eb11 | 55,067 |
def delete(book_id):
"""
Delete A Blogpost
"""
post = BookModel.get_one_book(book_id)
if not post:
return custom_response({'error': 'post not found'}, 404)
data = book_schema.dump(post).data
post.delete()
return custom_response({'message': 'deleted'}, 204) | 427d2ca79c4155572d7916f426278fafed9085f3 | 55,068 |
def points_in_polygon(outline,qx,qy):
"""
Get points that are within the given polygon. Returns the index list.
poly: list of (x,y) points that define the polygon
qx,qy: list of the x and y coordinats of the points
that are to be checked.
===RETURNS===
ix,iy: indices of x and y for ... | f644786a0448d937368681ed83185a96de014c0c | 55,069 |
from datetime import datetime
def json_dump_default(value):
""" Default JSON serializer. """
if isinstance(value, Decimal):
return float(value)
elif isinstance(value, (date, datetime)):
return value.isoformat()
elif hasattr(value, 'serialize') and callable(value.serialize):
r... | ae11f85db2d1e4e1954e70015cddec4dc9425822 | 55,070 |
from typing import Optional
import os
def check_params_service_bus_push(
store_param: Optional[str],
):
"""
Loads and checks the App Configuration settings for the Service Bus Binding variant.
Also sets the directory in the container to store the messages to, to the topic name, if not set already.... | 47a72e90e64956680728716800389f497ab66ca2 | 55,071 |
import torch
def get_model(args):
"""Build the model."""
print_rank_0('building GPT2 model ...')
model = GPT2Model(num_layers=args.num_layers,
vocab_size=args.vocab_size,
hidden_size=args.hidden_size,
num_attention_heads=args.num_attention... | 477a5c2523633fda1e5c991c1fea3b37629f191e | 55,072 |
def dicts_to_matched_tuples(dict1, dict2):
""" Converts pair of dicts to pair of matched tuples so that their elements can be compared.
Throws an exception if the set of keys in both dicts are not the same.
"""
try:
return [(dict1[k], dict2[k]) for k in set(dict1.keys() + dict2.keys())]
... | 496dba21da3766db49934761fd8ec142aed0f1ab | 55,073 |
def transcriptsKnownSpliceSites(refs_1exon_by_chr, refs_exons_by_chr, start_ends_by_gene, trec, genome_dict, nPolyA):
"""
:param refs_1exon_by_chr: dict of single exon references (chr -> IntervalTree)
:param refs_exons_by_chr: dict of multi exon references (chr -> IntervalTree)
:param trec: id record (g... | 56f602eae34c7b756fa7a0eeb9899000cee50744 | 55,074 |
def translate(rna):
"""
Translate RNA sequence into Protein sequence
Starting from the first nucleotides
"""
codons = read_codons(join(MODULE_DIR, "codon.txt"))
protein = ""
for i in range(0, len(rna), 3):
base = rna[i : i + 3]
if len(base) != 3 or codons[base] == "Stop":
... | 466dc7b0edc60900110429b860fe8d0d2f2bae07 | 55,075 |
def int_parameter(level, maxval):
"""Scale 'val' between 0 and maxval.
:param level: Level of the operation that will be between [0, 'PARAMETER_MAX'].
:type level: int
:param maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX.
:type maxval: int
:return... | f69595c999e8fa0b2d4b3854e43bd88ccb646e81 | 55,076 |
def key(profile):
"""Get the last name in lower case"""
return profile["name"].split(' ')[-1].lower() | dd778619f601213f3cbae3504277fe6ee21ba3cd | 55,077 |
from typing import Tuple
from typing import List
def _rewrite_jaxpr(jaxpr: core.Jaxpr,
has_input_token: bool,
has_output_token: bool) -> Tuple[core.Jaxpr, bool]:
"""Rewrite a Jaxpr to thread the token, if needed."""
assert has_input_token or not has_output_token
if not has... | 7a4a4fbe1441c961df622e364bd7824a05730881 | 55,078 |
def create(data, row_ticks, col_ticks, ax=None,
cbar_kw={}, cbarlabel="", cbarpos=(0.95, 0.9), row_label=None, row_label_pos=(-0.083, 1.02), col_label=None, col_label_pos=None, reverse=True, **kwargs):
"""
Create a heatmap from a numpy array and two lists of labels.
Follows: https://matplotlib.o... | 8b74e54601f51fb8f9821aa47ae81160395533df | 55,079 |
def LF_consistency_in_report(x):
"""
The words 'clear', 'no', 'normal', 'free', 'midline' in
findings section of the report
"""
findings = x.text[x.text.find("FINDINGS:") :]
findings = findings[: findings.find("IMPRESSION:")]
sents = findings.split(".")
normalcy_words = ["clear", "no", ... | 423843f214e3805820a230cf7a82e666e42b3bbc | 55,080 |
def split_by_hw(mdl: Model, x_attack: np.array, y_attack: np.array):
"""
Split traces in two classes.
Class A: the hamming weight label is below 4, and class B: above 4.
Returns traces for classes A and B
"""
hws = np.argmax(y_attack, axis=1)
l4 = predict(mdl, x_attack[np.where(hws < 4)], ... | 1a60b8f5c7ebaa205e0c946263855361b888b7a0 | 55,081 |
def remove_anthrophony(ale, time_delta, freq_delta, cutoffs=(1000, 11000)):
"""
Removes anthrophony from a PSD spectrogram
Parameters
----------
ale: numpy float64 array
a 3d array (channels, frequency bands, time steps)
representing the spectrogram of a wave signal (with ale ap... | e247449e89f91fe9f78134110493e73287870469 | 55,082 |
def collect_data(data_file):
"""
Sets up Data Object using data
:return: Pandas DataFrame created from data_file data
"""
dat = Table.read(data_file, format='fits')
df_bytes = dat.to_pandas() # Convert to pandas dataframe
df = pd.DataFrame() # Init empty dataframe for converted types... | bc3d2b2157e520338530a98471da57daa595ddfe | 55,083 |
def objectToTypes(object,world=None):
"""Returns a string defining the type of the given Python Klamp't object.
If multiple types could be associated with it, then it returns a list of all
possible valid types."""
if hasattr(object,'type'):
return object.type
if isinstance(object,ContactPoin... | 2c76334ecd1351df521aed4ec717f803dbea3e86 | 55,084 |
def setup_file_explorer(qtbot):
"""Set up FileExplorerTest."""
widget = FileExplorerTest()
qtbot.addWidget(widget)
return widget | 76637bfd13513091c0d66c0780b8cb32ab9122ba | 55,085 |
def solution(a: list, k: int) -> list:
"""
>>> solution([], 0)
[]
>>> solution([], 100)
[]
>>> solution([1] * 100, 100) == [1] * 100
True
>>> solution([1, 3], 1)
[3, 1]
>>> solution([1, 3], 2)
[1, 3]
:param a: An array of integers
:param k: Number of rotations
:r... | f1ff42df2ec1181357732ea7910b8994099dfa65 | 55,086 |
def compute_radius(X, max_x, max_y):
"""Compute the radius of a chip coordinate.
"""
center = [max_x / 2.0, max_y / 2.0]
return np.sqrt((X.ix[:,0] - center[0])**2 + (X.ix[:,1] - center[1])**2) | aa4771f5e0b4bfc4393f6cb00a5cd497d28026da | 55,087 |
def tx_or_block_from_bytes(data: bytes) -> BaseTransaction:
""" Creates the correct tx subclass from a sequence of bytes
"""
# version field takes up the first 2 bytes
version = int.from_bytes(data[0:2], 'big')
try:
tx_version = TxVersion(version)
cls = tx_version.get_cls()
r... | b863dcfc5980d3cda0c910175900d3fc4141b30c | 55,088 |
from typing import Tuple
def new_tile(
*, # Enforce the use of keywords, so that parameter order doesn't matter.
walkable: int,
transparent: int,
dark: Tuple[int, Tuple[int, int, int], Tuple[int, int, int]],
light: Tuple[int, Tuple[int, int, int], Tuple[int, int, int]],
) -> np.ndarray:
"""He... | 1f138058d8f005674ec766ab35e2de4c473c8739 | 55,089 |
def density(x):
"""
Standard set of parameters for density remap.
Parameters
----------
x : numpy.ndarray
Returns
-------
numpy.ndarray
"""
return _clip_cast(amplitude_to_density(x)) | cc1f3a37010ceefb74106c7f7ec5e6bfffd44661 | 55,090 |
def real_time(buoy, dataset="txt"):
"""Get realtime data from the NDBC. There are six different data sources
to pull from:
- data_spec: Raw Spectral Wave Data
- ocean: Oceanographic Data
- spec: Spectral Wave Summary Data
- supl: Supplemental Measurements Data
- swdir: Spectral Wave Data (a... | 81cf144bf4e13f89624fdb0ccdd3523e80d1d5fb | 55,091 |
def GetBPM_FromMIDI(midiFileName):
""" returns list of [bpm, pos] floats """
mid = MidiFile(midiFileName, clip = True)
bpms = [[round(tempo2bpm(msg.tempo), 2), msg.time] for msg in mid.tracks[0] if msg.type == "set_tempo"]
# this one replicates the extra bpm added in the box files
... | 10b115ccdbee6308ff1c542007ce049436dbaf17 | 55,092 |
from typing import Any
def make_execution_engine(
engine: Any = None, conf: Any = None, **kwargs: Any
) -> ExecutionEngine:
"""Create :class:`~fugue.execution.execution_engine.ExecutionEngine`
with specified ``engine``
:param engine: it can be empty string or null (use the default execution
eng... | ddba690eb05b84c51756432f9cc969f5397fe876 | 55,093 |
def get_nice_levels(variable, center_on_zero=False, nlevel=11, min_percentile=0.1, max_percentile=99.9):
"""
Create levels for contour plots
Parameters
----------
variable : xarray.DataArray or np.ndarray
the values for which the levels should be created
nlevel : int
nu... | f1636c41872573ea3172257526053f1bb31d2ca3 | 55,094 |
from typing import Tuple
from typing import Optional
def parse_proxy(
proxy: bytes, default_scheme: bytes = b"http", default_port: int = 1080
) -> Tuple[bytes, bytes, int, Optional[ProxyCredentials]]:
"""
Parse a proxy connection string.
Given a HTTP proxy URL, breaks it down into components and chec... | 3ea90f90b4eb1d16adfc57babe28035d67610213 | 55,095 |
import logging
def _get_logger():
"""
Generate a logger with a stream handler.
"""
logger = logging.getLogger('epc')
hndlr = logging.StreamHandler()
hndlr.setLevel(logging.INFO)
hndlr.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
logger.addHandler(hndlr)
return logger | 8c96d2395e1d907a389346e5e3b94f41c0b62fe3 | 55,096 |
def split_matrix_to_train_and_test(mat, true_labels, train_indexes, test_indexes,
print_stat=False):
"""
"""
train_mat = mat[train_indexes,:]
true_train_labels = true_labels[train_indexes]
test_mat = mat[test_indexes,:]
true_test_labels = true_labels[test_indexes]
if print_stat:
... | 67cceeaba8733a8692c38775527ea93b4aae2d33 | 55,097 |
def move_item(
client: EWSClient, item_id, target_folder_path, target_mailbox=None, is_public=None
):
"""
Moves an item within the same mailbox
:param client: EWS Client
:param item_id: item id
:param target_folder_path: target folder path
:param (Optional) target_mailbox: mailbox contai... | 8b214d331559d6223b7c15bc257f42cffff0fd78 | 55,098 |
def assign_dose_on_position_with_constraint(
source_genome: np.ndarray,
destination_genome: list,
index: int,
interval_in_indices: int,
last_index_with_non_zero_dose: int = None,
):
"""
Przypisuje niezerową dawkę w dozwolonym czasie z uwagi na obostrzenia czasowe.
Do użytku z:
* nor... | 779420afc9489099ee2648fcb360d4d50a6a2f9b | 55,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.