content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_approval_distance(election_1: ApprovalElection, election_2: ApprovalElection,
distance_id: str = None) -> float or (float, list):
""" Return: distance between approval elections, (if applicable) optimal matching """
inner_distance, main_distance = extract_distance_id(distance_... | 776640b12ac799248a35b49f6751c5fa27303ab8 | 3,636,341 |
from pathlib import Path
def get_base_folder():
"""Return the base folder of ProfileQC."""
return Path(__file__).parent | e0a49bbbe018333dd107466a5178c5579327edc1 | 3,636,342 |
def u16le_list_to_byte_list(data):
"""! @brief Convert a halfword array into a byte array"""
byteData = []
for h in data:
byteData.extend([h & 0xff, (h >> 8) & 0xff])
return byteData | 6e4dd1fe69a24f135d0dfa38d5d0ba109ad24b9e | 3,636,343 |
def process_IBM_strings(string):
"""
Format all the IBM string in the same way, creating a single string of lowercase characters
:param string:
:return:
"""
parts = string.split()
result = str(parts[0].lower())
for part in parts[1:]:
result += " " + str(part.lower())
return r... | 72216b014a18c72d4dec9ec54f24f13de0d46583 | 3,636,344 |
def get_sample_size(number_of_clones, fold_difference, error_envelope_x_vals, error_envelope_y_vals, number_of_error_bars):
"""
This returns the number of cells in a sample that produce the an
error bar of max_error_bar for a given number_of_clones in the
parent population.
This is the inverse ... | 392009961cd3797bdaab460cfee5808c8a0c4969 | 3,636,345 |
def get_r2(y,yhat):
""" Calcualte the coef. of determination (R^2) """
ybar = np.mean(y)
return 1 - (np.sum((y-yhat)**2))/(np.sum((y-ybar)**2)) | e632765696b92eb76032681be790b1e25979a6d3 | 3,636,346 |
from typing import Dict
from typing import Any
def get_context() -> Dict[str, Any]:
"""
Retrieve the current Server Context.
Returns:
- Dict[str, Any]: the current context
"""
ctx = _context.get() # type: ignore
if ctx is not None:
assert isinstance(ctx, dict)
return ... | dad971abb645fa7c194db5cd9ce45e7c38166f31 | 3,636,347 |
import pandas as pd
def kiinteisto_alueiksi(kiinteisto):
"""
kiinteist: kiinteisto/property register
An artificial property / constituency division will be made for the regionalization of postal codes.
A brute-force distribution is used, where the relative number of residential properties i... | fee095ccc4cb82b735c2d314a96ab20bf0790a9a | 3,636,348 |
def G1DListCrossoverSinglePoint(genome, **args):
"""
The crossover of G1DList, Single Point
.. warning:: You can't use this crossover method for lists with just one element.
"""
sister = None
brother = None
gMom = args["mom"]
gDad = args["dad"]
if len(gMom) == 1:
utils.raise... | 1cf77e96fb648a6d8664d157425f47f789248739 | 3,636,349 |
def optional_observation_map(env, inner_obs):
"""
If the env implements the `observation` function (i.e. if one of the
wrappers is an ObservationWrapper), call that `observation` transformation
on the observation produced by the inner environment
"""
if hasattr(env, 'observation'):
retur... | b1b57e74e498e520df80a310f95d1c79799a517d | 3,636,350 |
def RunMetadataLabels(run_metadata):
"""Returns all labels in run_metadata."""
labels = []
for dev_stats in run_metadata.step_stats.dev_stats:
for node_stats in dev_stats.node_stats:
labels.append(node_stats.timeline_label)
return labels | 277745263c75c4c6037f8b7a26b9421699bec3a5 | 3,636,351 |
def is_entity_extractor_present(interpreter: Interpreter) -> bool:
"""Checks whether entity extractor is present."""
extractors = get_entity_extractors(interpreter)
return extractors != [] | 0227bdd1f6d7a5040bff853de62075f040337f23 | 3,636,353 |
def get_workflow(name, namespace):
"""Get a workflow."""
api_group = "argoproj.io"
api_version = "v1alpha1"
co_name = "workflows"
co_client = _get_k8s_custom_objects_client()
return co_client.get_namespaced_custom_object(api_group, api_version,
n... | cea58e40b9279a3134766374cd8f5e9eb2e1b4f8 | 3,636,354 |
import torch
def step(x, b):
"""
The step function for ideal quantization function in test stage.
"""
y = torch.zeros_like(x)
mask = torch.gt(x - b, 0.0)
y[mask] = 1.0
return y | bac5dd8cbaa4da41219f03a85e086dd3bdd1e554 | 3,636,355 |
from typing import Union
def encode_intended_validator(
validator_address: Union[Address, str],
primitive: bytes = None,
*,
hexstr: str = None,
text: str = None) -> SignableMessage:
"""
Encode a message using the "intended validator" approach (ie~ version 0)
defined... | bb86535c06204bb0b2bf25a7e595cddb3bc83603 | 3,636,356 |
def _ip_desc_from_proto(proto):
"""
Convert protobuf to an IP descriptor.
Args:
proto (protos.keyval_pb2.IPDesc): protobuf of an IP descriptor
Returns:
desc (magma.mobilityd.IPDesc): IP descriptor from :proto:
"""
ip = ip_address(proto.ip.address)
ip_block_addr = ip_address(... | b24fd6636cc30c707b8f1539cf16515946370b39 | 3,636,357 |
import inspect
def inheritdocstrings(cls):
"""A class decorator for inheriting method docstrings.
>>> class A(object):
... class_attr = True
... def method(self):
... '''Method docstring.'''
>>> @inheritdocstrings
... class B(A):
... def method(self):
... pass
... | 4af61e59dc7b3ba53243107bacd0738c2bc2e2a9 | 3,636,358 |
def get_totd_text():
"""
Get the text for the Top of the Day post.
:return: The body for the post.
"""
sections = []
# Most Upvoted Posts
top_submissions = sorted([submission for submission in get_reddit().subreddit("all").top("day", limit=5)], key=lambda x: x.score, reverse=True)
items... | 2077da29ea28f2563485eed14dc277b1646e27cd | 3,636,359 |
import pickle
import time
def dump_ensure_space(file, value, fun_err=None):
"""
Only dump value if space enough in disk.
If is not enough space, then it retry until have space
Note: this method is less efficient and slowly than simple dump
>>> with open("test_ensure_space.tmp", "wb") as f:
..... | 622ed232a3e747e55004ab28225418fc3c6570ef | 3,636,361 |
import torch
def store_images(input, predicts, target, dataset='promise12'):
"""
store the test or valid image in tensorboardX images container
:param input: NxCxHxW
:param predicts: NxCxHxW
:param target: NxHxW
:return:
"""
N = input.shape[0]
grid_image_list = []
for i... | 14d853cdf98bea358f9170162d6a5ea27c1f88a8 | 3,636,362 |
from typing import Optional
from typing import List
from typing import Dict
import csv
def snmptable(ipaddress: str, oid: str, community: str = 'public',
port: OneOf[str, int] = 161, timeout: int = 3,
sortkey: Optional[str] = None
) -> OneOf[List[Dict[str, str]], Dict[str, Di... | bb3e749d17c5038a2ed8857fab2ac226ee175c3f | 3,636,363 |
def GetFile(message=None, title=None, directory=None, fileName=None, allowsMultipleSelection=False, fileTypes=None):
"""Ask the user to select a file.
Some of these arguments are not supported:
title, directory, fileName, allowsMultipleSelection and fileTypes are here for compatibility reasons.
"""
default_f... | 88b4d01b66542f4414f24cf123ba3a92e98befe2 | 3,636,364 |
def lda_recommend(context_list):
""" With multiprocessing using Dask"""
print("Recommending")
topn = 500
sleep(0.2)
vec_bow = id2word_dictionary.doc2bow(context_list)
# This line takes a LONG time: it has to map to each of the 300 topics
vec_ldamallet = ldamallet[vec_bow]
# Convert the q... | 7435de1aee9e43596b5467036b00b706502aa254 | 3,636,365 |
def grids_skf_lr(data_x, data_y, grid_params, weight_classes=None, scv_folds=5):
"""
:param data_x:
:param data_y:
:param grid_params:
:param weight_classes:
:param scv_folds:
:return:
"""
if weight_classes is None:
weight_classes = {0: 1, 1: 1}
m_log = LogisticRegressio... | 7cf79512b3663e8b01ea96219d746c3a6a2fd4b0 | 3,636,366 |
def zeros(rows, cols, fortran=True):
"""Return the zero matrix with the given shape."""
order = "F" if fortran else "C"
cparr = cp.zeros(shape=(rows, cols), dtype=cp.complex128, order=order)
return CuPyDense._raw_cupy_constructor(cparr) | 90e2a7bb7bfdaa5b8b242d1aa543b93dab5d1a60 | 3,636,367 |
def compute_trapezoidal_approx(bm, t0, y0, dt, sqrt_dt, dt1_div_dt=10, dt1_min=0.01):
"""Estimate int_{t0}^{t0+dt} int_{t0}^{s} dW(u) ds with trapezoidal rule.
Slower compared to using the Gaussian with analytically derived mean and standard deviation, but ensures
true determinism, since this rids the rand... | 719090d6427c0f37dd8aab4f8bfb60dfdfb8c362 | 3,636,368 |
def vavrycuk_psencik_hti(vp1, vs1, p1, d1, e1, y1,
vp2, vs2, p2, d2, e2, y2,
phi, theta1):
"""
Reflectivity for arbitrarily oriented HTI media, using the formulation
derived by Vavrycuk and Psencik [1998], "PP-wave reflection coefficients
in weakly aniso... | a48ff4cb76341e199c3d386b40d58bd6a2031e01 | 3,636,369 |
def concatenate_time_series(time_series_seq):
"""Concatenates a sequence of time-series objects in time.
The input can be any iterable of time-series objects; metadata, sampling
rates and other attributes are kept from the last one in the sequence.
This one requires that all the time-series in the lis... | ce2f51e0a14bf2b6de16ce366041522556b0793f | 3,636,370 |
def deeplink_url_patterns(
url_base_pattern=r'^init/%s/$',
login_init_func=login_init,
):
"""
Returns new deeplink URLs based on 'links' from settings.SAML2IDP_REMOTES.
Parameters:
- url_base_pattern - Specify this if you need non-standard deeplink URLs.
NOTE: This will probably clos... | bda7c28e0ce46e4b7f236562a3f8da09a5977c0b | 3,636,371 |
def read_words():
"""
Returns an array of all words in words.txt
"""
lines = read_file('resources/words.txt')
words = []
for line in lines:
words.extend(line.split(' '))
return words | 96768fc1cd593b29caefaa1489f0478832b10886 | 3,636,372 |
def lynotename(midinote):
"""Find the LilyPond/Pently name of a MIDI note number.
For example, given 60 (which means middle C), return "c'".
"""
octave, notewithin = midinote // 12, midinote % 12
notename = notenames[notewithin]
if octave < 4:
return notename + "," * (4 - octave)
else:
... | 7eda2d4b5075759413e25626b70c5cd56c183447 | 3,636,373 |
from datetime import datetime
def json_serial(obj):
"""
Fallback serializier for json. This serializes datetime objects to iso
format.
:param obj: an object to serialize.
:returns: a serialized string.
"""
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoform... | 1b4c23d84e89cb77d111160a5328046c62fb4227 | 3,636,374 |
def html_mail(sender='me@mail.com', recipients=['them@mail.com'],
html_content='<p>Hi</p>', subject='Hello!',
mailserver='localhost'):
""" html_mail takes input html, sender, recipents and
emails it in a mime type that will show as text or html on
the recipients mail reader.
... | 83257bb4718063153587bbc685c650595b911554 | 3,636,376 |
def gotu(input_path: str) -> biom.Table:
"""Generate a gOTU table based on sequence alignments.
"""
profile = workflow(input_path, None)['none']
return profile_to_biom(profile) | 59e119392da0c6179ed84b6de7da517ccad5107d | 3,636,377 |
def read_data_megset(beamf_type):
""" Read and prepare data for plotting."""
if beamf_type == 'lcmv':
settings = config.lcmv_settings
settings_columns = ['reg', 'sensor_type', 'pick_ori', 'inversion',
'weight_norm', 'normalize_fwd', 'use_noise_cov',
... | 6d2f3cd765779276e6730c56865e374058849662 | 3,636,378 |
import getpass
import logging
def collect_user_name():
""" Returns the username as provided by the OS. Returns a constant if it
fails.
"""
try:
uname = getpass.getuser()
except Exception as e:
logger = logging.getLogger(__name__)
msg = "Failed to collect the user name: erro... | 40e18be0ea51659346c7f761bafa8af194937e14 | 3,636,379 |
def get_dataframe() -> pd.DataFrame():
"""Dummy DataFrame"""
data = [
{"quantity": 1, "price": 2},
{"quantity": 3, "price": 5},
{"quantity": 4, "price": 8},
]
return pd.DataFrame(data) | 3089e1a33f5f9b4df847db51271f7c3f936b351c | 3,636,380 |
def get_node_mirna(mirna_name, taxid, psi_mi_to_sql_object):
"""
This function sets up a node dict and returns it. If the node is already in the SQLite database it fetches that node from the db, so it won't be inserted multiple times.
"""
# Testing if the node is already in the database
node_dict =... | daab8ab8f43c1e9395dbbc2640ecb78b39f6867f | 3,636,381 |
def generate_output_file_name(input_file_name):
"""
Generates an output file name from input file name.
:type input_file_name: str
"""
assert isinstance(input_file_name, str)
output_file_name = input_file_name + ".gen.ipynb"
return output_file_name | e638d676048e062711ca1a09d88a12d76fb9239d | 3,636,383 |
def prefixed_field_map(name: str) -> Mapper:
"""
Arguments
---------
name : str
Name of the property.
Returns
-------
Mapper
Field map.
See Also
--------
field_map
"""
return field_map(
name,
api_to_python=add_signed_prefix_as_needed,
... | 48be07a06f4f5b70d4e7b389a1896c94a181e62c | 3,636,384 |
def is_water(residue):
"""
Parameters
----------
residue : a residue from a protein structure object made with PDBParser().
Returns
-------
Boolean
True if residue is water, False otherwise.
"""
residue_id = residue.get_id()
hetfield = residue_id[0]
return hetfield[0... | 2d547da9dc8def26a2e9581a240efa5d513aab64 | 3,636,386 |
def gelu(input_tensor):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
input_tensor: float Tensor to perform activation.
Returns:
`input_tensor` with the GELU activation applied.
"""
cdf = 0.5 * (1.0 + tf.erf(input_tens... | c4f8fead676ef7e4b036f8c94467402445044330 | 3,636,387 |
def index():
""" Route for signing the policy document or REST headers. """
request_payload = request.get_json()
if request_payload.get('headers'):
response_data = sign_headers(request_payload['headers'])
else:
credential = [c for c in request_payload['conditions'] if 'x-amz-credential'... | f914761d9b58a290f20b537c4df9ce8272dd7b6c | 3,636,388 |
from sphinx.jinja2glue import BuiltinTemplateLoader
def create_template_bridge(self):
"""Return the template bridge configured."""
if self.config.template_bridge:
templates = self.app.import_object(
self.config.template_bridge, 'template_bridge setting')()
else:
templates = Bui... | 64a7a1dd70035b2507a0b8b9b3af8c91ccadb0ec | 3,636,389 |
def make_answer(rdtype, answers=None, additionals=None, authorities=None):
"""For mocking an answer. We make an answer without any message (what would
normally come over the network, to be parsed. We instead make a blank
object for the sake of test complexity, and later attach the appropriate\
rrsets to... | 877f0acefd3082189c91885ff98ac056799c1e1b | 3,636,390 |
def single_ray_belief_propagation(
S,
ray_voxel_indices,
ray_to_occupancy_accumulated_pon,
ray_to_occupancy_messages_pon,
output_size
):
"""Run the sum product belief propagation for a single ray
Arguments
---------
S: tensor (M,) dtype=float32
The depth probability distribut... | 5c9c7acbf13e0f0f8adef3f5bebb5b14b81a2b8e | 3,636,392 |
def cse_postprocess(cse_output):
""" Perform CSE Postprocessing
:arg: output from SymPy CSE with tuple format: (list of ordered pairs that
contain substituted symbols and their replaced expressions, reduced SymPy expression)
:return: output from SymPy CSE where postprocessing... | ec7211d366550de93fa2839232820fd2fb3746f7 | 3,636,393 |
def lap(j, s, alpha):
""" Laplace coefficient """
def int_func(x):
return np.cos(j*x)/(1. - (2.*alpha*np.cos(x)) + alpha**2.)**s
integral = integrate.quad(int_func, 0., 2.*np.pi)[0]
return 1./np.pi*integral | 013cb3611e7f678aac560896b80930e19e3d0579 | 3,636,394 |
import google
def calendar_add():
"""Adds a calendar to the database according to the infos in POST data.\
Also creates the calendar in google calendar service if no google_calendar_id is present in POST data.
"""
calendar_name = request.form["calendar_name"]
std_email = request.form["std_ema... | 558c8b3580109773d4012b1048f33f56aca376ee | 3,636,395 |
def proportional_allocation_by_location_and_activity(df, sectorcolumn):
"""
Creates a proportional allocation within each aggregated sector within a location
:param df:
:param sectorcolumn:
:return:
"""
# tmp replace NoneTypes with empty cells
df = replace_NoneType_with_empty_cells(df)
... | fb9376411d0b448a99563f41091f43863b694b8f | 3,636,396 |
def prepare_target():
"""
Creates a example target face
:return: list of RFTargetVertex
"""
# size = 2
# target = [
# rfsm.RFTargetVertex(0, 0, 0, -size, -size),
# rfsm.RFTargetVertex(0, 1, 1, -size, size),
# rfsm.RFTargetVertex(1, 1, 1, size, size),
# rfsm.RFTarg... | 27fa9a8bd2b5c7943b5882d2bf76312ea7e418bb | 3,636,398 |
import json
def data_fixture():
"""Fixture data."""
data = json.loads(load_fixture("data.json", "evil_genius_labs"))
return {item["name"]: item for item in data} | 9eebcabb4f1517d66f76be8956f74ce438aab8f1 | 3,636,399 |
def vectorize(sentence, idf_weight, vocab, convey='idf'):
"""
idf_weight: {word: weight}
vocab: {word: index}
"""
vec = np.zeros(len(vocab), dtype=np.float32)
for word in sentence:
if word not in vocab:
continue
if convey == 'idf':
vec[vocab[word]] += idf_... | a245bfb82be2193dabb219fd24fd8cf035d3a1a9 | 3,636,400 |
import re
async def director_v2_service_mock(
aioresponses_mocker: AioResponsesMock,
) -> AioResponsesMock:
"""mocks responses of director-v2"""
# computations
create_computation_pattern = re.compile(
r"^http://[a-z\-_]*director-v2:[0-9]+/v2/computations$"
)
get_computation_pattern =... | 2b09e504fc3d1520be220dc81fc403ef63b1e797 | 3,636,401 |
def test_validation_unset_type_hints():
"""Test that unset type hints are handled correctly (and treated as Any)."""
@my_registry.optimizers("test_optimizer.v2")
def test_optimizer_v2(rate, steps: int = 10) -> None:
return None
config = {"test": {"@optimizers": "test_optimizer.v2", "rate": 0.1... | d4816ee06e05fb2332f35a60f336dd1bf75eb2bd | 3,636,402 |
def get_online_featurestore_connector(featurestore=None):
"""
Gets a JDBC connector for the online feature store
Args:
:featurestore: the feature store name
Returns:
a DTO object of the JDBC connector for the online feature store
"""
if featurestore is None:
featurestore ... | ada51764b823c0959571ea928d6bddc6b2dbee7b | 3,636,403 |
def create_multipoint_geometry(u, v, osr_spref):
"""
wrapper; creates multipoint geometry in given projection
Parameters
----------
u : list of numbers
input coordinates ("Rechtswert")
v : list of numbers
input coordinates ("Hochwert")
osr_spref : OGRSpatialReference
... | cea52b749e7e60a9fea192fd5ff288bced7be388 | 3,636,404 |
def open_tif_image(input_path):
# type: (function) -> np.array
"""Function to open tif images.
Parameters:
input_path (string) = path where the image file is located;
return
np.array of the tif image"""
# get the image_path.
image_path = input_path
# rea... | ab834b5b2ab983cab3f79dd1fc1acfe1394df50b | 3,636,405 |
import requests
def get_icd(url: str) -> requests.Response:
"""Get an ICD API endpoint."""
return requests.get(url, headers=get_icd_api_headers()) | 2a7ce491004cd0b69e7d988e8aaca56b4130b261 | 3,636,406 |
def evaluate(words,labels_pred, labels):
"""
labels_pred, labels, words: are sent-level list
eg: words --> [[i love shanghai],[i love u],[i do not know]]
words,pred, right: is a sequence, is label index or word index.
Evaluates performance on test set
"""
# true_tags = ['PER', 'LOC', 'ORG', 'PERSON', 'person', ... | d1c98e5c7cbe94fdc5bd502e6ea33673cead1a7d | 3,636,407 |
import string
def getApproximateArialStringWidth(st: str) -> float:
"""Calculate rough width of a word in a variable width font.
By https://stackoverflow.com/users/234270/speedplane
Args:
st (str): The string you need a width for
Returns:
float: The rough width in picas
To make ... | d37cc49e4ffd347ddace5de1d420bc8c3c37b615 | 3,636,408 |
def prepare_text(input_string):
"""Converts an input string into a list containing strings.
Parameters
----------
input_string : string
String to convert to a list of string.
Returns
-------
out_list : list
List containing the input string.
"""
# ... | ddf060728127380ef3ec689f7ee8104b9c12ebea | 3,636,409 |
def TDF_Tool_TagList(*args):
"""
* Returns the entry of <aLabel> as list of integers in <aTagList>.
:param aLabel:
:type aLabel: TDF_Label &
:param aTagList:
:type aTagList: TColStd_ListOfInteger &
:rtype: void
* Returns the entry expressed by <anEntry> as list of integers in <aTagList>.... | 92cc1ffb20dad5bd0d49c818cae899fdbc9fafc0 | 3,636,410 |
import re
def img(header, body=None):
"""Alternate to Markdown's image tag. See
http://octopress.org/docs/plugins/image-tag/ for usage."""
attrs = re.match(__img_re, header).groupdict()
m = re.match(__img_re_title, attrs['title'])
if m:
attrs['title'] = m.groupdict()['title']
att... | 8745d00f576bb24d94dbeff465be9f2d82388034 | 3,636,411 |
def conexao_bd():
"""
Função que se conecta a um banco de dados MySQL
"""
# Pedido de senha caso o acesso ao BD necessite
# caso contrario so dar ENTER
conexao = sql.connect(
host='localhost',
user='root',
password=senha
)
cursor = conexao.cursor()
return c... | 2db6a7aaef02639d506c4ec393851abc3c9f278d | 3,636,412 |
def fill_bin_content(ax, sens, energy_bin, gb, tb):
"""
Parameters
--------
Returns
--------
"""
for i in range(0,gb):
for j in range(0,tb):
theta2 = 0.005+0.005/2+((0.05-0.005)/tb)*j
gammaness = 0.1/2+(1/gb)*i
text = ax.text(theta2, gammaness, "... | aa2121697429d330da3ec18f08f36248e3f57152 | 3,636,413 |
def blackbody1d(temperature, radius, distance=10*u.pc,
lambda_min=2000, lambda_max=10000, dlambda=1):
"""
One dimensional blackbody spectrum.
Parameters
----------
temperature : float or `~astropy.units.Quantity`
Blackbody temperature.
If not a Quantity, it is assume... | 80bef199c3a11d19f60204913cb44dbf6f40b47f | 3,636,414 |
def expm1_op_tensor(x):
"""
See :func:`oneflow.expm1`
"""
return Expm1()(x) | dc844e014a806ae507052618eccd889a9a0b589d | 3,636,415 |
def transect_rotate(adcp_transect,rotation,xy_line=None):
"""
Calculates all possible distances between a list of ADCPData objects (twice...ineffcient)
Inputs:
adcp_obs = list ADCPData objects, shape [n]
Returns:
centers = list of centorids of ensemble locations of input ADCPData object... | bc493c8cf93cbfdbe614ed39f973ee735fbe3294 | 3,636,418 |
def F(x, t, *args, **kwds):
"""
F(x) = ddx
"""
return -kwds.get('μ', 1) * x / np.sum(x**2)**(3/2) | bbe4afa78dab5aafa27c26a09f31fa8bcc37d989 | 3,636,419 |
from typing import List
from typing import Dict
def get_capacity_potential_per_country(countries: List[str], is_onshore: float, filters: Dict,
power_density: float, processes: int = None):
"""
Return capacity potentials (GW) in a series of countries.
Parameters
... | f68285a349c147c773d8053afa377e674b0e585a | 3,636,420 |
import ast
from typing import Set
def all_statements(tree: ast.AST) -> Set[ast.stmt]:
"""
Return the set of all ast.stmt nodes in a tree.
"""
return {node for node in ast.walk(tree) if isinstance(node, ast.stmt)} | 9f7cc367f01ec3bb90869879e79eb9cbe6636820 | 3,636,421 |
def calc_predicted_points_for_pos(
pos, gw_range, team_model, player_model, season, tag, session
):
"""
Calculate points predictions for all players in a given position and
put into the DB
"""
predictions = {}
df_player = None
if pos != "GK": # don't calculate attacking points for keepe... | da30553d3cfe0bacd4198f3ae949466596d130a5 | 3,636,422 |
def image_preprocess2(img):
"""
image preprocess version 2
using: yellow threshold, white threshold, sobelX, sobelY, ROI
Parameters
----------
img: image (np.array())
Return
----------
the source points
"""
# set white and yellow threshold
... | 8581865049d7c0b9e33936e09bd034d4981f4d57 | 3,636,423 |
from typing import Dict
def get_all_feeds(cb: CbThreatHunterAPI, include_public=True) -> Dict:
"""Retrieve all feeds owned by the caller.
Provide include_public=true parameter to also include public community feeds.
"""
url = f"/threathunter/feedmgr/v2/orgs/{cb.credentials.org_key}/feeds"
params ... | e8cfea478a43919cf8753e0c1c9b8bb3228db736 | 3,636,424 |
from typing import Tuple
import ctypes
def spkltc(
targ: int, et: float, ref: str, abcorr: str, stobs: ndarray
) -> Tuple[ndarray, float, float]:
"""
Return the state (position and velocity) of a target body
relative to an observer, optionally corrected for light time,
expressed relative to an ine... | 46ad18c4fbf0c654771a7e6568831e6551f52e44 | 3,636,425 |
def remove_outlier_from_time_average(df, time=4, multiplier=3):
"""
Remove outliers when averaging transients before performing the fitting routines, used to improve the signal to noise ratio in low biomass systems.
The function sets a time window to average over, using upper and lower limits for outl... | c3c92e25514e02b6baa425672b31c8ec45b4f7fc | 3,636,426 |
import json
def parse_tb_file(path, module):
"""
Parse a translation block coverage file generated by S2E's
``TranslationBlockCoverage`` plugin.
"""
with open(path, 'r') as f:
try:
tb_coverage_data = json.load(f)
except Exception:
logger.warning('Failed to p... | dac9567c0c931ce9921eb5c766d00b3faa305887 | 3,636,427 |
def load(filename):
""" Load nifti2 single or pair from `filename`
Parameters
----------
filename : str
filename of image to be loaded
Returns
-------
img : Nifti2Image or Nifti2Pair
nifti2 single or pair image instance
Raises
------
ImageFileError: if `filenam... | e537f81883b27da4add0a7c16addc3c4f7f66e4b | 3,636,428 |
def create_softmax_loss(scores, target_values):
"""
:param scores: [batch_size, num_candidates] logit scores
:param target_values: [batch_size, num_candidates] vector of 0/1 target values.
:return: [batch_size] vector of losses (or single number of total loss).
"""
return tf.nn.softmax_cross_en... | a4b10b9f72f0e7e38474c5ec887ed3be215fc7fb | 3,636,430 |
def page_not_found(e):
"""
Catches 404 errors and render a 404 page stylized with the design of the web app.
Returns 404 static page.
"""
return render_template('404.html'), 404 | abf420f299f63a2ab3bccfca578f46be040590fd | 3,636,431 |
def effort_remaining_after_servicing_tier_2_leads():
"""
Real Name: Effort Remaining after Servicing Tier 2 Leads
Original Eqn: MAX(Effort Remaining after Servicing Existing Clients - Effort Devoted to Tier 2 Leads, 0)
Units: Hours/Month
Limits: (None, None)
Type: component
Subs: None
H... | 2ab3ee8968bb6e667bdf53cf4629ad0b1ecd732d | 3,636,432 |
def sliceThreshold(volume, block_size = 5):
"""
convert slice into binary using adaptive local ostu method
volume --- 3D volume
block_size --- int value
"""
if type(volume) != np.ndarray:
raise TypeError('the input must be numpy array!')
x, y, z = volume.shape
... | b66d4a46025ccc9fe6c15e61dcd57e060437f91e | 3,636,433 |
def rastrigin_d_dim(x: chex.Array) -> chex.Array:
"""
D-Dim. Rastrigin function. x_i ∈ [-5.12, 5.12]
f(x*)=0 - Minimum at x*=[0,...,0]
"""
A = 10
return A * x.shape[0] + jnp.sum(x ** 2 - A * jnp.cos(2 * jnp.pi * x)) | a7ac23b0a2b76afceb193629aad265186664c012 | 3,636,434 |
def fMaxConfEV(arr3_EvtM_bol, arr3_Evt, arr3_Conf):
""" Return highest confidence and its corresponding timing, given
arr3_EvtM_bol already masked to year of interest.
Something in this fuction or calling it is broken.
"""
print('\t\tStats (max conf)...', end='')
arr3_ConfM_bolY ... | 84a701fde4243c588de43582b3c7aa6c37dd434c | 3,636,435 |
def regex_validation_recursion(node: dict) -> (bool, str):
"""
Validates the regex inside a singular node of a Spcht Descriptor
:param dict node:
:return: True, msg or False, msg if any one key is wrong
:rtype: (bool, str)
"""
# * mapping settings
if 'map_setting' in node:
if '$... | 53f7e605c7bcd83cacba85e8aa0c5dc25e26d05c | 3,636,436 |
def build_probability_matrix(graph):
"""Get square matrix of shape (n, n), where n is number of nodes of the
given `graph`.
Parameters
----------
graph : :class:`~gensim.summarization.graph.Graph`
Given graph.
Returns
-------
numpy.ndarray, shape = [n, n]
Eigenvector of... | 44cf85a02d95df8d2d1a7580714e90cab0f087dc | 3,636,438 |
def yuanshanweir_transfer_loss_amount():
"""
Real Name: YuanShanWeir Transfer Loss Amount
Original Eqn: (Tranfer From YuanShanWeir To DaNanWPP+Transfer From YuanShanWeir To BanXinWPP)/(1-WPP Transfer Loss Rate)*WPP Transfer Loss Rate
Units: m3
Limits: (None, None)
Type: component
Subs: None
... | d5e028fb4450258f7fbdd708e7948f80eda04d2f | 3,636,439 |
def _gifti_to_array(gifti):
""" Converts tuple of `gifti` to numpy array
"""
return np.hstack([load_gifti(img).agg_data() for img in gifti]) | 363cf55a7509acf842b1d2dcbfb4ff45980e6692 | 3,636,441 |
from typing import List
from typing import Type
from typing import Union
def learn_naive_factorization(
data: np.ndarray,
distributions: List[Type[Leaf]],
domains: List[Union[list, tuple]],
scope: List[int],
learn_leaf_func: LearnLeafFunc,
**learn_leaf_kwargs
) -> Node:
"""
Learn a lea... | ef79c457d7c3a0630b8b8734bb892d1b1937e6ab | 3,636,442 |
def opt_IA_search_assist(fun, lbounds, ubounds, budget):
"""Efficient implementation of uniform random search between
`lbounds` and `ubounds`
"""
lbounds, ubounds = np.array(lbounds), np.array(ubounds)
dim, x_min, f_min = len(lbounds), None, None
opt_ia = optIA.OptIA(fun, lbounds, ubounds, ssa=... | b8d496ce403ae4882dc5a54947febdf1a7f298b4 | 3,636,443 |
def _fi18n(text):
"""Used to fake translations to ensure pygettext retrieves all the strings we want to translate.
Outside of the aforementioned use case, this is exceptionally useless,
since this just returns the given input string without
any modifications made.
"""
return text | e505b58f4ff1e64c07b4496f69bee8b6e86b5129 | 3,636,445 |
def is_required_version(version, specified_version):
"""Check to see if there's a hard requirement for version
number provided in the Pipfile.
"""
# Certain packages may be defined with multiple values.
if isinstance(specified_version, dict):
specified_version = specified_version.get("versio... | 6c8bfe0fe77f7a7d14e1ca2dd8005a8d82d0998c | 3,636,446 |
async def cmd_project_uninstall(ls: TextXLanguageServer, params) -> bool:
"""Command that uninstalls a textX language project.
Args:
params: project name
Returns:
True if textX project is uninstalled successfully, otherwise False
Raises:
None
"""
project_name = params[0... | cc460057b5ecaf0c97bd715fc98020c9cfbe960f | 3,636,447 |
def _check_load_mat(fname, uint16_codec):
"""Check if the mat struct contains 'EEG'."""
read_mat = _import_pymatreader_funcs('EEGLAB I/O')
eeg = read_mat(fname, uint16_codec=uint16_codec)
if 'ALLEEG' in eeg:
raise NotImplementedError(
'Loading an ALLEEG array is not supported. Please... | 384c0034230167ccf66c91aa048a0ef048d2e2bd | 3,636,448 |
def local_desired_velocity(env, veh_ids, fail=False):
"""
Encourage proximity to a desired velocity.
We only observe the velocity of the specified car.
If a collison or failure occurs, we return 0.
"""
vel = np.array(env.k.vehicle.get_speed(veh_ids))
num_vehicles = len(veh_ids)
if any... | 6df0ba2c2bc481ca7364aafc1cb05cfd197cfba2 | 3,636,449 |
def All(q, value):
"""
The All operator selects documents where the value of the field is an list
that contains all the specified elements.
"""
return Condition(q._path, to_refs(value), '$all') | b31db5f1c6cf26b339a5de6656db3318eff0c5f1 | 3,636,450 |
def key(i):
"""
Helper method to generate a meaningful key.
"""
return 'key{}'.format(i) | 04658ebead9581ff97406111c9b85e361ee49ff8 | 3,636,451 |
def svn_repos_fs_change_rev_prop3(*args):
"""
svn_repos_fs_change_rev_prop3(svn_repos_t repos, svn_revnum_t rev, char author, char name,
svn_string_t new_value, svn_boolean_t use_pre_revprop_change_hook,
svn_boolean_t use_post_revprop_change_hook,
svn_repos_authz_func_t authz_read_func,... | 7c49ab3ff13a3b078831a6ad0214849ae8ee5d8b | 3,636,452 |
def pretty_ct(ct):
"""
Pretty-print a contingency table
Parameters
----------
ct :
the contingency table
Returns
-------
pretty_table :
a fancier string representation of the table
"""
output = StringIO()
rich_ct(ct).to_csv(output)
output.seek(0)
try... | 547e3d36bb91f2ab2c53783099da04ef3bda1497 | 3,636,453 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.