content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def decorator_with_default_params(real_decorator, args, kwargs, default_args=None, default_kwargs=None):
"""
This function makes it easy to build a parametrized decorator, having a default value.
Construct your decorator like this:
>>> def decorator(*d_args, **d_kwargs): # d_args with d like decorator
... | 63e38bbdaea3483250db7281908a0053e072e866 | 3,625,500 |
import json
import copy
def get_args(request, required_args):
"""
Helper function to get arguments for an HTTP request
Currently takes args from the top level keys of a json object or
www-form-urlencoded for backwards compatability.
Returns a tuple (error, args) where if error is non-null,
the... | b44e058590945211ca410005a5be2405b4756ca4 | 3,625,501 |
def compute_ndcg_ps_parity_check(scores, labels, topk=10):
"""
adapter for pps ndcg calculating util
:param scores: raw scores
:param labels: actual labels, ordered numerically
:param topk: default is 10
:return: ndcg score as float
"""
return compute_ndcg_ps_parity_check_original_api(li... | de49eea462b7562c11fa1bfe5445578a3a739d32 | 3,625,502 |
import os
def iter_filth_clss():
"""Iterate over all of the filths that are included in this sub-package.
This is a convenience method for capturing all new Filth that are added
over time.
"""
return iter_subclasses(
os.path.dirname(os.path.abspath(__file__)),
Filth,
_is_ab... | 972c7d7d0270793883dea8860bb096173ececba5 | 3,625,503 |
import re
def create_table(request):
"""
创建餐桌
---
serializer: table.serializers.TableCreateSerializer
omit_serializer: false
responseMessages:
- code: 201
message: Created
- code: 400
message: Bad Request
- code: 401
message: Not authentic... | 25e6a62f26a26014c6f1b972628ed369f7cd14d5 | 3,625,504 |
async def test_login_status(hass, config_entry, login, alexa_setup_callback) -> bool:
"""Test the login status and spawn requests for info."""
async def request_configuration(hass, config_entry, login):
"""Request configuration steps from the user using the configurator."""
async def configura... | 3bc0153ac5987e7171ce03bc1d3029b5fefb8849 | 3,625,505 |
def transl(tx,ty=None,tz=None):
"""Returns a translation matrix (M)
:param float tx: translation along the X axis
:param float ty: translation along the Y axis
:param float tz: translation along the Z axis
"""
if ty is None:
xx = tx[0]
yy = tx[1]
zz = tx[2]
else:
... | 7d79b5db7a64966738171fbcecc4e25f63804cf3 | 3,625,506 |
import os
def pem_wrapper(method):
"""
Decorator to set REQUESTS_CA_BUNDLE.
:param method: Method to use.
:type method: function
"""
def wrapper(*args, **kwargs):
"""
Set REQUESTS_CA_BUNDLE before doing function.
"""
os.environ["REQUESTS_CA_BUNDLE"] = grab_pem(... | a7d2b3d01801416d0bec8633b9c5be18778b48f9 | 3,625,507 |
def find_most_sim(mesh, doc_id, top_n=10):
"""Find documents most similar to the given document."""
doc = mesh.doc_cache[doc_id]
results = []
doc_conc = list(map(lambda x: x[1], mesh.graph.out_edges(doc_id)))
for other_doc in mesh.doc_cache.values():
if other_doc._.id != doc_id:
... | 2eef0091bebb7dd8f4aa1a186020aafb6eefca7c | 3,625,508 |
def split_hosts_list(hosts_list, split_type, log_file=None):
"""
Return a list of multiple hosts list for the safe deployment.
:param hosts_list list: Dictionnaries instances infos(id and private IP).
:param split_type: string: The way to split the hosts list(1by1-1/3-25%-50%).
... | e30951f809700246ef142e206ca3a7a3cc89ce90 | 3,625,509 |
def load_panel_from_excel(excelfile):
"""Load a pandas Panel object by reading it from an Excel spreadsheet.
:param excelfile:
Path to Excel file.
:returns:
pandas Panel object.
"""
paneldict = {}
xl = pd.ExcelFile(excelfile)
for sheet in xl.sheet_names:
frame = pd.read_... | e4b2c7a63ed726997fca67fe0521cfe891ff1146 | 3,625,510 |
import configparser
import os
import sys
def load_config(config_file):
"""
load config
"""
config = configparser.RawConfigParser()
config.optionxform = str
config_file = real_path(config_file)
if not os.path.exists(config_file):
print("config file %s not exist!" % config_file)
... | e5de60b9c8941719edc95f40586cf2594bf55582 | 3,625,511 |
import tqdm
import requests
def tweets_request(tweets_ids):
"""
Make a request to Tweeter API
"""
df_lst = []
for batch in tqdm(tweets_ids):
url = "https://api.twitter.com/2/tweets?ids={}&&tweet.fields=created_at,entities,geo,id,public_metrics,text&user.fields=description,entities,id,... | a022504710096393403f6bf806fe2f12d20008be | 3,625,512 |
def prefix_to_netmask(in_prefix):
"""
Converts a prefix into a netmask
:param in_prefix: Cidr prefix n <= 32
:return: Netmask value
"""
prefix = int(in_prefix)
if prefix > 32 or prefix <= 0:
return None
return IPAddress(inet_ntoa(pack(">I", (0xffffffff << (32 - prefix)) & 0xffff... | 387d25ac1d568ebaa285556b5b8e99f964b3ccf9 | 3,625,513 |
import itertools
def compute_class_correspondence(predicted_domain, true_domain, verbose=True):
"""Compute the best match of two lists of labels among all permutations."""
def mismatches(domain1, domain2):
return (domain1 != domain2).sum()
def associate(domain, current_ids, new_ids):
new_... | 48e71dd115a150a26ece9ec4879b37f3a6699dce | 3,625,514 |
from typing import Union
from typing import Optional
from typing import Iterable
def l2norm(
mdata: Union[MuData, AnnData],
mod: Optional[Union[Iterable[str], str]] = None,
rep: Optional[Union[Iterable[str], str]] = None,
n_pcs: Optional[Union[Iterable[int], int]] = 0,
copy: bool = False,
) -> Opt... | 5a9130e48c2067acf7b366ff18fd5256473acb25 | 3,625,515 |
def topsis(df, weights, impacts):
"""
Validates dataframe, impacts, weights and calculates performance score.
Outputs a dataframe with "Performance Score" and "Rank" column appended.
"""
validate_data(df, weights, impacts)
ops_df = df.iloc[:,1:]
## normalized matrix
ops_df1 = ops_df ** 2
demoninat... | b8ecf2ee4e8f14a00a9a9a4408cb76f8d1bb1d3c | 3,625,516 |
def mergeGC_genecategories(GC_content_df, gene_categories):
"""merged GC content df with gene categories"""
# read in gene categories
gene_cats = pd.read_csv(gene_categories, sep="\t", header=None)
gene_cats.columns = ["AGI", "gene_type"]
# merge to limit to genes of interest
GC_content_categori... | a9b5f67d0fce5106a2c426309b896df8b2e139e1 | 3,625,517 |
def noise_lut_range(atracks, xtracks, noiseLuts):
"""
Parameters
----------
atracks: np.ndarray
1D array of atracks. lut is defined at each atrack
xtracks: list of np.ndarray
arrays of xtracks. list length is same as xtracks. each array define xtracks where lut is defined
noiseL... | 23e977eb83de87f1b24d892efc271e823b86ca05 | 3,625,518 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up this integration using UI."""
if hass.data.get(DOMAIN) is None:
hass.data.setdefault(DOMAIN, {})
_LOGGER.info(STARTUP_MESSAGE)
username = entry.data.get(CONF_USERNAME)
password = entry.data.get(CONF_PASSWORD... | 1d5e99281fdfa642c637fc8d85be86f11456c8b3 | 3,625,519 |
def view_shape(shape, view):
"""Return the shape of a view of an array
:param shape: Tuple describing shape of the array
:param view: View object -- a valid index into a numpy array, or None
Returns equivalent of np.zeros(shape)[view].shape
"""
if view is None:
return shape
shp = t... | 7b9d5321d84e5ca1f90b0531ca2d0837a90e9153 | 3,625,520 |
def get_requester_ip(request):
""" Get the IP address from a request """
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip_addr = x_forwarded_for.split(',')[0]
else:
ip_addr = request.META.get('REMOTE_ADDR')
return ip_addr | f7cde3745fdd40947a1c63068802b0d79584d21d | 3,625,521 |
import os
def get_image_text(image, whitelist=None):
"""
Uses Tesseract to extract text from a grayscale image
Args:
image: a grayscale image
whitelist: string with the characters that should be detected.
If nothing is passed, every character is whitelisted... | 86feb40e4c49c164a3a2081a25b153ab11ef677a | 3,625,522 |
from typing import Dict
def _get_info_source(context) -> Dict:
"""Returns the current information source"""
return context.transaction_data[TransactionLoops.INFORMATION_SOURCE][-1] | d3062d91c4456ed94002acaf92481bdd501a84ad | 3,625,523 |
from datetime import datetime
from typing import List
def history_snapshot(
order_book_id: str,
bar_count: int,
dt: datetime.datetime,
fields: List[str]=None,
skip_suspended: bool=True,
include_now: bool=False,
adjust_type: str="none",
adjust_orig:datetime = None,
) -> pd.DataFrame:
... | 98b30d3607add30ae8e08e394dc2b7321beb14e9 | 3,625,524 |
def determine_header_length(trf_contents: bytes) -> int:
"""Returns the header length of a TRF file
Determined through brute force reverse engineering only. Not based
upon official documentation.
Parameters
----------
trf_contents : bytes
Returns
-------
header_length : int
... | e8aa5110691e877c34f208af5bd508f0f5ec4760 | 3,625,525 |
import math
from re import DEBUG
def dThetaXZ(x, z, thetab, case=None):
"""Analytical espression of the angular deviation from Bragg
reflection over a diffractor in conventional point-to-point
focusing geometries
Parameters
==========
x, z : masked array of floats
2D meshgrid where... | f28dbb8bd19b34b415839eb705af26d1e3648d99 | 3,625,526 |
import xml
def _parse_define(define: xml.etree.ElementTree.Element) -> str:
"""Parse <define> manifest stanza.
Schema:
<define name="EXAMPLE" value="1"/>
<define name="OTHER"/>
Args:
define: XML Element for <define>.
Returns:
str with a value NAME=VALUE or NAME.
... | 00f366d7dc969e32431301cce094144e9398e471 | 3,625,527 |
import re
def _join_lines(source):
"""Remove Fortran line continuations"""
return re.sub(r'[\t ]*&[\t ]*[\r\n]+[\t ]*&[\t ]*', ' ', source) | 9caa3b6f470a96a7b473f3cce12f57d3787e91dd | 3,625,528 |
import decimal
from datetime import datetime
def fromjson(datatype, value):
"""A generic converter from json base types to python datatype.
"""
if value is None:
return None
if isinstance(datatype, atypes.ArrayType):
return fromjson_array(datatype, value)
if isinstance(datatype,... | fcbb08948f1f4cf97850c7190d860c4788177858 | 3,625,529 |
import logging
import inspect
def get_logger(
name: str = "",
log_level_console: int = logging.DEBUG,
log_level_file: int = logging.DEBUG,
log_file: str = "application.log",
) -> logging.Logger:
"""
Creates and returns a logger instance as per hoofbite style guides.
Turn off console or fi... | 4e7b0cf655c512915b249066963e85d0016bf62c | 3,625,530 |
def format(t):
"""
function to format the stopwatch time to A:BC.D
Returns: the formatted six character string
"""
A = t/600
t = t - A * 600
# this round function isn't needed when t is an integer
CD = round(t/10.0, 1)
B = ""
if CD < 10.0:
B = "0"
r... | ad6dc72f0d6b090cf4d94d27e1f0560c58a9f42d | 3,625,531 |
def var(array, axis=None, controller=None):
"""Returns the variance of all values along a particular axis (dimension).
Given an array of m tuples and n components:
* Default is to return the variance of all values in an array.
* axis=0: Return the variance values of all components and return a one
... | 696ab35d107cf758fe0fac2241a00b3167353418 | 3,625,532 |
import requests
def get_kalliope_bijlage(path, session):
"""
Perform the API-call to get a poststuk-uit bijlage.
:param path: url of the api endpoint that we want to fetch
:param session: a Kalliope session, as returned by open_kalliope_api_session()
:returns: buffer with bijlage
"""
r = ... | b2a126b8e33bab50b1e2aa122645d7a45d6dfea9 | 3,625,533 |
def validate_dice_seed(dice, min_length):
"""
Validates dice data (i.e. ensures all digits are between 1 and 6).
returns => <boolean>
dice: <string> representing list of dice rolls (e.g. "5261435236...")
"""
if len(dice) < min_length:
print("Error: You must provide at least {0} dice rol... | e63922476e66825c159ba94db5eb9e65ae906a40 | 3,625,534 |
import re
def make_vocab_from_docs(docs):
"""
Make a dictionary that contains all words from the docs. The order of words is arbitrary.
docs: iterable of documents
"""
vocab_words=set()
for doc in docs:
doc=doc.lower()
doc=re.sub(r'-',' ',doc)
doc=re.sub(r' +',' ',doc) ... | 6869bae9cbfe1b17a105feb0f3c5a06afa1ec8a0 | 3,625,535 |
def filter_by_book_style(bibtexs, book_style):
"""Returns bibtex objects of the selected book type.
Args:
bibtexs (list of core.models.Bibtex): queryset of Bibtex.
book_style (str): book style key (e.g. JOUNRAL)
Returns:
list of Bibtex objectsxs
"""
return [bib for bib in ... | ca3b46772930a6f6e28b6fc0ee4d175ee8d69c3c | 3,625,536 |
import argparse
import logging
import os
def Main():
"""The main program function.
Returns:
bool: True if successful or False if not.
"""
output_formats = frozenset(['2008', '2010', '2012', '2013', '2015'])
argument_parser = argparse.ArgumentParser(description=(
'Converts source directory (autoc... | 14e4e188c817cb7864aafaf8bac522659288b9d2 | 3,625,537 |
def _rmse(a, b, weights, axis):
"""
Root Mean Squared Error.
Parameters
----------
a : ndarray
Input array.
b : ndarray
Input array.
axis : int
The axis to apply the rmse along.
weights : ndarray
Input array.
Returns
-------
res : ndarray
... | 77e6296a08d9c8210cb3e1f05d2fc0788a77b2a0 | 3,625,538 |
import argparse
from typing import Optional
import re
def ListParamProcessorCreate(type: object = str):
"""Create a ListParamProcessor
Args:
type (object) : type of each element in list.
Returns:
ListParamProcessor (argparse.Action) : Processor which receives list arguments.
Example... | 03cb001637cdee92f0258cc252dd32238c97889a | 3,625,539 |
from typing import Counter
def cdf_function_5(cd: ChemicalDiagram):
"""exclusion: all M hydroxide"""
env_dict = cd.get_env_dict()
def neighboring_hydrogen_count(node):
return max(
Counter(env_dict[node]["nb_elements"])["H"],
Counter(env_dict[node]["nb_elements"])["D"],
... | 59e394369d5ec5d9427c79a5a15c01030886fd57 | 3,625,540 |
import os
def load_npy_to_any(path='', name='file.npy'):
"""Load .npy file.
Examples
---------
- see save_any_to_npy()
"""
file_path = os.path.join(path, name)
try:
npy = np.load(file_path).item()
except:
npy = np.load(file_path)
finally:
try:
r... | 75eaac6be30fa6d373e521d0b60e28bfcb14cb52 | 3,625,541 |
def _ns_tag(ns_id, tag):
"""Return a namespace/tag item. The ns_id is translated to a full name
space via the NS module variable.
:param ns_id: The name space ID. Translated to a namespace via the module
variable NS
:type ns_id: str
:param tag: The tag
:type str: str
"""
return... | b5cf6d00c3c4a8afe373e12e7761ba9eba9287aa | 3,625,542 |
def half_size(A, amount=50, interp='bicubic', mode=None):
""" nearest, bilinear, bicubic, cubic """
return misc.imresize(A, amount, interp, mode) | 97cca97676fd56a90330a877fca3e6b45d347541 | 3,625,543 |
def load_labels(lamost_ids, filename='lamost_labels_all_dates.csv'):
""" Extracts training labels from file.
Assumes that first row is # then label names, first col is # then
filenames, remaining values are floats and user wants all the labels.
"""
print("Loading reference labels from file %s" %fi... | 13123d919dd1d2166fe8ce39fcf8727582324c4c | 3,625,544 |
def _create_alb(
stack, name: str, vpc: ec2.Vpc, target_group: elbv2.ApplicationTargetGroup
) -> elbv2.ApplicationListener:
"""Create Application Load Balancer for integration to the service's API"""
sg = ec2.SecurityGroup(stack, f'{name}-http-public-sg', vpc=vpc)
sg.add_ingress_rule(ec2.Peer.any_ipv4()... | 208f03b313acb799690800cb3f613e3eed5d2bfc | 3,625,545 |
import json
def load_mock_response(file_name: str) -> dict:
"""
Load one of the mock responses to be used for assertion.
Args:
file_name (str): Name of the mock response JSON file to return.
"""
with open(f'{file_name}', mode='r', encoding='utf-8') as json_file:
return json.loads(j... | 8385f435bf666e5c5a4636c0f93cf90436f6aff9 | 3,625,546 |
def fixedvals_from_searchspaces(params):
"""Converts any search space hyperparams in params dict into fixed default values."""
if any(isinstance(params[hyperparam], Space) for hyperparam in params):
logger.warning("Attempting to fit model without HPO, but search space is provided. fit() will only consid... | a2a2712efd55cab49f9288d800ad15b56580c479 | 3,625,547 |
import dask
import dask.array as da
from shapely.ops import unary_union
from shapely.geometry import MultiPolygon
from itertools import product
from functools import reduce
import os
def extract_patch_information(
basename,
input_dir="./",
annotations=[],
threshold=0.5,
patch_size=224,
generat... | 49afe42f657e8a9fc78f358165f7bcc3c4e70498 | 3,625,548 |
import torch
def attributions(scores: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
"""Error analysis for antecedent scoring
## Inputs
- `scores`: `(batch_size, max_antecedent_number)`-shaped float tensor.
The first dimension might be padded with `-float("-inf")` or
approximations... | 6ce0c443d6e344bfc84565f8f901984904216194 | 3,625,549 |
def get_recommendation_and_prediction_from_text(input_text, num_feats=10):
"""
플래스크 앱에 출력할 점수와 추천을 구합니다.
:param input_text: 입력 문자열
:param num_feats: 추천으로 제시한 특성 개수
:return: 추천과 현재 점수
"""
global MODEL
feats = get_features_from_input_text(input_text)
pos_score = MODEL.predict_proba([f... | f5998c9025beabf13e32f41bee7ff43236f58cc6 | 3,625,550 |
def Ct_a(a, F=None, method='Glauert', ac=None):
"""
High thrust corrections of the form: Ct = Ct(a)
see a_Ct
"""
if F is None:
F=np.ones(a.shape)
if method=='Glauert':
Ct = 4*a*F*(1-a)
if ac is None:
ac = 1/3
Ic = a>ac
Ct[Ic] =4*a[... | 9a503e2566e78e149cbc6225edf01841c56a6a7d | 3,625,551 |
def authors_to_string(*authors):
"""
>>> author1 = {'first': 'S.', 'last': 'Miyamoto'}
>>> author2 = {'first': 'K.', 'last': 'Kondo'}
>>> author3 = {'first': 'H.', 'last': 'Tanaka'}
>>> authors_to_string(author1)
'S. Miyamoto'
>>> authors_to_string(author1, author2)
'S. Miyamoto and K. K... | 2e6f63954dd6ad9c031eecbc42a39423196baba5 | 3,625,552 |
import pandas as pd
import os
def migration(path):
"""Canadian Interprovincial Migration Data
The `Migration` data frame has 90 rows and 8 columns.
This data frame contains the following columns:
source
Province of origin (source). A factor with levels: `ALTA`,
Alberta; `BC`, British Columbia; ... | 58ca0ebae1f79d7edeed1b983f2d2e1446b86b72 | 3,625,553 |
def square_quad_f(x, a, matrix):
"""
Compute the square of the quadratic function.
Parameters
----------
x : 1-D array
Point in which the square of the quadratic is to be evaluated.
minimizer : 1-D array
Minimizer of the square of the quadratic function.
matrix : 2-D... | 1ff7aafd5d4259bfccd110d4f2880071b8fad18a | 3,625,554 |
def calc_dist_matrix(chain_one, chain_two) :
"""Returns a matrix of C-alpha distances between two chains"""
''' an example
chain_one = chain
chain_two = chain'''
answer = np.zeros((len(chain_one), len(chain_two)), np.float)
for row, residue_one in enumerate(chain_one) :
for col, residue... | 88e12fdc9511c445a998c66d82a2aa3a51545c08 | 3,625,555 |
def compare_sequence(old, new):
"""Compare two Seq or DBSeq objects."""
assert len(old) == len(new), "%i vs %i" % (len(old), len(new))
assert str(old) == str(new), "%s vs %s" % (old, new)
if isinstance(old, UnknownSeq):
assert isinstance(new, UnknownSeq)
else:
assert not isinstance(... | bee02d5c4af5ea7faf7b30dcfca2f1ee1174c47a | 3,625,556 |
import collections
import math
def split_numbers(number):
"""
Split high precision number(s) into doubles.
TODO: Consider the option of using a third number to specify shift.
Parameters
----------
number: long double
The input high precision number which is to be split
Returns
... | f058febad24caa607dfea24d2641046052b31625 | 3,625,557 |
def _get_slope(x, y):
"""
Retrun the slope of x and y data, using scipy.signal.linregress
"""
slope = linregress(x, y)
return slope | 14882f8cd604c0360c3f75c6c0c065a5344c9855 | 3,625,558 |
def get_spans(tokens, tags):
"""Convert tags to textspans."""
spans = tags_to_spans(tags)
text_spans = [
x[0] + ": " + " ".join([tokens[i]
for i in range(x[1][0], x[1][1] + 1)])
for x in spans
]
if not text_spans:
text_spans = ["None"]
return text_spans | fa23e1164e6753652a123412879760529a675626 | 3,625,559 |
def applyPCA(data_points,pcaComponents):
"""Apply PCA to a list of values
Parameters
----------
data_points : numpy.ndarray
Array of type numpy.ndarray.
pcaComponents : int
Number of components to be used in PCA analysis.
Returns
Array of t... | 65b2d4e9c29dfc8e4c7d44c83ed761c69c55127e | 3,625,560 |
import requests
import json
def delete_account(Id, token: str):
"""Deletes the account resource."""
headers = Header(token)
URL = "https://api.mail.tm/accounts/"+Id
response = requests.delete(url=URL, headers=headers.header)
if response.status_code == 204:
return response.status_code
... | 9d173aca8968af511059734d9adb2e959527bfe8 | 3,625,561 |
import json
def load_quran_obj_from_json(input_json_path):
"""
Loads the Json object containing Qur'anic data from the specific path.
"""
try:
with open(input_json_path, 'rb') as quran_json_file:
# Import json file and return Qur'an object.
return json.load(quran_json_... | 708b873bb5694472585ce05924a8262fe60de77e | 3,625,562 |
import json
import requests
def get_company_info(secret1, secret2, symbol):
"""
scrapes data (currently from alphavantage) and returns the response in json format
Arguments:
secret1: one of the API keys to scrape data
secret2: a second API key to scrape data
symbol: synonymous to... | 145230e4cefd062c14bad11cc09344354d9701f9 | 3,625,563 |
from typing import Union
def cyclic_digraph(n: int = 3, metadata: bool = False) -> Union[sparse.csr_matrix, Bunch]:
"""Cyclic graph (directed).
Parameters
----------
n : int
Number of nodes.
metadata : bool
If ``True``, return a `Bunch` object with metadata.
Returns
-----... | fae1c67831a1bc151b05ec123c5d069fb4a3da40 | 3,625,564 |
def is_wildcard_query(query):
"""
Checks if provided query selects using a * wildcard
:type query str
:rtype bool
"""
if not is_select_query(query):
return False
query = preprocess_query(query)
tokens = get_query_tokens(query)
last_token = None
for token in tokens:
... | b952850f6f5eb4fcc7155889ab7da4d6b97f7900 | 3,625,565 |
import random
def random_val(index, tune_params):
"""return a random value for a parameter"""
key = list(tune_params.keys())[index]
return random.choice(tune_params[key]) | 1cf7ba9d1a3ff651f946a8013e338d62f4fec3ab | 3,625,566 |
def read_envvar_file(name, extension):
"""
Read values from a file provided as a environment variable
``NAME_CONFIG_FILE``.
:param name: environment variable prefix to look for (without the
``_CONFIG_FILE``)
:param extension: *(unused)*
:return: a `.Configuration`, possibly `.NotConfigu... | 6717f9f442d3693878c213cbb1a6c0276d86ac3a | 3,625,567 |
def take_while(array, callback=None):
"""Creates a slice of `array` with elements taken from the beginning.
Elements are taken until the `callback` returns falsey. The
`callback` is invoked with three arguments: ``(value, index, array)``.
Args:
array (list): List to process.
callback (m... | b00f3c43c769022443d8a19af739eb7a263cca20 | 3,625,568 |
import tokenize
def build_model():
"""
Using grid search, builds the model to classify the messages
Returns:
model (): The trained model over the data
"""
# text pipeline
text_pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
... | d874cba5c06483963bd60d360ac5a972ca0d54f0 | 3,625,569 |
def extract_cutted_data_and_timesteps_from_given_indexes(dataframe_indexes, dict_instances, result_data_shape, result_timesteps_shape):
"""This function extracts data and labels in window format via corresponding indexes located in dataframe_indexes
Cut format is needed for train recurrent models. The techni... | a1c256f48f16be94e8b67c1d7d407513fdda6764 | 3,625,570 |
import subprocess
def run(magic, command, args, options):
"""
Launch Rider. Open it in the code folder.
"""
platform = detect_platform()
if platform in ['osx', 'linux']:
cmd = "rider"
elif platform == 'win':
cmd = "rider.exe"
code = magic.get_uri('code')
if code is N... | 57aed06a58967e860e55fe57093f9bc3f303baf2 | 3,625,571 |
def git_version_specifier(refspec, branch, commit, tag):
"""
Return the minimal set of specifiers that the user
input reduces to, in a dict of variables for Ansible.
:param refspec: provided refspec like 'pull/1/head'
:param branch: provided branch like 'master'
:param commit: provided commit S... | 9b723b44f3bad03a74b78a10153f4d6120202fc6 | 3,625,572 |
import socket
def receive_bytes(socket: socket.socket, buffer_size: int) -> str:
"""
Receives the specified number of bytes
from the specified socket
@param socket - the socket from which to receive
@param buffer_size - the number of bytes to receive
@return - string
"""
receiver_buffe... | bb28fa45641596a02f6e325e3a62ccc51c9f9905 | 3,625,573 |
def roulette_selection(population, pop_fitness, select_n, config):
"""
Metoda selekcji ruletki
Minimalizujemy wartośc funkcji dopasowania, co jest podejściem odwrotnym do standardowego. By moc poprawnie
zastosowac algorytm selekcji ruletki wykorzystujemy odwrocone wartosci funkcji.
W celu rozproszen... | ac187093f9b22329449fffd0773b0d408089218a | 3,625,574 |
def create_additional_front_points(pt6x, pt7x, pt14x, pt9z, pt15x, pt8z, pt14z, pt9x, pt8x, pt15z):
"""Create pot surface points to create faces--Nameing them 21(L)-22(R) to not collide with current fuel vert numbers"""
# Left point
pt20x = pt6x
pt20z = pt14z
pt20y = 0
# Right point
pt21x = ... | c6e021c4ce1bf514be80b60558e6152c571da68c | 3,625,575 |
import optparse
import textwrap
import socket
import os
import sys
import logging
def console():
""" Defines the behavior of the console web2py execution """
usage = "python web2py.py"
description = """\
web2py Web Framework startup script.
ATTENTION: unless a password is specified (-a 'passwd')... | 86e4c35296534a2c9386b2d50227202a9acf2db4 | 3,625,576 |
def concatenate_digits(a, b):
"""
Concatenate the digits of a and b
e.g. a=42, b=666 returns 42666
"""
return a * (10 ** num_digits(b)) + b | dd912bf0b567bcfcd4a6f15e908d037bed95bd5a | 3,625,577 |
def base64_decode_openflow(data):
"""Decode openflow message from base64 string to msg object"""
(msg, packet_length) = OFConnection.parse_of_packet(base64_decode(data))
return msg | 91337a570eb492e0a3ffe2b1a051994be43d3dc3 | 3,625,578 |
import matplotlib.pyplot as _plt
from scipy.integrate import solve_ivp
def coupledHarmonicOscillator( N=10000,
T=1,
ICs={ 'y1_0': 0,
'x1_0': 0.9,
'y2_0': 0,
'x2_0': -1},
args={ 'k': 1,
'kappa': 1,
'm': 1e-4},
plot=False):
"""
Solve a ... | 95626b473cd6ddc6f92374a5f24e3c66dcae25b4 | 3,625,579 |
def impvol_table(data):
"""Implied volatility for structured data.
Parameters
----------
data : pandas DataFrame, record array, or dictionary of arrays
Mandatory labels: moneyness, maturity, premium, call
Returns
-------
array
Implied volatilities
Notes
-----
'... | 955b4e2cf6a924cc7bb1602c84bd68fdfca7b070 | 3,625,580 |
import json
def deserialize(payload: str) -> Model:
"""
:raises: ParsingError
"""
try:
raw_data = json.loads(payload)
except json.decoder.JSONDecodeError:
raise ParsingError
return Model.from_dict(raw_data) | 7d9a02522f4984094ed97e27be5d705653b19ea6 | 3,625,581 |
def toPSPmatrix(psp, N_neuron, index):
"""
推定したPSPの値からPSP matrix作る
indexをもとに、行列を作成する。
args:
psp: 推定結果のndarray
return:
psp_mat: PSP行列の2次元ndarray。行は結合先、列は結合元のニューロン番号を表す。
"""
# hintom diagramにする
psp_mat = np.zeros([N_neuron, N_neuron])
# 明示的にindexが与えられているのならば
assert... | 25d89a32d5c0162c380a6dcb6038eb828f843cda | 3,625,582 |
def repeat(a, n, axis, name='repeat'):
"""repeat a tensor along the axis.
For expamle:
a=[0, 1, 2, 3], n=2, axis=0
return [0, 0, 1, 1, 2, 2, 3, 3]
"""
with tf.name_scope(name):
ndim = len(a.shape)
if axis < 0:
axis += ndim
if axis < 0 or axis >= ndim:
... | ab90dcc2e92692407c73b7f3fc002807b840462d | 3,625,583 |
def get_syn_func_caller(func_name, domain_dim=None, fidel_dim=None,
noise_type='no_noise', noise_scale=None,
to_normalise_domain=True):
""" Returns a FunctionCaller object from the function name. """
func_name = func_name.lower()
funcs = ['hartmann', 'hartmann6', 'h... | c57f7d766292c0d28cfb16556217d6a12723378e | 3,625,584 |
from typing import Dict
def make_network_arc_consistent(csp: CSP, assignment: Dict[str, int]) -> bool:
"""Implementation of the AC-3 algorithm
Parameters
----------
csp : CSP
binary CSP constraint
assignment : [type]
current assignment of variables in CSP
Returns
-------
... | f7a78ad1acac7bf663019acc9570f97876234333 | 3,625,585 |
def cuda_if_gpu(T):
"""
Move tensor to GPU, if one is available.
:param T:
:return:
"""
return T.cuda() if use_cuda else T | 3faeec3afdcacd58991954649933510e3025b16f | 3,625,586 |
def convert_archive_posts(archive_posts):
"""Convert a list of SQL post rows to the format used for display within the post archive."""
converted_archive = [];
current_year = ""
current_month = ""
for post in archive_posts:
# If the posts created year is not the current year being parsed, ... | 1572d6105c4ed217f67021ebd7c9a3f1058a7617 | 3,625,587 |
def sigmoid(x):
"""
Compute the sigmoid of x
Arguments:
x -- A scalar or numpy array of any size
Return:
s -- sigmoid(x)
"""
s = 1 / (1 + np.exp(-x))
return s | ecba59afab22911bb2795cdc8059e63e49eebfc3 | 3,625,588 |
def stream_bytes(
data: ty.Union[bytes, gen_bytes_t], *, chunk_size: int = default_chunk_size
) -> ty.Tuple[gen_bytes_t, ty.Dict[str, str]]:
"""Gets a buffered generator for streaming binary data.
Returns a buffered generator which encodes binary data as
:mimetype:`multipart/form-data` with the corresponding head... | ab5ced446f8abd6ea59289785d2f56e5d3852b1a | 3,625,589 |
def VerifyType(owner, attr, value, template, callback):
"""Checks if an attribute has correct form.
@type owner: str
@param owner: name of the object containing the attribute
@type attr: str
@param attr: name of the attribute
@type value: dict
@param value: actual value of the attribute
@type template:... | 08fdd3e26104daad74b30fadb8535831e37c28ec | 3,625,590 |
def _get_search_text(keywords):
"""Get search text."""
search_text = ' '.join(['"{}"'.format(keyword) for keyword in keywords])
search_text = search_text.replace(':', ' ')
search_text = search_text.replace('=', ' ')
return search_text | cabb5d9ca5b5faf3d9287261aab0cd01df21a680 | 3,625,591 |
def _ExtractAddrs(header_value):
"""Given a message header value, return email address found there."""
friendly_addr_pairs = list(rfc822.AddressList(header_value))
return [addr for _friendly, addr in friendly_addr_pairs] | de717d17dd016b6e6f0d8c1b512225505e44f5a2 | 3,625,592 |
def readnext(x):
"""x is a list"""
if len(x) == 0:
return False
else:
return x.pop(0) | dd27ad3c8f750ef3e6df640fd710a0469b0839d0 | 3,625,593 |
import numpy
def ceil(x1, **kwargs):
"""
Compute the ceiling of the input, element-wise.
For full documentation refer to :obj:`numpy.ceil`.
Limitations
-----------
Parameter ``x1`` is supported as :obj:`dpnp.ndarray`.
Keyword arguments ``kwargs`` are currently unsupported.
... | 6b1260b79313f737f0c7eb1fe6bca433c9501557 | 3,625,594 |
def check_pq(pq):
"""Input validation for position and orientation quaternion.
Parameters
----------
pq : array-like, shape (7,)
Position and orientation quaternion: (x, y, z, qw, qx, qy, qz)
Returns
-------
pq : array, shape (7,)
Validated position and orientation quaterni... | 7b9d2be8c42fe514d2caa9a1fc97f753ed7c7df9 | 3,625,595 |
def elevate_nurbs_curve_degree(n, p, uk, cpw, t=1):
"""
Elevate the degree of a NURBS curve *t* times.
:param int n:
:param int p:
:param ndarray uk:
:param ndarray cpw:
:param int t:
:return: New number of control points - 1, new knot vector, and the new
control points of NURB... | 04c07ad0e10a0c3d954df9fbe9dcfdc565f1b6c5 | 3,625,596 |
async def async_setup(hass, config):
"""Platform setup, do nothing."""
return True | ece370c157b4c13098d80bd4b58b3ba17be86059 | 3,625,597 |
def coding_problem_19(house_costs):
"""
A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost
while ensuring that no two neighboring houses are of the same color. Given an N by K matrix where the nth row and
kth column represents the cost to ... | f9d8b33f449d7a2f87118be3e4d894988b781476 | 3,625,598 |
def create_account(data):
"""Creates a new account for a customer identified by customer_id"""
mandatory_params = ['customer_id', 'initial_deposit']
result = check_required_params(mandatory_params, data)
if result:
return result
customer = Customer.query.filter_by(id=data['customer_id']).fi... | 7a689ab614c4b0517e4e0f1da99e80d082d8816b | 3,625,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.