content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def headloss_minor_elbow(FlowRate, Diam, KMinor):
"""Return the minor head loss (due to changes in geometry) in an elbow.
:param FlowRate: flow rate through pipe
:type FlowRate: u.m**3/u.s
:param Diam: diameter of pipe
:type Diam: u.m
:param KMinor: minor loss coefficient
:type KMinor: u.di... | f30d203c6ba46365474b3775cd28c45d8e147de4 | 60,955 |
def is_void(typ):
""" Check if the given type is void """
return isinstance(typ, BasicType) and typ.type_id == BasicType.VOID | d723cb4be0f35a1073ef94d150c20809a78b7edd | 60,956 |
def ensure_link_pathway_genome(kegg_genome_id: str, error_on_missing: bool = False) -> str:
"""Get the protein-pathway links for the given organism.
:raises: FileNotFoundError
"""
return ensure_path(
KEGG_PATHWAY_PREFIX,
'link_pathway',
url=f'{BASE}/link/pathway/{kegg_genome_id}... | 6e569cc8725c1aad3108613a02ec622097f52843 | 60,957 |
import codecs
def load_data_multilabel_new(vocabulary_word2index, vocabulary_word2index_label, valid_portion=0.05,
max_training_data=1000000,
traning_data_path='../train-zhihu4-only-title-all.txt', multi_label_flag=True,
use_seq2se... | 5a7e364961c3122fbbb85bbebc46549f01a2b217 | 60,958 |
def entropy(y0, y1, w0, w1):
"""
depracated
Impurity - entropy
:param y0: probabilistic output for samples in a set 0
:param y1: probabilistic output for samples in a set 1
:param w0: weight of the set 0 impurity
:param w1: weight of the set 1 impurity
:return: weighted impurity - entrop... | 0da9ae86309a5a6fffd71cd8553466877b58727c | 60,961 |
from typing import List
from typing import Tuple
def modified_mask_encodings(
encoding: List[int], tok,
markers: List[str]) -> Tuple[List[int], List[List[int]]]:
"""Modifies the text corresponding to encoding, to add spaces before discourse markers and finds the apt encodings
to use for the ma... | 695ad9b6bbd90e1cc3bb92ac50efb7c5cda74b29 | 60,962 |
def make_cube_bbox(bbox):
"""
:param bbox: (2,3) mi,mx
mx
(YZ) (XYZ)
6.........7
/. /|
/ . / |
/ . / |
3.........5 |
| . | |
| 2.....|...4
... | b6e34764439fcfc77198837c27f9fd7b607f5a67 | 60,963 |
def _calc_net_active_face_flux_at_node(grid, unit_flux_at_faces, out=None):
"""Calculate net face fluxes at nodes, ignore inactive faces.
Given a flux per unit width across each face in the grid, calculate the net
outflux (or influx, if negative) at each node (nodes without cells are
zero, or unchanged... | 31849c0fd6eb26bb6fb617b6aabd1ba8259c4c54 | 60,964 |
def convert_id_to_label(pred_ids_result, idx2label, batch_size):
"""
将id形式的结果转化为真实序列结果
:param pred_ids_result:
:param idx2label:
:return:
"""
result = []
for row in range(batch_size):
curr_seq = []
for ids in pred_ids_result[row][0]:
if ids == 0:
... | 4ee2373f411977290d3f1dca55f3a3e9253d1af4 | 60,965 |
import token
def hour_expr(k):
"""hour_expr <- num_hour OPTSPC HOUR"""
success, k1, h = num_hour(k)
if not success:
return False, k, None
success, k2, _ = optspc(k1)
success, k3, t = token('HOUR', k2)
if not success:
return False, k, None
return True, k3, h | 4e0e437c759e0b93dff7c87b06a5c175ce2ae322 | 60,966 |
def Cities():
""" Inserting the cities """
c = db.cursor()
with open('cities', 'r') as f:
cities = f.read()
# print('The cities are: {0}'.format(cities))
citylist = cities.split('\n')
if citylist[len(citylist)-1] == '':
del citylist[len(citylist)-1]
# print(citylist)
... | 96a18d6841f7d14ae9bb6cf05f753684369d0293 | 60,967 |
def list_networks():
""" zerotier-cli listnetworks command
Returns:
list: A list of networks (dict) that the device is connected to.
Raises:
CalledProcessError: If the cli call failed.
ValueError: If the json string could not be successfully parsed into a dict.
"""
return c... | 0fd12b30ba660da3cf95fa835d968cc5f0679400 | 60,968 |
def build_raw_spike_net():
"""Network that only collects raw spikes"""
NNEURONS = 64
Dout = 1
tap_matrix = np.zeros((NNEURONS, Dout))
net = graph.Network("net")
net.pool = net.create_pool("p1", tap_matrix)
HAL.map(net)
set_analog_config()
return net | eb1628c37d8d16556dab5abe9cf77817a4a673a8 | 60,970 |
def bin_to_int(bin_list, inverse=True):
""" Given arbitrary length list of binary values, calculate integer value.
Parameters
----------
bin_list : list of int
List of binary values for calculating integer value.
inverse : bool, optional
If true (default) caluclate integer from bin_... | 0ab74bafe4d045081732f10733704d7bbeb4a9ea | 60,971 |
def preprocessing_document_list(sentences):
"""Sentence preprocessing pipeline for 'gensim'. Tokenized text is returned."""
tokenized_data = []
for sentence in sentences:
tokenized_data.append(text_preprocessing(sentence))
return tokenized_data | 05dbdcfc1e3efd1e18049d6791fc296041beca35 | 60,972 |
import copy
import torch
def predict_one_sample(model, tokenizer, device, args, content):
"""
对单个样本进行预测
Args:
model: 模型
tokenizer: 分词器
device: 设备信息
args: 配置项信息
content: 新闻正文
Returns:
"""
# 对新闻正文进行预处理,并判断如果超长则进行截断
content_tokens = tokenizer.tokenize... | 2d62d2f85d9afd6e5bed63edd19987e62af7823b | 60,973 |
def generateMetaGraph (mazeMap, playerLocation, coins):
"""
Generate a metaGraph from mazeMap, containing all coins and the player.
This function is built on the shortestPaths lib.
"""
nodes = [playerLocation] + coins
metaGraph = {}
bestPaths = {}
i = len(nodes)-1
while i >= 0:
... | d0caefe7e174d8620c40e312c7e4ca5f205c1b4a | 60,976 |
def RegisteredStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | f53036c086455a410c13265a4bc942b9066725a0 | 60,977 |
def callattr(value, attr, args = None, kwargs = None):
"""
gets the attribute(s) from a value and calls its
:Example:
---------
>>> from pyg import *
>>> value = Dict(function = lambda a, b: a + b)
>>> assert callattr(value, 'function', kwargs = dict(a = 1, b = 2)) == 3
>>> assert calla... | d4c20f8872255b5a85dffcedaede331d259fbe61 | 60,978 |
def _partial_multi_dot(player_payoff_tensor, strategies, index_avoided):
"""Computes a generalized dot product avoiding one dimension.
This is used to directly get the expected return of a given action, given
other players' strategies, for the player indexed by index_avoided.
Note that the numpy.dot function i... | 87aa4bf817fef359594e5e763792e0f37eef1e95 | 60,979 |
def safe_path_exists(o):
"""Check if `o` is a path to an existing file.
``pathlib2.Path(o).is_file()`` and ``os.path.exists()`` raise various types of
exceptions if unable to convert `o` to a value suitable for use as a path. This
method aims to allow checking any object without raising exceptions.
... | 774926eeac2c397d8543f6a6c1318f566301f2ff | 60,980 |
import types
import typing
def column_factory(
*,
spec: types.Schema,
schemas: types.Schemas,
required: typing.Optional[bool] = None,
logical_name: str,
model_schema: types.Schema,
) -> typing.Tuple[typing.List[typing.Tuple[str, sqlalchemy.Column]], types.Schema]:
"""
Generate column b... | dc3b5a570143c677d0ee674b6dd46822e9d3a561 | 60,981 |
def encode(e, properties=True, lnk=True, indent=False):
"""
Serialize the EDS object *e* to an EDS-PENMAN string.
Args:
e: a EDS object
properties (bool): if `False`, suppress variable properties
lnk: if `False`, suppress surface alignments and strings
indent (bool, int): if... | 97bbc7c7700abdbaca8c49213f27b488718fb259 | 60,982 |
import torch
def tensor_cross_prod(u, M):
"""
:param u: N x 3
:param M: N x P x 3
:return:
"""
s0 = u[:, 1][:, np.newaxis] * M[..., 2] - u[:, 2][:, np.newaxis] * M[..., 1]
s1 = -u[:, 0][:, np.newaxis] * M[..., 2] + u[:, 2][:, np.newaxis] * M[..., 0]
s2 = u[:, 0][:, np.newaxis] * M[...... | f312ff3c2954a514b1486d20bfbc0a3cd5d8db48 | 60,983 |
import math
def get_visual_pool_size(
vis_arch,
num_frames,
crop_size,
):
"""
Compute the pooling size used in VisualClassifyHead.
args:
vis_arch (string): the architecture of the visual conv net.
num_frames (int): number of frames per clip.
crop_size (int): spatial siz... | cc924b3e2ce0a4dbb7d4ea241aeadd6863606172 | 60,985 |
def get_db_cluster_data(cluster_properties, source_region, result):
"""
Get data from cluster for result outputs.
"""
cluster_response = {}
logger.info("Source Region {}, Region {}".format(source_region, region))
if source_region == region:
cluster_response = aws.describe_db_clusters(DBC... | 6a570b190cfe488d0798769acd6d7f03da12adc3 | 60,986 |
def sample_config():
"""
sample config dict to test workflow utils
"""
sample_config = {
"QC": {
"picard_rmdup": "False",
"adapter": "AATGATACGGCGACCACCGAGATCTACACTCTTTCCCTACACGACGCTCTTCCGATCT",
"min_seq_length": "25",
"quality_trim": "True",
... | 42c959aa9478a8b1b188cc9cebda51cd99544e4b | 60,987 |
def compute_num_freqs(frequencies):
"""Computes the number of frequencies for each time point.
Parameters
----------
frequencies : list of np.ndarray
Frequency values
Returns
-------
num_freqs : np.ndarray
Number of frequencies at each time point.
"""
return np.arra... | 62a4460a6fda7cf23960b183e0c413f421dfaa7a | 60,988 |
def separate_substructures(tokenized_commands):
"""Returns a list of SVG substructures."""
# every moveTo command starts a new substructure
# an SVG substructure is a subpath that closes on itself
# such as the outter and the inner edge of the character `o`
substructures = []
curr = []
for c... | 0b2e57a7014525a9ab9b2d57b35afd05842fb2db | 60,989 |
def roty(t):
"""
Computes rotation matrix around the y-axis.
Parameters:
- - - - -
t : input angle in radians
"""
ct = np.cos(t)
st = np.sin(t)
R = np.asarray(
[[ct, 0, st],
[0, 1, -st],
[-st, 0, ct]])
... | 95bf899cb038c73e0e951ace8fbc323331808030 | 60,990 |
from datetime import datetime
def validateDate(date):
"""
Verifica se a data tem um dos seguintes formatos:\n
- %Y-%m-%d %H:%M:%S \n
- %Y/%m/%d %H:%M:%S \n
- %Y-%m-%d %H:%M \n
- %Y/%m/%d %H:%M \n
:param date: data
:return: boolean
"""
for fmt in ('%Y-%m-%d %H:%M:%S', '%Y/%m/%... | 9c8949497c0b207458a61994b5cf76578cd486bf | 60,991 |
def get_power_spectral_density_matrix(
complex_tensor: ComplexTensor
) -> ComplexTensor:
"""
Cross-channel power spectral density (PSD) matrix
Args:
complex_tensor: speech or noise [..., F, C, T]
Returns
psd: [..., F, C, C]
"""
# outer product: [..., C_1, T] x [..., C_2... | e0c93e201f7e950e1950ab9300b0ca49ba5cfb61 | 60,992 |
def attach(client, volume_id, host, mode=None):
"""A convenience wrapper around _AttachmentState.attach()"""
with __manager__.get_state() as attach_state:
attachment = attach_state.attach(client, volume_id, host, mode=mode)
return attachment | 8a6a09fe28c5d953a2a46fbe160bbef40077e295 | 60,993 |
def remove_peca(tabuleiro, pos):
"""
remove_peca: tabuleiro X posicao -> tabuleiro
Modifica destrutivamente o tabuleiro, removendo a peca da posicao dada.
Devolve o proprio tabuleiro.
"""
del tabuleiro[posicao_para_str(pos)]
return tabuleiro | eb1a908ae8bb8e11ff724b5a5968f6b81584f947 | 60,995 |
def _from_rgb(rgb):
"""translates an rgb tuple of int to a tkinter friendly color code
"""
return "#%02x%02x%02x" % rgb | 464cab5007935824b8b7af28e97cc882ec0653ee | 60,996 |
import time
def daskrej(
flist,
shape=None,
dtype=None,
num_chunks=8,
sigma_thresh=(10,),
combine_func=np.median,
save_intermediate=False
):
"""
Parameters
----------
flist
shape
dtype
num_chunks
Returns
-------
"""
... | 122fc905eab34bff3e18351a8ab84c256604e583 | 60,998 |
import time
import random
def P_m2(event_params, single_centre, binary_centre, sn_base, n_epochs):
"""Calculate the marginalised binary model probability of a specific light curve.
Args:
event_params: [list] Single lens model parameters.
sn_base: [float] Signal to noise baseline of data.
... | 8b75c83ea140eed2b34d30bdab7426f5d48665dd | 60,999 |
def create_vocabulary(inputs, key_words=[]):
"""
Create a vocabulary object from a sentence or a list of sentence
:param inputs:
:param vocab_size:
:param key_words:
:return:
"""
vocab = Vocabulary()
vocab.set_key_words(key_words)
if isinstance(inputs[0], list):
# inp... | 72539c2300daf22f142c851d0d706a55014f7b3d | 61,000 |
def playerScoresDict(tournament_num):
"""Get playerScores() in dictionary form."""
players_list = playerScores(tournament_num)
players_dict = {str(player[0]): player for player in players_list}
return players_dict | 50c9301a8074bcb134684927ee6451fb82701927 | 61,001 |
def get_chem_names(particles):
"""
Create a list of chemical names for the dispersed phase particles
Reads the composition attribute of each particle in a `particles` list
and compiles a unique list of particle names.
Parameters
----------
particles : list of `Particle` objects
... | 7b1a462732b6bdd389fb0d9c2b80aab5a5f385d5 | 61,002 |
import requests
def get_APOD(date):
"""This will do the request on the NASA api"""
payload = 'https://api.nasa.gov/planetary/apod'
params = {'api_key' : 'DEMO_KEY',
'date' : date}
response = requests.get(payload, params = params)
return response.json() | 45cdbadd7c67a71033e506fdc8a2358e8f7d8c09 | 61,003 |
def test_no_args(capsys, flat_mode):
""" Tests that the no-args example works in both modes """
if not flat_mode:
@decorator
def replace_with_hello():
"""
Decorator to replace anything with the 'hello' string.
"""
def _apply_decorator(f):
... | 02d9204dbf9984736bd4d3c806881a58a3972b5b | 61,005 |
def validate_active_image(method):
"""The decorator to validate the active image to be not `None`."""
@wraps(method)
def wrapper(self, *args):
if not self.active_image:
QMessageBox.warning(self, "There is no uploaded image", "Please, open an image using\n"
... | 07139485879efc77678f9e08694531b9b7f815fe | 61,006 |
def calc_out_size_1d_maxpool(in_size, ksize, stride, padding):
"""
Calculates output size on one dimension.
:param in_size: [int] Input size.
:param ksize: [int] Kernel size.
:param stride: [int] Stride size.
:param pad: [string] Padding method, `SAME` or `VALID`.
:... | ace5e17f761db5cb32d1b88f8aafb7506f9842e6 | 61,007 |
import re
def replace_with_dict( s, d ):
"""
replaces the substrings in the dictionary keys with their values
Parameters
----------
s: string
d: dict
Returns
-------
string
Examples
--------
>>>s1 = "asdf qwer"
>>>d1 = { 'asdf', 'foo' }
>>>d2 = { 'qwer', 'bar... | c7e185860eb3e13f65cdf614301c1a5afed894f9 | 61,008 |
import numpy as np
def mape(predictions, actuals):
"""
Calcuate Mean Absoute Percentage Error (MAPE)
Reported as percentage
Parameters
----------
predictions: numpy array of predicted values
actuals: numpy array of actual values
Returns
-------
Returns float of calculate... | 560b5960cfdf870b2d9954419140d85d3d8a5a27 | 61,010 |
def completed_project_incidents(request):
"""
incident for specific project
"""
project_id = request.GET.get('project_id')
template = loader.get_template('project_management/completed_incidents.html')
project = Project.objects.get(id=project_id)
state = True
if ProjectTeam.objects... | d85c46ba1872ca3273aedc6af39be6ef70ec9a13 | 61,011 |
from typing import Set
def uniq(a: Tensor) -> Set:
"""
return unique element of Tensor
Use python Optimized mode to skip assert statement.
:rtype set
:param a: input tensor
:return: Set(a_npized)
"""
return set([x.item() for x in a.unique()]) | 29bd1d63a2adeecfeb8a33439c5030c7fdaaf5ac | 61,012 |
def env_cfg_path() -> str:
"""Get a L5 environment config file from artefacts.
Note: the scope of this fixture is "session"-> one per test session
:return: the L5Kit gym-compatible environment config python dict
"""
env_cfg_path = "./l5kit/tests/artefacts/gym_config.yaml"
return env_cfg_path | d762e1ee39a54fab6cd3f00961a552801eeddcc6 | 61,013 |
def to_timestamp(value):
"""
Convert datetime to a timestamp string MediaWiki would understand.
:type value: datetime
:rtype str
"""
# datetime.isoformat() wouldn't work because it sometimes produces +00:00
# that MW does not support.
# Also perform sanity check here to make sure this is... | 4acb92d65060ada4e0d783c1eef5b108bd81f88f | 61,014 |
from typing import Annotated
def remove_completer(
name: Annotated[str, Arg(completer=complete_completer_names)],
):
"""Removes a completer from xonsh
Parameters
----------
name:
NAME is a unique name of a completer (run "completer list" to see the current
completers in order)
... | e439000162d7baad0f673416dec89e73791a02d9 | 61,015 |
def unhandled_intent_handler(handler_input):
"""Handler for all other unhandled requests."""
# type: (HandlerInput) -> Response
speech = "Say yes to continue or no to end the game!!"
handler_input.response_builder.speak(speech).ask(speech)
return handler_input.response_builder.response | 2ff305a4a70b45797fda5f89cd0accae23fc9a96 | 61,016 |
import ast
def _find_all(self, node_type):
"""Finds all nodes defined by string node_type
:param node_type: the string representing the "type" of node to look for
:return: a list of Ast Nodes (easy_nodes) of self that are of the specified type (including self if self
meets that criteria)
... | fb887a459cbf37b79da0b3fe8afd970f8b5bfd09 | 61,018 |
def LSTNetModel(task, window, rnn_type, skip_rnn_type, continuous_columns, categorical_columns,
cnn_filters, kernel_size, rnn_units, rnn_layers, skip_rnn_units, skip_rnn_layers, skip_period,
ar_order, drop_rate=0., nb_outputs=1, nb_steps=1, out_activation='linear', **kwargs):
"""Long-and Short-term ... | 75a4ba1d4a90e484f1c411cb0d172a5609061f3d | 61,020 |
def provide_help():
"""
send an api syntax error status and show the correct usage of the api
Return:
return a dictionary with keys 'syntax', 'status' , 'description' specifying error & help
"""
# reference syntax
syntax_str = 'HOST:PORT/geocode?address=ADDRESS'
# description of par... | cf76a136d6b7e64a06f8a740972a391d8945b03d | 61,021 |
def rmask_byte(num_mask_bits,value):
"""
This function applies a right-justified mask of a specified number of bits to an unsigned integer representing a single byte value.
>>> rmask_byte(3,list(b'\\xff')[0])
7
>>> bin(7)
'0b111'
"""
return ((1<<(num_mask_bits))-1) & value | 156fe1797590c5418a28db13b1064dfdb4e7bc4c | 61,022 |
def strip_predicate(predicate: Predicate) -> Predicate:
"""Remove classifier from predicate to make new Predicate."""
return Predicate(predicate.name, predicate.types, lambda s, o: False) | 7c01cf2de85c11511af18f2538fe70e2d390750b | 61,023 |
def json_str_to_compas_obj(json_str): # type: (str) -> compas.data.Data
"""Convert JSON string to object based on :class:`compas.data.Data`."""
return compas.data.json_loads(json_str) | 63064dc6a777c799e97f90525f92c6e4faca8457 | 61,025 |
async def truth(_: Request) -> dict:
"""Get a random truth question."""
truth_resp = get_random_text_response("truths")
return {"truth": truth_resp} | 606666357bc1ae04ae4de8d7a543017ccc4d1ca7 | 61,026 |
def normalized_name(name):
"""Return normalized name with special chars like slash, colon, etc normalized
to hyphen(-). This is important as otherwise these chars break local and cloud
storage paths."""
return SPECIAL_CHARS_REGEX.sub('-', name).strip('-') | c311bdcc9b9d0541cce1b993853d054946df059f | 61,027 |
def download_records(accessions, verbose=False, wait=5,
retries=3, taxon_id=9606):
"""Download records for each UniProt accession via the UniProt API.
The call will retry upon timeout up to the number specified by `retries`.
Parameters
----------
accession : str
UniPr... | 705cc2fca39982ca6c91b19089035e2fae99781d | 61,028 |
def split_tail(biggest_vertex: Vertex, original_vertex: Vertex) -> Vertex:
"""Get the split tail of the vertex
Args:
biggest_vertex: The vertex with the biggest id in the original graph
original_vertex: Vertex in the original graph
Returns:
New split vertex that is a tail of all ar... | a60fab3c810635d14ad758d6e964609c2f1222c3 | 61,029 |
from datetime import datetime
import uuid
import random
def plugin_poll(handle):
""" Extracts data from the sensor and returns it in a JSON document as a Python dict.
Available for poll mode only.
Args:
handle: handle returned by the plugin initialisation call
Returns:
returns a sens... | 1b3afbef00324e0958f703462297d21695aad28a | 61,031 |
def get_L(NO3):
"""
Fundamentally this gives the nutrient concentration that is part
of the phytoplankton growth rate, but it involves the
Michaelis-Menten functions for nutrient limitation.
For zero nutrients L = 0. As the nutrients become large
compared to their half-saturations L goes to 1.... | 586faba87d0a5e3b3e4bf57cac59da5b608ad259 | 61,032 |
def homepage(env, start):
"""WSGI app to show the home page"""
global _cached
start('200 OK' , _head('text/html'))
if not _cached: _cached = open('blockbox.html').read()
return _cached | 106b9654200da642f12c98639489275a71f6cbdf | 61,033 |
def build_sequence_mask(sequence_length,
num_heads=None,
maximum_length=None,
dtype=tf.float32):
"""Builds the dot product mask.
Args:
sequence_length: The sequence length.
num_heads: The number of heads.
maximum_length: ... | d1d69f41c0443242514af95c52239025ab0fdd86 | 61,035 |
def circle_locs(im, locs, inner_radius=3, outer_radius=4, fill_mode="nan"):
"""
Returns a copy of im with circles placed around the locs.
Arguments
im: The background image
locs: Nx2 matrix of peak locations
circle_radius: Radius of circle to draw
fill_mode:
"nan... | 4b72dad7394cad8cc8d85b1038285a1098ed8bec | 61,037 |
def run_program(intcodes):
"""run intcodes, which are stored as a dict of step: intcode pairs
intcodes encode the operation as well as the parameter mode. The two least
significant digits are the operation. The most significant digit(s) are the
parameter mode, one digit per parameter, read right-to-lef... | 8714ea4988b52db9cab332c74b601c198b7fb511 | 61,038 |
def verify_token(token: str) -> str:
"""
Mock google and fb auth.
:param token: email
:return: email
"""
return token.strip() | 806a6e5cb65bf6919afda7cc13bc5fa8e521a750 | 61,039 |
def stacked_rnn():
"""Stacked RNN model."""
inputs = keras.Input((None, 3))
layer = keras.layers.RNN([keras.layers.LSTMCell(2) for _ in range(3)])
x = layer(inputs)
outputs = keras.layers.Dense(2)(x)
model = keras.Model(inputs, outputs)
return ModelFn(model, (None, 4, 3), (None, 2)) | b3bacb649df5b96a95bfbcdb0c694ee15fd6d6d8 | 61,040 |
def dup_jacobi(n, a, b, K):
"""Low-level implementation of Jacobi polynomials."""
seq = [[K.one], [(a + b + K(2))/K(2), (a - b)/K(2)]]
for i in range(2, n + 1):
den = K(i)*(a + b + i)*(a + b + K(2)*i - K(2))
f0 = (a + b + K(2)*i - K.one) * (a*a - b*b) / (K(2)*den)
f1 = (a + b + K(2)... | c3f30a412e796376545b202c550a3fb5a6734e00 | 61,041 |
def data_topology_get(): # noqa: E501
"""data_topology_get
returns topology.Topology # noqa: E501
:rtype: TopologyTopology
"""
return 'do some magic!' | 3fecb83fcea17cc8c963d3c47dd69416a0455838 | 61,042 |
def state_resolver(state: str) -> str:
"""Given a state name, returns it's dcid."""
state_alpha_code = USSTATE_MAP_SPACE[state]
geo_dcid = USSTATE_MAP[state_alpha_code]
return geo_dcid | 734a3c8d14ed8352c73bf4df7dfec59d98f0bad3 | 61,043 |
def hash_to_action(a_hash):
"""Deciphering the hash to a game action."""
if a_hash == -1:
raise ValueError('Invalid action hash')
if a_hash < NUM_CARDS:
return {'action_type': 'DISCARD', 'card_index': a_hash}
if a_hash < NUM_CARDS + NUM_CARDS:
return {'action_type': 'PLAY', 'card_index': a_hash - NU... | 9a815ba452f2ef9953d89b6ea2053de0155d728b | 61,047 |
import pdb
def UL(tran):
"""Compute UL (Utility Loss) for record and middle.
"""
ul = 0
supp_sum = len(ATT_TREES[-1]['*'])
for t in mid[-1]:
try:
supp = len(ATT_TREES[-1][t])
except:
pdb.set_trace()
ul += (2 ** supp)
ul = ul / (2 ** supp_sum) * 1... | 0645b8feea4dfb930e55774ee4d73f097cad6765 | 61,049 |
def decimal_day_to_unix_time(year: int, month: int, day: float):
"""A function to convert decimal day time formats to UNIX time.
Parameters
----------
year : int
The year of the time stamp to be converted.
month : int
The month of the time stamp to be converted.
day : float
... | 8a8e6e386a16eb186255c37f0c21e4bae0af2f02 | 61,050 |
def NewDockerClientNoCheck(**kwargs):
"""Factory method for building a docker.Client from environment variables.
Args:
**kwargs: Any kwargs will be passed to the docker.Client constructor and
override any determined from the environment.
Returns:
A docker.Client instance.
Raises:
DockerDaem... | f9e532399c2f2fc8604307e7291a16d05daf931d | 61,051 |
def list_ports(zone, permanent=True):
"""
List all ports in a zone.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_ports
"""
cmd = "--zone={0} --list-ports".format(zone)
if permanent:
cmd += " --permanent"
return __firewall_... | eb99f515809de167ffeefca0bf9c63aef2208ad9 | 61,052 |
def log_db(app):
"""Return mongo client mock for the log db"""
return api.config.log_db | 7ee7eb7012bfc808fa490bd85c06a7b1a8bb8ae2 | 61,053 |
def printif(string: str, pre_sep: str = " ", post_sep: str = " ") -> str:
"""Print `string` if `string` is not null."""
if string not in [None, ""]:
return f"{pre_sep}{string}{post_sep}"
return "" | cfd7272ae106fda7c0f4e6705875a3656d90d52c | 61,054 |
from typing import List
def get_immunity_strat(
compartments: List[str],
immunity_params: ImmunityStratification,
) -> Stratification:
"""
This stratification is intended to capture all the immunity consideration.
This relates both to "cross" immunity between the strains being simulated (b... | b81a3b3704d9caed2fb15d48ef6ffabe60ef660e | 61,055 |
def _irfft_grad_helper(rank, rfft_fn):
"""Returns a gradient function for an IRFFT of the provided rank."""
# Can't happen because we don't register a gradient for IRFFT3D.
assert rank in (1, 2), "Gradient for IRFFT3D is not implemented."
def _grad(op, grad):
"""A gradient function for IRFFT with the provi... | 2284f9f3e06bd5bad196efb3e3f5d225f5b0922c | 61,056 |
def api_enable_fusion(val: bool = True) -> None:
"""Whether or not allow fusion the operators
Args:
val (bool, optional): True or False. Defaults to True.
"""
return enable_if.unique([enable_fusion, do_nothing])(val=val) | 40d4fdbee933487f9d02ff2df5023032c3c59e9f | 61,059 |
def random_apply(transform_fn, image, p):
"""Randomly apply with probability p a transformation to an image"""
if tf.random.uniform([]) < p:
return transform_fn(image)
else:
return image | 12d2ab0eae20333b6881d838bfbca8ab020eb0be | 61,060 |
def get_incident_ids() -> list:
"""
Gets all the campaign incident ids.
Returns:
List of all the ids.
"""
incidents = demisto.get(demisto.context(), "EmailCampaign.incidents")
return [incident["id"] for incident in incidents] | b4f8c089c93520da546bf7b00e0f8d1eed51b4c0 | 61,061 |
def normalize_genotypes(genotypes):
"""Normalize the genotypes.
Args:
genotypes (Genotypes): The genotypes to normalize.
Returns:
numpy.array: The normalized genotypes.
"""
genotypes = genotypes.genotypes
return (genotypes - np.nanmean(genotypes)) / np.nanstd(genotypes) | 367c6293f0a03c70d05f45916b7a191ba99fbb18 | 61,062 |
from io import StringIO
def GetLines(data, strip=False):
"""Returns a list of all lines in data.
Args:
strip: If True, each line is stripped.
"""
ret = StringIO(data).readlines()
if strip:
ret = [x.strip() for x in ret]
return ret | 8ce3a3e829eed590ba0978a659ff1d3b063dc50d | 61,063 |
def mannwhitneyu(a, b, sigLevel=.05):
"""
Determine if sample a and b are the same at given significance level.
"""
if len(a) <= 20 and len(b) <= 20:
return mannwhitneyu_small(a, b, sigLevel)
else:
try:
# MWU in SciPy is one-sided, multiply by 2 to get two-sided.
... | 08ca7dcae3a5771047fa9700d545681977f0ae65 | 61,064 |
def _get_hyperparameters() -> kt.HyperParameters:
"""Returns hyperparameters for building a TFDF model."""
hp = kt.HyperParameters()
# Defines search space.
# For a complete list of configuration parameters of learners, please refer to
# https://github.com/google/yggdrasil-decision-forests/blob/main/documenta... | 1e9da47d8cbdc9e72f6fc44bf1791c26428c8a08 | 61,065 |
def _netmiko_connect(connection_dict):
"""
to handel netmiko connection
:param connection_dict: netmiko connection dict
:return: netmiko connection object
"""
try:
connection = ConnectHandler(**connection_dict)
except (NetMikoTimeoutException, NetmikoTimeoutError) as e:
prin... | 07fc7c6f97eb0bcde9690678ae2762c016286b7f | 61,066 |
def polyphase_forward(x, hk, rearrange_filter=True):
"""
Polyphase implementation of the analysis process (fast)
Parameters
----------
x: torch.Tensor
signal to analyse ( B x 1 x T )
hk: torch.Tensor
filter bank ( M x T )
"""
x = rearrange(x, "b c (t m) -> b (c m) t"... | 1df0cd727a83be86e5a355e196751c57952cea3c | 61,067 |
def merge_config(user, default):
"""Merges a user configuration with the default one."""
if isinstance(user, dict) and isinstance(default, dict):
for kk, vv in default.items():
if kk not in user:
user[kk] = vv
else:
user[kk] = merge_config(user[kk... | 7b4463f3e9c213782b6da5f25bcf64daa2c69d91 | 61,069 |
def _json_add_readers(json, filenames):
""" Add merge Filter element and readers to a Writer element and return Filter element """
for f in filenames:
_json_add_reader(json, f)
if len(filenames) > 1:
json['pipeline'].insert(0, {
'type': 'filters.merge'
})
re... | 9d35f44050464292c944176c98fa1ee62d026315 | 61,070 |
import math
def bic(observations,variables,pred_vector,true_vector):
"""
Function that calculates the BIC value for a dataframe
Args:
observations
variables
pred_vector
true_vector
Returns:
bic
"""
return math.log(sum((pred_vector-true_vector)**2)/observ... | b7747991b929d5151aba27e48018654277e61c52 | 61,071 |
def list_name(pat_id):
""" Returns all of the Names for a patient """
app.logger.info("Request for Patient's Names...")
pat = Pprofile.find_or_404(pat_id)
results = [name_item.serialize() for name_item in pat.name]
return make_response(jsonify(results), status.HTTP_200_OK) | 92c70614f1f513358b7bf40010b1772dfdd48e14 | 61,072 |
def get_bilateral_specificity(C,lrd,left):
"""
Returns the bilateral (contralateral) specificity probabilities
Parameters:
-----------
C : Connecomte object
lrd : dict
Left/right dictionary
left : list
List of the left nodes
Returns:
spec : dict
Keys are cell na... | d72ebaea472e753cd93b7bb7ab4c536d1a717b92 | 61,073 |
def reduce_nodelist(nodelist: template.NodeList) -> template.NodeList:
"""
A function which trims whitespaces and comment nodes from a nodelist.
Notice that this function might remove a relevant regular html space ' ',
so use with care.
"""
new_nodelist = template.NodeList()
for node in ... | a2578f67636f7abc1090794d2425da219425089b | 61,074 |
def GetNodeInfo(storage_units, hv_specs):
"""Gives back a hash with different information about the node.
@type storage_units: list of tuples (string, string, list)
@param storage_units: List of tuples (storage unit, identifier, parameters) to
ask for disk space information. In case of lvm-vg, the identifier... | 886065df101557ca49e879dc8f187028455142b2 | 61,075 |
from typing import Union
from typing import TextIO
from typing import Sequence
from pathlib import Path
import pandas
import io
def get_locations(files: Union[TextIO, Sequence[Path]]) -> pandas.DataFrame:
"""
retrieve locations of GNSS receivers
Requires pymap3d.ecef2geodetic
"""
if isinstance(fi... | d9ab00c22f95945b54584a8c4d99a259cf667dd3 | 61,076 |
import numpy
def createslicemeshes(grid, x=None, y=None, z=None, step=None, offset=None):
"""
Creates meshes for slices through the given data, using the current GR
colormap. Use the parameters x, y or z to specify what slices should be
drawn and at which positions they should go through the data. If ... | 387a2b93c06a2f5bfba9b95c5ccf5b4604dd3e26 | 61,077 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.