content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main(dns_name, host_names: str):
"""Console script for route53dyn"""
host_names_list = [x.strip() for x in host_names.split(',')] or [host_names]
monitor(dns_name, host_names_list) | 5,325,600 |
def Modelo(Mags, Phi, Me, alpha):
""" Modelo para ajustar
Parameters
----------
Mags, ERR : list
Magnitudes observadas
Phi, Me, alpha : .float, .float, .float
Parámetros del modelo
Returns
--------
F : list
Valores de la función
"""
... | 5,325,601 |
def totient(n):
"""
Calculates Euler's totient
"""
count = 0
for i in range(1, n):
if (fractions.gcd(n, i) == 1):
count = count + 1
return count | 5,325,602 |
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) | 5,325,603 |
def test_required():
"""Catch dataframe missing required columns"""
d = pd.DataFrame()
with raises(ValueError) as exc:
CyclingData.validate_dataframe(d)
assert 'missing a required column' in str(exc) | 5,325,604 |
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)
:return: last inserted ro... | 5,325,605 |
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)
... | 5,325,606 |
def test_salt_and_pepper_attack_in_batch():
"""
Salt and pepper attack method unit test in batch.
"""
batch_size = 32
np.random.seed(123)
net = SimpleNet()
inputs = np.random.rand(batch_size*2, 10)
model = ModelToBeAttacked(net)
labels = np.random.randint(low=0, high=10, size=batch_... | 5,325,607 |
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"):
... | 5,325,608 |
def main():
"""Train a flow-based neural density estimator with maximum likelihood estimation"""
make_logger()
logger = logging.getLogger("tf")
np.set_printoptions(precision=3)
tf.reset_default_graph()
# load a config file whose contents are added to globals(), making them easily accessible els... | 5,325,609 |
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:
output ... | 5,325,610 |
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
dtype (dtype): output tensor dtype.
... | 5,325,611 |
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... | 5,325,612 |
def assert_within(parent, child):
"""
Assert that a path is within another.
"""
assert is_within(parent, child), f"Path {child} is not within {parent}" | 5,325,613 |
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 radar
Returns:
==... | 5,325,614 |
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 and the localstack opensearch co... | 5,325,615 |
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"
result = requests.get(url)
... | 5,325,616 |
def rgb2bgr(x):
"""
given an array representation of an RGB image, change the image
into an BGR representtaion of the image
"""
return(bgr2rgb(x)) | 5,325,617 |
def test_confirmation(test_client, login, confirmation, user):
"""
Тест процесса записи на курс: стоит защита от подмены
ссылки на редирект, категория появляющегося алерта - success
"""
response = test_client.get('/')
assert response.status_code == 200
assert b'success' in response.data
... | 5,325,618 |
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)]),
'Worldwide': [3, 4, 4, 7, ... | 5,325,619 |
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)... | 5,325,620 |
def test_symlink_missing_src(file, source):
"""
Test symlink when src is missing should still create the link
"""
target = source.parent / "symlink.lnk"
missing_source = source.parent / "missing.txt"
try:
file.symlink(str(missing_source), str(target))
assert salt.utils.path.islin... | 5,325,621 |
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 agents to d... | 5,325,622 |
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.
... | 5,325,623 |
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
GMSH dictiona... | 5,325,624 |
async def test_abort_if_no_url_available(hass, flow_handler, local_impl):
"""Check no_url_available generating authorization url."""
flow_handler.async_register_implementation(hass, local_impl)
flow = flow_handler()
flow.hass = hass
with patch.object(
local_impl, "async_generate_authorize_... | 5,325,625 |
def bisect_driver(bisect_stage, execargs):
"""Call appropriate bisection stage according to value in bisect_stage."""
bisect_dir = os.environ.get('BISECT_DIR', '/tmp/sysroot_bisect')
if bisect_stage == 'POPULATE_GOOD':
bisect_populate(execargs, bisect_dir, 'good')
elif bisect_stage == 'POPULATE_BAD':
bi... | 5,325,626 |
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.
... | 5,325,627 |
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... | 5,325,628 |
def list_open_orders(args):
"""List open orders."""
# Parameters to pass to the API
api_params = {
# TODO
}
if args.txid:
api_params.update({'txid': args.txid})
res_ol = query_api('private', 'QueryOrders', api_params, args)
else:
res = query_api('private', 'OpenO... | 5,325,629 |
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_bom=True,
normaliz... | 5,325,630 |
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 = pow(MPKa/100+1,... | 5,325,631 |
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... | 5,325,632 |
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)) | 5,325,633 |
def f(x):
""" Approximated funhction."""
return x.mm(w_target)+b_target[0] | 5,325,634 |
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 soup in soups:
if '.torrent' not in so... | 5,325,635 |
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) | 5,325,636 |
def pg_compare(target_db_url, other_db_url):
"""Compare target DB to other DB using PostgreSQL settings."""
ca, ra = _conn(target_db_url)
cb, rb = _conn(other_db_url)
params_a = PostgreSQLParameter.all_settings(ra)
params_b = PostgreSQLParameter.all_settings(rb)
host_a = ca.get_dsn_parameters(... | 5,325,637 |
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 | 5,325,638 |
def check_numeric_problems(RMs, freq_array,theta):
"""Checks for conditions that might cause numeric instability in the
time-integration, and warns the user if there might be concerns.
Specifically, checks for extreme jumps in polarization angle between
timesteps (will cause integration errorrs),
... | 5,325,639 |
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=timeoutInSeconds)
... | 5,325,640 |
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... | 5,325,641 |
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
matching.
Returns a dictionary in which each key is a name of a filed and... | 5,325,642 |
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/dbsnp.vcf.gz
step_conf... | 5,325,643 |
def plot_bboxes(bboxes, img, map_class_name=None):
"""
description: Plots bounding boxes on an image,
param:
x (np.ndarray): bounding boxes with confidence score and class id
img (np.ndarray): a image object
map_class_name: (dict): a map from class id to class name
"""
if bb... | 5,325,644 |
def data_prep_pipeline(
root,
input_filenames_or_glob,
output_filename,
data_prep_behavior,
beam_params,
suffix,
):
"""Set up beam data prep pipeline based on `data_prep_behavior`."""
if data_prep_behavior == 'many_models':
make_many_models_beam_pipeline(
root,
input_... | 5,325,645 |
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 ... | 5,325,646 |
def GetCLIInfoMgr():
""" Get the vmomi type manager """
return _gCLIInfoMgr | 5,325,647 |
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
"""
from datetime import datetime
now = datetime.now()
if type(time) is int:
diff = now - datetime.fromtim... | 5,325,648 |
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 | 5,325,649 |
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)
... | 5,325,650 |
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)... | 5,325,651 |
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... | 5,325,652 |
def schema_downgrades():
"""schema downgrade migrations go here."""
op.drop_table('installed_payloads') | 5,325,653 |
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"],
... | 5,325,654 |
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)
is consi... | 5,325,655 |
def cli_frontend(ctx, verbose, test_env):
"""
Optimus is a static site builder using Jinja2, webassets and Babel.
"""
printout = True
if verbose == 0:
verbose = 1
printout = False
# Verbosity is the inverse of logging levels
levels = [item for item in OPTIMUS_LOGGER_CONF]
... | 5,325,656 |
def group_n(gen, n):
"""
chunks data into groups of size n
:param gen: data source
:param n: group size
"""
data = []
count = 0
for row in gen:
count += 1
data.append(np.asarray(row, dtype=float))
if count == n:
yield np.asarray(data)
data ... | 5,325,657 |
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... | 5,325,658 |
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
... | 5,325,659 |
def test_listing_log_subdir_files_for_day(dispatcher, filesystem, mocker):
"""Test --list flag on log lists all files"""
mocker.patch('builtins.print')
log_base = filesystem.get_log_base_path()
day_path = log_base / '2020/01-january/2020-01-01'
day_path.mkdir(parents=True)
(day_path / 'index.md'... | 5,325,660 |
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... | 5,325,661 |
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 | 5,325,662 |
def link(srcPath, destPath):
"""create a hard link from srcPath to destPath"""
import os
return os.link(srcPath, destPath) | 5,325,663 |
def isChinese():
"""
Determine whether the current system language is Chinese
确定当前系统语言是否为 中文
"""
return SYSTEM_LANGUAGE == 'zh_CN' | 5,325,664 |
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... | 5,325,665 |
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 stored in '~/astroML_data'.
download_if_... | 5,325,666 |
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.__module__)
if getat... | 5,325,667 |
def publish_layer(layer_name: str, desc: str) -> None:
"""Upload lambda code base (as a zip file) to its associated AWS Lambda.
:param layer_name: Name of the layer.
:param desc: Description of the layer.
:raises RuntimeError: Either update layer fails
"""
with open(LAYER_ZIP, 'rb') as f_obj: ... | 5,325,668 |
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) | 5,325,669 |
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[hap]))
else:
ph... | 5,325,670 |
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 cluster id and the value is ... | 5,325,671 |
def get_valid_blendable_attribute_types():
"""
Returns a list of valid blendable attribute types in current DCC
:return: list(str)
"""
raise NotImplementedError() | 5,325,672 |
def test_mmb_predict_sample_from_extracted_vba_df():
"""
Test ensures the mmb_predict function can make a prediction from a single vba_sample.
"""
resetTest()
mmb = MaliciousMacroBot(benign_path,
malicious_path,
model_path, retain_sample_conten... | 5,325,673 |
def set_random_state(state_dict):
"""Resets the random state for experiment restore.
"""
random.setstate(state_dict["random"])
np.random.set_state(state_dict["numpy"])
torch.torch.set_rng_state(state_dict["torch"]) | 5,325,674 |
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... | 5,325,675 |
def drbd_stop(resource):
"""Stop drbd resource"""
try:
subprocess.check_call(["drbdadm", "secondary", resource],
stdout=DEVNULL)
# Allow time for demotion to be processed
time.sleep(1)
subprocess.check_call(["drbdadm", "down", resource], stdout=DEVNU... | 5,325,676 |
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... | 5,325,677 |
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
-------
... | 5,325,678 |
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)))
... | 5,325,679 |
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,
... | 5,325,680 |
def Oplus_simple(ne):
"""
"""
return ne | 5,325,681 |
def save_update(self, entity_manager = None):
"""
Saves or updates the current instance into the data source
described in the current entity manager.
This method provides the persistence layer for
creating an object.
:type entity_manager: EntityManager
:param entity_manager: The opt... | 5,325,682 |
def test_export_filename_template_1():
""" export photos using filename template """
import glob
import locale
import os
import os.path
import osxphotos
from osxphotos.__main__ import export
locale.setlocale(locale.LC_ALL, "en_US")
runner = CliRunner()
cwd = os.getcwd()
# p... | 5,325,683 |
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 = {
... | 5,325,684 |
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... | 5,325,685 |
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... | 5,325,686 |
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... | 5,325,687 |
def test_determinism_even_sequences():
"""
Check that EvenSequencesSubsetIterator deterministically visits
entries of a dataset of sequence data.
"""
rng = np.random.RandomState(123)
lengths = rng.randint(1,10, 100)
data = [['w']*l for l in lengths]
batch_size = 5
my_iter = EvenSeque... | 5,325,688 |
def on_connect(unused_client, unused_userdata, unused_flags, rc):
"""Callback for when a device connects."""
print('on_connect', mqtt.connack_string(rc))
gateway_state.connected = True | 5,325,689 |
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,... | 5,325,690 |
def download_corpus(corpus: str, saving_directory: str = None) -> None:
"""Function that downloads a corpus from AWS.
:param corpus: Name of the corpus to be loaded.
:param saving_directory: RELATIVE path to the saving folder.
"""
corpus = corpus.lower()
if not saving_directory:
saving_... | 5,325,691 |
def _remove_sources_list(ctx, config, remote):
"""
Removes /etc/yum.repos.d/{proj}.repo
:param remote: the teuthology.orchestra.remote.Remote object
:param proj: the project whose .repo needs removing
"""
builder = _get_builder_project(ctx, remote, config)
builder.remove_repo()
if remot... | 5,325,692 |
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('.', 1)
try:
... | 5,325,693 |
def rate_comments(request):
""" Render a bloom page where respondents can rate comments by others. """
return render(request, 'rate-comments.html') | 5,325,694 |
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... | 5,325,695 |
def home():
"""
List all users or add new user
"""
users = User.query.all()
return render_template('home.html', users=users) | 5,325,696 |
def test_show_avg_silhouette_scores_3d():
"""Tests the show avg silhouette scores function in K Means Clustering for 3d config."""
clu = KMeansClustering(is_3d=True)
fig = clu.show_avg_silhouette_scores(return_fig=True)
assert isinstance(fig, Figure) | 5,325,697 |
def download_projects():
"""Downloads all existing projects to disk so they can be used
for autocompletion"""
remote_projects = kimai.get_projects()
project_map = {}
for project in remote_projects:
map_key = "(%s) %s" % (project['customerName'], project['name'])
project_map[map_key... | 5,325,698 |
def test_coherency_regularized():
"""
Tests that the regularized coherency algorithm runs smoothly, using the
different csd routines and that the result is symmetrical:
"""
for method in methods:
f, c = tsa.coherency_regularized(tseries, 0.05, 1000,
... | 5,325,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.