content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def blur(img_array, blur_factor):
"""
Blur the image by Gaussian Blur,
and it has effects on every channel.
Recommend: int around 5.
"""
for i in range(3):
img_array[:, :, i] = ndimage.gaussian_filter(img_array[:, :, i], blur_factor)
return np.uint8(img_array) | d26184c85889b496b684ece8a3caf5bcd1f36a27 | 38,534 |
def add(a, b):
"""Adds two integers"""
return a + b | 5e91983492e1995437c2810c2d7c04cdd9180906 | 38,535 |
def usmap(scenario,mode,yyyy,save='n'):
"""
scenario: 'base', 'bakken_rail_cap', 'US_midwest_pipelines', 'US_export_ban_lifted'
mode: 'Rail', 'Pipeline'
years: 2012, 2015, 2018
save: 'y', 'n'
"""
m = Basemap(width=12000000,height=7000000,
rsphere=(6378137.00,6356752.3142),\
resolution='l',area_thresh=1000.,p... | 497a29913914639ae28bda82750b99e9cf2ef361 | 38,536 |
import re
def replace_space(string):
"""Replace all spaces in a word with `%20`."""
return re.sub(' ', '%20', string) | 9b9b400f913efb7ee1e86a87335955744c9b1a3a | 38,538 |
import numpy
def _get_sitk_pixelid(numpy_array_type):
"""Returns a SimpleITK PixelID given a numpy array."""
if not HAVE_NUMPY:
raise ImportError('Numpy not available.')
# This is a Mapping from numpy array types to sitks pixel types.
_np_sitk = {numpy.character: sitkUInt8,
n... | 1ec0f992ebc786824e02a011f26137e7298580ff | 38,539 |
import re
def port_to_string(port):
"""
Returns clear number string containing port number.
:param port: port in integer (1234) or string ("1234/tcp") representation.
:return: port number as number string ("1234")
"""
port_type = type(port)
if port_type is int:
return str(port)
... | 5d526406566c7c37af223ed8e5744ba13771f55f | 38,540 |
from typing import OrderedDict
def get_s_macd(c: analyze.CZSC, di: int = 1) -> OrderedDict:
"""获取倒数第i根K线的MACD相关信号"""
freq: Freq = c.freq
s = OrderedDict()
k1 = str(freq.value)
k2 = f"倒{di}K"
default_signals = [
Signal(k1=k1, k2=k2, k3="DIF多空", v1="其他", v2='其他', v3='其他'),
Signa... | 483e9403c74993f9fec175c9adeb3e620ddf8291 | 38,541 |
from typing import Optional
def code_block(text: str, language: Optional[str] = None) -> str:
"""Creates a code block using HTML syntax. If language is given, then the code block will be
created using Markdown syntax, but it cannot be used inside a table.
:param text: The text inside the code block
:... | 5d8b272d2a93463171e5a51beaccd8293db280dc | 38,542 |
from typing import Counter
def test_network(neural_network, input_window, input_max, test_location=None, test_class=None, submission=False):
"""Test the performance of the neural network classifier against known spikes classes."""
if submission:
# If submission flag, define the indices of submission ... | a32ea3adfd9998d107135191aff8b95767d46cf0 | 38,543 |
def not_found():
"""Page not found."""
return render_template('404.html') | 6a299f514d62c3be42a1d1e351cb6f11eaf02e8b | 38,544 |
def _histogram_binsize_weighted(a, w, start, width, n):
"""histogram_even_weighted(a, start, width, n) -> histogram
Return an histogram where the first bin counts the number of lower
outliers and the last bin the number of upper outliers. Works only with
fixed width bins.
:Stochastics:
a : a... | 2c7e26a86bb4b9cd2f8b4b845a2cbae2086c889d | 38,546 |
def merge(line):
"""
Helper function that merges a single row or column in 2048
"""
result = list(line)
head = 0
i = 1
while (i < len(result)):
if (result[i] != 0):
if (result[head] == result[i]):
result[head] += result[i]
result[i] = 0
... | 1a843ef4dc9c1b6cf20036f24288cb6166ae207b | 38,547 |
def get_transcripts_from_tree(chrom, start, stop, cds_tree):
"""Uses cds tree to btain transcript IDs from genomic coordinates
chrom: (String) Specify chrom to use for transcript search.
start: (Int) Specify start position to use for transcript search.
stop: (Int) Specify ending position to use for tra... | 51aa6f1aa97d2f977840376ea2c4bf422ff8e7a6 | 38,548 |
def parse_flattened_result_only_intent(to_parse):
"""
Parse out the belief state from the raw text.
Return an empty list if the belief state can't be parsed
Input:
- A single <str> of flattened result
e.g. 'User: Show me something else => Belief State : DA:REQUEST ...'
... | 05c7346197fa3f98f1c4194ea7d92622483d0f51 | 38,549 |
def update(*, db_session, user: DispatchUser, user_in: UserUpdate) -> DispatchUser:
"""Updates a user."""
user_data = jsonable_encoder(user)
update_data = user_in.dict(exclude={"password"}, skip_defaults=True)
for field in user_data:
if field in update_data:
setattr(user, field, upd... | 786c2ec90a432a5da20b9483b38105d246165bd7 | 38,550 |
def cost_table(tea):
"""
Return a cost table as a pandas DataFrame object.
Parameters
----------
units : iterable[Unit]
Returns
-------
table : DataFrame
"""
columns = ('Unit operation',
'Purchase cost (10^6 USD)',
'Utility cost (10^6 USD... | 17489b80ab871caf9d3029b59e9e7f30cecc2905 | 38,551 |
def embed_conformer(
mol, forcefield: str = "uff", num_conformer: int = 10, prune_tresh: float = 0.1
):
"""Use Riniker/Landrum conformer generator: https://pubs.acs.org/doi/10.1021/acs.jcim.5b00654"""
conf_generator = ConformerGenerator()
mol, _ = conf_generator.generate_conformers(mol)
return mol | 515b78ae3e2fe131a554c0878336f26e12ef7bb7 | 38,552 |
def setup_august(hass, config, api, authenticator, token_refresh_lock):
"""Set up the August component."""
authentication = None
try:
authentication = authenticator.authenticate()
except RequestException as ex:
_LOGGER.error("Unable to connect to August service: %s", str(ex))
h... | 881f35f74c33ba2ab8f606b80e277ebc626f1b4a | 38,554 |
from pathlib import Path
def get_default_prms() -> dict:
""" Extract the default ampycloud parameters from the YAML configuration file. """
yaml = YAML(typ='safe')
out = yaml.load(Path(__file__).parent / 'prms' / 'ampycloud_default_prms.yml')
return out | e2f2a057d7584ba447a02506e3a7135f3271df28 | 38,555 |
def filter_row_by_data_type_audf(col_name, data_type):
"""
Filter a column using a Spark data type as reference
:param col_name:
:param data_type:
:return:
"""
data_type = parse_python_dtypes(data_type)
return abstract_udf(col_name, is_data_type, "boolean", data_type) | 3e8bdccb85532bf70063713049dc04c04344d5fc | 38,557 |
import re
def strip_outer_dollars(value):
"""Strip surrounding dollars signs from TeX string, ignoring leading and
trailing whitespace"""
if value is None:
return '{}'
value = value.strip()
m = re.match(r'^\$(.*)\$$', value)
if m is not None:
value = m.groups()[0]
return va... | 3ad283af2835ba2bcf2c57705f2faa9495ea4e7a | 38,558 |
def process_articles(article_results_list):
"""
Fuction that processes json result into a list
:return: a list of news articles
"""
articles=[]
for item in article_results_list:
id = item.get('id')
author = item.get('author')
title = item.get('title')
description ... | 98fcddcf8a97eb7a30e2872844f3e81d7182f10b | 38,559 |
def attrgetter_atom_split(tokens):
"""Split attrgetter_atom_tokens into (attr_or_method_name, method_args_or_none_if_attr)."""
if len(tokens) == 1: # .attr
return tokens[0], None
elif len(tokens) >= 2 and tokens[1] == "(": # .method(...
if len(tokens) == 2: # .method()
return ... | 4ed19a1ea087d1b92fbe9743421ef51c560bced1 | 38,560 |
def pytest_funcarg__barcamps(request):
"""return the barcamp collection"""
config = request.getfuncargvalue("config")
return config.dbs.barcamps | 23c3aea374428ab1045c422f0b8efb72be33f5c8 | 38,561 |
import logging
import psutil
def stop_service(service_name):
"""Stops the given service by sending unix control signals to the process.
Waits for the process to stop before returning from the function.
Kills the process and any children processes if the process does not exit normally."""
servic... | 1349d8b51f1934324c166ae2bf5ee1c5e61f0c31 | 38,562 |
import json
def mark_as_read(request, app_key, user_id):
"""
mark all unread notifications for that user, as read
"""
app = Application.objects.get(secret_key=app_key)
unreads = get_unread_logentry_list(app, user_id)
for log in unreads:
logentryread = LogEntryRead(app=app, log=log, user_id=user_id)
logentry... | 0b6934b093e3b79984237cced5b3b272017a5eed | 38,563 |
def gauss(r, A, l):
"""Gaussian"""
return A * np.exp(-0.5 * (r / l) ** 2) | 46afc9c0130d562b66a95a64c66c7ffba614846a | 38,564 |
import copy
def variability(model_variability, variable_list=None):
"""Perform thermodynamic variability analysis.
Determine the minimum and maximum values for the input variables (Flux, Gibbs free
energies and metabolite concentrations). if min_growth constraint is applied then
growth is maintained ... | 6484c18f424330e15ea7b64d64d4acd4ba4a5bde | 38,565 |
def tabuleiro_inicial():
"""
tabuleiro_inicial: {} >>> tabuleiro
- Um "mirror" para a funcao "str_para_tabuleiro" com um valor especifico. Devolve sempre o mesmo tabuleiro.
"""
return str_para_tabuleiro("((-1, -1, -1), (0, 0, -1), (0, -1))") | 4ac3c124fde952d0cb94496499eff9998fb29c2f | 38,566 |
def create_processor_names_for_branch_action(processor_name, processors_to_add, seff, mapping_cache):
"""
If current seff contains a BranchAction, check if copying processor is required, if true: create corresponding
processor names and add to processors_to_add. If branch action does not require creation of... | 5b50392abf58857742a36b45dd6ef152a4844c53 | 38,567 |
def cast_to_scalar_tensor_of_dtype(t, dtype):
"""If not yet a tensor, casts it to a constant scalar tensor."""
if issubclass(type(t), ops.Tensor):
return t
return array_ops.constant(t, shape=[], dtype=dtype) | d3c85844b636d708686ab98a7b38a672ffd45009 | 38,568 |
def plot_stacked_bar_chart(data, series_labels, col_labels=None, x_label=None, y_label=None, log_scale=False):
"""
For plotting e.g. species distribution across locations.
Reference: https://stackoverflow.com/questions/44309507/stacked-bar-plot-using-matplotlib
Args:
data: a 2-dimensional numpy ... | fd125eb1495d3264e8e9ec4bec29d2387a19d4de | 38,570 |
def check_is_admin(roles):
"""Whether or not roles contains 'admin' role according to policy setting.
"""
init()
return policy.check('context_is_admin', {}, {'roles': roles}) | daecaf480916d7576c9aa0a42ea949eb2ea6e0d0 | 38,571 |
from typing import Sequence
from typing import Tuple
def merge_requirements(
requirements: Sequence[Tuple[Feature, Requirements]]
) -> Tuple[Feature, Requirements]:
"""Determine the lowest common denominator in the given requirements."""
if len(requirements) == 1:
return requirements[0][0], requir... | 2fc98482311b374d8d2d3d222a1113fab75f74e1 | 38,572 |
def resource_data_get_all(resource, data=None):
"""
Looks up resource_data by resource.id. If data is encrypted,
this method will decrypt the results.
"""
if data is None:
data = (model_query(resource.context, models.ResourceData)
.filter_by(resource_id=resource.id))
if... | f4370f7d7f9d8a7a338ba964c7958b26bf7bc849 | 38,573 |
def setig():
"""The
"""
return load(_os.path.join("npc", "setig.csv")) | 60f2c8849830b4af0512065c42203bdff05c06bc | 38,574 |
from typing import Optional
def serialize(model, data, fields=None, exc: Optional[set] = None, rels=None, root=None, exclude=None, functions=None,
**kwargs):
"""
This utility function dynamically converts Alchemy model classes into a
dict using introspective lookups. This saves on manually m... | 5a6350347ac58e12b9400137796ac701e3002447 | 38,576 |
from datetime import datetime
def interval(
value: int | datetime.timedelta | None = None,
unit: str = 's',
years: int | None = None,
quarters: int | None = None,
months: int | None = None,
weeks: int | None = None,
days: int | None = None,
hours: int | None = None,
minutes: int | ... | 11448a6e99fd547f241721cf2d4f3ea8e7469d7a | 38,577 |
def numpy_product(quat0, quat1):
"""Returns the quaternion product of q0 and q1."""
quat = np.zeros(4)
x0, y0, z0, w0 = quat0[0], quat0[1], quat0[2], quat0[3]
x1, y1, z1, w1 = quat1[0], quat1[1], quat1[2], quat1[3]
quat[0] = w0*x1 + x0*w1 + y0*z1 - z0*y1
quat[1] = w0*y1 - x0*z1 + y0*w1 + z0*x1
... | a76d25b372c7a565e4cc7f535ff0ff49130b9adb | 38,578 |
def estimate_price(mileage, theta0, theta1):
"""
Estimate price function:
"""
return theta0 + theta1 * mileage | 43ba05aacc3cb94f9bf3223f6ea8f74a569c2537 | 38,579 |
def init_axis(title = '', geometry = ''):
"""
Initializes plotting area and returns a handle for plot area
:param None:
:return: Axis object
"""
fig = plt.figure()
ax = fig.add_subplot(111)
plt.axis("equal")
mngr = plt.get_current_fig_manager()
#mngr.window.setGeometry(50,100,640, 545)
mngr.window.wm_geome... | cb31c8c9a35ba5b0bfde862bb9daac37d94a5cb4 | 38,580 |
def similar_date(anon, obj, field, val):
"""
Returns a date that is within plus/minus two years of the original date
"""
return anon.faker.date(field=field, val=val) | d9a723d3c22954797895b43d57f297330272c8cb | 38,581 |
def launch_request_handler(handler_input):
"""Handler for Skill Launch."""
return launch_request(handler_input) | e5df4bcfaa2b39adc1afd1ca9d5da1227441d8f1 | 38,582 |
def tweetDiv(tweet):
"""View text of tweet"""
res = '<div class="panel"><div class="header"><img src="'
res = res + tweet['user']['profile_image_url']
res = res + '" ><div class="text">'
res = res + tweet['user']['name']
res = res + '</div></div><p><small><small>'
res = res + tweet['created_... | c852c8bf2181636f3052dc9a94d6e435fafe216a | 38,583 |
from typing import Union
from typing import Optional
def variable_like(inputs: Union[tf.Tensor, tf.Variable],
initializer: initializers.Initializer = initializers.Zeros(),
trainable: Optional[bool] = None,
name: Optional[str] = None) -> tf.Variable:
"""Creates a... | a44a4d598f4d8fd625389262719e4bcbc727896e | 38,584 |
def make_signing_service(config, entity_id):
"""
Given configuration initiate a SigningService instance
:param config: The signing service configuration
:param entity_id: The entity identifier
:return: A SigningService instance
"""
_args = dict([(k, v) for k, v in config.items() if k in KJ... | 603d47cf08779a7d36238c5a8cd8ac3c0dacba40 | 38,585 |
from functools import reduce
def fsum(iterable):
"""fsum(iterable)
Return an accurate floating point sum of values in the iterable.
"""
return reduce(Add, iterable) | ece802387b3e2910d45ec9a520c51702216543fb | 38,586 |
def structure_sampling_values(graph, centrality, function):
""" helper function to compute the centrality values for an edge"""
cent = centrality.get_values(graph)
edges = graph.get_edges()
left_values =cent[edges[:,0]]
right_values=cent[edges[:,1]]
values = function(left_values, right_values)
... | a0608646867704dea6b1e27e4cfee8b3062ab0da | 38,587 |
from pathlib import Path
from typing import Union
def riglob(path: Path, pattern: str = None, regex: Union[str, PTYPE] = None, files=True, directories=True):
"""same as Path.rglob method, but instead match on given pattern or regex, case-insensitively, and filtering on
path type (file and / or directory
I... | 44579b2e243f66f80d368ef49f9b34057875b038 | 38,588 |
def get_all(isamAppliance, check_mode=False, force=False):
"""
Get information on all existing Transactions
"""
return isamAppliance.invoke_get("Retrieving a list of transactions", "{0}".format(module_uri),
requires_modules=requires_modules, requires_version=requires_... | 2dbc495db106e500279909cbe25d9a940272d498 | 38,589 |
def get_naive_affinities(raw, offsets):
"""get naive pixel affinities based on differences in pixel intensities."""
affinities = []
for i, off in enumerate(offsets):
rolled = np.roll(raw, tuple(-np.array(off)), (0, 1))
dist = np.linalg.norm(raw - rolled, axis=-1)
affinities.append(di... | f405b30a796539418d4f1a71bb544d502a1264dd | 38,590 |
def generallaplacian(W, G=None):
"""
Compute the general laplacian of graph.
Parameters:
- - - - -
W: float, array
weight adjacency matrix
Returns:
- - - -
L: float, sparse array
surface mesh Laplacian matrix
"""
[D, Dinv] = degree(W)
n = D.shape[0]
i... | 0af8e2a9ab71d7d6730689d282427cfe208e6564 | 38,591 |
def dummy_wrapper(fn):
"""Simple wrapper used for testing"""
def _run_callable(*args, **kwargs):
return fn(*args, **kwargs)
return _run_callable | 60d92942fd1d87b835ea05dd00baea8a71117fac | 38,592 |
def _validate_privatekey_pem(key_pem):
"""Implement private key validation.
Args:
key_pem (str): RSA PKCS#8 PEM private key (traditional OpenSSL format)
of at least 2048 bit strength.
"""
assert isinstance(key_pem, str)
# Create the cryptography package private key object and p... | d520ba02a4dce0cc47885f252a6edda2aa138023 | 38,593 |
def integrate(func,a,b):
"""
Wrapper for definite integration using scipy.integrate.quad().
"""
## calculate integral and error
val, abserr = spint.quad(func,a,b, limit=100)
## get relative error
relerr = np.nan
if val != 0:
relerr = np.abs(abserr/val)
## warning parameters
maxrel, maxabs = 1e-4, 1e-6
## e... | f16d46088f7aa9d2b575a4bf63736b65642764d4 | 38,594 |
def get_backlinks(dictionary):
"""
Returns a reversed self-mapped dictionary
@param dictionary: the forwardlinks
"""
o = dict()
for key, values in dictionary.items():
try:
for v in values:
try:
o[v].add(key)
except KeyE... | 43b28e4f177a7813ba8d8c0960d04e71ad28f83b | 38,595 |
def shift_date(date_str, n):
"""
:param date_str: 日期, 'YYYYMMDD'格式的字符串
:param n: 时间跨度, int
:return: 调整后的交易日,date
"""
tc = ts.util.dateu.trade_cal()
tc = tc[tc.isOpen == 1]
tc.set_index('calendarDate', inplace=True)
if len(tc[:date_str]) < n:
return tc.iloc[0].name
else... | 7a9a1cb500e9ac38b5a51a17b35e05d33760ea32 | 38,596 |
def mfcc_filter_banks(sampling_rate, num_fft, lowfreq=133.33, linc=200 / 3,
logsc=1.0711703, num_lin_filt=13, num_log_filt=27):
"""
Computes the triangular filterbank for MFCC computation
(used in the stFeatureExtraction function before the stMFCC function call)
This function is t... | 99f08847b24785afdacdd5769656bc0aa4a8218b | 38,597 |
def make_BinaryQuadraticModel_from_JSON(obj: dict):
"""make BinaryQuadraticModel from JSON.
Returns:
corresponding BinaryQuadraticModel type
"""
label = obj['variable_labels'][0]
if isinstance(label, list):
#convert to tuple
label = tuple(label)
mock_linear = {label:1.... | e95329fedb4ca997452a38158fa3a0d1c504f26a | 38,599 |
def compare_album(left_album: Album, right_album: Album):
"""Compare two album items and return True if they match."""
# do not match on year and albumtype as this info is often inaccurate on providers
if (
left_album.provider == right_album.provider
and left_album.item_id == right_album.ite... | fb26aaae45da19eea74399c24ba0ca58ffee484e | 38,600 |
def get_elw_ticker_name(ticker: str) -> str:
"""종목 이름 조회
Args:
ticker (str): 티커
Returns:
str: 종목명
>> get_elw_ticker_name("58F194")
KODEX 200
"""
return krx.get_etx_name(ticker) | 7d06e8589e5d37aaa2c62905ded6f6f16a89329c | 38,601 |
from typing import Callable
from typing import Tuple
def smart_implicit_midpoint_proposal_factory(vector_field: Callable, thresh: float=1e-6, max_iters: int=1000) -> Callable:
"""This proposal distribution for Hamiltonian Monte Carlo uses the smart
implicit midpoint integrator.
Args:
vector_field... | c98313a844b5398877e47f9379f9d06a2c7d9848 | 38,602 |
def get_block_symbol_data(editor, block):
"""
Gets the list of ParenthesisInfo for specific text block.
:param editor: Code editor instance
:param block: block to parse
"""
def list_symbols(editor, block, character):
"""
Retuns a list of symbols found in the block text
... | 7e6f486e209c686000c8c605ea352a1ceeab7c3c | 38,603 |
def is_windows() -> bool:
"""Determine if the current platform is Windows or not."""
return _system() == "Windows" | 05cf690ed82c63b761b1c002a97b242c9cd4063c | 38,604 |
import re
def jieba_clear_text(text):
"""
jieba分词,并使用自定义停用词表去除停用词以及长度为1的词
"""
text_n= "".join(re.findall(u"[\u4e00-\u9fa5]", text))
raw_result = "$".join(jieba.cut(text_n))
myword_list = []
#去除停用词
for myword in raw_result.split('$'):
if myword not in stopwords:
myw... | 6b9f3c8be4799cec20ecda64dd62334a851e807d | 38,605 |
def prepare_data(train_file_idxs, test_file_idxs, mel_list,
target_list):
"""
modified prepare_framewise_data() in classify.py of the baseline code
"""
X_train = []
y_train = []
for idx in train_file_idxs:
X_train.append(mel_list[idx])
y_train.append(target_list[idx])
train_idxs = np.random.perm... | f21d1a68ccc689b4d0c31351db05f9be08179c17 | 38,606 |
import zipfile
def unzip(zip_address, file_name, encoding='UTF-8'):
"""解压zip数据包
:param zip_address: 压缩包的地址
:param file_name: 压缩包里面文件的名字
:param encoding: 文件的编码
:return: 压缩包里面的数据:默认编码的UTF-8
"""
f = zipfile.ZipFile(zip_address)
fp = f.read(file_name)
lines = fp.decode(encoding)
r... | ba71fd6f923c2c410b0461796da513583c15b9aa | 38,607 |
def parse() -> dict:
"""Parse command line arguments"""
parser = ArgumentParser()
parser.add_argument('-p', '--publish', action='store_true', default=False)
return vars(parser.parse_args()) | bfc6be67dbfa5f83b07f5191d2cc67d61ca1fdf5 | 38,608 |
def gen_text (lm, seed, nletters=1000):
"""Same as generate_text, except now handles keys its not seen before"""
for k in lm.keys():
order = len(k)
if len(seed) < order:
seed = ' ' * order + seed
history = seed[-order:]
out = []
for i in range(nletters):
if history not ... | f023e05a6b02c4511a15fffa4b41ab219c185638 | 38,609 |
import math
import random
def parse(image, origin_anchors):
"""
:param image: input picture, shape like (H, W, 3)
:param origin_anchors: text like ["201,162,207,229",
"208,162,223,229",
"224,162,239,229"]
... | df30c459554f147819c9ebd2a6e25c4be1c69fac | 38,610 |
def has_name_keywords(ustring):
"""是否含有名称的标识字符"""
if (u'店名' in ustring) or \
(u'店家' in ustring) or \
(u'名字' in ustring):
return True
return False | e009e567ecf060b0b225802de523dea60ab8a02e | 38,611 |
def evaluate_df(df_true, df_subm):
"""
Score submitted dataframe wrt the true dataframe
Policy:
- If everything is perfect, 100%
- Else, we look at the F1 score. This score takes into account
whether the submitted solution contains everything it should,
while it also pen... | 8045e343db75cbaa8eedfab4692d8c1abb41dedb | 38,612 |
def process_data(input_file):
"""
Parse the complete stroke trial database and retain relevant columns.
Data cleaning phase
"""
f = open(input_file, 'r')
header = f.readline().split(",")
data = []
for line in f:
data.append(map(float, line.split(",")))
return header, np.array(data) | 557c06799b9c141fe4b1de07ce5029ec5c34bf38 | 38,613 |
from typing import List
def get_error_string_for_multiple_dbs(tables: List[Table]):
"""
Get error string for tables belonging to multiple databases.
:param tables: list of table
:return: String: error string
"""
return f'Tables should belong to same db {", ".join([f"{table.table_name}: {table.... | 216fabd7de3a68d348501f6be88ca7a94e57a188 | 38,614 |
def list_endpoints_formatted_text():
"""List all endpoints for the app."""
return flask.jsonify(
[
f"{entry['endpoint']:50s} {entry['methods']:25s} {entry['route']}"
for entry in sitemap_builder()
]
) | 38933dc33149b659d6728ce57cd8ec93538a1873 | 38,615 |
def db_with_transactions(db_2_accounts):
"""Inserts 2 accounts of 8 transactions each."""
accounts_db = select_accounts(db_2_accounts)
for account_db in accounts_db:
transactions = make_transactions(8, account_uuid=account_db.uuid)
for transaction in transactions:
db_2_accounts.t... | a111128fd954f75c9e25bc12bd1251edbd72735b | 38,616 |
def integer_schedule(x, name="undefined"):
"""Deserializes an integer schedule."""
if type(x) == dict:
if x["type"] == "constant":
return lambda i: x["value"]
elif x["type"] == "geometric":
return lambda i: x["coefficient"] * (x["base"]**i)
elif x["type"] == "list... | a9233daaf7e7ad5bef236c80dfee922f156e4ba3 | 38,617 |
def point_set_to_vtk(pse, origin=(0.0, 0.0, 0.0)):
"""Convert the point set to a :class:`pyvista.PolyData` data object.
Args:
pse (:class:`omf.pointset.PointSetElement`): The point set to convert
Return:
:class:`pyvista.PolyData`
"""
points = np.array(pse.geometry.vertices)
out... | 2742d5bd73a847b8419ca09192cadd87cba0a8d6 | 38,618 |
def find_all_primes(x=22):
"""Find all the primes up to x"""
allprimes = []
for i in range(2, x + 1):
if is_prime(i):
allprimes.append(i)
print("There are %d primes between 2 and %d" % (len(allprimes), x))
return allprimes | efb358cc6ed8d9ece8bad067ad323e7d1db2da8d | 38,619 |
def bbox_flip(bbox, width, flip_x=False):
"""
invalid value in bbox_transform if this wrong (no overlap), note index 0 and 2
also note need to save before assignment
:param bbox: [n][x1, y1, x2, y2]
:param width: cv2 (height, width, channel)
:param flip_x: will flip x1 and x2
:return: flippe... | 485496752c83e0e8424b9f67a56a861373db5fc5 | 38,621 |
def diff_pd(df1, df2):
"""Identify differences between two pandas DataFrames"""
assert (df1.columns == df2.columns).all(), \
"DataFrame column names are different"
if any(df1.dtypes != df2.dtypes):
"Data Types are different, trying to convert"
df2 = df2.astype(df1.dtypes)
if df1.... | a6a56a1735497357f6474d2f540941ff93e06b5f | 38,622 |
def is_learned_based_on_exercise_outcomes(exercise_log):
"""
:return:
"""
if exercise_log.is_empty():
return False
return (
exercise_log.last_exercise().is_too_easy() or
len(exercise_log.most_recent_correct_dates())
>= CORRECTS_IN_DISTINCT_DAYS_FOR_... | 8d4d6769c36eda61e854f6a3a4800d6b6f19f88e | 38,623 |
def greeting(): # OK
"""Beschreibung:
Dient zum besonderen aussehen
:return: gibt die eingegebenen Zeichen decodiert aus
Details:
print(b'\xe2\x95\x94'.decode('utf-8')) ergibt ╔ die linke obere Ecke
print(b'\xe2\x95\x91'.decode('utf-8')) ergibt ║
somit lassen sich "Rahmen bau... | 4800675329568bda9015782bb2f30513fb842931 | 38,624 |
def openmooc_settings(request):
"""The context processor function"""
copy_attrs = ('INSTANCE_URL',
'INSTANCE_TITLE',
'INSTANCE_NAME',
'FULL_ASKBOT_URL',
)
custom_settings = {}
for key in copy_attrs:
custom_settings[key] = g... | 04b1b3cafc14b00626e82f34280f4655d8add346 | 38,625 |
def cbpowerspectrum( transferfile,
Omegacdm ,
Omegab ,
h ,
Omeganu = 0.0,
As = None,
ns = None ,
koverh = None ):
"""
Returns the baryon- CDM matter power spectrum using the transfer function
output, usng the cosmological parameters As, ns, h, Omegab, Omegacdm
args:
As : If As is None, a default va... | b53616af621d3251e9435b1d15485eba41050f53 | 38,626 |
import logging
import json
def read_json_file_into_memory(json_file):
"""
Purpose:
Read properly formatted JSON file into memory.
Args:
json_file (String): Filename for JSON file to load (including path)
Returns:
json_object (Dictonary): Dictonary representation JSON Object
... | 70c2e6ab6180700ce77469b8afa0d0df8e0eee95 | 38,627 |
def load(trainFile, testFile):
"""
Builds various numpy arrays from the given .csv format training
and test tests.
Args:
trainFile: file name/path for the input training set
testFile: file name/path for the input test set
Returns:
y_train: labels in the training set as a nu... | 6ac7414432f4695e863c046e607fff9f8bebc19a | 38,628 |
from datetime import datetime
def process_arguments(args):
"""
This receives all arguments from calls to the public API functions so it
can validate and, if necessary, modify them. In particular, it can be used
to translate older style API calls into newer ones so as to maintain
backwards compatib... | 8a48f733bc4b3f19c4baac054cd982fa62691ba4 | 38,629 |
from typing import List
def print_trace(m,route: List[List[float]]):
"""
Save the map with route locally.
:param Location: list of latitude and longtitude of all locations on the route.
List[float] : the length is 2, while the first element is latitude
... | f351e4dcd6d73f8391efff61d28c0a7be69156a6 | 38,630 |
import ipaddress
def validateIP(ipaddressToValidate):
"""
Description: validates an IP address
Input: IP to be validated (string)
Return: True or False (boolean)
"""
try:
ipaddress.ip_address(ipaddressToValidate)
return True
except Exception:
... | 9c4ad0d8a82c7ac8ae0888be58cb7e643571cbba | 38,631 |
def calc_mean_dff(data, *args):
""" Return the mean dF/F value, and the SEM of all neurons in the data matrix.
Subtracts the offset of each cell before the computation.
"""
min_vec = np.atleast_2d(np.nanmin(data, axis=1)).T
data_no_offset = data - min_vec
return np.nanmean(data_no_offset, axis=1... | 61692a1b74e100642bc54bfd96a86ba49c88dd83 | 38,632 |
def tweet(auth, interval=1800, ignore=None):
"""
Decorator wrapping a string-returning function that returns
a function that tweets the results of calling the function
:param auth: Twitter auth object
:param interval: how long to wait between tweets
:param ignore: an optional list of Twitter API... | 15a39e7754f927d172d050a0000ca32125488d18 | 38,633 |
def to_base_10(num: str, from_base: int, key="0123456789abcdefghijklmnopqrstuvwxyz", digits=100, minus_sign="-") -> int:
"""Convert a num in from_base to base 10."""
if len(key) < from_base:
raise ValueError("Must have key length > base")
if num == key[0]:
return 0
if num[0] == minus_s... | 128127fe1f55250f46e057fa92f72d25966be626 | 38,634 |
def find_nearp(position, path):
""" Finds and returns the closes point in the path to the given position"""
x=path[0]
y=path[1]
z=path[2]
dx=position[0]-x
dy=position[1]-y
dz=position[2]-z
distance=np.sqrt(dx*dx+dy*dy+dz*dz) #caculate distance between position and every points in the pa... | e00a2fbe7002b7c43b932effe139c4a482e71f4f | 38,635 |
def unshard_env_batch(pytree):
"""Reshapes all arrays in the pytree.
`[ndev, env_s, bs, ...]` --> `[host_bs, env_s, ...]
Args:
pytree: A pytree of arrays to be sharded.
Returns:
Sharded data.
"""
def _unshard_array(array):
ndev, envs, bs = array.shape[:3]
new_shape = (envs, ndev * bs) +... | b94cd6e117ab897b4ca91a31e9777c3d2aa39dfc | 38,636 |
def guided_filter(p, i, r, e):
"""
:param p: input image
:param i: guidance image
:param r: radius
:param e: regularization
:return: filtering output q
"""
# 1
mean_I = cv2.boxFilter(i, cv2.CV_64F, (r, r))
mean_p = cv2.boxFilter(p, cv2.CV_64F, (r, r))
corr_I = cv2.boxFilter(i... | 437aa4ea3e7ac37d3b707be4844b637eeba320e4 | 38,637 |
from typing import Any
from typing import List
from typing import Tuple
from typing import Type
def _get_suffix_value_pairs(
tree_or_leaf: Any) -> List[Tuple[str, Type["Module"]]]:
"""Helper for naming pytrees of submodules."""
dict_or_leaf = serialization.to_state_dict(tree_or_leaf)
if not isinstance(dict_... | e83064b4657054ab7b33921811a55da3cc1f44bf | 38,638 |
def ffmpegFormats(select = 'E'):
"""Expects ffmpeg to output something like:
File formats:
D. = Demuxing supported
.E = Muxing supported
--
D 3dostr 3DO STR
E 3g2 3GP2 (3GPP2 file format)
E 3gp 3GP (3GPP file format)
D 4xm 4X Technologies
E a64 a... | a14da6886956cc552b9c9ddcb18bd6c71bdce18b | 38,639 |
def week_menu():
"""Меню расписания на неделю"""
kb = InlineKeyboardMarkup()
monday = InlBtn(text="Пн", callback_data="get_monday_schedule")
tuesday = InlBtn(text="Вт", callback_data="get_tuesday_schedule")
wednesday = InlBtn(text="Ср", callback_data="get_wednesday_schedule")
thursday = InlBtn(t... | aca7ebf922176c027d1d6fdb3f7f50b2bbce14b2 | 38,640 |
import posixpath
def sanitize_path(path):
"""Make path absolute with leading slash to prevent access to other data.
Preserve potential trailing slash.
"""
trailing_slash = "/" if path.endswith("/") else ""
path = posixpath.normpath(path)
new_path = "/"
for part in path.split("/"):
... | 03837bf40926341ef0982cf7543339b6168f40ff | 38,641 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.