content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
def _generate_random_pos_def_tri_diag(
batch_shape: Tuple, outer_dim: int, inner_dim: int, has_sub_diag: bool
) -> Tuple[np.ndarray, SymmetricBlockTriDiagonal]:
"""
Create a random tri-diagonal symmetric positive definite matrix.
This works by creating a lower triangular tri-... | d3f59a2fa58b92ae39a9a52e72b77dd5fdff89a2 | 47,500 |
import json
def get_deployment(*, name, namespace, k8s_client, raw=True):
"""Get a Deployment resource.
Parameters
----------
namespace : `str`
The Kubernetes namespace where the Strimzi Kafka cluster operates.
name : `str`
The name of the Deployment.
k8s_client
A Kube... | c1fd2cdc74b6713f993a84727bbf7398a0351070 | 47,501 |
def algorithm2(f,r1,r2,x0,y0,L = (1,1),maxit = [1000,1000],tol = [1e-3,1e-3],warmstart=True,):
"""
Variable projection method for problems of the form
min_{x,y} f(x,y) + r_1(x) + r_2(y)
with $f$ Lipschitz smooth and r_1, r_2 are convex and proxible.
Input
-----
f - function retu... | fcac0a26031db8536f91b4432faaeb2e125bfaed | 47,502 |
def PopularTagsPerLang(df, lang, top_k = 10):
"""
Function:
Get top k tags with largest number of fanworks by media and in selected language.
Input:
- df: pandas.DataFrame.
- lang: list[str], languages to include.
- top_k: int, number of top tags to include.
Output:
- df_top: pandas.... | c5e0d4e459924292880b3eaee770412083ea59e7 | 47,503 |
def hist_match(source, template):
"""
Adjust the pixel values of a grayscale image such that its histogram
matches that of a target image
Arguments:
-----------
source: np.ndarray
Image to transform; the histogram is computed over the flattened
array
templat... | 9dfff0344bb1dbb81a9e19833a9296c31f19187f | 47,504 |
def design_matrix(x):
"""
Build the design matrix for linear regression for
a given array of x-values.
This creates a (N, 2) matrix, where the first column are the
x values and the second contains all 1.
"""
X = np.empty((len(x), 2), dtype=x.dtype)
X[:, 0] = x
X[:, 1] = 1
retur... | 726662f47802084d1e04bced45d5625568be8647 | 47,505 |
def r_min_KimKim(T_sat, sigma, h_fg, rho, deltaT_sub):
""" minimum droplet radius """
r_min = 2*T_sat*sigma / (h_fg * rho * deltaT_sub)
return r_min | c2e9a7e0741f6d663a73ff04eb32939732c34f36 | 47,506 |
def get_prefix(given_name):
"""
Assuming the given name adheres to the naming convention of crab this
will extract the prefix element of the name.
:param given_name: Name to extract from
:type given_name: str or pm.nt.DependNode
:return: str
"""
return str(given_name).split(':')[-1].sp... | 192c4331c511b936d0eb320f6453ed61d0064ef9 | 47,507 |
def get_predicates(): # noqa: E501
"""get_predicates
Get a list of predicates used in statements issued by the knowledge source # noqa: E501
:rtype: List[BeaconPredicate]
"""
df = dh.load_edges()
d = df.groupby(['edgelabel', 'relation']).size().to_dict()
predicates = []
for (edge_l... | d174ae8553ba4b279b711e116ae6d574bddfe7b2 | 47,508 |
def cat_transform(train_var: np.array, test_var: np.array):
"""remap number to categorical variable and save dictionaries.
test_var is then mapped according to the train_var"""
dict_list = []
train_var_shape = train_var.shape
test_var_shape = test_var.shape
if len(train_var.shape)==1:
tr... | 87cf094a700676e3d67e5d56d8059e902cbb6196 | 47,509 |
def cov(data):
"""
Covariance matrix
note: specifically for mean-centered data
note: numpy's `cov` uses N-1 as normalization
"""
return _np.dot(data.T, data) / data.shape[0] | 12ffb86e30237a07b3bcf213c1677793de0e4bf7 | 47,510 |
def dynesty_loglike_bma(cube, interpolator):
"""Dynesty log likelihood wrapper for BMA."""
theta = build_params(cube, coordinator, fixed, use_norm)
return log_likelihood(theta, star, interpolator, use_norm, av_law) | a302773cafca43946d995fe33b6b20c0d5bc51dd | 47,511 |
def get_graph_from_workflow(workflow):
""" :type workflow: dart.model.workflow.Workflow """
entity = GraphEntity('workflow', workflow.id, workflow.data.name, workflow.data.state)
return {'results': graph_entity_service().get_entity_graph(entity).to_dict()} | 8a4ef74228ad4563a3cacefe4469e9136c72a1d9 | 47,512 |
from sys import exc_info
from datetime import datetime
def update(api, bus_indices, default_line_frequency, period, use_trace, trace_path, state_queue):
"""Update the state of the sensor.
Parameters
----------
api : GridAPI
API to use to query the grid for the state.
bus_indi... | b6dac8591ab9d1aa516b3271bbb77cc56f06cbea | 47,513 |
import sys
def setup_pipeline(config):
"""
Given a configuration from QLF, this sets up a pipeline [pa,qa] and also returns a
conversion dictionary from the configuration dictionary so that Pipeline steps (PA) can
take them. This is required for runpipeline.
"""
qlog=qllogger.QLLogger()
lo... | 2902b3da12087af5a4da20738e9da83e352cd425 | 47,514 |
import os
def get_module(full_name, file_path):
"""Python function from Mochi.
Compiles a Mochi file to Python bytecode and returns the
Python module.
"""
name = full_name.split('.')[-1]
base_path = os.path.dirname(file_path)
mochi_name = os.path.join(base_path, name + '.mochi')
py_na... | 8cff9cde6a35bb7d3f9526b5488cb45782f435c4 | 47,515 |
def justice_league_super(superhero):
"""Fetch the Justice League character whose super name matches
the path variable supplied by the user, or a 404 if not."""
canonicalized = superhero.replace(" ", "").lower()
for character in justice_league_members:
search_term = character["superhero"].rep... | 560ea906140b0496528f58dbbdb759b5d40c4a01 | 47,516 |
from datetime import datetime
import time
def store(username, group, usersList):
"""Store the scraped users list in a file saved into a folder that has the
same name as the username."""
date = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%dT%H:%M:%S')
path = '{}/{}{}.pkl'.format(_base_director... | c22b143183985c373109eb1b7237292fe3f652c7 | 47,517 |
import re
import zipfile
def northwind(table_name):
"""
Yield a stream of "records" as dictionaries, with certain adjustments.
So it turns out my source of NorthWind data has a bizarre nonstandard format:
Embedded commas are those followed by whitespace!
The usual csv module doesn't handle that by default and ... | 303fa89d19e12c17ab14cc0591a4182ce28f489c | 47,518 |
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
def get_rbf_svm_classifier(X_train, y_train, random_state=None, cv_folds=5):
"""
A classifier that performs classification based on support vector machine.
X - a (n_training_examples, n_featu... | 12681ff67b4ea4422a9d586f72190abbfb59e564 | 47,519 |
import nipype.interfaces.utility as niu
import nipype.pipeline.engine as pe
from nipype.interfaces.fsl.epi import Eddy
from clinica.utils.dwi import generate_acq_file, generate_index_file
def eddy_fsl_pipeline(low_bval, use_cuda, initrand, name="eddy_fsl"):
"""Use FSL eddy for head motion correction and eddy curr... | 85539355d60efc49e68217bc0eb6b9dfff934cba | 47,520 |
def calc_z1_from_Vs30(Vs30_in_meter_per_sec):
"""
Calculate z1 (basin depth) from Vs30. The correlation used here is
z1 = 140.511 * exp(-0.00303 * Vs30), where the units of z1 and Vs30 are
both SI units. This formula is documented in Section 2.5 (page 30) of the
following PhD thesis:
Shi, Ji... | b1fe0d4b28e85308a74ee574447d85825a730d57 | 47,521 |
import copy
def rand_replace(rep_fun):
"""
Wrapper of contrastive sample generate functions.
"""
def gen_neg_subwords(example, tokenizer, cont_ent_idx, auxiliary_json=None, max_seq_len=128):
cont_example = copy.deepcopy(example)
entities = cont_example.entities
if not entitie... | f044c444a774ada638691a006c649d10a0e64e92 | 47,522 |
def locate_ellipsoid(frame, spacing=1, rad_range=None, maxfit_size=2,
spline_order=3, threshold=0.1):
"""Locates an ellipsoid in a 3D image and returns center coordinates and
radii along x, y, z. The function fully analyzes the vesicle.
Parameters
----------
image3d: 3D ndarray... | eea3ee01c137c051e729330d9cd78d94519bfa4e | 47,523 |
def _hist_bin_sturges(*input_data):
"""
Sturges histogram bin estimator.
A very simplistic estimator based on the assumption of normality of
the data. This estimator has poor performance for non-normal data,
which becomes especially obvious for large data sets. The estimate
depends only on size ... | 2d952357d8ae96ac89ded17673d677ef2ff8b953 | 47,524 |
def dialog_response(attributes, endsession):
""" create a simple json response with card """
return {
'version': '1.0',
'sessionAttributes': attributes,
'response':{
'directives': [
{
'type': 'Dialog.Delegate'
}
... | dc652f754f8c5eed46e6bf299e68fb6c30244436 | 47,525 |
import torch
import os
def infer_optimal_calib(input_files, model_wrappers, image_shape, half):
"""
Process a single input file to produce and save visualization
Parameters
----------
input_file : list (number of cameras) of lists (number of files) of str
Image file
output_file : str
... | 150aeea8ed2905624e4c554f40084df31f315c46 | 47,526 |
import os
from cPickle import UnpickleableError as unpick_error
import cPickle as pickle
from cPickle import PicklingError as unpick_error_2
import pickle
from pickle import UnpicklingError as unpick_error
from pickle import PicklingError as unpick_error_2
def canpickle(obj):
"""
Determine if object can be pi... | 84bee9f460cc752d71af03155334d6d491bb5a82 | 47,527 |
import argparse
def create_parser():
"""
Read in the cmd line arguments 'data' arg is the data set
which shall be used.
"""
parser = argparse.ArgumentParser()
parser.add_argument("data")
args = parser.parse_args()
return args | 9074961ca858022fb43c8a261c891cde73aa3e92 | 47,528 |
import requests
import sys
import json
def getMetadata(path, filename):
"""
Get the metadata for a specified file.
Returns a JSON as follows:
{
hits: [
{metadata for file}
...
]
}
This will usually only be one hit.
"""
token = authenticate()
url = "http://{}:{}/query_metadata?project=\"{}\"&source=... | eb808b943908576d58885fe1d2a080aaffbf1dec | 47,529 |
import concurrent
import json
def api_cert_info():
""" Return a JSON with the certificate info """
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
cert_list = []
for hostinfo in executor.map(lambda x:
get_certificate(x[0], int(x[1]))... | cb6c0ce9cc162aca59df8d27031e2fe850e923d6 | 47,530 |
def mbed_os_support():
"""! Function used to determine if host OS is supported by mbed-lstools
@return Returns None if host OS is not supported else return OS short name
@details This function should be ported for new OS support
"""
result = None
os_info = mbed_lstools_os_info()
if (os_inf... | f982ff17caf3345ded984607e856a26e15222172 | 47,531 |
def sub_field(k, v):
"""Return a nested dictionary with field keys k and value v."""
res = {}
field_d = res
fields = k.split('.')
for f in fields[:-1]:
field_d[f] = {}
field_d = field_d[f]
field_d[fields[-1]] = v
return res | 193869fdfaca84172c71ca935f5fdb312682b19e | 47,532 |
def mkkekz(u_t, v_t, wap, utt, vtt, p_l, lat, nlat, ntp, nlev):
"""Compute the zonal mean - eddy KE conversions from u and v.
Arguments:
- u_t: a 3D zonal velocity field;
- v_t: a 3D meridional velocity field;
- wap: a 3D vertical velocity field;
- utt: a climatological mean 3D zonal velocity f... | fb4bbec756b00a969f99b65b81e111842bc2d110 | 47,533 |
def sieve5(n):
"""Return a list of the primes below n."""
"""from http://codereview.stackexchange.com/questions/42420/sieve-of-eratosthenes-python"""
prime = [True] * n
result = [2]
append = result.append
sqrt_n = (int(n ** .5) + 1) | 1 # ensure it's odd
for p in range(3, sqrt_n, 2):
... | 73aa9c984cb877df66d17480457b18cd0fd927e5 | 47,534 |
def make_chapter_xml((time,name)):
""" Creates the xml for the chapter """
chapter = Template("""
<ChapterAtom>
<ChapterTimeStart>$time</ChapterTimeStart>
<ChapterDisplay>
<ChapterString>$name</ChapterString>
<ChapterLanguage>eng</ChapterLanguage>
</ChapterDisplay>
</Ch... | 48720d11d7ede90a81c94997084a5659840127e0 | 47,535 |
def dropout(input, rate=.5, noise_shape=None, training=False, name=None):
"""
Apply dropout on `input`.
Args:
input (Tensor): The input tensor.
rate (float or tf.Tensor): The rate of dropout.
noise_shape (tuple[int] or tf.Tensor): Shape of the noise.
If not specified, us... | 3c4fb09a846a98f8bd5c4c6e596170f31dbd1830 | 47,536 |
def refresh_pkce_token(
client_id: str,
refresh_token: str
) -> RefreshingToken:
"""
Request a refreshed PKCE user token.
Parameters
----------
client_id
client ID
refresh_token
refresh token
Returns
-------
RefreshingToken
automatically refreshing u... | b0428ba80460c089a4c82d0bf6b895adac32d70f | 47,537 |
def jsonify_new_book(book):
"""return json object of newly uploaded book"""
book_data = {'book_id': book.book_id,
'title': book.title,
'author': book.author,
'image_url': book.image_url,
'genre': book.genre,
'description': book.des... | f43742a58adf5624703f1f2705fe93f0566c798a | 47,538 |
def build_smod(builder, a, b, name):
"""Builds expression for signed int modulo."""
rem = BuildSRem(builder, a, b, "")
neg_rem = BuildMul(builder, rem, ConstInt(TypeOf(rem), -1, True), "")
return BuildSelect(builder, _mod_scale(builder, a, b), neg_rem, rem, name) | d329822f075298b242bf3f379dc5cf887829012a | 47,539 |
def upload_indicators_command(
client: QRadarClient,
ref_name=None,
element_type=None,
timeout_type=None,
query=None,
time_to_live=None,
limit=1000,
page=0,
):
"""
Finds indicators according to user query and updates QRadar reference set
Returns:
(string, dict). Huma... | 338e9870c56b64a743cb5c9974ca6976cc06aa3f | 47,540 |
def create_stream(context=None):
""" create a stream.
.. note::
case 1. context is None. Get the context and create a new stream.
case 2. context is not None. Create a new stream on existing context.
Args:
context (int): If context is None, it will get context and then create a stre... | 65258ea31a1f8058252160761e04ae85db9be6b2 | 47,541 |
import torch
def get_prediction(model, batch, device):
"""Get predicted labels for given input batch and model."""
images = torch.tensor(batch, dtype=torch.float).to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
return predicted | e8bb4257dc19f26fa206e26fa844ec9717974e52 | 47,542 |
import os
def parse_args(input_args, parser, allow_unknown=True):
"""Parse an argument list using parser generated by create_parser()
Parameters
----------
input_args: list
A list of arguments
Returns
-------
args: argparse.Namespace
A simple object storing the input argu... | 7187f873c543f07bd7a9f11c73d5c720bdbc6732 | 47,543 |
def keep_points_outside_shape(xy_iterable, shape, exclusion_buffer):
"""From an iterable of (x, y) iterables, select points outside a shapely shape, with an exclusion buffer (positive)"""
return [
np.array(xy, dtype=np.float32)
for xy in xy_iterable
if not shape.buffer(exclusion_buffer).... | fa04fc3d5354a7fb609aec95a28ca9ab0e7c5061 | 47,544 |
import shutil
import os
def testing_gallery(tmpdir):
"""Testing gallery with two albums:
- testing-album
- album-incomplete (without album metadata in album.ini)
Both galleryes contain four photos: Photo{1..4}.jpg
"""
shutil.copy(os.path.join(DATA_PATH, 'gallery.ini'), str(tmpdir))
_create... | eb95226e7f53e68436c4a0737bd729186248ad0e | 47,545 |
def ControlsAreSame(control1, control2):
"""return 1 if control1 and control2 are the same control, otherwise return 0"""
return _AutomationClient.instance().dll.CompareElements(control1.Element, control2.Element) | 03b0625e3da27c7f8b841d2eda38968d1c5fd636 | 47,546 |
def close():
"""
Close all pool connections and shutdown the pool.
"""
global db_pool
db_pool.close()
return db_pool | 49356105507890d612cc6dcc11c748c0cf1be6d5 | 47,547 |
import os
def create_app(test_config=None):
"""create and configure the app"""
app = Flask(__name__, instance_relative_config=True)
app.secret_key = os.urandom(12) # Generic key for dev purposes only
# ======== Routing ============================= #
# -------- Home -----------------------------... | 04aa92f2041069d18320883d89d56c8298c5b0c2 | 47,548 |
import os
def create_dir_structure(directory_path,
create_sub_dir):
"""
Creates required directory structures inside the parent
directory figures.
Args:
directory_path: string
Given path that already exists.
create_sub_dir: string
... | f027bb2d323070ef7c6e0f2176731eea9aa5d783 | 47,549 |
import torch
def build_optimizer(network, optimizer:str, learning_rate:float):
"""Optimizer creation
Args:
network (torch.model): Network to train
optimizer (str): optimizer type one of [sgd,adam,rmsprop]
learning_rate (float): float learning rate
Returns:
[torch.optim.op... | 7a4604d2001edba1fdc0f0b80ee7ab2c2e167084 | 47,550 |
def test_creating_tables_from_models():
# language=rst
"""
Creating tables from models
---------------------------
Say I have some model:
"""
class Foo(models.Model):
a = models.IntegerField()
def __str__(self):
return f'Foo: {self.a}'
# @test
clas... | b4ed5f203ae09e6d51c1c601de0d9e6e9a873ded | 47,551 |
def send_msg(app, msg):
"""
Send an openflow message.
"""
return app.send_request(event.SendMsgRequest(msg=msg))() | 5895a10bea0636608b86e98c2f188b422ab4a8b1 | 47,552 |
def vq_loss(x,
targets,
codebook_size,
beta=0.25,
decay=0.999,
epsilon=1e-5,
soft_em=False,
num_samples=10,
temperature=None,
do_update=True):
"""Compute the loss of large vocab tensors using a VQAE codebook.
... | 0567e993e9c1f132311ee4c3d31ae1001a4ae036 | 47,553 |
async def get_crypto(symbol):
"""Returns the data of a crypto.
symbol: bytes
"""
data = crypto.get(symbol.encode())
if data:
return orjson.loads(data)
return None | 59121d7145a6a1f56bbc1452d73e804250fa1608 | 47,554 |
def get_monthly_fields(cases, varlist, from_time, to_time,
pressure_adjust=True,
raw_data_path=get_input_datapath(),
model='NorESM'):
"""
Get monthly fields of files (i.e. not averaged)
:param cases: list of cases to load
:param varlis... | 4c7a15524fc281c72f1c1ced0fa7fca51e8180f2 | 47,555 |
def valid_search_inputs_1():
"""Basic search input tests for Sra and Ena (single inputs)"""
return [
[
0,
20,
["covid-19"],
None,
None,
None,
None,
None,
None,
None,
None,
... | d576c50c26eb5d606b3b4cdf5223ecf2a11fdb15 | 47,556 |
import random
def chooseRandPixel(mask):
""" Returns [x,y] numpy array of random pixel.
NOTE: the returned [x, y] correspond to [row, col] in the mask
@param {numpy matrix} mask from which to choose random pixel.
E.g., self.level_dims = self.slide.level_dimensions
sel... | dd643005588155c437739033e1e3ce6c9d1fe94f | 47,557 |
def _setup_batch(batch_shape):
"""Create random time points with batch_shape and a Constant kernel"""
num_data = 9
np.random.seed(1234)
shape = batch_shape + (num_data,)
return (
tf.convert_to_tensor(
generate_random_time_points(expected_range=4.0, shape=shape), tf.float64
... | ac6c628ee30b324a6b0b6c13a5477b0679077d6a | 47,558 |
def query_build_version(config, log):
"""Find the build version we're looking for.
AppVeyor calls build IDs "versions" which is confusing but whatever. Job IDs aren't available in the history query,
only on latest, specific version, and deployment queries. Hence we need two queries to get a one-time status... | cbb4db3e71468c7885913f47f0cf2243e78ec95f | 47,559 |
import warnings
def get_directed_edges(
nodes,
edges,
direction="oneway",
from_id_col="u",
to_id_col="v",
node_id_col="id",
force_bidirectional=False,
network_type=None,
):
"""Prepares the edges and nodes for exporting to different graphs."""
allowed_network_types = Conf._possi... | 66be62d88487c0123029d5e93ec46c151e82b846 | 47,560 |
def list_split(l, indices):
"""Split list at given indices.
Closed lists have the same first and last elements.
If the list is closed, splitting wraps around if the first or last index is not in the indices to split.
Parameters
----------
l : list
A list.
indices : list
... | a882842f6d51eeda010017dbdd2bfa722ebb363d | 47,561 |
def create_filing(token=None, filing_json=None, business_id=None, filing_date=EPOCH_DATETIME, bootstrap_id: str = None):
"""Return a test filing."""
filing = Filing()
if token:
filing.payment_token = str(token)
filing.filing_date = filing_date
if filing_json:
filing.filing_json = fi... | b82090be5bb53e2d64a1907ecc5a8ad0d2970ce1 | 47,562 |
def load_notes_midi(midi_path):
"""
Load all MIDI notes from a MIDI file, keeping track of sustain pedal activity.
TODO - make sustain pedal stuff optional?
TODO - break this up more?
Parameters
----------
midi_path : string
Path to MIDI file to read
Returns
----------
ba... | 73bb389af2b6be74c4afdbf77e57517fe9f8af9d | 47,563 |
from typing import List
def get_tracks_as_np_strings(labels: Labels) -> List[np.string_]:
"""Get list of track names as `np.string_`."""
return [np.string_(track.name) for track in labels.tracks] | bcbbc5567fdf48d99318de89b07eee480349ea75 | 47,564 |
import torch
def _model_validation_for_base(opt, base_model, device, tokenizer, with_mask=False):
"""
validation set 을 이용하여 모델 정확도 계산
"""
corpus_list, asp_info = loader.load_validation_data()
transform = nlp.data.BERTSentenceTransform(
tokenizer, max_seq_length=opt["bert_max_len"], pad... | ef5c029cd8666f444206c58c53f031a4a351538b | 47,565 |
def no_op(ctx, node, name, args):
"""Skip node."""
return None | 1fede015a843657f3959bb8da4c2216a8674e60c | 47,566 |
import sys
import json
def mastQuery(request):
"""Perform a MAST query.
Parameters
----------
request (dictionary): The MAST request json object
Returns head,content where head is the response HTTP headers, and content is the returned data
"""
server='mast.stsci.edu'
# Grab Pyt... | 3b3a88e8d565d0d164134fff8fb316ecc67a00b9 | 47,567 |
from typing import Union
def log_likelihood(z:Union[np.ndarray,float,int], x:np.ndarray, P:np.ndarray, H:np.ndarray, R:np.ndarray) -> Union[np.ndarray,float,int]:
"""
Returns log-likelihood of the measurement z given the Gaussian
posterior (x, P) using measurement function H and measurement
covariance... | c50098e557bab4f2095458bf61c9ed91ddb14121 | 47,568 |
import operator
def recession_index(data, compare=operator.gt):
"""returns the index of the start of the recession
Parameters
----------
data: DataFrame
GDP data to search
compare: function
compare quarters (change to < to find end)
Returns
-------
int : iloc of star... | 4bcdedffb094cb3d0112796c1ad39d666bd435a1 | 47,569 |
def copy_tree(t):
"""Returns a copy of t. Only for testing purposes.
>>> t = tree(5)
>>> copy = copy_tree(t)
>>> t = tree(6)
>>> print_tree(copy)
5
"""
return tree(root(t), [copy_tree(b) for b in branches(t)]) | 64fcd5e820b14d5a34daf221defceb00949ed04d | 47,570 |
import os
def set_owner(conn, uuid, owner):
"""Set ON_OWNER by uuid.
@param uuid: uuid of the VM
@param owner: string representing owner
"""
# Save owener regardless if VM is working or not
# Old logic will write owner info only if VM is working.
owners_file = '/etc/opennode/kvmowners'
... | e1c69a0e2b3f0212da009a01e85d47a80965828e | 47,571 |
import time
def wait_for_element_not_visible(
driver, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=settings.LARGE_TIMEOUT
):
"""
Searches for the specified element by the given selector.
Raises an exception if the element is still visible after the
specified timeout.
@Params
driver ... | 2e76b4d81e0ef3342f110e5c7c89e4d4ef30ad43 | 47,572 |
from .irc import ConnectInfo as IRCConnectInfo
def connect_info_factory(info_type: str, **kwargs):
"""
Creates a specific ConnectInfo based on the type of connection we are looking for. Any
additional kwargs specified are passed on to the appropriate ConnectInfo constructor.
:param info_type: the con... | dcca8457f5e7a4f4dec76687859d33cd3274c7af | 47,573 |
def entity_similarity(algo, entity1, entity2):
"""
measure the similarity of the two entities
:param algo: the algorithm to measure similarity
:param entity1, entity2: two entities to measure analogy
:return: [float] in [0. 1)
"""
if algo == "jaccard":
return jaccard_similarity_score... | a886180219d6f4347fab605719305d86c97eec7a | 47,574 |
import gzip
import os
def hook_compressed_text(filename, mode, encoding='utf8'):
"""
#lines are byte strings and not text string if we use gzip.open by default.
"""
ext = os.path.splitext(filename)[1]
if ext == '.gz':
return gzip.open(filename, mode + 't', encoding=encoding)
#elif ext... | 7c3b76e4d33cb400020e677554f0d9584fa799b1 | 47,575 |
import warnings
import functools
def deprecated(func):
""" Decorator to be used to mark functions as deprecated.
It will result in a warning being emitted when the function is used.
Usage::
@other_decorators_must_be_upper
@deprecated
def some_old_function(x,y):
return... | ef4ca24b5da4a4df2b3c2a11f2e6b71791233a85 | 47,576 |
import argparse
def setup_cli(args, cfg):
""" Configure command-line arguements """
description ="""
Benign_domains outputs a list of preceived benign domains. This is
intended to help gather data for ML training sets and generate white
lists. The core set of domains are provided by majestic mill... | 3bdd81fa9526ce06bf56bf847e04def67b9ce72e | 47,577 |
import requests
def metadata_label_cbor(self, label: str, **kwargs):
"""
Transaction metadata per label.
https://docs.blockfrost.io/#tag/Cardano-Metadata/paths/~1metadata~1txs~1labels~1{label}~1cbor/get
:param label: Metadata label
:type label: str
:param return_type: Optional. "object", "js... | 0d64f86aa2baf95ac4815fd1edf041412e0679b7 | 47,578 |
def uses_gpu(*args):
"""Mark to differentiate tests that use the GPU is some capacity.
These tests will be run on CPU-only test nodes and on test nodes with GPUS.
To mark a test that must have a GPU present to run, use
:py:func:`tvm.testing.requires_gpu`.
Parameters
----------
f : function... | 20cf77b58216b0f8b0d0d68beb7c5b3c833f9e69 | 47,579 |
def get_imbalances(regressions):
# Deprecated
"""
Generates a numpy array of the imbalances.
For a value *x* where *x* is the beta of a regression:
========= ====== =======================================================
*x* < 0 **-1** The regression had a negative beta value
*x* = nan **0** The regression ... | f755c9ca1253d511b33dbe1f1884d9bb4431f80a | 47,580 |
import subprocess
def get_course_ids():
"""
Get a list of course ids that is necessary for the rest of the
functions to work.
"""
global course_ids
dump_course_ids = subprocess.Popen(['/edx/bin/python.edxapp',
'/edx/app/edxapp/edx-platform/manage.py',
... | 9017db92c197a756646e916ceab7ebacd481f453 | 47,581 |
def get_optimizer(learning_rate, config):
"""Returns the optimizer of choice given the configurations."""
if isinstance(config, experiment.MomentumOptimizer):
optimizer = tf.keras.optimizers.SGD(
learning_rate=learning_rate,
momentum=config.momentum,
nesterov=config.nesterov
)
... | 7f49cab554fcda1cb38f4d146d99c2e9e0916365 | 47,582 |
def get_gitlab_project_data(initial_data, headers, resources):
"""
Get all directories and files of given projects.
Parameters
----------
initial_data: list
List of all top level projects
headers: dict
The authorization header that GitLab expects
resources: list
A li... | dce6a29de688ccf2999d6a48d98693cb38138dd9 | 47,583 |
from typing import List
import re
def convert_observations(observations:str)->List[str]:
"""
Parses a string with observations separated by comas.
Args:
observations: str -> Obesrvations string, each observation must be separated
by a coma. Example "Green, ugly, has ... | 45c43303d9d2819094120a25a639cd1d02fa4d8c | 47,584 |
def prepare_data(data, nlags):
"""prepares data for LSTM model, x=last nlags values, y=(nlags+1)'th value"""
data_x, data_y = [], []
for i in range(data.shape[0]):
for j in range(0, data.shape[1] - nlags):
data_x.append(data[i, j : j + nlags])
data_y.append(data[i, j + nlags]... | 147389d381f689c68fff44b6b036777e25669c4f | 47,585 |
import math
def divisors(n: int) -> list[int]:
"""Get the proper divisors of a number n"""
limit = int(math.sqrt(n)) + 1
proper_divisors = {1}
for i in range(2, limit):
if n % i == 0:
proper_divisors.add(n // i)
proper_divisors.add(i)
return list(proper_divisors) | 0a71ecccbda802d3a3575f024073fac575355ffa | 47,586 |
def compressImage(image, height):
"""
Note: Should probably replace this method with one from photutils or PIL.Image. Will probably be faster/more accurate and can handle
both increasing and decreasing resolution
"""
"""
Compresses the image to a given size. Given that 3D printing cannot handle fine resolution, a... | 83cb9faf1576dda452dbfa391038de6c7e8ee3e0 | 47,587 |
def get_lsb_num(num):
"""docstring"""
cnt = 0
while not (num >> cnt) & 1:
cnt += 1
#
return cnt + 1 | 6abf34d4831b80310dbf57bf08b7fce0b6c0a73d | 47,588 |
def foreign_key(
table_name: str, schema: str, parent_name: str, parent_schema: str
) -> str:
"""Return column names (child and parent) of the foreign key."""
return f"""
SELECT
att2.attname as child_column,
att.attname as parent_column
FROM
(SELECT
unnest(con1.co... | e1c7221fd308ee44f7b09718e66028351262334a | 47,589 |
from pathlib import Path
def available_models():
"""Check for available neural network models.
This function returns a list of all neural network models saved.
If None is available, it returns a message informing there's no models previously
saved.
Returns
-------
dirs : list
Lis... | f3bbfa56ea0eaa2e06467e479cdefd18d02e8021 | 47,590 |
def problem33(nr_digits):
"""Problem 33 - Digit canceling fractions"""
a_sum = 1
b_sum = 1
for a in range(10**(nr_digits - 1), (10**nr_digits) - 1):
for b in range(a + 1, 10**nr_digits):
# print(a/b);
a_str = str(a)
b_str = str(b)
for sa in rang... | b771db51002a3a408d57cb3422d64c69611f0e53 | 47,591 |
async def test(ctx):
"""Tests if the parameters taken in the function match the parameters that the event has"""
return ctx | 25ad99daa6685a596cf6f88d9a38b55d2b117ef8 | 47,592 |
def add_entrypoints(setupcfg: ConfigUpdater, opts: ScaffoldOpts):
"""Add [options.entry_points] to setup.cfg"""
new_section_name = "options.entry_points"
if new_section_name in setupcfg:
return setupcfg, opts
new_section = ConfigUpdater()
new_section.read_string(templates.setup_cfg(opts))
... | fc6c4fc6a35bf6b521141ca1fb4a85ebfe601fea | 47,593 |
def create_top_video_photo():
"""
Creates a video which contains the estimated lane line markers using a top view and the top view image
:return:
"""
def process_image(image):
warped, warped_cam, perspec = lane_finder.find_lanes_using_window(image)
return warped_cam
find_lanes_... | 5e2f2d4fd3eb95ee3a339c957c04cd60d30b33bc | 47,594 |
def expr2bdd(expr):
"""Convert an expression into a binary decision diagram."""
return bdd(expr2bddnode(expr)) | fbaf81d2af0b9aed6729850ca40764fa825a5079 | 47,595 |
def extCalcLayers(
cz,
r_detector,
prop_height,
detector_depth,
max_layers,
min_detector_depth,
rhos,
YeFrac,
YeOuterRadius,
default_elec_frac,
coszen_limit,
radii):
"""Layer density/distance calculator for each coszen s... | 382afac0d0d3f749f98d777a383173ee24755c37 | 47,596 |
import zlib
def iterative_decompress(
stream, offset, size, chunk_size=4096, wbits=DETECT_HEADER, retry=False
):
""" decompress data from stream chunk-wise """
decompressor = zlib.decompressobj(wbits)
n_read = 0
decomp = b''
return_err = None
try:
while n_read < size:
... | 37e33f9150e696b8bc42cb8a9676110a97b3a7d3 | 47,597 |
import os
def loadPeaks(peakFile=None, peakfolder=None, isNF=True, CTFlist=[], skiprows=0):
"""
loads 1 to many peak bedfile into one pandas dataframe.
all og the peaks will be concatenated into one dataframe. this function can
work with jkobject|nfcore/chipseq nextflow pipelines output (isNF)
Args:
-----
... | 9eb696c670121583886a52b98cbacc26d2240374 | 47,598 |
import math
def compute_dimension(bounds, pixel_resolution: tuple):
"""
:param bounds:
:param pixel_resolution: width and height of pixels in the units of its coordinate reference system extracted from
transformation of image
:return:
"""
output_width = int(math.ceil((bounds[2] - bounds[0... | 83d3c133a8471d41d69cad4fb00d529e36634731 | 47,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.