content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import sympy
import warnings
def _add_aliases_to_namespace(namespace, *exprs):
"""
Given a sequence of sympy expressions,
find all aliases in each expression and add them to the namespace.
"""
for expr in exprs:
if hasattr(expr, 'alias') and isinstance(expr, sympy.FunctionClass):
... | e90e311aacd9c9c41363badc690ad25c18501251 | 23,195 |
def rotICA(V, kmax=6, learnrate=.0001, iterations=10000):
""" ICA rotation (using basicICA) with default parameters and normalization of
outputs.
:Example:
>>> Vica, W = rotICA(V, kmax=6, learnrate=.0001, iterations=10000)
"""
V1 = V[:, :kmax].T
[W, changes_s] = basicICA(V1, learnrate, i... | 2db4bb0d5c5c5f70c9f7cf5a20b27fd2b146e26f | 23,196 |
import socket
def getipbyhost(hostname):
""" return the IP address for a hostname
"""
return socket.gethostbyname(hostname) | 9556f537e16fd710a566a96a51d4262335967893 | 23,197 |
def reduce_mem_usage(df) -> pd.DataFrame:
"""DataFrameのメモリ使用量を節約するための関数.
Arguments:
df {DataFrame} -- 対象のDataFrame
Returns:
[DataFrame] -- メモリ節約後のDataFrame
"""
numerics = [
'int8', 'int16', 'int32', 'int64', 'float16', 'float32', 'float64'
]
start_mem = df.memory_u... | b317c85aee9f51d221b3895bcc9ac1a6bc3535f6 | 23,198 |
import typing
def findparam(
parameters: _TYPE_FINDITER_PARAMETERS,
selector: _TYPE_FINDITER_SELECTOR
) -> typing.Iterator[_T_PARAM]:
"""
Return an iterator yielding those parameters (of type
:class:`inspect.Parameter` or :class:`~forge.FParameter`) that are
mached by the selector.... | 61da9c7e453d04bf2db9c5f923e815e250da4b53 | 23,199 |
def FSA(profile_exp, profile_sm, diffsys, time, Xlim=[], n=[400, 500], w=None, f=None, alpha=0.3, name=''):
"""
Forward Simulation Analysis
Extract diffusion coefficients based on a diffusion profile.
Please do not close any plot window during the FSA process.
This is the final step of FSA.
Pa... | 049475203d30ac02dadc0cb281d38909ba32039c | 23,201 |
def permutacion_matriz(U, fila_i, idx_max, verbose=False, P=None, r=None):
"""Efectua una permutación por filas de una matriz
Args:
U (matriz): MAtriz a permutar
fila_i (int): indice de fila origen
idx_max (int): indice de fila a la que permutar
verbose (bool, optional): verbose... | 2ff9ae6a0b789de24c3479df49275fa254876dd2 | 23,202 |
def get_compliance_by_rules(scan_id):
"""
Lists compliance results by rule for a scan.
"""
items = []
offset = 0
while True:
params = {'offset': offset}
response = get('scans/%s/compliance_by_rules' % scan_id, params)
items.extend(response['items'])
if not respons... | 205dccc9b7714eb9a2179272b2fc1cec4cbc26e3 | 23,203 |
def QuadRemeshBrep1(brep, parameters, guideCurves, multiple=False):
"""
Create Quad Remesh from a Brep
Args:
brep (Brep): Set Brep Face Mode by setting QuadRemeshParameters.PreserveMeshArrayEdgesMode
guideCurves (IEnumerable<Curve>): A curve array used to influence mesh face layout
... | 042e89c1da55fd74f18c9592fc18bd2e0a18e2a8 | 23,204 |
def tags2turbo(lon, lat, dist, bdim=155, timeout=60, pretty_print=False, maxsize=None, tags=[]):
""" """
gtypes = ('node', 'way', 'relation',)
turbo = Turbo()
qconditions = [{
"query": filter2query(tags),
"distance": dist,
"gtypes": gtypes, # Optional. Possible values:
# ... | a9eae6c63266818f9e05993100432bdce2df851e | 23,205 |
async def get_people(from_number: int = None, up_to_number: int = None):
"""
Endpoint to get all people from-to given number
:return: list of people from-to numbers
"""
return _people[from_number:up_to_number] | 0ea214227493642eace1a1dc864268176cf872af | 23,206 |
import chunk
def window(x, y, width, overlap=0., x_0=None, expansion=None, cap_left=True,
cap_right=True, ret_x=True):
"""Break arrays x and y into slices.
Parameters
----------
x : array_like
Monotonically increasing numbers. If x is not monotonically increasing
then it wi... | 947b84a33e351e7e75fbdaf4997de689f44c83ec | 23,209 |
import json
def mark_property_purchased(request):
"""
Api to mark a property as purchased by the buyer without page reload using vue or htmx
"""
data = json.loads(request.body)
property = data['property_id']
if not property.property_status == Property.SOLD and property.property_sold:
p... | 2ce7e22b8cf566361d307c53423b0b0a26ab2dbc | 23,210 |
def argmax_unique(arr, axis):
"""Return a mask so that we can exclude the nonunique maximums, i.e. the nodes that aren't completely resolved"""
arrm = np.argmax(arr, axis)
arrs = np.sum(arr, axis)
nonunique_mask = np.ma.make_mask((arrs == 1) is False)
uni_argmax = np.ma.masked_array(arrm, mask=nonun... | e6691fea688c6f0044fd9e0a70e4651ae56aaa49 | 23,212 |
from typing import Dict
import json
def get_json(response: func.HttpResponse) -> Dict:
"""Get JSON from an HttpResponse."""
return json.loads(response.get_body().decode("utf-8")) | 58fa7916d6b988b2e949e55db838f3f6b9430fb3 | 23,213 |
def _float_feature(value):
"""Returns a float_list from a float / double."""
if isinstance(value, list):
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) | 2caaa8b572ee2744cf6deeaff6a287fb472cef7f | 23,214 |
def sendVillasNodeOutput(message, output_mapping_vector, powerflow_results, state_estimation_results, scenario_flag):
"""
to create the payload according to "villas_node_output.json"
@param message: received message from the server (json.loads(msg.payload)[0])
@param output_mapping_vector: according to... | dc992622a625219c6befb865cee87c4d3ffa0aef | 23,215 |
def find_org_rooms(dbs, user_id, meeting_date):
"""
获取可分配的机构
:param dbs:
:param user_id:
:param meeting_date:
:return:
"""
orgs = dbs.query(SysOrg.id, SysOrg.org_name, SysOrg.parent_id)\
.outerjoin(SysUserOrg, (SysUserOrg.org_id == SysOrg.id))\
.filter(SysUserOrg.user_id ... | 18f3c9c75377a4c212141c0b14f4e4802d7782b5 | 23,216 |
def config_openapi(app: FastAPI, settings: ApiSettings):
"""Config openapi."""
def custom_openapi():
"""Config openapi."""
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="Arturo STAC API", version="0.1", routes=app.routes
... | d57f37ce33cef4639f635330c6313a9fea5ab7dc | 23,217 |
from typing import Sequence
def twelve_tone_matrix(
row: Sequence,
) -> DataFrame:
""" Returns a twelve-tone matrix in the form of a Pandas DataFrame.
"""
inverted_row = inversion(row)
inv_mat = transposition(inverted_row, row[0]-inverted_row[0])
new = [row]
for i in range(1, 12):
... | 3ab247e7e347aa3c84e4b040380f0529e8081625 | 23,218 |
async def upstream_http_exception_handler(request, exc: HTTPError):
"""Handle http exceptions from upstream server"""
logger.warning(f"Upstream HTTP error [{request.query_params['url']}]: {repr(exc)}")
# Convert to FastApi exception
exc = HTTPException(502, f"Upstream server returned: [{exc.status}] {ex... | 9f96e83c5b120bdcb8f6f7173ec928a33be1b210 | 23,219 |
from typing import List
from pathlib import Path
import re
def extract_latest_checkpoint_and_epoch(available_files: List[Path]) -> PathAndEpoch:
"""
Checkpoints are saved as recovery_epoch={epoch}.ckpt, find the latest ckpt and epoch number.
:param available_files: all available checkpoints
:return: ... | f11d627b79baef580c0dc354a9d9be28552fe4d9 | 23,220 |
def bark_filter_banks(nfilts=20,
nfft=512,
fs=16000,
low_freq=0,
high_freq=None,
scale="constant"):
"""
Compute Bark-filterbanks. The filters are stored in the rows, the columns
correspond to fft bi... | 227edcca91c64515b73531d80e1bd9db7faf9bb0 | 23,221 |
import json
def auth_check_response_fixture():
"""Define a fixture to return a successful authorization check."""
return json.loads(load_fixture("auth_check_response.json")) | 18bb02313534376f4244430725135d089941693f | 23,222 |
def cancel_session(session_id):
"""
Cancel all tasks within a session
Args:
string: session_id
Returns:
dict: results
"""
lambda_response = {}
all_cancelled_tasks = []
for state in task_states_to_cancel:
res = cancel_tasks_by_status(session_id, state)
... | 5d07d9038023ad15eaca33bb409b5a4c4db66089 | 23,223 |
def get_cli_args():
"""Gets, parses, and returns CLI arguments"""
parser = ArgumentParser(description='Check modules formatting')
parser.add_argument('filepath', help='path to a file to check')
parser.add_argument('-n', '--fqcn',
dest='fqcn',
metavar='FQ... | 4e54a7141e19ebba9c0502e4bb40293a583e2d96 | 23,225 |
def __virtual__():
"""
Determine whether or not to load this module
"""
return __virtualname__ | 3b5f873a504d44aba03691f58d8f19a834287eff | 23,226 |
def load_glove_embeddings():
"""
Load the glove embeddings into a array and a dictionary with words as
keys and their associated index as the value. Assumes the glove
embeddings are located in the same directory and named "glove.6B.50d.txt"
RETURN: embeddings: the array containing word vectors
... | eaac7465e7a4d9658add81ea7a17e62684d38bed | 23,227 |
def _f2_rsub_ ( self , other ) :
"""Operator for ``2D-function - other''"""
return _f2_rop_ ( self , other , Ostap.MoreRooFit.Subtraction , "Subtract_" ) | 2b771d39ea3d1cd3cb7f8c4bc88c11d3814f2e4e | 23,228 |
def attenuate(source, factor=0.01, duration=1.0, srate=None):
"""Exponential attenuation towards target value within 'factor' in time 'duration' for constant signals."""
if srate is None:
srate = get_srate()
return onepole(source, 1.0, -factor ** (srate / duration), 1.0 - factor ** (srate / duration... | d67c141ec36bfcaf9dde2518488f8cc5d2b24ef5 | 23,229 |
def IsMultiPanel(hcuts, vcuts) -> bool:
"""
Check if the image is multi-panel or not.
Could have more logic.
"""
return bool(hcuts or vcuts) | fc62a31007445eac90b6f5ceb3a7c9c006dd2eef | 23,231 |
def is_subject_mutable(context, subject):
"""Return True if the subject is mutable in this context."""
if context.is_admin:
return True
if subject.owner is None or context.owner is None:
return False
return subject.owner == context.owner | 74e36a2f79111c9d09ea9f90579ce9b51beb3e61 | 23,232 |
from datetime import datetime
def time_filter(df, start_date, end_date):
"""Remove times that are not within the start/end bounds."""
if start_date:
datetime_start = datetime.strptime(start_date, '%Y-%m-%d')
start_selection = df.index >= datetime_start
if end_date:
datetime_end =... | 13e66add286ddad649e4ae09dc9d6ec5dd013d8a | 23,233 |
def collapse_umi(cells):
"""
Input set of genotypes for each read
Return list with one entry for each UMI, per cell barcode
"""
collapsed_data = {}
for cell_barcode, umi_set in cells.items():
for _, genotypes in umi_set.items():
if len(set(genotypes)) > 1:
pas... | e98b44193487691fb04e8e0f4ec25c3438175c65 | 23,235 |
def get_corrected_PRES(PRES: np.ndarray, ele_gap: float, TMP: np.ndarray) -> np.ndarray:
"""気圧の標高補正
Args:
PRES (np.ndarray): 補正前の気圧 [hPa]
ele_gap (float): 標高差 [m]
TMP (np.ndarray): 気温 [℃]
Returns:
np.ndarray: 標高補正後の気圧 [hPa]
Notes:
気温減率の平均値を0.0065℃/mとする。
... | 1be9c2bd5a07714463ac7a6b05bc4d7ca1f84e70 | 23,236 |
def mishra_bird(x, *args):
"""Mishra's Bird constrained function with 2 parameters.
To be used in the constrained optimization examples.
When subject to:
(x[0] + 5) ** 2 + (x[1] + 5) ** 2 < 25
the global minimum is at f(-3.1302, -1.5821) = -106.7645
Bounds: -10 <= x[0] <= 0
-6.... | ca6fd1211f8715ef1cbc39c75e252107774da54d | 23,237 |
def find_target_migration_file(database=DEFAULT_DB_ALIAS, changelog_file=None):
"""Finds best matching target migration file"""
if not database:
database = DEFAULT_DB_ALIAS
if not changelog_file:
changelog_file = get_changelog_file_for_database(database)
try:
doc = minidom.par... | 39a3ed89dacd9393f69e081aaf44c64f34852592 | 23,238 |
from functools import reduce
def encode_message(ctl, addr, src_id, msg_code, data=""):
"""Encode a message for the PIM, assumes data formatted"""
ctl = create_control_word(addr.is_link) if ctl == -1 else ctl
length = 7 + len(data)
ctl = ctl | (length << 8)
msg = bytearray(length)
msg[0:2] = ct... | 3ffef7a1b65e5dabc6ae4c237018d446b7852cc1 | 23,239 |
def rule_16(l, r):
"""
Rule for "vyaṁjana sandhi - ghośī karaṇaya"
:return:
"""
l_suffix = utils.endswith(l, letters.AGOSHA_LETTERS)
r_prefix = utils.startswith(r, letters.GOSHA_LETTERS)
if l_suffix is not None and r_prefix is not None:
if r_prefix in letters.VOWELS:
ret... | ea151d8697128e933ecd927ac2e18d039f578a1c | 23,240 |
def is_vertex_cover(G, vertex_cover):
"""Determines whether the given set of vertices is a vertex cover of graph G.
A vertex cover is a set of vertices such that each edge of the graph
is incident with at least one vertex in the set.
Parameters
----------
G : NetworkX graph
The graph on... | 4213db1953ec976b1606c3756fa73ff0cae9f578 | 23,241 |
def datetimeformat(value, formatstring='%Y-%m-%d %H:%M', nonchar=''):
"""Formates a datetime.
Tries to convert the given ``value`` to a ``datetime`` object and then formats
it according to ``formatstring``::
{{ datetime.now()|datetimeformat }}
{{ "20171224T235959"|datetimeformat('%H:%M') }... | a95510b5734168899d81c893f647b5b836ee3b27 | 23,242 |
def get_interface_for_name(protocols, target_interface_name):
# type: (Iterable[Protocol], str) -> Optional[Interface]
"""Given a name string, gets the interface that has that name, or None."""
for protocol in protocols:
for interface in protocol.interfaces:
if interface.name == target_i... | 22c8d4ad64058a068700fd8f16a1dee49efe4001 | 23,243 |
def extract_validation_set(x: ndarray, y: ndarray, size=6000):
"""Will extract a validation set of "size" from given x,y pair
Parameters:
x (ndarray): numpy array
y (ndarray): numpy array
size (int): Size of validation set. Must be smaller than examples count
in x, y and multiple of... | a5cc15cdd7a5889a29196c2bcee7b50aae5b3bc5 | 23,245 |
def send_update(peer_ip, attr, nlri, withdraw):
"""
send update message
:param peer_ip: peer ip address
:return:
"""
if cfg.CONF.bgp.running_config['factory'].fsm.protocol.send_update({
'attr': attr, 'nlri': nlri, 'withdraw': withdraw}):
return {
'status': True
... | f53f4ba009d21e3d36867d5292131fcffb73dc5e | 23,246 |
def generate_basic_blame_experiment_actions(
project: Project,
bc_file_extensions: tp.Optional[tp.List[BCFileExtensions]] = None,
extraction_error_handler: tp.Optional[PEErrorHandler] = None
) -> tp.List[actions.Step]:
"""
Generate the basic actions for a blame experiment.
- handle caching of B... | bd2785e3e611fea95f9e64b8f68ecf8746905bff | 23,247 |
from typing import Any
from typing import Optional
from typing import Union
from typing import OrderedDict
from typing import Mapping
from typing import Literal
def is_json_encodable(t: Any) -> bool:
""" Checks whether a type is json encodable. """
# pylint:disable=invalid-name,too-many-return-statements,too-... | bdebbebd28d16949c2786386c4be666f3445783e | 23,248 |
def request_parse_platform_id(validated_request):
"""Parses the PlatformID from a provided visibility API request.
Args:
validated_request (obj:Request): A Flask request object that has been generated for a
visibility/opportunity endpoint.
Requires:
... | 68fd6847549cf68edddfed2fca4e9177a6e41e6f | 23,249 |
def crear_comentario_submeta(request, pk):
""" Crea y agrega un comentario a una meta identificada por su id """
# meta = get_object_or_404(Meta, pk=pk)
meta = Submeta.objects.get(pk=pk)
# si ya se creo se guarda el comentario y se redirecciona el navegador a
# la meta
if request.method == "POST... | 56452834478c43560eaf168553ac4723091d400d | 23,250 |
def load_mask_from_shapefile(filename, shape, transform):
"""Load a mask from a shapefile."""
multipolygon, _ = load_shapefile2multipolygon(filename)
mask = multipolygon2mask(multipolygon, shape, transform)
return mask | 82af816cb92828862003929a42ddb62f5153cada | 23,251 |
def _spectra_resample(spectra, wvl_orig, wvl_target):
"""
:param spectra:
:param wvl_orig:
:param wvl_target:
:param k:
:return:
"""
idx_finite = np.isfinite(spectra)
min_wvl_s = np.nanmin(wvl_orig[idx_finite])
max_wvl_s = np.nanmax(wvl_orig[idx_finite])
idx_target = np.logi... | 5dedfce082d1d417cd609e53a2c73fafa69c451a | 23,252 |
from datetime import datetime
def test_standard_surface():
"""Test to read a standard surface file."""
def dtparse(string):
return datetime.strptime(string, '%y%m%d/%H%M')
skip = ['text']
gsf = GempakSurface(get_test_data('gem_std.sfc'))
gstns = gsf.sfjson()
gempak = pd.read_csv(get... | 4538481d85b313826d488e09c5504956f06b7865 | 23,253 |
def calc_mu(Rs):
""" Calculates mu for use in LinKK """
neg_sum = sum(abs(x) for x in Rs if x < 0)
pos_sum = sum(abs(x) for x in Rs if x >= 0)
return 1 - neg_sum/pos_sum | 915cd4718d255e963fede2b73b5637a1afc13d4b | 23,254 |
def computeAnomaly(data):
"""
Remove the seasonality
"""
period = _get_period(data)
meanclim = computeMeanClimatology(data)
anom = data.groupby(f'time.{period}') - meanclim
return anom | 2d42fb7c2f219f78e2971a554eaddb593f5dbc9c | 23,255 |
def product(*args):
"""Calculate product of args.
@param args: list of floats to multiply
@type args: list of float
@return: product of args
@rtype: float
"""
r = args[0]
for x in args[1:]:
r *= x
return r | 3862c4c9ac2ccd8336f70d86a17ae9fee4c7fed5 | 23,256 |
def unpack_into_tensorarray(value, axis, size=None):
"""
unpacks a given tensor along a given axis into a TensorArray
Parameters:
----------
value: Tensor
the tensor to be unpacked
axis: int
the axis to unpack the tensor along
size: int
the size of the array to be us... | e6320350d5963a47ec8f853e5b9c819b730c352f | 23,257 |
from datetime import datetime
def get_error_page(status_code, message):
"""
获取错误页面
:param status_code:
:param message:
:return:
"""
context = {
'site_web': settings.SITE_TITLE,
'site_url': reverse(settings.SITE_NAME),
'status_code': status_code,
'message': m... | 76da02826b026fd63562c2d51976ee77ad86f794 | 23,258 |
def fits_difference(*args, **keys):
"""Difference two FITS files with parameters specified as Differencer class."""
differ = FitsDifferencer(*args, **keys)
return differ.difference() | 4ccfd9c521d76e5b3d47a2be8afefe594895e570 | 23,259 |
def esta_balanceada(expressao):
"""
Função que calcula se expressão possui parenteses, colchetes e chaves balanceados
O Aluno deverá informar a complexidade de tempo e espaço da função
Deverá ser usada como estrutura de dados apenas a pilha feita na aula anterior
:param expressao: string com express... | c35a2f8ca4afef76e722d03809edca9f4dbac3fd | 23,260 |
def create_doc(im_src, tag, coords, fea_arr, fea_bin_arr):
"""
Create elasticsearch doc
Params:
im_src: image file name
tag: tag or class for image
coords: list of boxes corresponding to a tag
fea_arr: list of ImFea objects
fea_bin_arr: list of ImFeaBin objects
"... | 4e7afe795d30873516840b66a0e4a54b4599fe8c | 23,261 |
def scaled_mouse_pos(mouse): # pragma: no cover
"""
Renvoie la position de la souris mise à l'échelle de l'image.
Parameters
----------
mouse : int * int
La position réelle de la souris
Returns
-------
int * int
La position mise à l'échelle
"""
# Récupération d... | ad216c50f1492bb0248c04f3195aceed4622bfe1 | 23,262 |
import re
def is_valid_zcs_image_id(zcs_image_id):
"""
Validates Zadara Container Services (ZCS) image IDs, also known as the ZCS
image "name". A valid ZCS image name should look like: img-00000001 - It
should always start with "img-" and end with 8 hexadecimal characters in
lower case.
:typ... | 4b2e689c5ff62c32c147dec1c05b77cf0df31c9a | 23,263 |
import random
def get_topology2(gid: int, cfg: Config):
"""
Create a uniformly and randomly sampled genome of fixed topology:
Sigmoid with bias 1.5 --> Actuation default of 95,3%
(key=0, bias=1.5) (key=1, bias=?)
____ / /
/ /
GRU... | 4b8d21b8e22857c0bec06f58d6d13857a3834649 | 23,264 |
def dry_press(
H,
Pv,
alt_setting=P0,
alt_units=default_alt_units,
press_units=default_press_units,
):
"""
Returns dry air pressure, i.e. the total air pressure, less the water
vapour pressure.
"""
HP = pressure_alt(H, alt_setting, alt_units=alt_units)
P = alt2press(HP, ... | eceffd1bf8c13edc77c3a3bbb4131acf6c6b9bca | 23,266 |
def InvocationAddCallerAuthid(builder, callerAuthid):
"""This method is deprecated. Please switch to AddCallerAuthid."""
return AddCallerAuthid(builder, callerAuthid) | 63144e4311430009c419543c4ebb6a4f83f60281 | 23,267 |
def max_pool1d(input, ksize, strides, padding, data_format="NWC", name=None):
"""Performs the max pooling on the input.
Note internally this op reshapes and uses the underlying 2d operation.
Args:
input: A 3-D `Tensor` of the format specified by `data_format`.
ksize: An int or list of `ints` that has length `1` ... | d20db7475284f9b52ce1bc0d10d68f6ab96555a0 | 23,268 |
from typing import Concatenate
def DeepLabV3Plus(shape):
""" Inputs """
inputs = Input(shape)
""" Pre-trained ResNet50 """
base_model = ResNet50(weights='imagenet', include_top=False, input_tensor=inputs)
""" Pre-trained ResNet50 Output """
image_features = base_model.get_layer('conv4_block6... | da838d36b7926fc394bb8153ff3e6ed67926059b | 23,269 |
def white_noise(template, rms_uKarcmin_T, rms_uKarcmin_pol=None):
"""Generate a white noise realisation corresponding to the template pixellisation
Parameters
----------
template: ``so_map`` template
the template for the white noise generalisation
rms_uKarcmin_T: float
the white noise t... | 2e72d5362e66409081e0a4a222d49d18034006e2 | 23,271 |
def index():
"""process request to the root."""
return render_template('index.html') | ea02cfd380d51670ca69cbec74f9b299dd650e88 | 23,272 |
import torch
def aromatic_bonds(mol: IndigoObject) -> dict:
"""Get whether bonds in a molecule are aromatic or not.
Args:
IndigoObject: molecule object
Returns:
dict: key - feature name, value - torch.tensor of booleans
"""
is_aromatic = []
for bond in mol.iterateBonds():
... | 92bae4b5b5a67f8165732ab64e345f85ddaa7d28 | 23,273 |
import warnings
def get_unitroot(df: pd.DataFrame, fuller_reg: str, kpss_reg: str) -> pd.DataFrame:
"""Calculate test statistics for unit roots
Parameters
----------
df : pd.DataFrame
DataFrame of target variable
fuller_reg : str
Type of regression of ADF test
kpss_reg : str
... | 2d459e0980cb8983a03269f4e6b57e831065e6a0 | 23,274 |
def lat_avg(data, lat_wgt):
"""Perform latitude average of data:
Inputs:
data - n dimensional spatial data. The last 2 dimensions are assumed to lat and
lon respectively
lat_wgt - weights by latitudes"""
lat_shape = lat_wgt.shape
data_shape = data.shape
# If one dimension... | 2cef0a7e0eeead1983a8ae9dfc9d4cd7954a2c29 | 23,275 |
def create_line(line_coefficients, height=5, step=0.5, vis=False):
"""
Args:
line_coefficients: A dictionary containing cylindrical coefficients:
(r, x0, y0, z0_, a, b, c
r not used: to keep the same form between cylinder coefficients and ... | 0cafddb6263841152d506c08177ef8cc0691dd89 | 23,276 |
def get_result_summaries_query(start, end, sort, state, tags):
"""Returns TaskResultSummary.query() with these filters.
Arguments:
start: Earliest creation date of retrieved tasks.
end: Most recent creation date of retrieved tasks, normally None.
sort: Order to use. Must default to 'created_ts' to use ... | 45e0d7c09ea2c2a4cd9f3827fff5eaf09b12d98a | 23,277 |
def approx_jacobian(tform, image, delta=0.01):
"""approximate the image pixel gradient wrt tform using central differences
(This has been so helpful while troubleshooting jacobians,
let's keep it around for unit testing.
Parameters
----------
tform : TForm
current transform, to be appl... | 4153471fe4f94255a21b4d63c564aabe0db3b1d6 | 23,278 |
from typing import Collection
def create_collection(collection_id: str) -> Collection:
"""Creates a STAC Collection for Landsat Collection 2 Level-1 or Level-2
data.
Args:
collection_id (str): ID of the STAC Collection. Must be one of
"landsat-c2-l1" or "landsat-c2-l2".
Returns:
... | 111992f59a9a69aac0742350a0bce8b66b1ebb5d | 23,279 |
def rician_noise(image, sigma, rng=None):
"""
Add Rician distributed noise to the input image.
Parameters
----------
image : array-like, shape ``(dim_x, dim_y, dim_z)`` or ``(dim_x, dim_y,
dim_z, K)``
sigma : double
rng : random number generator (a numpy.random.RandomState instance)... | a7f5962a8c388cd69f1bdb364fa8fd5dcd1e2dd4 | 23,280 |
def compute_composition_df(seq_df):
"""
Compute the composition matrix for all proteins.
Args:
seq_df: df, dataframe with sequences
Returns:
df, with the composition of the proteins
"""
# get composition table
df_seq_comp = pd.DataFrame(
list(seq_df["sequence"].app... | 4d68dc4568914df8349dd32d9e24a55f74896023 | 23,282 |
def make_gradient_squared(
grid: CylindricalSymGrid, central: bool = True
) -> OperatorType:
"""make a discretized gradient squared operator for a cylindrical grid
{DESCR_CYLINDRICAL_GRID}
Args:
grid (:class:`~pde.grids.cylindrical.CylindricalSymGrid`):
The grid for which the opera... | a5e64b5e217200b9b5d22b20484217c2483420f2 | 23,283 |
def state(git_root):
"""Return a hash of the current state of the .git directory. Only considers
fsck verbose output and refs.
"""
if not git_root.is_dir():
return 0
rc, stdout, stderr = util.captured_run(*"git fsck --full -v".split(), cwd=git_root)
refs = "".join([ref.name + ref.value f... | c86f528dc80cdb12e88e83ce0bfdb7b393d8ede5 | 23,284 |
def search_handler(data_type_name, search_key=None, search_value=None):
"""
Purpose: Adapt PathError and QueryError to appropriate Django error types.
Input Parameters:
data_type_name - One of the searchable types 'PasswordData' or 'GroupData'.
search_key - Name of searchable field for type ... | 5c2fd5a9e3199418febe215ee10524f70a5e9af3 | 23,285 |
def render_CardsCounter_edit(self, h, comp, *args):
"""Render the title of the associated object"""
text = var.Var(self.text)
with h.div(class_='list-counter'):
with h.div(class_='cardCounter'):
with h.form(onsubmit='return false;'):
action = h.input(type='submit').action... | fca04ae6551961f1c0187d016ac06614d1a77388 | 23,286 |
def get_embedding_tids(tids, mapping):
"""Obtain token IDs based on our own tokenization, through the mapping to BERT tokens."""
mapped = []
for t in tids:
mapped += mapping[t]
return mapped | a31c9b0cf5b791590d6e30d8238cf0eb6ae2272b | 23,287 |
import requests
def extract_stream_url(ashx_url):
""" Extract real stream url from tunein stream url """
r = requests.get(ashx_url)
for l in r.text.splitlines():
if len(l) != 0:
return l | 679ca261510413f652d0953551b65db8e5c2a62e | 23,289 |
def check_for_rematch(player_id1, player_id2):
"""Checks whether the two players specified have played a match before.
Args:
player_id1: ID of first player
player_id2: ID of second player
Returns:
Bool: True if they have met before, False if they have not.
"""
query = """SELECT EXI... | 8ee0652dc089cb286021f1d54672439881e86e56 | 23,290 |
def nextrandombitsAES(cipher, bitlength):
"""
<Purpose>
generate random bits using AES-CTR
<Arguments>
bitlength: the lenght of the random string in BITS
<Side Effects>
Increases the AES counter
<Returns>
A random string with the supplied bitlength (the rightmost bits are zero if bitlength is not a mult... | ccc8a0ca2e2af595452e996d17e2d51125bf1d97 | 23,291 |
def _binparams2img(mc, param):
"""
Maximum data of all the bins
Parameters
----------
mc : dict
Molecular cloud dimensions
param : boolean
Parameter
----------
"""
if not param in sos.all_params:
raise Exception('Parameter not v... | 70224eeb3e9a6096d4ac19232f55966873078174 | 23,292 |
def arccos(x):
"""
Compute the inverse cosine of x.
Return the "principal value" (for a description of this, see
`numpy.arccos`) of the inverse cosine of `x`. For real `x` such that
`abs(x) <= 1`, this is a real number in the closed interval
:math:`[0, \\pi]`. Otherwise, the complex principle ... | 67b387ce0ee0b3b7927d97f163bd3258f87388bf | 23,293 |
def request_authentication(user, organization_id, short_code):
"""
Request for an authentication token from Safaricom's MPesa API
"""
mpesa_api_account = get_object_or_404(
MpesaAPIAccount.objects.filter(
organization__owner=user,
linked_account__identifier=short_code,
... | afc012a8160c24d44b6e8986d09ffdf61ad25554 | 23,294 |
def none_to_null(value):
""" Returns None if the specified value is null, else returns the value
"""
return "null" if value == None else value | 394b1f9620cf69c862905171f4aec96838ffc631 | 23,295 |
def get_dsd_url():
"""Returns the remote URL to the global SDMX DSD for the SDGs."""
return 'https://registry.sdmx.org/ws/public/sdmxapi/rest/datastructure/IAEG-SDGs/SDG/latest/?format=sdmx-2.1&detail=full&references=children' | 996568a92825aa7a7bf1be1db8ac2cac0828360a | 23,296 |
from jcvi.utils.orderedcollections import SortedCollection
def range_closest(ranges, b, left=True):
"""
Returns the range that's closest to the given position. Notice that the
behavior is to return ONE closest range to the left end (if left is True).
This is a SLOW method.
>>> ranges = [("1", 30,... | c32d19a4725d733855cf86bc7edd62133c42fa0f | 23,297 |
def _fill_array(data, mask=None, fill_value=None):
"""
Mask numpy array and/or fill array value without demasking.
Additionally set fill_value to value.
If data is not a MaskedArray and mask is None returns silently data.
:param mask: apply mask to array
:param fill_value: fill value
"""
... | de6190f9960a854e6cb67fe5eb61fd6f984cb147 | 23,298 |
def make_Dog(size, name):
"""Create dog entity."""
new_dog = Dog(size=size, name=str(name))
if new_dog.called() == "":
return f"The {size} dog says {new_dog.talk()}."
return f"{new_dog.called()}, the {size} dog says {new_dog.talk()}." | 4c091b09d045fc8d354beebffbb1ef12b9d63840 | 23,299 |
def one_way_mi(df, feature_list, group_column, y_var, bins):
"""
Calculates one-way mutual information group variable and a
target variable (y) given a feature list regarding.
Parameters
----------
df : pandas DataFrame
df with features used to train model, plus a target variable
... | 2b3e8336a5843a2e4bedc4f42699c233bb2118d3 | 23,301 |
import tqdm
def draw_parametric_bs_reps_mle(
mle_fun, gen_fun, data, args=(), size=1, progress_bar=False
):
"""Draw parametric bootstrap replicates of maximum likelihood estimator.
Parameters
----------
mle_fun : function
Function with call signature mle_fun(data, *args) that computes
... | 75569e4be203fe4614f55f077c5d0abff20b468e | 23,302 |
def parse_subpalette(words):
"""Turn palette entry into a list of color-to-index mappings.
For example, #AAA=2 or #AAAAAA=2 means that (170, 170, 170) will be
recognized as color 2 in that subpalette.
If no =number is specified, indices are recognized sequentially from 1.
Return a list of ((r, g, b), index) tuple... | 13d52a4b8092755cac28401356183025dac7dfb3 | 23,303 |
import json
def data_word2vec(input_file, num_labels, word2vec_model):
"""
Create the research data tokenindex based on the word2vec model file.
Return the class _Data() (includes the data tokenindex and data labels).
Args:
input_file: The research data
num_labels: The number of class... | b5330fce3c71a62896fdfdc40a20743df0a313aa | 23,304 |
def object_difference():
"""Compute the difference parts between selected shapes.
- Select two objects.
Original code from HighlightDifference.FCMacro
https://github.com/FreeCAD/FreeCAD-macros/blob/master/Utility/HighlightDifference.FCMacro
Authors = 2015 Gaël Ecorchard (Galou)
"""
global v... | b99fb61e0d85cc66ae395273f785f8f7441fd297 | 23,306 |
def diffusionkernel(sigma, N=4, returnt=False):
""" diffusionkernel(sigma, N=4, returnt=False)
A discrete analog to the continuous Gaussian kernel,
as proposed by Toni Lindeberg.
N is the tail length factor (relative to sigma).
"""
# Make sure sigma is float
sigma = floa... | 3fe620454963eec357072bd0ecd64fd66b392600 | 23,307 |
def CalculateTopologicalTorsionFingerprint(mol):
"""
#################################################################
Calculate Topological Torsion Fingerprints
Usage:
result=CalculateTopologicalTorsionFingerprint(mol)
Input: mol is a molecule object.
... | 0c646ea977ea257c523425a7f8526c16f8531e14 | 23,308 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.