content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def merge(A, p, q, r):
""" ソート済みの二区間、A[p..q] と A[q+1..r]をマージする
p < q < r
Θ(n)
"""
n1 = q - p + 1
n2 = r - q
L = [0] * n1
R = [0] * n2
for i in range(0, n1):
L[i] = A[p + i]
for j in range(0, n2):
R[j] = A[q + j + 1]
i = 0
j = 0
for k in ran... | 5,326,500 |
def parse_csv_data(csv_filename: FileIO) -> list[str]:
"""Returns contents of 'csv_filename' as list of strings by row"""
try:
return open(csv_filename).readlines()
except FileNotFoundError:
logging.warning("File with path '%s' not found", csv_filename)
return [] | 5,326,501 |
def make_crews(crews, config, state, parameters, timeseries, deployment_days):
""" Generate crews using BaseCrew class.
Args:
crews (list): List of crews
config (dict): Method parameters
state (dict): Current state of LDAR-Sim
parameters (dict): Program parameters
... | 5,326,502 |
def generate_parquet_file(
name: str, columns: Mapping[str, str], num_rows: int, custom_rows: Mapping[int, Mapping[str, Any]] = None
) -> str:
"""Generates a random data and save it to a tmp file"""
filename = os.path.join(tmp_folder(), name + "." + filetype)
if os.path.exists(filename):
return... | 5,326,503 |
def decrease_others(obj: []) -> []:
"""
decrease the confidence of those that aren't increased
"""
# TODO: | 5,326,504 |
def _interpolate_sym(y0, Tkk, f_Tkk, y_half, f_yj, hs, H, k, atol, rtol,
seq=(lambda t: 4*t-2)):
"""
Symmetric dense output formula; used for example with the midpoint method.
It calculates a polynomial to interpolate any value from t0 (time at y0) to
t0+H (time at Tkk). Based on De... | 5,326,505 |
def _gtin_fails_checksum(gtin: str) -> bool:
"""Determines if the provided gtin violates the check digit calculation.
Args:
gtin: a string representing the product's GTIN
Returns:
True if the gtin fails check digit validation, otherwise False.
"""
padded_gtin = gtin.zfill(14)
existing_check_digit ... | 5,326,506 |
def mergeGuideInfo(seq, startDict, pamPat, otMatches, inputPos, effScores, sortBy=None):
"""
merges guide information from the sequence, the efficiency scores and the off-targets.
creates rows with too many fields. Probably needs refactoring.
for each pam in startDict, retrieve the guide sequence next... | 5,326,507 |
def reset_rf_samples():
""" Undoes the changes produced by set_rf_samples.
"""
forest._generate_sample_indices = (lambda rs, n_samples:
forest.check_random_state(rs).randint(0, n_samples, n_samples)) | 5,326,508 |
def search_orf(seq:str, min_orf:int) -> list:
"""Search full orf over ceration length in 6 frames"""
scod = "M"
send = "*"
orf_regions = {}
# Load 6 reading frames
seq1 = seq
seq2 = seq1[1: ]
seq3 = seq1[2: ]
seq4 = rc_seq(seq1)
seq5 = seq4[1: ]
seq6 = seq4[2: ]
# Shrink ... | 5,326,509 |
def test_word_combinations(text, expected_counter: Counter, i: Index, epoch: date):
"""Add date suffix"""
EPOCH_SUFFIX: str = ":1970:1"
expected_counter_dated = Counter(**{key + EPOCH_SUFFIX: value for key, value in expected_counter.items()})
i.index_text(text, epoch)
assert i.backend.counter == ex... | 5,326,510 |
def getPath():
"""
Gets path of the from ./metadata.json/
"""
with open('metadata.json', 'r') as openfile:
global path
json_object = json.load(openfile)
pairs = json_object.items()
path = json_object["renamer"]["path"]
return path | 5,326,511 |
def read_ann_h5ad(file_path, spatial_key: Optional[str] = None):
"""
read the h5ad file in Anndata format, and generate the object of StereoExpData.
:param file_path: h5ad file path.
:param spatial_key: use .obsm[`'spatial_key'`] as position. If spatial data, must set.
:return: StereoExpData obj.
... | 5,326,512 |
def get_token(token_method, acc=None, vo=None, idt=None, pwd=None):
"""
Gets a token with the token_method provided.
:param token_method: the method to get the token
:param acc: Rucio account string
:param idt: Rucio identity string
:param pwd: Rucio password string (in case of userpass auth_typ... | 5,326,513 |
def valid_float_0_to_1(val):
"""
:param val: Object to check, then throw an error if it is invalid
:return: val if it is a float between 0 and 1 (otherwise invalid)
"""
return validate(val, lambda x: 0 <= float(x) <= 1, float,
'Value must be a number between 0 and 1') | 5,326,514 |
def get_usps_data():
"""
"""
trainset = dsets.USPS(root='./data',
train=True,
transform=transforms.ToTensor(),
download=True)
testset = dsets.USPS(root='./data',
... | 5,326,515 |
def logout():
"""
Logs out a user
Returns:
(str): A JWT access token
"""
res = {}
try:
response = jsonify({"msg": "logout successful"})
unset_jwt_cookies(response)
return make_response(response), 200
except Exception as e:
res["data"] = N... | 5,326,516 |
def bm_reduction(mat):
""" Performs the Bloch-Messiah decomposition of single mode thermal state.
Said decomposition writes a gaussian state as a a thermal squeezed-rotated-displaced state
The function returns the thermal population, rotation angle and squeezing parameters
"""
if mat.shape != (2, ... | 5,326,517 |
def pinlattice_2ring_full():
"""Full, non-test instance of PinLattice object for testing
Subchannel object"""
n_ring = 2
pitch = 1.0
d_pin = 0.5
return dassh.PinLattice(n_ring, pitch, d_pin) | 5,326,518 |
def dmenu_view_previous_entry(entry, folders):
"""View previous entry
Args: entry (Item)
Returns: entry (Item)
"""
if entry is not None:
text = view_entry(entry, folders)
type_text(text)
return entry | 5,326,519 |
def unary_to_gast(node):
"""
Takes unary operation such as ! and converts it to generic AST.
javascript makes negative numbers unary expressions. This is our
current workaround.
"""
if node.operator == "-":
return {"type": "num", "value": node.argument.value * -1}
return {
"... | 5,326,520 |
def _norm_intensity(spectrum_intensity: np.ndarray) -> np.ndarray:
"""
Normalize spectrum peak intensities.
Parameters
----------
spectrum_intensity : np.ndarray
The spectrum peak intensities to be normalized.
Returns
-------
np.ndarray
The normalized peak intensities.
... | 5,326,521 |
def axes_to_list(axes_data: dict) -> list:
"""helper method to convert a dict of sensor axis graphs to a 2d array for graphing
"""
axes_tuples = axes_data.items()
axes_list = [axes[1].tolist() for axes in axes_tuples]
return axes_list | 5,326,522 |
def list(
repo_info: str,
git_host: str = DEFAULT_GIT_HOST,
use_cache: bool = True,
commit: str = None,
protocol: str = DEFAULT_PROTOCOL,
) -> List[str]:
"""Lists all entrypoints available in repo hubconf.
:param repo_info:
a string with format ``"repo_owner/repo_name[:tag_name/:bra... | 5,326,523 |
def repeatfunc(func: Callable, times: Int = None, *args):
"""Repeat calls to func with specified arguments.
Example: repeatfunc(random.random)
:param func: function to be called
:param times: amount of call times
"""
if times is None:
return starmap(func, repeat(args))
return star... | 5,326,524 |
def command_group(launcher, backend, local_rank): # pylint: disable=unused-argument
"""Defines a command group for launching distributed jobs.
This function is mainly for interaction with the command line. The real
launching is executed by `main()` function, through `result_callback()`
decorator. In o... | 5,326,525 |
def create_shortcut(anti_ghosting: bool):
"""
creates a new shortcut on desktop
"""
try:
desktop = winshell.desktop()
path = os.path.join(desktop, "Fishybot ESO.lnk")
shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
if anti_ghosting:
... | 5,326,526 |
def prod(values: Iterable[int]) -> int:
"""Compute the product of the integers."""
return functools.reduce(operator.mul, values) | 5,326,527 |
def get_stars_dict(stars):
"""
Transform list of stars into dictionary where keys are their names
Parameters
----------
stars : list, iterable
Star objects
Return
------
dict
Stars dictionary
"""
x = {}
for st in stars:
try:
x[st.name] = ... | 5,326,528 |
def main():
"""Start the bot."""
logger.debug('start bot')
# Create the EventHandler and pass it your bot's token.
updater = Updater(TOKEN_TELEGRAM)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHan... | 5,326,529 |
def initialize_molecular_pos(
key: PRNGKey,
nchains: int,
ion_pos: Array,
ion_charges: Array,
nelec_total: int,
init_width: float = 1.0,
dtype=jnp.float32,
) -> Tuple[PRNGKey, Array]:
"""Initialize a set of plausible initial electron positions.
For each chain, each electron is assig... | 5,326,530 |
def urlencode(query, *args, **kwargs):
"""Handle nested form-data queries and serialize them appropriately.
There are times when a website expects a nested form data query to be sent
but, the standard library's urlencode function does not appropriately
handle the nested structures. In that case, y... | 5,326,531 |
def tmpEnv(**environ):
"""
Temporarily set the process environment variables.
>>> with tmpEnv(PLUGINS_DIR=u'test/plugins'):
... "PLUGINS_DIR" in os.environ
True
>>> "PLUGINS_DIR" in os.environ
False
:param environ: Environment variables to set
"""
oldEnviron = dict(os.enviro... | 5,326,532 |
def zca_whiten_np(images, epsilon=1e-6):
"""Whitening the images using numpy/scipy.
Stolen from https://github.com/keras-team/keras-preprocessing/blob/master/keras_preprocessing/image/image_data_generator.py
A good answer on ZCA vs. PCA: https://stats.stackexchange.com/questions/117427/what-is-the-differe... | 5,326,533 |
def find_best_post_processing(cmd):
"""
Find best postprocessing approach to use with the new dataset based on the f0.5 score macro-averaged.
"""
# add stop words to the list found during the development of rcATT
stop_words = stopwords.words('english')
new_stop_words = ["'ll", "'re", "'ve", 'ha', 'wa',"'d",... | 5,326,534 |
def set_kernel(kernel, **kwargs):
"""kernelsを指定する
Parameters
----------
kernel : str or :obj:`gpytorch.kernels`
使用するカーネル関数を指定する
基本はstrで指定されることを想定しているものの、自作のカーネル関数を入力することも可能
**kwargs : dict
カーネル関数に渡す設定
Returns
-------
out : :obj:`gpytorch.kernels`
カーネル... | 5,326,535 |
def prepare_multi(multi):
"""Processes the formatted string and generates a list of rules to update.
Parameters
----------
multi : str
A comma-separated string of devices and rules to update.
Format: `devicename|mac|rule`.
Example: `mediaserver||pl... | 5,326,536 |
def holding_period_return(multivariate_df: pd.DataFrame, lag: int, ending_lag: int = 0, skip_nan: bool = False):
"""
Calculate the rolling holding period return for each column
Holding period return for stock = Price(t - ending_lag) / Price(t - lag) - 1
:param multivariate_df: DataFrame
:param lag: ... | 5,326,537 |
def test_slim_eval_nonuniform(benchmark):
"""Benchmark slim_eval_fun with non-uniform core tensors"""
slim_eval_runner(benchmark, uniform=False) | 5,326,538 |
def _unpack_var(var):
"""
Parses key : value pair from `var`
Parameters
----------
var : str
Entry from HEAD file
Returns
-------
name : str
Name of attribute
value : object
Value of attribute
Examples
--------
>>> var = "type = integer-attribut... | 5,326,539 |
def cmd_ok(packet: Packet, cmd: int,
writer: io.BufferedWriter = None) -> bool:
"""
Returns true if command is okay, and logs if not.
If the command is INCORRECT, a packet is sent to the
client with BAD_CMD command.
"""
ok = True
if packet is None:
Log.debug('F... | 5,326,540 |
def get_representation(keypoint_coordinates: torch.Tensor,
image: torch.Tensor,
feature_map: torch.Tensor) -> (torch.Tensor, torch.Tensor):
"""
:param keypoint_coordinates: Tensor of key-point coordinates in (N, 2/3)
:param image: Tensor of current image in (N,... | 5,326,541 |
def test_create_full_point_variable_indexes_slices(
double_pendulum_phase_backend_fixture):
"""Slices for endpoint Pycollo variables are correctly indexed."""
phase_backend = double_pendulum_phase_backend_fixture
phase_backend.create_variable_symbols()
phase_backend.preprocess_variables()
ph... | 5,326,542 |
def setup_proxy(whois_https_proxy):
"""
is a proxy needed?
:param whois_https_proxy:
:return:
"""
if whois_https_proxy:
uri = urlparse.urlparse(whois_https_proxy)
socks.set_default_proxy(socks.PROXY_TYPE_HTTP, uri.hostname, uri.port)
socket.socket = socks.socksocket | 5,326,543 |
async def async_setup(opp: OpenPeerPowerType, config: ConfigType):
"""Set up the System Health component."""
opp.components.websocket_api.async_register_command(handle_info)
return True | 5,326,544 |
def getSoup(url: str, ftrs: str = "html5lib") -> bsp:
"""
Function to extract soup from the url passed in, returns a bsp object.
"""
rspns = requests.get(url)
return bsp(rspns.content, ftrs) | 5,326,545 |
def _fit_HoRT(T_ref, HoRT_ref, a_low, a_high, T_mid):
"""Fit a[5] coefficient in a_low and a_high attributes given the
dimensionless enthalpy
Parameters
----------
T_ref : float
Reference temperature in K
HoRT_ref : float
Reference dimensionless enthalpy
... | 5,326,546 |
def load_scipy_special__cephes(finder: ModuleFinder, module: Module) -> None:
"""
The scipy.special._cephes is an extension module and the scipy module
imports * from it in places; advertise the global names that are used
in order to avoid spurious errors about missing modules.
"""
module.AddGlo... | 5,326,547 |
def get_q_k_size(database,elph_save):
"""
Get number of k and q points in the (IBZ) grids
"""
# kpoints
db = Dataset(database+"/SAVE/ns.db1")
Nk = len(db.variables['K-POINTS'][:].T)
db.close()
# qpoints
Nq = len(glob('./elph_dir/s.dbph_0*'))
return Nq,Nk | 5,326,548 |
def false(feedback, msg, comment, alias_used="false"):
"""
Marks a post as a false positive
:param feedback:
:param msg:
:return: String
"""
post_data = get_report_data(msg)
if not post_data:
raise CmdException("That message is not a report.")
post_url, owner_url = post_data... | 5,326,549 |
def so3_to_SO3_(so3mat):
"""
Convert so(3) to SO(3)
Parameters
----------
so3mat (tf.Tensor):
so(3)
N x 3 x 3
Returns
------
ret (tf.Tensor):
SO(3)
N x 3 x 3
"""
omgtheta = so3_to_vec(so3mat)
c_1 = near_zero(tf.norm(omgtheta,axis=1))
c_2 ... | 5,326,550 |
def set_non_keyable(node_name, attributes):
"""
Sets the given attributes of the given node name as a non keyale attributes
:param node_name: str, name of a Maya node
:param attributes: list<str>, list of attributes in the node that we want to set as non keyable attributes
"""
attributes = pyth... | 5,326,551 |
def batch_get_item(RequestItems=None, ReturnConsumedCapacity=None):
"""
The BatchGetItem operation returns the attributes of one or more items from one or more tables. You identify requested items by primary key.
A single operation can retrieve up to 16 MB of data, which can contain as many as 100 items. Ba... | 5,326,552 |
def find_worst_offenders(
all_resource_type_stats: Dict[str, ResourceTypeStats],
version: str,
) -> Dict[str, ResourceTypeStats]:
"""
Finds the resource types with the worst polymorphing and nesting
"""
# find the resource type with the most number of shapes
most_polymorphic_resource_type = ... | 5,326,553 |
def optimize(nn_last_layer, correct_label, learning_rate, num_classes):
"""
Build the TensorFLow loss and optimizer operations.
:param nn_last_layer: TF Tensor of the last layer in the neural network
:param correct_label: TF Placeholder for the correct label image
:param learning_rate: TF Placeholde... | 5,326,554 |
async def all_pairs(factory, weth, dai, wbtc, paused_token):
"""all_pairs set up a very specific arbitrage opportunity.
We want a opportunity that requires less then 2 WETH and provides significant profit as
to be able to separate profit from gas costs. If the numbers do not make sense it is because
th... | 5,326,555 |
def meeting_point(a, b, window=100, start=0):
"""
Determines the point where the moving average of a meets that of b
"""
cva = np.convolve(a, np.ones((window,))/window, mode='valid')
cvb = np.convolve(b, np.ones((window,))/window, mode='valid')
for x, (val_a, val_b) in enumerate(zip(cva, cvb))... | 5,326,556 |
def fixed_dictionaries(
mapping: Dict[T, SearchStrategy[Ex]],
*,
optional: Optional[Dict[T, SearchStrategy[Ex]]] = None,
) -> SearchStrategy[Dict[T, Ex]]:
"""Generates a dictionary of the same type as mapping with a fixed set of
keys mapping to strategies. ``mapping`` must be a dict subclass.
G... | 5,326,557 |
def estimate_R0(model, curves: pd.DataFrame, method="OLS", **kwargs) -> ValueStd:
"""
Estimate R0 from epidemic curves and model.
{args}
Returns:
A ValueStd with R0 and its associated standard deviation.
See Also:
naive_R0
OLS_R0
"""
return METHODS_R0[method](model... | 5,326,558 |
async def test_discovery() -> None:
"""Test a successful call to discovery."""
session = Mock()
with patch(
"pydeconz.utils.request",
new=AsyncMock(
return_value=[
{
"id": "123456FFFFABCDEF",
"internalipaddress": "host1",
... | 5,326,559 |
def get_bone_list(armature, layer_list):
"""Get Bone name List of selected layers"""
ret = []
for bone in armature.data.bones:
if is_valid_layer(bone.layers, layer_list):
ret.append(bone.name)
return ret | 5,326,560 |
def clean_packages_list(packages):
"""
Remove comments from the package list
"""
lines = []
for line in packages:
if not line.startswith("#"):
lines.append(line)
return lines | 5,326,561 |
def IndividualBuilder(size, possList, probList):
"""
Args:
size (int) - the list size to be created
PossArr - a list of the possible mutations
types (mutation, deletion,...)
ProbArr - a list of the probibilities of the possible
mutations occuring.
Returns:
... | 5,326,562 |
def getConfigId(dsn_string, test_data):
"""Returns the integer ID of the configuration name used in this run."""
# If we have not already done so, we query the local DB for the ID
# matching this sqlbench config name. If none is there, we insert
# a new record in the bench_config table and return the newly ge... | 5,326,563 |
def get_file_open_command(script_path, turls, nthreads):
"""
:param script_path: path to script (string).
:param turls: comma-separated turls (string).
:param nthreads: number of concurrent file open threads (int).
:return: comma-separated list of turls (string).
"""
return "%s --turls=%s ... | 5,326,564 |
def invert_contactmap(cmap):
"""Method to invert a contact map
:param :py:obj:`~conkit.core.ContactMap` cmap: the contact map of interest
:returns: and inverted_cmap: the contact map corresponding with the inverted sequence (1-res_seq) \
(:py:obj:`~conkit.core.ContactMap`)
"""
inverted_cmap = ... | 5,326,565 |
def main_loop():
"""Loop."""
# myIRHelper.check()
animation.animation_helper.main_loop()
# myIRHelper.check()
# time.sleep(0.1) | 5,326,566 |
def indexes_with_respect_to_y(Y):
"""
Checks Y and returns indexes with respect to the groups.
Parameters
----------
Y : numpy array like of one single output.
Corresponding to a categorical variable.
Returns
-------
List of indexes corresponding to each group.
"""
catego... | 5,326,567 |
def rrotate(x, disp):
"""Rotate x's bits to the right by disp."""
if disp == 0:
return x
elif disp < 0:
return lrotate(x, -disp)
disp &= 31
x = trim(x)
return trim((x >> disp) | (x << (32 - disp))) | 5,326,568 |
def test_space_net_no_crash_not_fitted():
"""Regression test."""
iris = load_iris()
X, y = iris.data, iris.target
X, mask = to_niimgs(X, [2, 2, 2])
for model in [SpaceNetRegressor, SpaceNetClassifier]:
assert_raises_regex(RuntimeError,
"This %s instance is not fit... | 5,326,569 |
def main(cases_fname):
"""
This method use existing cluster, and then
for a given cluster launches pods (one pod per case),
which are read from input file
"""
if cases_fname is None:
return -1
cfg = read_config("config_cluster.json")
CID = cfg["CID"]
ZID = cfg["ZID"]
... | 5,326,570 |
def upload_configuration_to_zk(zookeeper_quorum, solr_znode, config_set, config_set_dir, tmp_dir,
java64_home, retry = 5, interval = 10, solrconfig_content = None, jaas_file=None):
"""
Upload configuration set to zookeeper with solrCloudCli.sh
At first, it tries to download configuration ... | 5,326,571 |
def setup_parameters():
"""
This function sets up the hyperparameters needed to train the model.
Returns:
hyperparameters : Dictionary containing the hyperparameters for the model.
options : Dictionary containing the options for the dataset location, augmentation, etc.
"""
# Dataset lo... | 5,326,572 |
def main(argv=None):
"""
Console scripts entry point.
"""
args = parse_args(argv)
style = DEFAULT_STYLE
# Validation
if not args.git and not args.cov and not args.text and not args.value and not args.print_version:
print("Not valid parameters. -git or -cov or -t and -v")
sy... | 5,326,573 |
def submit(test_df, test_pred_dict):
"""
提交测试结果
:param test_df: DataFrame 测试集特征(包含userid和feedid)
:param test_pred_dict: dict 测试集各行为的预估概率
:return:
"""
# 1,样本和预估结果的拼接
test_pred_df = pd.DataFrame.from_dict(test_pred_dict)
test_df.reset_index(drop=True, inplace=True)
test_df = pd.co... | 5,326,574 |
def search_for_start ( r, X, w0, applythreshold, hf0, pm=(.85,.93,1.,1.07,1.15), storeopt=False, modulation=False, doublemodulation=False):
"""Search for starting values
:Parameters:
*d*
data set
*w0*
coarse starting values
*pm*
increments or decremen... | 5,326,575 |
def replay(args):
"""
Starts a replay environment for the given replay directory, including setting up interfaces, running
a DNS server, and configuring and running an nginx server to serve the requests
"""
policy = None
cert_path = os.path.abspath(args.cert_path) if args.cert_path else None
... | 5,326,576 |
def point_sample(input, points, align_corners=False, **kwargs):
"""
A wrapper around :func:`grid_sample` to support 3D point_coords tensors
Unlike :func:`torch.nn.functional.grid_sample` it assumes point_coords to
lie inside ``[0, 1] x [0, 1]`` square.
Args:
input (Tensor): Feature map, sha... | 5,326,577 |
def compareStringsWithFloats(a,b,numTol = 1e-10, zeroThreshold = sys.float_info.min*4.0, removeWhitespace = False, removeUnicodeIdentifier = False):
"""
Compares two strings that have floats inside them. This searches for floating point numbers, and compares them with a numeric tolerance.
@ In, a, string, fi... | 5,326,578 |
def main():
"""
Main entry point of the indicator
"""
# First, attempt to connect to DBus service
# If you can't, then give up.
try:
bus = dbus.SessionBus()
dbus_object = bus.get_object(service.DBUS_OBJECT, service.DBUS_PATH)
dbus_client = dbus.Interface(dbus_object, serv... | 5,326,579 |
def login_render(auth_url: str) -> Any:
"""Return login page.
Arguments:
auth_url {str} -- Link to last.fm authorization page.
"""
return render_template("login.html", auth_url=auth_url, timestamp=time()) | 5,326,580 |
def save_image(file_path, mat, overwrite=True):
"""
Save 2D data to an image.
Parameters
----------
file_path : str
Path to the file.
mat : int or float
2D array.
overwrite : bool
Overwrite the existing file if True.
Returns
-------
str... | 5,326,581 |
def test_can_remove_agent(volttron_instance):
""" Confirms that 'volttron-ctl remove' removes agent as expected. """
assert volttron_instance is not None
assert volttron_instance.is_running()
# Install ListenerAgent as the agent to be removed.
agent_uuid = volttron_instance.install_agent(
a... | 5,326,582 |
def cleanup_cloud_storage(config, context, vdc):
""" Cleans up a previously created cloud storage resources """
log.info(("Removing persistent volumes in "
"virtual datacenter %s...") % vdc.getName())
for volume in vdc.listVolumes():
volume.delete() | 5,326,583 |
def receive_consensus_genome(*, session):
"""
Receive references to consensus genomes.
POST receiving/consensus-genome with a JSON body
"""
document = request.get_data(as_text = True)
LOG.debug(f"Received consensus genome")
datastore.store_consensus_genome(session, document)
return "... | 5,326,584 |
async def test_send(
connection: StaticConnection, connection_id: str, asynchronously_received_messages
):
"""Test send message"""
sent_message = await connection.send_and_await_reply_async(
{
"@type": "https://github.com/hyperledger/aries-toolbox/tree/master/docs/admin-basicmessage/0.1/... | 5,326,585 |
def switchUnicodeUrlOn(switch):
"""
Configure whether to use unicode (UTF-8) encoded URLs (default) or
Latin-1 encoded URLs.
@param switch: 1 if unicode URLs shall be used
"""
assert switch == 0 or switch == 1, "Pass boolean argument, please."
Constants.CONFIG_UNICODE_URL = sw... | 5,326,586 |
def get_genres_from_games(games, their_games):
"""
From the games we will get the same genres
"""
genres = set()
for d in games:
n = d['id']
if n in their_games:
genres.add(d['Genre'])
return genres | 5,326,587 |
def set_password(cfg, username, password):
"""Change password of exists MySQL user"""
try:
change_password(cfg, username, password)
LOG.info('Password for user %s changed', username)
except ProxySQLUserNotFound:
LOG.error("User not found")
exit(1)
except MySQLError as err... | 5,326,588 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up an OpenUV sensor based on a config entry."""
openuv = hass.data[DOMAIN][DATA_OPENUV_CLIENT][entry.entry_id]
binary_sensors = []
for sensor_type in openuv.binary_sensor_conditions:
name, icon = BINARY_SENSORS[sensor_type]
... | 5,326,589 |
def webfinger(request):
"""
A thin wrapper around Bridgy Fed's implementation of WebFinger.
In most cases, this view simply redirects to the same endpoint at Bridgy.
However, Bridgy does not support the ``mailto:`` and ``xmpp:`` resource
schemes - quite reasonably, since there's no possible way to ... | 5,326,590 |
def send_to_teams(url, message_json, debug):
""" posts the json message to the ms teams webhook url """
headers = {'Content-Type': 'application/json'}
r = requests.post(url, data=message_json, headers=headers)
if r.status_code == requests.codes.ok:
if debug:
print('success')
... | 5,326,591 |
def getSSData(args):
"""
Calls the `dump.py` (dumps snapshots data) or `run.py` (dumps commit changes per snapshot) scripts written by Baishakhi Ray. For usage info, run `pydoc get_snapshot_data.printUsage`.
Args to be provided as a list!
Args
----
data_root: string
Path to the direct... | 5,326,592 |
def get_candidate_dir():
"""
Returns a valid directory name to store the pictures.
If it can not be determined, "" is returned.
requires:
import os
import pathlib
import platform
https://docs.python.org/3/library/pathlib.html#pathlib.Path.home
New in version 3.5.
h... | 5,326,593 |
def inflection_points(points, rise_axis, run_axis):
"""
Find the list of vertices that preceed inflection points in a curve. The
curve is differentiated with respect to the coordinate system defined by
`rise_axis` and `run_axis`.
Interestingly, `lambda x: 2*x + 1` should have no inflection points, ... | 5,326,594 |
def compile(raw_model):
"""Compile a raw model.
Parameters
----------
raw_model : list of dict
A raw GPTC model.
Returns
-------
dict
A compiled GPTC model.
"""
categories = {}
for portion in raw_model:
text = gptc.tokenizer.tokenize(portion['text'])
... | 5,326,595 |
def get_elements_html_by_attribute(*args, **kwargs):
"""Return the html of the tag with the specified attribute in the passed HTML document"""
return [whole for _, whole in get_elements_text_and_html_by_attribute(*args, **kwargs)] | 5,326,596 |
def patched_requests_mocker(requests_mock):
"""
This function mocks various PANOS API responses so we can accurately test the instance
"""
base_url = "{}:{}/api/".format(integration_params['server'], integration_params['port'])
# Version information
mock_version_xml = """
<response status = ... | 5,326,597 |
def filter_gq(records, name, min_gq):
"""Filter records based on a minimum genotype quality value."""
for record in records:
if 'GQ' in record.format:
gq = record.samples[name]['GQ']
if gq is not None and gq < min_gq:
continue
yield record | 5,326,598 |
def test_replica_remove():
""" Test logical file remove, which should remove the file from the remote resource
"""
try:
tc = testing.get_test_config ()
the_url = tc.job_service_url # from test config file
the_session = tc.session # from test config file
replica_url = tc.repli... | 5,326,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.