content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _ParsePath(path):
"""Parses a path into a bucket name and an object name."""
if not path:
return '', ''
parts = path.split(_PATH_DELIMITER, 1)
bucket = parts[0] if parts[0] else None
object_name = parts[1] if 1 < len(parts) else None
return bucket, object_name | f059eabe500164a92ae7c32bbae4ca4bc30c0eac | 3,628,374 |
def instance ():
"""
Get single instance of cache. If not setup already, the cache will be set up by default parameters.
"""
global _CacheInstance
if _CacheInstance != None:
return _CacheInstance
else:
return setup () | 117248d9519e1f745a7a6b368425ea2a0759aedc | 3,628,375 |
def bboxes_iou(boxes1,boxes2):
"""
Argument:
bboxes:dim = (num_box,4), 4 : [x_min,y_min,x_max,y_max]
Retiurn:
a np.array,dim = (num_box,1)
"""
boxes1 = np.array(boxes1)
boxes2 = np.array(boxes2)
boxes1_area = (boxes1[...,2] - boxes1[...,0]) * (boxes1[...,3] - boxes1[...,1])
... | 6ab80cbab148280331f5e25e5455b01894034eb0 | 3,628,376 |
def normalizeListVec(v):
"""Normalizes a vector list."""
length = v[0] ** 2 + v[1] ** 2 + v[2] ** 2
if length <= 0:
length = 1
v = [val / np.sqrt(length) for val in v]
return v | 8ee0f960011c79e8e9f8c666aa198c4a72002fe4 | 3,628,378 |
import itertools
def sim_1x5bits(K, kappa, num_sim):
"""
Compute simulation scalar products and
return a list of ranks and intersection values for several simulations.
Parameters:
K -- string
kappa -- string
num_sim -- integer
Return:
rank_wr_list -- list of tuples
"""
# Length of signal part
n ... | 2b5fb3f48b4841fc9b4c1824b7afd91ee15d7a75 | 3,628,379 |
import http
from typing import Optional
def athenaupload_start(
request: http.HttpRequest,
pk: int,
workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
"""Load a data frame using an Athena connection.
The parameters are obtained and if valid, an operation is scheduled for
exec... | 0fd167b85220c32dcab2dfcc59db96cfcddd0106 | 3,628,380 |
def dasum(x):
"""
Compute the sum of the absolute values of the entries in {x}
"""
# compute and return the result
return gsl.blas_dasum(x.data) | 78a09a0f23b88facba04361e2bd222777e769eea | 3,628,381 |
def get_datasets(filename):
"""
Get the names of datasets in an HDF5 file.
Parameters
----------
filename : str
Name of an HDF5 file visible to the arkouda server
Returns
-------
list of str
Names of the datasets in the file
See Also
--------
ls_hdf
... | c844c072501116b505dfcee93236633b8c915de2 | 3,628,383 |
def stats_particle(difference):
""""
Returns the relevant statistics metrics about the distribution of the reative energy difference, as the mean,
standard deviation, standard error and an appropriate label.
:parameter difference: array containing the difference between true energy and the predicted en... | ad5a886cf5167cd7b82deef2700f42eddb517163 | 3,628,384 |
async def rest_handler(request):
"""Defines a GET handler for the '/rest' endpoint.
Users make requests of this handler with a query string containing the following arguments:
cmd: The command c to execute | c E {find, stats}
params: A list of key-value parameters corresponding to the commands ... | 4bfdaa44f1a0189614447780ae6223db3646b32c | 3,628,387 |
def if_true(value, replace_with=None):
"""Replaces the value with the passed if the value is true."""
if not value:
return ''
if replace_with is None:
return value
return Template(replace_with).safe_substitute(value=value) | 968fac956801317454a9fec8a27c53107ed31881 | 3,628,388 |
async def quineables(ctx) -> None:
"""
Displays a list of files printable with
the quine command
"""
table = PrettyTable()
table.align = "c"
table.field_names = ["File Name", "File Path"]
for f, p in _generate_valid_files().items():
table.add_row([f, p])
return await ctx.send... | 01cbef961c5e1383c23ca0055c81fd2167211263 | 3,628,390 |
def piece_not(piece: str) -> str:
"""
helper function to return the other game piece that is not the current game piece
Preconditions:
- piece in {'x', 'o'}
>>> piece_not('x')
'o'
>>> piece_not('o')
'x'
"""
return 'x' if piece == 'o' else 'o' | 18bb3b45accf98d4f914e3f50372c4c083c1db4d | 3,628,391 |
def util(cpu='all', state='user', mode='avg1', host_os=detect_host_os()):
"""
Returns average percentage of time spent by cpu in a state over a period
of time
:raises: WrongArgumentError if unknown cpu is supplied
:raises: WrongArgumentError if unknown state is supplied
:raises: WrongArgumentEr... | 3a754200320a55211ce4d9e2470beb88b12eac57 | 3,628,392 |
import scipy
def fitgaussian(data):
"""Returns (height, x, y, width_x, width_y, angle)
the gaussian parameters of a 2D distribution found by a fit"""
params = moments(data)
errorfunction = lambda p: np.ravel(gaussian(*p)(*np.indices(data.shape)) - data)
p, success = scipy.optimize.leastsq(errorfun... | c7aa83c280a471f7191ea70e81e442320dcff76e | 3,628,393 |
def argsum(*args):
"""sum of all arguments"""
return sum(args) | 2445ef4f3fc321b3eae1997a8c44c628cd72d70a | 3,628,395 |
import multiprocessing
def fit_data_multi_files(dir_path, file_prefix, param, start_i, end_i, interpath="entry/instrument/detector/data"):
"""
Fitting for multiple files with Multiprocessing.
Parameters
----------
dir_path : str
file_prefix : str
param : dict
start_i : int
sta... | 3633054ff8238895e1c6a4fa68be4530d2ea1b22 | 3,628,396 |
def get_exp_parameters():
"""
Defines the default values for the hyper-parameters of the experiment.
:return: A dictionnary with values of the hyper-parameters
:rtype: dict
"""
parser = ArgumentParser(add_help=False)
parser.add_argument('--use_optuna', type=bool, default=False)
parse... | f24240aa14c9bf28c81684a6afedf6ab30796932 | 3,628,398 |
from typing import List
from typing import Dict
from typing import Tuple
from typing import Callable
def enum_options(values: List[Dict]) -> Tuple[List[str], int, Callable]:
"""Enumerate options of a enum parameter for display in a select box.
Returns a 3-tuple containing a list of option value, the list inde... | c1214f319847b40705f425e529420a5916debe6e | 3,628,399 |
def bits_to_netmask(bits):
""" Convert bits to netmask
Args:
bits ('int'): bits to converts
ex.) bits = 32
Raise:
None
Returns:
Net mask
"""
mask = (0xffffffff >> (32 - bits)) << (32 - bits)
return (str( (0xff000000 & mask) >> 24) ... | 33897b357d99027d6f96fc5fb63f38989dbbe930 | 3,628,400 |
from typing import Optional
from typing import Tuple
from typing import Type
import random
def random_array_spec(
shape: Optional[Tuple[int, ...]] = None,
name: Optional[Text] = None,
dtype: Optional[Type[np.floating]] = None,
minimum: Optional[np.ndarray] = None,
maximum: Optional[np.ndarray] = N... | 415b6f170b9912a7ed057cc740f761a7cb33bd0e | 3,628,401 |
def _clamp_angle(angle: Angle) -> Angle:
"""
Certain angles in the game should be prohibited because they are not funny
to play. The Function checks if angle is in the forbidden area and adjusts
the angle.
"""
delta_x = deg2rad(30.0)
delta_y = deg2rad(15.0)
new_angle = angle
if _... | 43c82a06dbe932efa51b6169806c9ff0be131868 | 3,628,402 |
def delete(where, item_id):
"""Returns True if successful; otherwise, False"""
item_uri = uri % (where, str(item_id))
h = httplib2.Http()
response, content = h.request(item_uri, method="DELETE", headers=headers)
return response["status"] == "204", response, content | cd47b963f3675c982cbef57d250b63ac5559eab1 | 3,628,403 |
def calculate_pair_true_positive(docs, dataset_prefix, target_event_types=None):
"""We need this because in generating trigger candidates, we heuristically reject some candidates
So we cannot calculate the true positive from the candidates. We need to go back to the doc level annotations.
:type docs: list[... | 57acfacd341524575434e71bfb18530b7c65e2ed | 3,628,404 |
import time
def getXYforPlanet(time_et, planet, camera, observer=''):
"""
compute for all time instances in this class the xy position of a planet
within a camera_name field-of-view. If not visible, return (-1,-1).
If planet is visible, also return the size of the planet in pixels.
Routine is test... | 7677ebae00247ac227d6a89259b727e535c6e4f2 | 3,628,405 |
def change_format(df):
"""
This function changes the format of the data
"""
df['date'] = pd.to_datetime(df['date'])
to_be_numeric = ['open', 'high', 'low', 'close', 'volume']
df[to_be_numeric] = df[to_be_numeric].apply(pd.to_numeric)
return df | 0eab34c1bdef1fe955a20470228e08887e189e54 | 3,628,406 |
from functools import reduce
def _get_cell_nodes(G, cell_idx):
"""Get array of nodes for a cell."""
# To get face nodes in MRST:
# (The second column in cells_faces are cell indices)
# >> G.faces.nodes(G.faces.nodePos(cell_idx) : G.faces.nodePos(cell_idx+1)-1, 1)
cell_faces = G.cells.faces[G.cells... | d5cc87478bf38e1a3e489af593eea562dc60e0b8 | 3,628,407 |
import base64
def b64_receipt_to_full_service_receipt(b64_string: str) -> dict:
"""Convert a b64-encoded protobuf Receipt into a full-service receipt object"""
receipt_bytes = base64.b64decode(b64_string)
receipt = external_pb2.Receipt.FromString(receipt_bytes)
full_service_receipt = {
"objec... | 7f456d579617c471d79b43a1d2079fad0c024e8a | 3,628,408 |
from pathlib import Path
def main(file: str = "", action: str = "") -> int:
"""This is now we figth!"""
if not file:
return usage()
# Resolve shell variables and ~
rom = Path(expandvars(file)).expanduser()
if action == "check":
return check(rom)
if action == "dump":
... | 3671d36a9a12b11b294a33c48d585eceee7da3af | 3,628,409 |
def find_elements(node, xpath, allow_zero=True, allow_multiple=True):
"""Attempt to find child elements in a node by xpath. Raise exceptions if conditions are violated. Return a
(possibly empty) list of elements."""
all_elements = node.findall(xpath)
if (len(all_elements) == 0 and not allow_zero) or (le... | 2255fcd63f35837c647dd6dca81ab648d59addc8 | 3,628,410 |
from typing import Type
def name(class_name: str, chain_class: Type[ChainAPI]) -> Type[ChainAPI]:
"""
Assign the given name to the chain class.
"""
return chain_class.configure(__name__=class_name) | fc7069911c6698ecf3adb1418a08737fd7a8fa31 | 3,628,411 |
import json
def unlock(vault_path, key):
"""
Unlock legacy vault and retrieve content
"""
f = open(vault_path, "rb")
try:
nonce, tag, ciphertext = [f.read(x) for x in (16, 16, -1)]
finally:
f.close()
# Unlock Vault with key
cipher = AES.new(get_hash(key), AES.MODE... | 059638ee12053db59bbd297dfc1ee2358a747f96 | 3,628,412 |
from datetime import datetime
def module_build_from_modulemd(yaml):
"""
Create a ModuleBuild object and return. It is not written into database.
Please commit by yourself if necessary.
"""
mmd = load_mmd(yaml)
build = ModuleBuild()
build.name = mmd.get_module_name()
build.stream = mmd.... | bc605653ca26d6da6466c796f828397c5d142d07 | 3,628,413 |
def largest_rectangle_area(heights):
""" return largest rectangle in histogram """
stack = [-1]
max_area = 0
for i in range(len(heights)):
# we are saving indexes in stack that is why we comparing last element in stack
# with current height to check if last element in stack not bigger t... | fefb750d57a250c322a6464be250fe2cb3a9a2df | 3,628,414 |
def url_for(root, path, language=None):
"""If page at `path` exists, returns it's root-relative URL;
otherwise throws an exception.
"""
base_url = settings.BASE_URL
if language and language != settings.DEFAULT_LANGUAGE:
base_url += '%s/' % language
node = root.find_descendant(path)
... | 2822c199a6195160b3319c7ef2979fb9dbef67ac | 3,628,416 |
def build_upload_dict(metadata, tags, project):
"""Build the metadata/tags/projects in a dict compatible with what the OneCodex backend expects."""
upload_args = {}
if metadata:
# format metadata keys as snake case
new_metadata = {}
for md_key, md_val in metadata.items():
... | 3ed5ffc2caa884c5dce89e54259ddd103832e006 | 3,628,418 |
from typing import Any
async def books_in_category(category: str) -> Any:
"""Retrieve the books of the given category from the database."""
result = [book for book in BOOKS if book.category == category]
return result | b78cdb386e9c2d73b60a4ccc94f9b56cf4b0b840 | 3,628,419 |
import json
def GetActivationIDsSince(since, limit=100):
"""
Returns the activation IDs (including the namespace)
"""
configs = GetDBConfigs()
url = configs['db_protocol']+'://'+configs['db_host']+':' + \
configs['db_port']+'/'+configs['db_prefix']+'activations/_find'
headers = {
... | 7c0912bd4e09795c5d3831c19f9337cedbedb8c2 | 3,628,420 |
def getOffset(viewID=DEFAULT_VIEW):
"""getOffset(string): -> (double, double)
Returns the x and y offset of the center of the current view.
"""
return _getUniversal(tc.VAR_VIEW_OFFSET, viewID) | bfcdc714bf708b839bc3207c10096f793274a4d6 | 3,628,421 |
import scipy
def laplacian_power(k: int):
"""Compute the coefficients of x^n, x^{n - 1}y, ..., y^n for the k-th power of the Laplacian."""
result = np.zeros(2*k + 1)
# The k-th power is given by (x^2 + y^2)^k = sum_{i = 0}^k {k choose i} x^{2i}y^{2(k - i)}.
# So the coefficient of x^{2i}y^{2(k - i)} i... | 4826472a8f630d8a219f8a47b980b34875f5aefc | 3,628,422 |
from typing import Iterable
from typing import Any
def _as_valid_media_array(x: Iterable[Any]) -> np.ndarray:
"""Converts to ndarray (if not already), and checks validity of data type."""
a = np.asarray(x)
if a.dtype == bool:
a = a.astype(np.uint8) * np.iinfo(np.uint8).max
_as_valid_media_type(a.dtype)
... | d1a3aea15dbcfc8c8c1fb15f9fe1a908f944e055 | 3,628,423 |
def docker_vm_is_running():
"""Using VBoxManage is 0.5 seconds or so faster than Machine."""
running_vms = check_output_demoted(['VBoxManage', 'list', 'runningvms'])
for line in running_vms.splitlines():
if '"{}"'.format(constants.VM_MACHINE_NAME) in line:
return True
return False | be9868cba3c44c53c56890b12812e1a30ae653a8 | 3,628,424 |
def fixture_frame_bucket() -> FrameBucket:
"""Return instance of frame version bucket."""
return FrameBucket() | 7a6b8d56bf4c81e2fef93d9da5a0a95ce883efb7 | 3,628,425 |
def _convert_asset_for_get_list_result(asset):
"""Converts an EarthEngineAsset to the format returned by getList."""
result = _convert_dict(
asset, {
'name': 'id',
'type': ('type', _convert_asset_type_for_get_list_result)
},
defaults={'type': 'Unknown'})
return result | 681e1a2324e928761b29312433c24ccaa635ecf7 | 3,628,426 |
def update_netbox_object(nb_obj, data, check_mode):
"""Update a Netbox object.
:returns tuple(serialized_nb_obj, diff): tuple of the serialized updated
Netbox object and the Ansible diff.
"""
serialized_nb_obj = nb_obj.serialize()
updated_obj = serialized_nb_obj.copy()
updated_obj.update(dat... | 51e07fff4f7f34ee01325fffd74209889073ee16 | 3,628,427 |
def rle_1d(arr):
"""Return the length, starting position and value of consecutive identical values.
Parameters
----------
arr : sequence
Array of values to be parsed.
Returns
-------
(values, run lengths, start positions)
values : np.array
The values taken by arr over each ... | d9616406b84a58e1f9bb201107dd94eab9bc76d6 | 3,628,428 |
def get_time_until_next_departure(trip_call=None):
"""Gets the time until the departure from the next station in minutes
"""
if trip_call is None:
trip_call = get_trip()
return get_time_until_departure(evaNr=get_next_station_eva_number(trip_call=trip_call), trip_call=trip_call) | e1f7f7530d8fbd87ce2c7c8c88b122d3f98e73c2 | 3,628,429 |
def generateMessage(rotation, tiltRight, tiltLeft, eyeLeft, blinkLeft, blinkRight, eyeRight):
"""
"""
messageToSend = []
messageToSend.append(int(rotation))
messageToSend.append(int(tiltRight))
messageToSend.append(int(tiltLeft))
messageToSend.append(int(eyeLeft))
messageToSend.append(i... | fcda9d537cda1fd7dc6fbc1e888d2a1af598104c | 3,628,430 |
from re import M
def compute_performance_metrics(y_true, y_pred):
""" Compute precision, recall, and f1 score.
y_true: true label
y_pred: predicted label
Labels are not hot encoded
Return a dictionary containing Accuracy, Precision, Recall, F1 Score (samples, macro, weighted) and Hamming ... | e4449e733d2b644e7f89a9258c876c0b6788ecac | 3,628,431 |
def metablock(parsed):
"""
Remove HTML tags, entities and superfluous characters from meta blocks.
"""
parsed = " ".join(parsed.replace("\n", "").split()).replace(" ,", ",")
return strip_tags(decode_entities(parsed)) | 8c5e639ee4b8ce083013a530b0a50b750d37dcf1 | 3,628,432 |
def unit_vector(vector):
""" Returns the unit vector of the vector. """
vec_norm = np.linalg.norm(vector)
if vec_norm == 0:
return vector * 0
else:
return vector / np.linalg.norm(vector) | 6cb334012a71f61d5c5b8014aa67cc730bbc6c68 | 3,628,433 |
def app_metadata_json():
"""Create metadata.json content for a test app."""
return {
"description": "A test app that does not really exist.",
"title": "Test App",
"version": "1.0.0",
"authors": "aiidalab",
"logo": "img/logo.png",
"state": "development"
} | a07c21259c43980e51e0a8e115e589b02e493d04 | 3,628,434 |
def get_text(original, token, replace):
"""Convenience function for getting the text to use for a match when
formatting.
If ``replace`` is False, returns the part of ``original`` between
``token.startchar`` and ``token.endchar``. If ``replace`` is True, returns
``token.text``.
"""
if repla... | b0e2e53611cb5b26b04d0e8350f1ae88a6b56056 | 3,628,436 |
def LoadUCursor(fc,flist=None):
"""Important note: Function creates two outputs, also only opens cursor,
no "with" function to automatically close,
remeber to delete cursor and fieldlist when finished"""
fields = [field.name for field in arcpy.ListFields(fc)]
if flist:
for f in flist:
... | c18542a711670ed0d28bc682cca8958bd2c9e360 | 3,628,437 |
import torch
def cal_region_id(data, fps_index, result_path, save=True):
""" calculate and save region id of all the points
Input:
data: (B,num_points,3) tensor, point cloud, num_points=1024
fps_index: (num_regions,) ndarray, center idx of the 32 regions
result_path: path to save file
... | 7a845b0b47c45455d7bef5c428e4aa774934308e | 3,628,438 |
def is_perfect_piggy(turn_score):
"""Returns whether the Perfect Piggy dice-swapping rule should occur."""
# BEGIN PROBLEM 4
"*** REPLACE THIS LINE ***"
if turn_score==1:
return False
elif is_perfect_square(turn_score) or is_perfect_cube(turn_score):
return True
else:
ret... | bca796f0eb90c8de0bc5d78780d702e3fd5cc153 | 3,628,439 |
from freqtrade.worker import Worker
from typing import Dict
from typing import Any
def start_trading(args: Dict[str, Any]) -> int:
"""
Main entry point for trading mode
"""
# Import here to avoid loading worker module when it's not used
# Create and run worker
worker = None
try:
w... | 61776c7f3a9cee79fb53cceffe6a3dcd81db7449 | 3,628,440 |
def make_pairs(values):
"""
Makes a list pairs from an iterable. However, different iterables have
different behaviours when making a list of pairs.
If you are trying to make a list of pairs from a CoupledPair,
the CoupledPair object is wrapped in a list and returned back to you.
If you are tr... | 80f4902852c84717f2fd213006cebaf3de69079e | 3,628,441 |
def directed_decision_free_path(cbn: CausalBayesianNetwork, start_node: str, end_node: str) -> bool:
"""
Checks to see if a directed decision free path exists
"""
for node in [start_node, end_node]:
if node not in cbn.nodes():
raise KeyError(f"The node {node} is not in the (MA)CID")
... | 39a7ba85314ed4429e5b795101429758b02b807a | 3,628,442 |
def post_detail(request, year, month, day, post):
"""
Crear una vista para mostrar el detalle de solo un Post
"""
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,... | 60a8930b673c4f99c43075cff5c2fe1665ccede0 | 3,628,443 |
import struct
def calc_genkey_pubkey_digest(mode, key_id, public_key, temp_key, sn, other_data=None):
"""
Replicate the internal TempKey calculations of the GenKey command in
digest mode.
"""
if len(public_key) != 64:
raise ValueError('public_key must be 64 bytes')
if len(temp_key) != ... | 3a0bff6e535b12e7d53d3ad90af019821d04c78a | 3,628,444 |
def create_repeated_leaf_node(parent_index,
values):
"""Creates a repeated PrensorField.
Args:
parent_index: a list of integers that is converted to a 1-D int64 tensor.
values: a list of whatever type that the field represents.
Returns:
A PrensorField with the parent_in... | 147c6c4b60a65bbaa979a6e2f460101d24f58cb1 | 3,628,446 |
from datetime import datetime
import time
def api_rate_limit(func):
"""Decorator to limit how often a function can be called"""
def inner(self, *args, **kwargs):
if self._previous_request_timestamps[0] >= datetime.now() - timedelta(seconds=1):
print("API Rate Limiting... 10 Requests per se... | d15f4fe65e6c8fbdfc87f924b4c77b3fee8fed56 | 3,628,447 |
def calc_Ti(Te, Tg, n):
"""Calcuate the infectious period."""
return (Tg - Te) * 2.0 * n / (n + 1.0) | 7ba0176b821032e4f69ff7fe368393c2773c7d0d | 3,628,448 |
def function_from_graph_def(graph_def, inputs, outputs, captures=None):
"""Creates a ConcreteFunction from a GraphDef.
Args:
graph_def: A GraphDef to make a function out of.
inputs: A Tensor name or nested structure of names in `graph_def` which
should be inputs to the function.
outputs: A Tensor... | 852810bcffb067b5d7aad47d58395afe7c3bc0ac | 3,628,449 |
def resource_not_found(error):
"""
Error handling for bad request
"""
return jsonify({
"success": False,
"error": 400,
"message": "bad request"
}), 400 | a0c85f191e38022b8d6801b098c54d8863dba9a7 | 3,628,450 |
def _get_indent(line):
"""Return the indentation in front of a line"""
indent = line.replace(line.lstrip(), '')
return indent | 6a5dd97d4c5702a55b8b1ddaad91c5ecb99458fa | 3,628,451 |
def predict_test(this_model, this_true_data, this_y_scaler, target_var, environment):
"""
Using selected best model for this horizon, generates prediction (which is then inversed transform)
Is called in a loop of features which exceed the minimum correlation coefficient
Parameters
----------
t... | 53f4b9b725a6c3fe5693b553f91e755cf950ebd8 | 3,628,452 |
import math
def aline(x: int, y: int, length: int, col: int, angle: int = 0) -> [int, int]:
"""
Draws a angled line. Because lazy math
:param x: start X position
:param y: start Y position
:param length: length of the line in pixels
:param col: colour as integer, see pyxel for that
:param... | 0220b6d0ffabb3b8f238efa3cb157a13dd3e1777 | 3,628,453 |
import logging
def ps_(project):
"""
containers status
"""
logging.info('ps ' + project.name)
running_containers = project.containers(stopped=True)
items = [{
'name': container.name,
'name_without_project': container.name_without_project,
'command': container.human_rea... | 7fe4da390105b29477d4903bc7cb292b1e2ccbc6 | 3,628,454 |
def _GetRegionalSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.regionHealthChecks, 'Update',
client.messages.ComputeRegionHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
he... | ec47ac791fcf912ba7c05077b34f2f62e0949691 | 3,628,455 |
def select_conf(query_message):
"""
Have the user select from a list of all domains with enabled vhost files.
Args:
query_message - The message to display to the user in the prompt
"""
files = enabled_sites()
questions = [
inquirer.List('f',
message=query_mes... | f4e61bc6a5a41bf26cdde853903101babd0eb06d | 3,628,456 |
def load_8_color_sim(measurements, time, thresholds, remove_edges=True, data=False, start_n = 13, end_n = 46, ignore=[22]):
"""
"""
num_frames = len(measurements)
data_dict = load_ME_sim(measurements, time, thresholds, center_only=True, remove_edges=False, direction='horizontal')
k_hat_data = load_... | 53348717952b62e7c51307e8070342a4b426c53e | 3,628,457 |
def service_delete_route(service_id):
"""delete service"""
form = ButtonForm()
if form.validate_on_submit():
service = Service.query.get(service_id)
db.session.delete(service)
db.session.commit()
return redirect(url_for('storage.host_view_route', host_id=service.host_id))
... | e4f7e30c2f5755252451115f06e5a12f7374b26c | 3,628,458 |
def setVariable(name, value):
"""
Assign a variable in scope. name = value
:type name: string
:param name: name of variable to set
:type value: varies
:param value: value to set. May be a basic type (string, int) or an object
"""
return CONTEXT.scope.setValue(name, value) | 7979e3b63dc41bfcdc3ccac10edc1f2c4dd6ebbe | 3,628,459 |
def HighFlowSingleInletGadoxetate2DSPGR_Rat(xData2DArray, Ve, Kbh, Khe,
constantsString):
"""This function contains the algorithm for calculating
how MR signal from a 2D scan varies with time using the
High Flow Single Inlet Two Compartment Gadoxetate Model model.
... | 4b856e9aa0209ab6e92232b42c7c6b8e029672d1 | 3,628,460 |
def to_nltk_tokens(
df,
sentence_cols=["sentence1", "sentence2"],
token_cols=["sentence1_tokens", "sentence2_tokens"],
):
"""
This function converts a sentence to word tokens using nltk.
Args:
df (pd.DataFrame): Dataframe with columns sentence_cols to tokenize.
sentence_cols (li... | 310095ba481376fe3c58c9d09c10a89793e4cd27 | 3,628,461 |
def problems(mod, msg):
"""Ansible module exist with an error."""
return mod.exit_json(changed=False, failed=True, msg=msg) | 3ec1a8c8843ba9b33d47e61d1b775aadb32ab45e | 3,628,462 |
def to_sql_name(name):
"""
Ensure ``name`` is a valid SQL name.
"""
return name.lower().replace(' ', '_') | f3157d9444793d0af05e27317fdab2aa55531b84 | 3,628,463 |
def natural_breaks(values, k=5, init=10):
"""
natural breaks helper function
Jenks natural breaks is kmeans in one dimension
Parameters
----------
values : array
(n, 1) values to bin
k : int
Number of classes
init: int, default:10
Number of different sol... | 86373c0f43eddb15fb3fab75a27f0e1270f2c359 | 3,628,465 |
def _get_base_code_module(builder_name: tfds.core.naming.DatasetName) -> str:
"""Find the code location of the requested dataset."""
builder_name = str(builder_name)
module_path = utils.sunds_dir() / 'datasets'
if (module_path / builder_name).exists():
return f'sunds.datasets.{builder_name}'
else:
rai... | d169465d9dcca94d274e4ff09653aa591692ada6 | 3,628,466 |
def polygon_to_points( poly ):
"""
Plotting helper, which rearranges polygon vertices into lists
of X and Y coordinates. The first point is duplicated at the end
of each list, to make a closed path.
:Parameters:
poly: tuple of ((x1,y1),(x2,y2),...)
The coordinates of t... | 958621cb7ff2d4fe22c4482e07a6a7ba614f9fc1 | 3,628,467 |
def make_headers(worksheet):
"""
Make headers from worksheet
"""
headers = {}
cell_idx = 0
while cell_idx < worksheet.ncols:
cell_type = worksheet.cell_type(0, cell_idx)
if cell_type == 1:
header = slughifi(worksheet.cell_value(0, cell_idx))
if not header.... | fb5f66e4d0cc931dcf6ccbb8848244cd4483498f | 3,628,468 |
import re
def alphanumerical(string):
"""
A function to filter a string to only allow alphanumerical characters.
"""
pattern = re.compile('[^a-zA-Z0-9]+')
return pattern.sub('', string) | 3acd64f629e601c72421ac73955a61c1426d3a9d | 3,628,469 |
from typing import Tuple
def _avgpool2d_im2col_reduce(
x: AbstractTensor,
pool_size: Tuple[int, int],
strides: Tuple[int, int],
padding: str,
) -> AbstractTensor:
"""Perform 2D average pooling by the im2col method."""
batch, channels, height, width = x.shape
pool_height, pool_width = pool_size
... | 123377c9d6dfcdaaf874c47156b0cdb177fbf126 | 3,628,470 |
def helper_parse_UniProt_dump_other_functions(list_of_string):
"""
e.g. input
[['EMBL; AY548484; AAT09660.1; -; Genomic_DNA.'],
['RefSeq; YP_031579.1; NC_005946.1.'],
['ProteinModelPortal; Q6GZX4; -.'],
['SwissPalm; Q6GZX4; -.'],
['GeneID; 2947773; -.'],
['KEGG; vg:2947773; -.'],
... | 292cd9eca3636ba3cd6813df574de3bdd54aa48f | 3,628,471 |
import numpy
def normalise_signal_minmax(signal: numpy.ndarray) -> numpy.ndarray:
""" """
return numpy.interp(signal, (signal.min(), signal.max()), (-1, 1)) | 266cb3c86fa5f48c997bb8f18e42cc38b2d05d7e | 3,628,472 |
from typing import List
from typing import Tuple
import statistics
def znormalizeSpeakerData(
featureTimeList: List[Tuple[float, ...]], index: int, filterZeroValues: bool
) -> List[Tuple[float, ...]]:
"""
znormalize time series data
The idea is to normalize each speaker separately to be able
to c... | 67978c7118f5e7645913d9bc79b5fb3726cbc217 | 3,628,474 |
def only_float(val):
"""Pass input val value or array only if it is a float.
:param val: value to be evaluated
:returns: evaluated value
:rtype: np.float64 or np.ndarray
"""
if isinstance(val, (np.float64, float)):
return val
elif hasattr(val, "__iter__") and not isinstance(val, str... | ba097f39047c55065dd5b3189ce54a3bb89151a7 | 3,628,476 |
def dcos_ca_bundle():
"""
Retrieve DC/OS CA bundle and returns the content.
"""
return transport_encryption.fetch_dcos_ca_bundle_contents().decode("ascii") | ae383804c2b91691564d595696904b6d498bff81 | 3,628,477 |
def slr_range_bias(dset):
"""Calculate the partial derivative of the measurement with respect to range bias.
Args:
data: A Dataset containing model data.
Returns:
Tuple: Array of partial derivatives, and list of names of derivatives
"""
# Check if stations to estimate for ac... | d02c21366d8d6e516391d82a51da8f4748dcfa70 | 3,628,478 |
def calc_cond_hf(data: h5py.File, direction: str='full'):
"""Calculate the conductive heat flow for the whole model cube in x, y, z direction
Args:
data (h5py.File): HDF5 file with simulated variables
direction (str, optional): string to return either full (x,y,z) heat flow, or just one directi... | dc83ef46daaa91384a8791eb2bac6117064c3853 | 3,628,479 |
def decode_dbkey(dbkey):
""" Decodes dbkey and returns tuple ( username, dbkey )"""
if isinstance(dbkey, str) and ':' in dbkey:
return dbkey.split(':')
else:
return None, dbkey | de2a076b36e4ea82412478384b65845af225b1ab | 3,628,480 |
def get_case_related_entities(st, related_cases):
"""Returns the all the entities featured in the related cases without duplicates.
INPUT: Storage unit, related cases.
OUTPUT: All the entities and their types contained in the related cases without duplicates"""
existing_ners = {}
for c in related_ca... | 7ecc8927720a22d5dc05c948b9abbae458aee426 | 3,628,481 |
def create_view(request):
""" Takes a http request and renders a page for creating a Hub.
"""
if(request.method == 'POST'):
form = HubCreateForm(request.POST)
# Check if the form is valid:
if form.is_valid():
queryset_hub = Hub.objects.filter(seller_name... | 2552acd9995f5fb10f1c5cb639e21cc37a887aec | 3,628,482 |
async def async_setup(hass, config):
"""Start the Fortigate component."""
conf = config[DOMAIN]
host = conf[CONF_HOST]
user = conf[CONF_USERNAME]
api_key = conf[CONF_API_KEY]
devices = conf[CONF_DEVICES]
is_success = await async_setup_fortigate(
hass, config, host, user, api_key, d... | 29d9e3049f5bb45ad9b85eaf39e25e517871eaf6 | 3,628,483 |
import random
def get_documents_words(news_files, corpus_news):
"""
Given a set of documents it will return the dictionary with their
respective categories
:param news_files: List of raw news file names
:param corpus_news: PlainTextCorpusReader object
:return: Dictionary with words and categor... | ad189bf0e00118bebbb21794d959d903242ca10c | 3,628,484 |
def process(ele):
"""reshape 'dtce' and 0-1 normalizes it"""
ele['dtce'] = tf.reshape(ele['dtce'], [ele['height'], ele['width']])
ele['dtce'] = (ele['dtce'] - tf.reduce_min(ele['dtce']))/(tf.reduce_max(ele['dtce']) - tf.reduce_min(ele['dtce']))
return ele | 8ed6f643e177834898619295c293c1b0a169fae1 | 3,628,485 |
def get_CIFAR10_data(cifar10_dir, num_training=49000, num_validation=1000, num_test=1000,
subtract_mean=True):
"""
Load the CIFAR-10 dataset from disk and perform preprocessing to prepare
it for classifiers.
"""
# Load the raw CIFAR-10 data
X_train, y_train, X_test, y_test =... | fa90aec774ced080f78dbb7123cd2b873ad28361 | 3,628,486 |
def response_for_created_event(event, status_code):
"""
Method returning the response when an event has been successfully created.
:param status_code:
:param event: Event
:return: Http Response
"""
return make_response(jsonify({'event' : {
'event_id': event.event_id,
'event_n... | 1b86d011aa3a564d4b06018bfadd1992ce8c8515 | 3,628,488 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.