content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import pickle
def read_img_pkl(path):
"""Real image from a pkl file.
:param path: the file path
:type path: str
:return: the image
:rtype: tuple
"""
with open(path, "rb") as file:
return pickle.load(file) | 8c7045d460e0583b02b565b818888c6b7991bc6b | 3,636,800 |
from datetime import datetime
def create_new_session(connection_handler, session_tablename="session"):
"""
Creates a new session record into the session datatable
:param connection_handler: the connection handler
:param session_tablename: the session tablename (default: session)
... | f955ed02b7292aab6d71b96a0412aa56c1212999 | 3,636,801 |
def splitData(y, tx, ratios=[0.4, 0.1]):
""" Split the dataset into train, test and validation sets """
indices = np.arange(len(y))
np.random.shuffle(indices)
splits = (np.array(ratios) * len(y)).astype(int).cumsum()
training_indices, validation_indices, test_indices = np.split(indices, splits)
... | 6cbf2907f32906779f8cf4193336cb867e66bf14 | 3,636,802 |
def conv_compare(node1, node2):
"""Compares two conv_general_dialted nodes."""
assert node1["op"] == node2["op"] == "conv_general_dilated"
params1, params2 = node1["eqn"].params, node2["eqn"].params
for k in ("window_strides", "padding", "lhs_dilation", "rhs_dilation",
"lhs_shape", "rhs_shape"):
... | cd7bad7d298e5f3faa971a9c968b3cd3a6a27812 | 3,636,803 |
import json
def render_zones(zones: dict):
"""Render the zones based on accept header"""
requested_types = bottle.request.headers.get("Accept")
if "application/json" in requested_types:
output = json.dumps(zones)
content_type = "application/json"
elif "text/html" in requested_types:
... | c4bbbef191fc6507d13bddcb4ffe1d51124a3e18 | 3,636,804 |
from typing import Union
import numbers
def less(left: Tensor, right: Union[Tensor, np.ndarray,numbers.Number],dtype=Dtype.float32,name='less'):
"""Elementwise 'less' comparison of two tensors. Result is 1 if left < right else 0.
Args:
left: left side tensor
right: right side tensor
d... | 4848bbbadf5ff789c1b406b1b53f0de4b436b155 | 3,636,805 |
def load_sample_image(image_name):
"""Load the numpy array of a single sample image
Read more in the :ref:`User Guide <sample_images>`.
Parameters
----------
image_name : {`china.jpg`, `flower.jpg`}
The name of the sample image loaded
Returns
-------
img : 3D array
The... | 7a1131f49a04343a4d8c0dbfed1099420ee906fb | 3,636,806 |
from datetime import datetime
def read_date_from_GPM(infile, radar_lat, radar_lon):
"""
Extract datetime from TRMM HDF files.
Parameters:
===========
infile: str
Satellite data filename.
radar_lat: float
Latitude of ground radar
radar_lon: float
Longitude of ground... | 1366ad4da74b5c31f88435257bbf2c6bc4662b92 | 3,636,807 |
from typing import Optional
def build_cluster_endpoint(
domain_key: DomainKey,
custom_endpoint: Optional[CustomEndpoint] = None,
engine_type: EngineType = EngineType.OpenSearch,
preferred_port: Optional[int] = None,
) -> str:
"""
Builds the cluster endpoint from and optional custom_endpoint an... | 82136d78ea6edf68fc5c8bf92653be033649bdfd | 3,636,808 |
import requests
import re
def get_community_pools():
"""Get community pool coins
Returns:
List[dict]: A list of dicts which consists of following keys:
denom, amount
"""
url = f"{BLUZELLE_PRIVATE_TESTNET_URL}:{BLUZELLE_API_PORT}/cosmos/distribution/v1beta1/community_pool"
res... | c4a78e0a953933f453f7684e66aff2b39572f593 | 3,636,809 |
def rgb2bgr(x):
"""
given an array representation of an RGB image, change the image
into an BGR representtaion of the image
"""
return(bgr2rgb(x)) | c9412018e6595513c29da54f8179ff2a7c953d07 | 3,636,810 |
from datetime import datetime
def draw_des1_plot(date, plot_A, plot_B):
"""
This function is to draw the plot of DES 1.
"""
#make up some data for the plot
df = pd.DataFrame({'date': np.array([datetime.datetime(2020, 1, i+1)
for i in range(12)]),
... | 811f4d844bafe3d35287b774f61c9337a3163d47 | 3,636,811 |
def kolmogorov_smirnov_rank_test(gene_set, gene_list, adj_corr, plot=False):
"""
Rank test used in GSEA method. It measures dispersion of genes from
gene_set over a gene_list. Every gene from gene_list has its weight
specified by adj_corr, where adj_corr are gene weights (correlation
with fenotype)... | 6c38a40d18465729e544694bd4c61547b98076ea | 3,636,812 |
import re
async def segment_url(request: schemas.UrlSegmentationRequest) -> schemas.SegmentationResponse:
""" This endpoint accept the URL of an image, and returns a SegmentationResponse.
The endpoint will try to download the image at the given URL.
Note: not all servers allow for non-browser user... | 9cdec9a06946629d35a0dc882e27a9a218075d32 | 3,636,813 |
def generate_answers(session, model, word2id, qn_uuid_data, context_token_data, qn_token_data):
"""
Given a model, and a set of (context, question) pairs, each with a unique ID,
use the model to generate an answer for each pair, and return a dictionary mapping
each unique ID to the generated answer.
... | 253e2ef5a4d03d6eccf418aae23373cd17e0c143 | 3,636,814 |
import cmath
def _add_agline_to_dict(geo, line, d={}, idx=0, mesh_size=1e-2, n_elements=0, bc=None):
"""Draw a new Air Gap line and add it to GMSH dictionary if it does not exist
Parameters
----------
geo : Model
GMSH Model objet
line : Object
Line Object
d : Dictionary
... | 07f14b04cfb9f72d8150cfd39332ba2979cd3ae4 | 3,636,815 |
def create_game(gm):
"""
Configure and create a game.
Creates a game with base settings equivalent to one of the default presets.
Allows user to customize the settings before starting the game.
Parameters
----------
gm : int
Game type to replicate:
0: Normal mode.
... | fbab4b67f5be9c8b38ad0f7cbfba68053cec8f85 | 3,636,816 |
def mat_toeplitz_2d(h, x):
"""
Constructs a Toeplitz matrix for 2D convolutions
Parameters
----------
h: list[list]
A matrix of scalar values representing the filter
x: list[list]
A matrix of scalar values representing the signal
Returns
-------
list[list]
A... | 10ca8c25eb421aa34c0caf67a63b621a93de6d32 | 3,636,817 |
import unicodedata
def fix_text_segment(
text,
*,
fix_entities='auto',
remove_terminal_escapes=True,
fix_encoding=True,
fix_latin_ligatures=True,
fix_character_width=True,
uncurl_quotes=True,
fix_line_breaks=True,
fix_surrogates=True,
remove_control_chars=True,
remove_b... | 645bbbfb2f1da94b941e51c50ef7fd682ac6e823 | 3,636,818 |
import random
def SSValues(MPKa,Rfa,r):
"""
Steady-State Values (Numerical solutions Linear)
Input: Annual MPK and Rf Rates, r (repetition index)
Output: Annual MPK and Rf Rates (Input), mu, gamma, SS Capital, SS Wage, SS Investment, Value function
"""
#Compute Parameters
MPK =... | 31e693da8878d84f6b619f0052a140bbf5307695 | 3,636,819 |
def simplify_junctures(graph, epsilon=5):
"""Simplifies clumps by replacing them with a single juncture node. For
each clump, any nodes within epsilon of the clump are deleted. Remaining
nodes are connected back to the simplified junctures appropriately."""
graph = graph.copy()
max_quadrance = epsil... | b88e63d0ac5242e93d1d061c3eeed773d9a7c6bc | 3,636,820 |
def sample_truncated_norm(clip_low, clip_high, mean, std):
"""
Given a range (a,b), returns the truncated norm
"""
a, b = (clip_low - mean) / std, (clip_high - mean) / std
return int(truncnorm.rvs(a, b, mean, std)) | de722881ce95b83239af74ba081539dfedca3363 | 3,636,821 |
def f(x):
""" Approximated funhction."""
return x.mm(w_target)+b_target[0] | 8a76358acd7d56aeb18c104198e253fda582652f | 3,636,822 |
import requests
from bs4 import BeautifulSoup
def get_urls():
""" get all sci-hub-torrent url
"""
source_url = 'http://gen.lib.rus.ec/scimag/repository_torrent/'
urls_list = []
try:
req = requests.get(source_url)
soups = BeautifulSoup(req.text, 'lxml').find_all('a')
for sou... | e14f15ebc7e39393bd614183e1eccb8fc1933359 | 3,636,823 |
def getVariablesForCookie(request=None):
""" returns dict with variables for cookie
"""
cookie_path = '/'
portalurl = absoluteURL(getSite(), request)
cookie_name = "%s%s"%('__zojax_comment_author_', md5(portalurl).hexdigest())
return dict(name=cookie_name, path=cookie_path) | ba6578036d69ceef45be1b583d8b52b699519823 | 3,636,824 |
import torch
def logsumexp(x, dim):
""" sums up log-scale values """
offset, _ = torch.max(x, dim=dim)
offset_broadcasted = offset.unsqueeze(dim)
safe_log_sum_exp = torch.log(torch.exp(x-offset_broadcasted).sum(dim=dim))
return safe_log_sum_exp + offset | 53a12a2c91c6a0cae3fcae46a860801f05480abe | 3,636,825 |
import requests
def make_request(session, verb, endpoint, data={},
timeoutInSeconds=REQUEST_TIMEOUT_IN_SECONDS,
max_retries=MAX_RETRIES):
""" Make a REST request """
try:
if verb is RequestVerb.post:
r = session.post(url=endpoint, json=data, timeout=timeou... | 5a0637a130a5f2c1c834ddfb61cccaceeeb5c3c9 | 3,636,826 |
def certificate_managed(
name, days_remaining=90, append_certs=None, managed_private_key=None, **kwargs
):
"""
Manage a Certificate
name
Path to the certificate
days_remaining : 90
Recreate the certificate if the number of days remaining on it
are less than this number. The... | 0d98b58b26bb8266bbd7817b3b8533940b7b5f33 | 3,636,827 |
from typing import Iterable
from typing import Dict
from typing import List
def _unique_field_to_col_matching(
rules: Iterable[Rule], field_to_matching_cols: Dict[str, List[int]]
) -> Dict[str, int]:
"""
Given a potential field to column matching this functions tries to determine a unique 1-to-1
matc... | b0f8f63eb86701605bc67140b91e2e67f368082a | 3,636,828 |
import yaml
import textwrap
def minimal_config():
"""Return YAML parsing result for (somatic) configuration"""
return yaml.round_trip_load(
textwrap.dedent(
r"""
static_data_config:
reference:
path: /path/to/ref.fa
dbsnp:
path: /path/to/d... | 806da8976dea510997b6fea8d264ac2e7d619e75 | 3,636,829 |
def walk(n=1000, mu=0, sigma=1, alpha=0.01, s0=NaN):
"""
Mean reverting random walk.
Returns an array of n-1 steps in the following process::
s[i] = s[i-1] + alpha*(mu-s[i-1]) + e[i]
with e ~ N(0,sigma).
The parameters are::
*n* walk length
*s0* starting value, defaults ... | c87e06b2fc046ece6acbffaf982b9258272f81a6 | 3,636,830 |
def GetCLIInfoMgr():
""" Get the vmomi type manager """
return _gCLIInfoMgr | 4adf784890a6c72cacd951f675350dd40d68c0d5 | 3,636,831 |
from datetime import datetime
def pretty_date(time=False):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
now = datetime.now()
if type(time) is int:
diff = now - datetime.fromtimes... | 28be383e0064640f3781c781db06eb3a914205dd | 3,636,832 |
def per_cpu_times():
"""Return system CPU times as a named tuple"""
ret = []
for cpu_t in cext.per_cpu_times():
user, nice, system, idle = cpu_t
item = scputimes(user, nice, system, idle)
ret.append(item)
return ret | b43152c58323fc0d74ec8297e419622485bd7505 | 3,636,833 |
def cooldown(rate, per, type=commands.BucketType.default):
"""See `commands.cooldown` docs"""
def decorator(func):
if isinstance(func, Command):
func._buckets = CooldownMapping(Cooldown(rate, per, type))
else:
func.__commands_cooldown__ = Cooldown(rate, per, type)
... | c15bc00a7b71c95086088f5d42c09de350c148d5 | 3,636,834 |
def construct_psi_k2(theta, y, X, kappa = 30):
"""
Kappa-based filter for time-varying autoregressive component, based on
Platteau (2021)
"""
#get parameter vector
T = len(y)
omega = theta[0]
alpha = theta[1]
beta = theta[2]
#Filter Volatility
psi = np.zeros(T)
#i... | e020f7f437dbba96aac15a51491496f701995693 | 3,636,835 |
def calHoahaoSancai(tian_ge, ren_ge, di_ge):
"""
三才五行吉凶计算
:return:
:param tian_ge: 天格
:param ren_ge: 人格
:param di_ge: 地格
:return:
"""
sancai = getSancaiWuxing(tian_ge) + getSancaiWuxing(ren_ge) + getSancaiWuxing(di_ge)
if sancai in g_sancai_wuxing_dict:
data = g_sancai... | ea75055c3b2c749af9b97b8271aea2242de3c85f | 3,636,836 |
def load_coeff_swarm_mio_internal(path):
""" Load internal model coefficients and other parameters
from a Swarm MIO_SHA_2* product file.
"""
with open(path, encoding="ascii") as file_in:
data = parse_swarm_mio_file(file_in)
return SparseSHCoefficientsMIO(
data["nm"], data["gh"],
... | cbc2eac4a293ecf432c2520aef741c7499a9be70 | 3,636,837 |
import os
def verify_variable_with_environment(var, var_name, env_name):
"""
Helper function that assigns a variable based on the inputs and gives relevant outputs to understand what is being
done. If the variable is defined, it will make sure that the environment variable (used by some lower-level code)
... | 24a02fed71edfdc3a5830eafec5e2d552b038831 | 3,636,838 |
def plot_trajectory_from_data(X : np.array, y : np.array, sample_n = 0, excludeY=True, ylabel=None, xlabel=None):
"""
Plots trajectory from data
sample_n: sample index
"""
fig, ax = plt.subplots()
dim = X.shape[2]
for d in range(dim):
trajectory = list(X[sample_n,:,d... | 7bff6c0da9342501e0b230e423ca5a2201757f40 | 3,636,839 |
import os
def ls(directory, create=False):
"""
List the contents of a directory, optionally creating it first.
If create is falsy and the directory does not exist, then an exception
is raised.
"""
if create and not os.path.exists(directory):
os.mkdir(directory)
onlyfiles = [f
... | 42672a4070a00ca35ede6be83d7349518bcdb255 | 3,636,840 |
async def get_prices(database, match_id):
"""Get market prices."""
query = """
select
timestamp::interval(0), extract(epoch from timestamp)::integer as timestamp_secs,
round((food + (food * .3)) * 100) as buy_food, round((wood + (wood * .3)) * 100) as buy_wood, round((stone + (st... | 3571006c37319135a3202622b73e7e2379ca93ee | 3,636,841 |
import os
def ete_database_data():
""" Return path to ete3 database json """
user = os.environ.get('HOME', '/')
fp = os.path.join(user, ".mtsv/ete_databases.json")
if not os.path.isfile(fp):
with open(fp, 'w') as outfile:
outfile.write("{}")
return fp | 19fbb418ae91dab9c3dfc94da4a27375f507780b | 3,636,842 |
import os
def link(srcPath, destPath):
"""create a hard link from srcPath to destPath"""
return os.link(srcPath, destPath) | cdcb988e953c3918e616b179f3dc5d547bb75ccf | 3,636,843 |
def isChinese():
"""
Determine whether the current system language is Chinese
确定当前系统语言是否为 中文
"""
return SYSTEM_LANGUAGE == 'zh_CN' | 8de1502c153189bc66774569fc00b2408d4ed694 | 3,636,844 |
def load_db(db):
"""
Load database as a dataframe. Extracts the zip files if necessary. The database is indexed by the user, session.
"""
if DEV_GENUINE == db or DEV_IMPOSTOR == db:
extract_dev_db()
if GENUINE == db or UNKNOWN == db:
extract_test_db()
return pd.read_csv(db, ind... | 9ebab9118d7572575fc3b82bbb02bdf1de68e6f5 | 3,636,845 |
from astropy.io import fits
import os
def fetch_rrlyrae_mags(data_home=None, download_if_missing=True):
"""Loader for RR-Lyrae data
Parameters
----------
data_home : optional, default=None
Specify another download and cache folder for the datasets. By default
all astroML data is store... | 86ec6100fe0756f34de94639c4d8444dc3895f0a | 3,636,846 |
import inspect
import sys
def is_implemented_in_notebook(cls):
"""Check if the remote class is implemented in the environments like notebook(e.g., ipython, notebook).
Args:
cls: class
"""
assert inspect.isclass(cls)
if hasattr(cls, '__module__'):
cls_module = sys.modules.get(cls.... | f017fea802fc4c98af1282ee51a51304d8ac01d9 | 3,636,847 |
def _pool_tags(hash, name):
"""Return a dict with "hidden" tags to add to the given cluster."""
return dict(__mrjob_pool_hash=hash, __mrjob_pool_name=name) | de9a9e7faa4d4f9dd3bfe05cb26790ff8ae66397 | 3,636,848 |
import sys
import example
def main():
""" Simple test of phylotree functions. """
if len(sys.argv) > 1:
phy_fn = sys.argv[1]
with open(phy_fn, 'r') as phy_in:
phy = Phylotree(phy_in, anon_haps=True)
for hap in phy.hap_var:
print(hap, ','.join(phy.hap_var... | f17dffcacc1f0bb061b58d1597e1a5ea4e4fd48f | 3,636,849 |
from pathlib import Path
def clusters_dictionary():
"""
Read the column 'label' from final_dataframe.tsv' and return the clusters as a dictionary.
If the column 'label' is not in final_dataframe.tsv', call k_means_clustering and perform
the clustering.
:return: a dictionary, where the key is the c... | 6d47865a98a4b2136fd2ec9baf346a880ee8acfb | 3,636,850 |
def normalize_medians_for_batch(expression_matrix, meta_data, **kwargs):
"""
Calculate the median UMI count per cell for each batch. Transform all batches by dividing by a size correction
factor, so that all batches have the same median UMI count (which is the median batch median UMI count)
:param expre... | a29284266cc621f0d74c8ff4931a273d71a1914a | 3,636,851 |
def apply_wet_day_frequency_correction(ds, process):
"""
Parameters
----------
ds : xr.Dataset
process : {"pre", "post"}
Returns
-------
xr.Dataset
Notes
-------
[1] A.J. Cannon, S.R. Sobie, & T.Q. Murdock, "Bias correction of GCM precipitation by quantile mapping: How wel... | e974a19d537888b866cf3117524815559c28108a | 3,636,852 |
def get_nb_build_nodes_and_entities(city, print_out=False):
"""
Returns number of building nodes and building entities in city
Parameters
----------
city : object
City object of pycity_calc
print_out : bool, optional
Print out results (default: False)
Returns
-------
... | ff3b36dcd2ca7cd0be316b573f20a6dd16bd1c1d | 3,636,853 |
def generate_pairs(agoals, props):
"""Forms all the pairs that are applicable to the current goals"""
all_pairs = []
for i in range(0, len(agoals)):
for j in range(i, len(agoals)):
goal1, goal2 = agoals[i], agoals[j]
all_pairs.extend(list(form_pairs(goal1, goal2, props)))
... | d0c7881682f057207db22cf5fb612f1a42d10c6d | 3,636,854 |
def construct_aircraft_data(args):
"""
create the set of aircraft data
:param args: parser argument class
:return: aircraft_name(string), aircraft_data(list)
"""
aircraft_name = args.aircraft_name
aircraft_data = [args.passenger_number,
args.overall_length,
... | da77ae883d67879b9c51a511f46173eb5366aead | 3,636,855 |
def Oplus_simple(ne):
"""
"""
return ne | 7476203cb99ee93dddcf9fda249f5532e908e40f | 3,636,856 |
def lin_exploit(version):
"""
The title says it all :)
"""
kernel = version
startno = 119
exploits_2_0 = {
'Segment Limit Privilege Escalation': {'min': '2.0.37', 'max': '2.0.38', 'cve': ' CVE-1999-1166', 'src': 'https://www.exploit-db.com/exploits/19419/'}
}
exploits_2_2 = {
... | 499e21091fb508b26564d06ad119d8b8ea783443 | 3,636,857 |
async def get_device(
hass: HomeAssistant,
config_entry_id: str,
device_category: str,
device_type: str,
vin: str,
):
"""Get a tesla Device for a Config Entry ID."""
entry_data = hass.data[TESLA_DOMAIN][config_entry_id]
devices = entry_data["devices"].get(device_category, [])
for d... | 8a3be6e7d1a5f69790b98d07433af1b6e6fe1b16 | 3,636,858 |
def cartesian2complex(real, imag):
"""
Calculate the complex number from the cartesian form: z = z' + i * z".
Args:
real (float|np.ndarray): The real part z' of the complex number.
imag (float|np.ndarray): The imaginary part z" of the complex number.
Returns:
z (complex|np.ndar... | 1fd44bc0accff8c9f26edfa84f4fcfafb2323728 | 3,636,859 |
def compare_maps(ra_id, method_id, type_id, method_comp=None, type_comp=None):
"""Function to compare maps / or just print off a given map"""
# Get the map
map_one = GPVal.objects.filter(my_anal_id=ra_id,
type_id=type_id,
method_id=method_id)
if meth... | 57008a0ad144974a06ae0a12de8a8133924c50e9 | 3,636,860 |
def _row_reduce_list(mat, rows, cols, one, iszerofunc, simpfunc,
normalize_last=True, normalize=True, zero_above=True,
dotprodsimp=None):
"""Row reduce a flat list representation of a matrix and return a tuple
(rref_matrix, pivot_cols, swaps) where ``rref_matrix`` is a flat list,... | a3791c303b483b158f766bacac73fd0ba63f5f18 | 3,636,861 |
import importlib
def get_action_class(class_str):
"""Imports the action class.
Args:
class_str (str): A string action class.
Returns:
Action: A child class of Action.
Raises:
ActionImportError: If the class doesn't exist.
"""
(module_name, class_name) = class_str.rsplit('.... | fdbf6f793d8a864b82f491a15c2a0268b14715b6 | 3,636,862 |
def rate_comments(request):
""" Render a bloom page where respondents can rate comments by others. """
return render(request, 'rate-comments.html') | f87777be409d79abc6c9649ec6dbe6df8cdb2ab4 | 3,636,863 |
def gaussian2d(size=(32, 32), sigma=0.5):
"""
Generate a Gaussian kernel (not normalized).
:param size: k x m size of the returned kernel
:param sigma: standard deviation of the returned Gaussian
:return: A tensor with the Gaussian kernel
"""
x, y = tf.meshgrid(tf.linspace(-1.0, 1.0, size[0... | 4a27fffe68fb031e6f47304bece9e8cfffd7224b | 3,636,864 |
def home():
"""
List all users or add new user
"""
users = User.query.all()
return render_template('home.html', users=users) | 4fb67376f51d677c544ba745680bc9fefed0ced0 | 3,636,865 |
def vgg13_bn(**kwargs):
"""
VGG 13-layer model (configuration "B") with batch normalization
"""
model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs)
return model | 3d1ac037754384cf37dbb35c1589cbbeebc3d698 | 3,636,866 |
def lr_insight_wr():
"""Return 5-fold cross validation scores r2, mae, rmse"""
steps = [('scaler', t.MyScaler(dont_scale='for_profit')),
('knn', t.KNNKeepDf())]
pipe = Pipeline(steps)
pipe.fit(X_raw)
X = pipe.transform(X_raw)
lr = LinearRegression()
lr.fit(X, y)
cv_results ... | 6d98e5e92ba10e390e96b3494a9dedb2c118df69 | 3,636,867 |
import collections
def complete_list_value(exe_context, return_type, field_asts, info, result):
"""
Complete a list value by completing each item in the list with the inner type
"""
assert isinstance(result, collections.Iterable), \
('User Error: expected iterable, but did not find one ' +
... | bc5af63592ccf6e08bf8f7da14f7852b78ec1ff0 | 3,636,868 |
def projection_ERK(rkm, dt, f, eta, deta, w0, t_final):
"""Explicit Projection Runge-Kutta method."""
rkm = rkm.__num__()
w = np.array(w0) # current value of the unknown function
t = 0 # current time
ww = np.zeros([np.size(w0), 1]) # values at each time step
ww[:,0] = w.copy()
tt = np.zeros... | 137e81c1d4764cde38985d15d04716138b90ccab | 3,636,869 |
def integer(name, value):
"""Validate that the value represents an integer
:param name: Name of the argument
:param value: A value representing an integer
:returns: The value as an int, or None if value is None
:raises: InvalidParameterValue if the value does not represent an integer
"""
if... | bcdb6e02944edc875e42a1e23209ec5002b205f6 | 3,636,870 |
def generate_Euler_Maruyama_propagators():
"""
importer function
function that creates two functions:
1. first function created is a kernel propagator (K)
2. second function returns the kernel ratio calculator
"""
# let's make the kernel propagator first: this is just a batched ULA move
... | d9bc844761e7f0d1689492ebc51159e64d64e4d9 | 3,636,871 |
def get_vtx_neighbor(vtx, faces, n=1, ordinal=False, mask=None):
"""
Get one vertex's n-ring neighbor vertices
Parameters
----------
vtx : integer
a vertex's id
faces : numpy array
the array of shape [n_triangles, 3]
n : integer
specify which ring should be got
o... | 58601345c35a96e4d0e58bfa2821dbc80f911c6c | 3,636,872 |
from typing import Tuple
from typing import Optional
from typing import List
import sys
def run_from_text(text: str, n_merges: int=sys.maxsize) -> Tuple[str, int, Optional[List[BpePerformanceStatsEntry]]]:
"""
>>> def run_and_get_merges(text: str):
... return [(m, occ) for m, occ, _ in run_from_text(t... | 4ccfe137eb5c6d08e52e35a03995034dd64ef328 | 3,636,873 |
import json
def load_line_delimited_json(filename):
"""Load data from the file that is stored as line-delimited JSON.
Parameters
----------
filename : str
Returns
-------
dict
"""
objects = []
with open(filename) as f_in:
for i, line in enumerate(f_in):
t... | f8ab6c57d565428f19c71770ca91bc2718f5709f | 3,636,874 |
def tolower(x: StringOrIter) -> StringOrIter:
"""Convert strings to lower case
Args:
x: A string or vector of strings
Returns:
Converted strings
"""
x = as_character(x)
if is_scalar(x):
return x.lower()
return Array([elem.lower() for elem in x]) | 7b35e364aac78ce6e087aeeba9970e9981cdc7f0 | 3,636,875 |
import numpy
import math
def MWA_Tile_analytic(za, az,
freq=100.0e6,
delays=None,
zenithnorm=True,
power=False,
dipheight=config.DIPOLE_HEIGHT,
dip_sep=config.DIPOLE_SEPARATION,
... | 7d1a8a2b8f02c5ae47bcc85302d670a9e3e4d413 | 3,636,876 |
import json
def traindata():
"""Generate Plots in the traindata page.
Args:
None
Returns:
render_template(render_template): Render template for the plots
"""
# read data and create visuals
df_features = read_data_csv("./data/features... | 513312785a8ba7621693c05606e457b535b39c90 | 3,636,877 |
def import_file(file_path, title, source_mime_type, dest_mime_type):
"""Imports a file with conversion to the native Google document format.
Expects the env var GOOGLE_APPLICATION_CREDENTIALS to be set for
credentials.
Args:
path (str): Path to file to import
title(str): The title of th... | 386994c49895accb1433879b43d0e7a9e0b37beb | 3,636,878 |
def test_extract_requested_slot_from_text_with_not_intent():
"""Test extraction of a slot value from text with certain intent
"""
# noinspection PyAbstractClass
class CustomFormAction(FormAction):
def slot_mappings(self):
return {"some_slot": self.from_text(not_intent='some_intent')}... | a96deace8c9d291c3b67a13c250e84a519012fa7 | 3,636,879 |
import os
def _get_info_file_path():
"""Get path to info file for the current process.
As with `_get_info_dir`, the info directory will be created if it does
not exist.
"""
return os.path.join(_get_info_dir(), "pid-%d.info" % os.getpid()) | e551a02bf1cca73bfde996cf77ecb6277c43e714 | 3,636,880 |
def create_generic_io_object(ioclass, filename=None, directory=None,
return_path=False, clean=False):
"""
Create an io object in a generic way that can work with both
file-based and directory-based io objects
If filename is None, create a filename.
If return_path is Tr... | 1f10537695f507f9ea0c9eec6834efd7c0d6d6fe | 3,636,881 |
def select_channels(img_RGB):
"""
Returns the R' and V* channels for a skin lesion image.
Args:
img_RGB (np.array): The RGB image of the skin lesion
"""
img_RGB_norm = img_RGB / 255.0
img_r_norm = img_RGB_norm[..., 0] / (
img_RGB_norm[..., 0] + img_RGB_norm[..., 1] + img_RGB_nor... | 7daacf660c30702b8cbbe6da5da97937d11c0c0a | 3,636,882 |
def upper_case(string):
"""
Returns its argument in upper case.
:param string: str
:return: str
"""
return string.upper() | bbf3fc8b856d466ec73229145443566d85a3457a | 3,636,883 |
import json
def repositoryDefinitions():
"""
Load repositoryDefinitions page
"""
i_d = wmc.repository.get_definition_details()
p_d = json.dumps(i_d, indent=4) + " "
msg = Markup(JSONtoHTML(p_d))
return render_template('repositoryDefinitions.html', data=msg) | a4325e962a81421b4a35c4919d1fa637ae267a0a | 3,636,884 |
def available_adapter_names():
"""Return a string list of the available adapters."""
return [str(adp.name) for adp in plugins.ActiveManifest().adapters] | b5674e901de02bc9e2b94cb9fa8b0885b197cb21 | 3,636,885 |
import argparse
import os
def parse_user_arguments(*args, **kwds):
"""
Parses the arguments of the program
"""
parser = argparse.ArgumentParser(
description = "Generate the profiles of the input drug",
epilog = "@oliva's lab 2017")
parser.add_argument('-d','--drug_name',dest=... | 5a8fa5ec8c7e9b974be5eee1585b6842a5c7aab5 | 3,636,886 |
import os
def createNewLetterSession(letter):
"""
# Take letter and create next session folder (session id is current max_id + 1)
# Return path to session directory
"""
# Search for last training folder
path = "gestures_database/"+letter+"/"
last = -1
for r,d,f in os.walk(path):
for folder in d:
last ... | fc6da33f4a815db30c09bf6477b9707323a6da05 | 3,636,887 |
def count_sort(seq):
""" perform count sort and return sorted sequence without
affecting the original
"""
counts = defaultdict(list)
for elem in seq:
counts[elem].append(elem)
result = []
for i in range(min(seq), max(seq)+1):
result.extend(counts[i])
return result | a035592a9a258f138f0064f4f733f405ee2b75d0 | 3,636,888 |
def detect_overrides(cls, obj):
"""
For each active plugin, check if it wield a packet hook. If it does, add
make a not of it. Hand back all hooks for a specific packet type when done.
"""
res = set()
for key, value in cls.__dict__.items():
if isinstance(value, classmethod):
... | 55b7299c6239050dd94e8e4ffc3484f987c60125 | 3,636,889 |
def morningCalls():
"""localhost:8080/morningcalls"""
session = APIRequest.WebServiceSafra()
return session.listMorningCalls() | 181d491ddd9549ff8cb3b15c66201ee6b9a88249 | 3,636,890 |
def resize_image(img, h, w):
""" resize image """
image = cv2.resize(img, (w, h), interpolation=cv2.INTER_NEAREST)
return image | f4e1c8f24abb44714d3894a255b32d50e72e09b5 | 3,636,891 |
from typing import Dict
def _parse_pars(pars) -> Dict:
"""
Takes dictionary of parameters, converting values to required type
and providing defaults for missing values.
Args:
pars: Parameters dictionary.
Returns:
Dictionary of converted (and optionally validated) parameters.
... | cda13c228f7764718ca0becceae3d721ba111eda | 3,636,892 |
def _get_base_class_names_of_parent_and_child_from_edge(schema_graph, current_location):
"""Return the base class names of a location and its parent from last edge information."""
edge_direction, edge_name = _get_last_edge_direction_and_name_to_location(current_location)
edge_element = schema_graph.get_edge... | 7860208cb305745f5c62aec664acd60a57715f48 | 3,636,893 |
from typing import Callable
def projection(
v: GridVariableVector,
solve: Callable = solve_fast_diag,
) -> GridVariableVector:
"""Apply pressure projection to make a velocity field divergence free."""
grid = grids.consistent_grid(*v)
pressure_bc = boundaries.get_pressure_bc_from_velocity(v)
q0 = grid... | e20ff776603be0faef2d63e29c58f99c255ec19d | 3,636,894 |
def a07_curve_function(curve: CustomCurve):
"""Computes the embedding degree (with respect to the generator order) and its complement"""
q = curve.q()
if q.nbits()>300:
return {"embedding_degree_complement":None,"complement_bit_length":None}
l = curve.order()
embedding_degree = curve.embeddi... | 1f06c9c4425e7d24241d425cfbd9a764d6589963 | 3,636,895 |
def _horizontal_metrics_from_coordinates(xcoord,ycoord):
"""Return horizontal scale factors computed from arrays of projection
coordinates.
Parameters
----------
xcoord : xarray dataarray
array of x_coordinate used to build the grid metrics.
either plane_x_coord... | a366c37172bed098607e4c5c7194812d3d82141f | 3,636,896 |
def ultosc(
df,
high,
low,
close,
ultosc,
time_period_1=7,
time_period_2=14,
time_period_3=28,
):
"""
The Ultimate Oscillator (ULTOSC) by Larry Williams is a momentum oscillator
that incorporates three different time periods to improve the overbought and
oversold signals.... | d6f69906bb09e3a7075339cd4a6554d5336f6caa | 3,636,897 |
def mating(child_id, parent1, parent2, gt_matrix):
"""
Given the name of a child and two parents + the genotype matrices, mate them
"""
child_gen = phase_parents(parent1, parent2, gt_matrix)
parent1.add_children(child_id)
parent2.add_children(child_id)
child = Person(child_id)
child.se... | 9962eb24ff175b0b2d77a787dbc50a342ed4a202 | 3,636,898 |
def _tmp(
generator_reconstructed_encoded_fake_data,
encoded_random_latent_vectors,
real_data,
encoded_real_data,
generator_reconstructed_encoded_real_data,
alpha=0.7,
scope="anomaly_score",
add_summaries=False):
"""anomaly score.
See https://arx... | 181bd45d23e14585072917d2ad707f13f13b7d4f | 3,636,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.