content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import idwgopt.idwgopt_default as idwgopt_default
def default(nvars):
""" Generate default problem structure for IDW-RBF Global Optimization.
problem=idwgopt.default(n) generate a default problem structure for a
an optimization with n variables.
(C) 2019 by A. Bemporad.
"""
problem = idw... | 6e865ffdab0b3913c793357b6cb2688a6cd4dc00 | 25,877 |
from point import Point
from line import Segment
from polygon import Polygon
def convex_hull(*args):
"""
Returns a Polygon representing the convex hull of a set of 2D points.
Notes:
======
This can only be performed on a set of non-symbolic points.
Example:
========
>>> from ... | ee1c1fd65dfe849a36a6dfc8e86a4e1e2ee8ca69 | 25,878 |
from typing import Dict
def find_namespaces(tree: ElementTree) -> Dict[str, str]:
"""
Finds the namespaces defined in the ElementTree of an XML document. It looks for namespaces
defined in the root element of the XML document. To avoid namespaces being left out, they shall
all be defined in the root e... | 8b2a523c9d7152280fa609563e94eda4facebe4b | 25,879 |
def filterStories(stories, triggerlist):
"""
Takes in a list of NewsStory instances.
Returns: a list of only the stories for which a trigger in triggerlist fires.
"""
filteredStories = []
for story in stories:
for trig in triggerlist:
if trig.evaluate(story) and story not in... | 1fcf2592e22c97cd13919dbfe5b8a4acde682761 | 25,880 |
def lcs(a, b):
"""
Compute the length of the longest common subsequence between two sequences.
Time complexity: O(len(a) * len(b))
Space complexity: O(min(len(a), len(b)))
"""
# This is an adaptation of the standard LCS dynamic programming algorithm
# tweaked for lower memory consumption.
... | 0201e9efade98aece854e05d0910192251e5f63c | 25,881 |
def save(config, filename="image.img", host=None):
"""Save the Image File to the disk"""
cmd = DockerCommandBuilder(host=host).save(config.getImageName()).set_output(filename).build()
return execute(cmd) | 628dca6307b6a5d975e90e08649f20790bc8b639 | 25,882 |
def lines2bars(lines, is_date):
"""将CSV记录转换为Bar对象
header: date,open,high,low,close,money,volume,factor
lines: 2022-02-10 10:06:00,16.87,16.89,16.87,16.88,4105065.000000,243200.000000,121.719130
"""
if isinstance(lines, str):
lines = [lines]
def parse_date(x):
return arrow.get(... | 4d2049d08f885de3b999b1537a48c03088f45da3 | 25,884 |
import torch
def pgd_linf_untargeted(model, X, y, epsilon=0.1, alpha=0.01, num_iter=20, randomize=False):
""" Construct FGSM adversarial examples on the examples X"""
if randomize:
delta = torch.rand_like(X, requires_grad=True)
delta.data = delta.data * 2 * epsilon - epsilon
else:
... | b19091048d269853c6b55c4d96d5919c4efcfbe6 | 25,885 |
def cal_NB_pvalue (treatTotal,controlTotal,items):
"""calculate the pvalue in pos of chromosome.
"""
pvalue = 1
(treatCount,controlCount,pos)=items
pvalue = negativeBinomail(treatCount,treatTotal,controlCount,controlTotal)
return (pvalue,treatCount,controlCount,pos) | f68809ffb40949c2d4ca1486870ec421d48bbfb5 | 25,886 |
def handle_watches(connection, author):
"""Return an array of watches for the author."""
database = connection['test']
collection = database['watches']
watches = []
# this should not except
for post in collection.find({"author" : ObjectId(author)}):
watches.append(cleanup_watc... | bfb765e30d249fac30fdbf567006283be1808e6c | 25,887 |
def new_mm(*args, figsize, **kwargs):
"""Wrapper for plt.subplots, using figsize in millimeters
:rtype: figure, axes
"""
return plt.subplots(*args, figsize=(figsize[0] / 25.4, figsize[1] / 25.4), **kwargs) | 7111f1fd8261d3367bff03fd36ed86cc26917fe8 | 25,888 |
def compute_center_of_mass(coordinates, masses):
"""
Given coordinates and masses, return center of mass coordinates.
Also works to compute COM translational motion.
Args:
coordinates ({nparticle, ndim} ndarray): xyz (to compute COM) or velocities (COM velocity)
masses ({nparticle,} arr... | d190c20930209e180524c07c8bf8fef9ab95734b | 25,889 |
def chars_count(word: str):
"""
:param word: string to count the occurrences of a character symbol for.
:return: a dictionary mapping each character found in word to the number of times it appears in it.
"""
res = dict()
for c in word:
res[c] = res.get(c, 0) + 1
return res | 30c27b23c04909a65264247d068e9e2c695c6ecc | 25,890 |
def do_expressiondelete(**kwargs):
"""
Worker to remove expression from engine
proexpobj: expression object
profileexplist: expression list object
return 0 if expression deleted
"""
proexpobj = kwargs.get('proexpobj')
profileexplist = kwargs.get('profileexplist')
if profileexplist.... | 4d4f26aca34417026ac326d237f817b88afe525c | 25,891 |
import csv
def read_csv_as_nested_dict(filename, keyfield, separator, quote):
"""
Inputs:
filename - name of CSV file
keyfield - field to use as key for rows
separator - character that separates fields
quote - character used to optionally quote fields
Output:
Returns a ... | b86a19e531ac2d0c815839714ee93fbc618e911d | 25,892 |
def msgpackb(lis):
"""list -> bytes"""
return create_msgpack(lis) | 4e2667ff32c58be09620cd8360ff0207406a7871 | 25,893 |
from azureml._execution import _commands
from azureml.core.runconfig import RunConfiguration
from azureml._project.project import Project
def prepare_compute_target(experiment, source_directory, run_config):
"""Prepare the compute target.
Installs all the required packages for an experiment run based on run_... | d6a7f2f45483c2e0a42bcb03407791ca781318ab | 25,894 |
def streaming_ndarray_agg(
in_stream,
ndarray_cols,
aggregate_cols,
value_cols=[],
sample_cols=[],
chunksize=30000,
add_count_col=False,
divide_by_count=False,
):
"""
Takes in_stream of dataframes
Applies ndarray-aware groupby-sum or groupby-mean: treats ndarray_cols as ... | a47a3f82444dc1ef7d5eb5f63d7dd77c862fc605 | 25,895 |
from typing import List
def get_cropped_source_data(
stack_list: List[str], crop_origin: np.ndarray, crop_max: np.ndarray
) -> np.ndarray:
"""
Read data from the given image files in an image stack
:param List[str] stack_list: List of filenames representing images in a stack
:param np.ndarray cro... | 40f2537417a99d070979ba206de7c6e91a313b02 | 25,896 |
def valid_random_four_channel_images() -> str:
"""
Make a folder with 5 valid images that have 4 channels.
:return: path to the folder
"""
# use .png because that supports 4 channels
return make_folder_with_files('.png', file_type='image', resolution=(300, 300), n_files=6, channels=4) | 6b39f46467b4ded5a773964255293a3b587d9b6d | 25,897 |
def build_template(spec) -> Template:
"""Build a template from a specification.
The resulting template is an object that when called with a set of
bindings (as produced by a matcher from `build_matcher`), returns
an instance of the template with names substituted by their bound values.
This is a g... | ef44befe0a937b786a48b1e1ddf729f5c1327e3b | 25,898 |
def roll(y, z):
"""Estimate angular roll from gravitational acceleration.
Args:
y, z (float, int, array-like): y, and z acceleration
Returns:
(float, int, array-like): roll
"""
return np.arctan2(y, z) * 180/np.pi | ccb0bf948baf7fee9853f4b842139e8a964c25b6 | 25,901 |
def check_valid_move(grid: np.ndarray, current_position: tuple, move: tuple) -> bool:
"""
Checking if move is valid for the current position in provided grid
:param grid: validated array of a grid
:param current_position: current position
:param move: move in tuple form
:return: True or False
... | 60f58c618a01aad744e1ae7c6d425fc69db20686 | 25,904 |
def check_valid_game(season, game):
"""
Checks if gameid in season schedule.
:param season: int, season
:param game: int, game
:return: bool
"""
try:
get_game_status(season, game)
return True
except IndexError:
return False | 5bc95a2dc397b933c1e5716eb5a7e79641b87968 | 25,905 |
def console(session_console):
"""Return a root console.
Be sure to use this fixture if the GUI needs to be initialized for a test.
"""
console = session_console
assert libtcodpy.console_flush() == 0
libtcodpy.console_set_default_foreground(console, libtcodpy.white)
libtcodpy.console_set_def... | 25c13c549a40c24f7abc90ecb7c303bbc791643b | 25,906 |
def conv(out_channels, kernel_size, stride=2, padding=1, batch_norm=True):
"""Creates a convolutional layer, with optional batch normalization.
"""
layers = []
conv_layer = Conv2D(out_channels, kernel_size, strides = stride, padding = 'same', use_bias = False, data_format = "channels_first")
# bias ... | fe568a8b3cd5092db6751677f1accd3d73e36e77 | 25,907 |
def t90_from_t68(t68):
"""
ITS-90 temperature from IPTS-68 temperature
This conversion should be applied to all in-situ
data collected between 1/1/1968 and 31/12/1989.
"""
return t68 / 1.00024 | a2d8c7ccc0797d47fa8f732bdb61c1ec1e15700e | 25,908 |
def prettify(elem):
"""Return a pretty-printed XML strong for the Element.
"""
rough_string = ElementTree.tostring(elem, "utf-8")
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | b7686ca0b6d6def2e86f465fa0eb5726fe29d2ab | 25,909 |
def _pad(
s: str,
bs: int,
) -> str:
"""Pads a string so its length is a multiple of a specified block size.
:param s: The string that is to be padded
:type s: str
:param bs: The block size
:type bs: int
:returns: The initial string, padded to have a length that is a multiple of... | 1da441d51c57da688ebcf46b7a30feb36cd007fe | 25,911 |
import json
def get_json(headers) -> str:
"""Construct a str formatted like JSON"""
body: dict = {}
for key, value in headers.items():
body[key] = value
return json.dumps(body, indent=2) | 8471f044ae986acd2173d5e9be26c110ee1b1976 | 25,912 |
from typing import Any
def is_jsonable_object(obj: Any) -> bool:
"""
Return `True` if ``obj`` is a jsonable object
"""
cls = obj if isinstance(obj, type) else type(obj)
return isinstance(getattr(cls, PHERES_ATTR, None), ObjectData) | f0492544c88efc46d135bc913bc7f8dd7a7f7462 | 25,914 |
def Dir(obj):
"""As the standard dir, but also listup fields of COM object
Create COM object with [win32com.client.gencache.EnsureDispatch]
for early-binding to get what methods and params are available.
"""
keys = dir(obj)
try:
## if hasattr(obj, '_prop_map_get_'):
## k... | 8abc62fbe09e953fb171626a888838e21346ad9e | 25,915 |
def image_classify(request):
""" Image classification """
if request.method == 'POST':
# Get upload image
img = request.FILES.get('img', None)
if img:
return JsonResponse(dict(name=img.name, size=img.size))
else:
return JsonResponse(dict(code=401, msg='Ba... | 4f459f7a7afd90b1c6de7f174b4926d0d90b35cb | 25,916 |
def calculate_performance_indicators_V1(df):
"""Compute indicators of performances from df of predictions and GT:
- MAE: absolute distance of predicted value to ground truth
- Accuracy: 1 if predicted value falls within class boundaries
Note: Predicted and ground truths coverage values are ratios betwee... | f5c374ffb558eaf65a4c29894fbcb831162a451d | 25,917 |
def PH2_Calc(KH2, tH2, Kr, I, qH2):
"""
Calculate PH2.
:param KH2: hydrogen valve constant [kmol.s^(-1).atm^(-1)]
:type KH2 : float
:param tH2: hydrogen time constant [s]
:type tH2 : float
:param Kr: modeling constant [kmol.s^(-1).A^(-1)]
:type Kr : float
:param I: cell load current... | fe69353bfdde4f301439b89f9946782457d07645 | 25,918 |
import scipy
def log_transform(image):
"""Renormalize image intensities to log space
Returns a tuple of transformed image and a dictionary to be passed into
inverse_log_transform. The minimum and maximum from the dictionary
can be applied to an image by the inverse_log_transform to
convert i... | 8e8d6779b313c7ff02e7aafa291e4d2abd687ac1 | 25,919 |
from bs4 import BeautifulSoup
from typing import Optional
def parse_cpu(website: BeautifulSoup, product_id: int) -> Optional[CPU]:
"""Parses the given Intel ARK website for a CPU."""
# thanks for making accessing so easy btw.
# a simple string used for identification of the CPU
raw = website.find(att... | 1e7d068caba63947c39ce3a2391009986c5d6ad3 | 25,920 |
from typing import List
def create_result_dict(
begin_date: str,
end_date: str,
total_downloads: int,
downloads_per_country: List[dict],
multi_row_columns: dict,
single_row_columns: dict,
) -> dict:
"""Create one result dictionary with info on downloads for a specific eprint id in a given ... | 59ed6c40e98a8a68e1914f8f14b992b702851ccd | 25,921 |
def getConcentricCell(cellNum, matNum, density, innerSurface, outerSurface, universe, comment):
"""Create a cell which has multiple components inside a cell."""
uCard = ''
if type(universe) is int:
uCard = 'u=' + str(universe)
listType = []
if type(innerSurface) == type(listType):
ne... | f0e8af3210774500eac0fde195896f3b85473e3f | 25,922 |
import tqdm
def weight_compression(weights, bits, axis=0, quantizer=None):
"""Creates an in, out table that maps weight values to their codebook values.
Based on the idea presented by https://arxiv.org/pdf/1911.02079.pdf
Arguments:
weights: Numpy array
bits: Number of bits to compress weights to. This ... | f7fd3a1908c51a1781367bfd717d9db6f7740934 | 25,925 |
import multiprocessing
def noncoherent_dedispersion(array, dm_grid, nu_max, d_nu, d_t, threads=1):
"""
Method that de-disperse dynamical spectra with range values of dispersion
measures and average them in frequency to obtain image in (t, DM)-plane.
:param array:
Numpy 2D array (#freq, #t) wi... | 866e129e74ae121c093c70a67c811f6a0bf0d3bc | 25,926 |
def ParseLabelTensorOrDict(labels):
"""Return a tensor to use for input labels to tensor_forest.
The incoming targets can be a dict where keys are the string names of the
columns, which we turn into a single 1-D tensor for classification or
2-D tensor for regression.
Converts sparse tensors to dense ones.
... | d0f5dcd32fc04418caa9715be2779897703927cb | 25,928 |
def showCallGraph(pyew, doprint=True, addr=None):
""" Show the callgraph of the whole program """
dot = CCallGraphGenerator(pyew)
buf = dot.generateDot()
if doprint:
showDotInXDot(buf)
return buf | 936176e312652536dc4cea8eaf3da531ec519615 | 25,929 |
def make_template(center, data):
"""Make templated data."""
if isinstance(data, dict):
return {key: make_template(center, val) for key, val in data.items()}
if isinstance(data, list):
return [make_template(center, val) for val in data]
env = get_env(center)
return env.from_string(s... | 54763209c2b65604c3c781bdbf7553198048757f | 25,930 |
def get_sequana_adapters(type_, direction):
"""Return path to a list of adapters in FASTA format
:param tag: PCRFree, Rubicon, Nextera
:param type_: fwd, rev, revcomp
:return: path to the adapter filename
"""
# search possible types
registered = _get_registered_adapters()
if type_ not ... | a331f9f0839d1193b9deefb3dbbdc8e31f882843 | 25,931 |
def board_str(board):
"""
String representation of the board. Unicode character for the piece,
1 for threat zone and 0 for empty zone.
"""
mat = ''
for row in board:
for squ in row:
if squ > 1:
mat += '%s ' % chr(squ)
else:
mat +=... | 769d846c5b03c8b75145e3b81cab17ed7331fbbf | 25,932 |
def build_pubmed_url(pubmed_id) -> str:
"""
Generates a Pubmed URL from a Pubmed ID
:param pubmed_id: Pubmed ID to concatenate to Pubmed URL
:return: Pubmed URL
"""
return "https://pubmed.ncbi.nlm.nih.gov/" + str(pubmed_id) | 5794fbec75de0451547d6f0570bb89964026c394 | 25,933 |
def create_build_job_query(user, time_frame, local=False):
"""Create the query to get build jobs from graylog
Args:
user(str): Fed ID
time_frame(int): Graylog search period in hours
local(bool): If True also search string for local builds
Returns:
str: Query string for a gr... | ada2dd0c40ef0de8221e03dbdf5c2410705ff2cf | 25,934 |
def convert_to_json(payload_content):
"""Convert the OPC DA array data to JSON (Dict) and return the aggregated JSON data."""
try:
json_response = {}
for t in payload_content: # tuple in payload_content
temp = {}
key = t[0].replace(".", "-").replace("/", "_")
... | be7aa3a60c9d8ad48e5a48e09bb16e5d456f2cba | 25,935 |
def unites(value=32767):
"""
Restock all resistance messages.
"""
invoker = spellbook.getInvoker()
value = min(value, 32767)
invoker.restockAllResistanceMessages(value)
return 'Restocked %d unites!' % value | 6cb8e977216b0559c1de85c14ff95983b92a11a1 | 25,936 |
def gif_summary(name, tensor, max_outputs, fps, collections=None, family=None):
"""Outputs a `Summary` protocol buffer with gif animations.
Args:
name: Name of the summary.
tensor: A 5-D `uint8` `Tensor` of shape `[batch_size, time, height, width,
channels]` where `channels` is 1 or 3.
... | c0c4fda8e988c6f5a3918ae45531692ef36588e4 | 25,937 |
def fFargIm(k,phi, x):
"""Imaginary part of the argument for the integral in fF()
"""
theta=phi*x
return (1/np.sqrt(1-k*k*np.sin(theta)**2)).imag | ec858c9b81e881e6d91299546904670723300b82 | 25,938 |
import warnings
def deprecated(func):
"""Prints a warning for functions marked as deprecated"""
def new_func(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) # turn off filter
warnings.warn('Call to deprecated function "{}".'.format(func.__name__),
c... | f92e71f8662d71d3ed5a93f914cf3352282d940c | 25,939 |
def _simulate_dataset(
latent_states,
covs,
log_weights,
pardict,
labels,
dimensions,
n_obs,
update_info,
control_data,
observed_factor_data,
policies,
transition_info,
):
"""Simulate datasets generated by a latent factor model.
Args:
See simulate_data
... | 5f3c046ffea328e01580e607762311a96b9bf66d | 25,940 |
def has_user_data(node: hou.Node, name: str) -> bool:
"""Check if a node has user data under the supplied name.
:param node: The node to check for user data on.
:param name: The user data name.
:return: Whether or not the node has user data of the given name.
"""
return _cpp_methods.hasUserDat... | 5953a24fa369f7d8c1aed7635d5fde3f30324c27 | 25,941 |
def load_ptsrc_catalog(cat_name, freqs, freq0=1.e8, usecols=(10,12,77,-5), sort=False):
"""
Load point sources from the GLEAM catalog.
Parameters
----------
cat_name : str
Filename of piunt source catalogue.
freqs : array_like
Array of frequencies to evaluate point sour... | 54f830e9fef746cdabe8b29cc9a7481b67593476 | 25,942 |
def get_model():
"""
Reference : http://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf
I have added dropout layers to reduce overfitting
"""
model = Sequential()
# Normalization and zero centering.
model.add(Lambda(lambda x: x / 255.0 - ... | 4591745f43719450f2da579b13ebd45a103bf76e | 25,944 |
def ser_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a single CPU core.
INPUTS:
in1 (no... | 3a0e22ef55b14dfce3eb706800439d55f97bcd19 | 25,945 |
def delete_ref(profile, ref):
"""Delete a ref.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
ref
The ref to ... | 4009c3bb787914ed4130760cf5d3fcfad4032496 | 25,946 |
def mean_ratio_reversion_test(hd1, hd2, n=20, offset=20, hold_time=30, return_index=False):
"""
Tests over the time period offset:offset-hold_time to see if the price ratio of the
price pair reverts to the mean.
"""
#Get initial price ratio
init_pr = hd1.close[offset]/hd2.close[offset]
#Get... | 248987fbbb718303b413fe1eb63384fba42edc07 | 25,947 |
def list_contents(path, root):
"""
@return list of relative paths rooted at "root"
"""
cmd = "svn ls %s/%s" % (root, path)
code, out = util.execute(cmd, return_out=True)
dirs = out.strip().split('\n')
return dirs | 4fd02b8aeb362bdca1d37f4dc3d481b38f1d9059 | 25,948 |
def evaluate_voting():
"""Evaluates the Voting-Results in the instance_dict. Returns Array with the Player-ID(s)"""
poll_dict = {}
for ip in instance_dict.keys():
if 'poll' in instance_dict[ip]:
if instance_dict[ip]['poll'] in poll_dict:
old = poll_dict[instance_dict[ip][... | 4c86e453e24114ad00239a3ad97c23f9b25dd243 | 25,949 |
import torch
def mmd(x1, x2, sigmas):
"""the loss of maximum mean discrepancy."""
x1 = torch.reshape(x1, [x1.shape[0], -1])
x2 = torch.reshape(x2, [x2.shape[0], -1])
# print('x1x2shape:', x1.shape)
diff = torch.mean(gaussian_kernel(x1, x1, sigmas)) # mean_x1x1
diff -= 2 * torch.mean(gaussian_... | 1248de57d5aac658c54c6f67b4ba072f3dcd3978 | 25,950 |
def choose(n,r):
"""
number of combinations of n things taken r at a time (order unimportant)
"""
if (n < r):
return 0
if (n == r):
return 1
s = min(r, (n - r))
t = n
a = n-1
b = 2
while b <= s:
t = (t*a)//b
a -= 1
b += 1
return t | 5852054f1a6381278039b0ec2184d0887e2b1d2b | 25,953 |
def _bisearch(ucs, table):
"""
Auxiliary function for binary search in interval table.
:arg int ucs: Ordinal value of unicode character.
:arg list table: List of starting and ending ranges of ordinal values,
in form of ``[(start, end), ...]``.
:rtype: int
:returns: 1 if ordinal value uc... | f9b985771fa94138ae9b0dfbb8fa9ee413c65a48 | 25,954 |
def get_xml_serial_number (root):
"""
Get the serial number from the system global settings XML.
Parameters:
root -- An XML element to the root of the system global settings.
Return:
The serial number.
"""
return get_xml_string_value (root, "serialNumber", "ser... | 5b1dd2ef70f34980cddce442a1c8707c5d81e478 | 25,955 |
def ParseMachineType(resource_parser, machine_type_name, project, location,
scope):
"""Returns the location-specific machine type uri."""
if scope == compute_scopes.ScopeEnum.ZONE:
collection = 'compute.machineTypes'
params = {'project': project, 'zone': location}
elif scope == comput... | 70b5311525569a4981fd0170a62a3f0d53a8a8f1 | 25,956 |
def redirect_to_default():
"""
Redirects users to main page if they make a GET request to /generate
Generate should only be POSTed to
"""
log("Received GET request for /generate, returning to default page")
return redirect(url_for("default")) | 951e610ac3e56ec6e84dbeacb3174fe79a1c6f9c | 25,957 |
def client_credential_grant_session():
"""Create a Session from Client Credential Grant."""
oauth2credential = OAuth2Credential(
client_id=None,
redirect_url=None,
access_token=ACCESS_TOKEN,
expires_in_seconds=EXPIRES_IN_SECONDS,
scopes=SCOPES_SET,
grant_type=auth... | 54b37e3a6ae582982e47e2135058ce6d7bafd6ea | 25,958 |
import requests
def _query(server, method, parameters, timeout=DEFAULT_TIMEOUT, verify_ssl=True, proxies=None):
"""Formats and performs the query against the API.
:param server: The MyGeotab server.
:type server: str
:param method: The method name.
:type method: str
:param parameters: The par... | a7615543dffc7270fddc12bc909488cdd03ad0be | 25,959 |
def volume_update(context, volume_id, values):
"""Set the given properties on an volume and update it.
Raises NotFound if volume does not exist.
"""
return IMPL.volume_update(context, volume_id, values) | 1f696458654daf25767ec2a888a2bfa7a8c1872d | 25,960 |
def get_E_Elc_microwave_d_t(P_Elc_microwave_cook_rtd, t_microwave_cook_d_t):
"""時刻別消費電力量を計算する
Parameters
----------
P_Elc_microwave_cook_rtd : float
調理時の定格待機電力, W
t_microwave_cook_d_t : ndarray(N-dimensional array)
1年間の全時間の調理時間を格納したND配列, h
d日t時の調理時間が年開始時から8760個連... | c49666272e86c8e10b8df15e639056ba8701f88b | 25,961 |
from typing import Tuple
from typing import Any
def set_up_text_location(
image: ImageDraw, img_opened: Image, text: str, font: ImageFont
) -> Tuple[Any, Any]:
"""
Returns coordinates of text location on the image
:param image: ImageDraw object
:param img_opened: opened PIL image
:param text: ... | 26f8a7719e033cd81db66e50ecd638abd67a6846 | 25,962 |
def service_detail(request, service_id):
"""This view shows the details of a service"""
service = get_object_or_404(Service, pk=service_id)
job_statuses = (
enumerations.QUEUED,
enumerations.IN_PROCESS,
enumerations.FAILED,
)
resources_being_harvested = HarvestJob.objects.fil... | 13abb413973428eda57c0c18e9ee71044f9e32ab | 25,963 |
def convolutional_block(X, f, filters, stage, block, s):
"""
Implementation of the convolutional block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main path
... | ab695bd12b7179c02f2cc8696eeeedf3f153bfce | 25,964 |
def process_input(values, puzzle_input, u_input):
"""Takes input from the user and records them in the location specified
by the "value", and returns the resulting puzzle input
"""
puzzle_input[values[0]] = u_input
return puzzle_input | 300c0850afa977d738f5a5ebbcb1b36ccd557b23 | 25,965 |
import json
def init_store():
"""
Function to initialize the store listener.
Parameters
----------
Returns
-------
dict
request response
"""
challenge_id = str(request.form.get('challenge_id'))
flag =... | c7c3c6d9f3b645edfdcf82a4fd9cdbf1abd62b01 | 25,966 |
def PyLong_AsSsize_t(space, w_long):
"""Return a C Py_ssize_t representation of the contents of pylong. If
pylong is greater than PY_SSIZE_T_MAX, an OverflowError is raised
and -1 will be returned.
"""
return space.int_w(w_long) | c0d64c9be4333a0d40133478bcc5fcad221d0efc | 25,967 |
import requests
def getssa_handler() -> Response:
"""Software Statement Assertion retrieval"""
if request.method == 'POST':
try:
r = requests.get(
'{}/tpp/{}/ssa/{}'.format(
cache.get('tpp_ssa_url'),
cache.get('tpp_id'),
... | ddf9c7538c12073906caf934eba07995dd6ab590 | 25,970 |
import copy
def dataTeapotShallow():
"""
Values set interactively by Dave Hale. Omit deeper samples.
"""
txf = [
30, 69,0.50, 99, 72,0.50,
63, 71,0.90, 128, 72,0.90,
29,172,0.35, 97,173,0.35,
63,173,0.75, 127,174,0.75,
33,272,0.20, 103,270,0.20,
70,271,0.60, 134,268,0.60]
n = len(t... | ef03e417424d975b24e258741c57db319f918ac1 | 25,971 |
from pathlib import Path
def count_labels(l_path, selected_class,num_workers=4):
"""Calculate anchor size.
Args:
l_path: path to labels.
selected_class: class to be calculated.
Returns:
(w, l, h)
"""
def count_single_label(label_file):
size = []
z_axis = []
... | e027ace155e6b7ca83dc98b7b0191109ca12420d | 25,972 |
def sorted_chromosome(all_samples):
"""
sorted_chromosome(AllSamples) -> list
:return: list of chromosome found in all samples
"""
sorted_chromosome_list = sorted(all_samples.chr_list.keys())
print(sorted_chromosome_list)
return sorted_chromosome_list | c1e49ac974e16c7f9b69581442186c3efc23ef70 | 25,973 |
def adjust_bb_size(bounding_box, factor, resample=False):
"""Modifies the bounding box dimensions according to a given factor.
Args:
bounding_box (list or tuple): Coordinates of bounding box (x_min, x_max, y_min, y_max, z_min, z_max).
factor (list or tuple): Multiplicative factor for each dimen... | 93a3c5947cb7c3335421084092dbae8840f8164b | 25,974 |
def round_dt64(t,dt,t0=np.datetime64("1970-01-01 00:00:00")):
"""
Round the given t to the nearest integer number of dt
from a reference time (defaults to unix epoch)
"""
return clamp_dt64_helper(np.round,t,dt,t0) | 5e3695993110f875cc62402a770c9cb56ff9e544 | 25,975 |
def distill_base():
"""Set of hyperparameters."""
# Base
hparams = common_hparams.basic_params1()
# teacher/student parameters
hparams.add_hparam("teacher_model", "")
hparams.add_hparam("teacher_hparams", "")
hparams.add_hparam("student_model", "")
hparams.add_hparam("student_hparams", "")
# Distill... | 7bbf85971e0323282a801c7db4e646f7b745d453 | 25,976 |
def authorize(*args, **kwargs):
"""Handle for authorization of login information."""
next_url = url_for('oauth.authorize', **{
'response_type': request.args.get('response_type'),
'client_id': request.args.get('client_id'),
'redirect_uri': request.args.get('redirect_uri'),
'scope'... | e38b958567b9fa7427c2b3dd7b04cabadbbf4a8c | 25,977 |
def summary_stats(r, riskfree_rate=0.027):
"""
Return a DataFrame that contains aggregated summary stats for the returns in the columns of r
"""
ann_r = np.round(r.aggregate(annualize_rets, periods_per_year=4), 2)
ann_vol = np.round(r.aggregate(annualize_vol, periods_per_year=4), 2)
ann_sr = np.... | 230534298d907d0bff9dd843d14e3a6c5481ddbf | 25,978 |
def mid_longitude(geom: Geometry) -> float:
"""Return longitude of the middle point of the geomtry."""
((lon,), _) = geom.centroid.to_crs("epsg:4326").xy
return lon | ada60c2b72fc36af7d37cd3e063d0154484727d0 | 25,979 |
def unique_count_weight(feature):
"""Normalize count number of unique values relative to length of feature.
Args:
feature: feature/column of pandas dataset
Returns:
Normalized Number of unique values relative to length of feature.
"""
return len(feature.value_counts()) / len(featu... | 0345208cd7d9d4bc2303db377206e5362db6cdde | 25,980 |
def mode_glass(frame_bg, frame_fg, args_glass):
"""
Description: In glass mode, your eyes will be located with a pair of glass.
Params:
frame_bg: The background layer.
frame_fg: The canvas layer.
args_glass: The arguments used in glass mode.
"""
frame_bg = wear_glasses.wear_g... | 4f2957a1aed66383fe2f8ea394fb4fca0f2ba550 | 25,981 |
def line_meshes(verts, edges, colors=None, poses=None):
"""Create pyrender Mesh instance for lines.
Args:
verts: np.array floats of shape [#v, 3]
edges: np.array ints of shape [#e, 3]
colors: np.array floats of shape [#v, 3]
poses: poses : (x,4,4)
Array of 4x4 transform... | 22b5fa7aaa475e56bcb120427437881f4fa28209 | 25,982 |
import math
def isPrime(n):
"""
check if the input number n is a prime number or not
"""
if n <= 3:
return n > 1
if n % 6 != 1 and n % 6 != 5:
return False
sqrt = math.sqrt(n)
for i in range(5, int(sqrt)+1, 6):
if n % i == 0 or n % (i+2) == 0:
return Fa... | 91da5b13840181d039902e2db3efb8cc09609465 | 25,983 |
def seqprob_forward(alpha):
"""
Total probability of observing the whole sequence using the forward algorithm
Inputs:
- alpha: A numpy array alpha[j, t] = P(Z_t = s_j, x_1:x_t)
Returns:
- prob: A float number of P(x_1:x_T)
"""
prob = 0
##########################################... | edc24df276db1e4d0ffcdd51231036f1dc1eadaa | 25,984 |
def center_filter(gt_boxes, rect):
"""
过滤边框中心点不在矩形框内的边框
:param gt_boxes: [N,(y1,x1,y2,x2)]
:param rect: [y1,x1,y2,x2]
:return keep: 保留的边框索引号
"""
# gt boxes中心点坐标
ctr_x = np.sum(gt_boxes[:, [1, 3]], axis=1) / 2. # [N]
ctr_y = np.sum(gt_boxes[:, [0, 2]], axis=1) / 2. # [N]
y1, x1,... | 3a9d946789b1ee2de732f6cc29970d0fdf051e1f | 25,985 |
def named_entities(s, package="spacy"):
"""
Return named-entities.
Use Spacy named-entity-recognition.
PERSON: People, including fictional.
NORP: Nationalities or religious or political groups.
FAC: Buildings, airports, highways, bridges, etc.
ORG: Companies, agencies, inst... | 239f7f4887ee72ac5f698b2b32098019ccde3965 | 25,986 |
def get_premium_client():
"""Get a connection to the premium Minio tenant"""
return __get_minio_client__("premium") | f6c28453e7f04835c2dd2c91458712c7c80f3ded | 25,987 |
def chunk_sample_text(path: str) -> list:
"""Function to chunk down a given vrt file into pieces sepparated by <> </> boundaries.
Assumes that there is one layer (no nested <> </> statements) of text elements to be separated."""
# list for data chunks
data = []
# index to refer to current chunk
... | 6e6c36db38383283bd6076f0b6b346dcfd608243 | 25,989 |
from typing import Dict
def describe_dag_diffs(x, y):
"""Returns a list of strings describing differences between x and y."""
diffs = []
# A pair of dictionaries mapping id(x_val) or id(y_val) to the first path at
# which that value was reached. These are used to check that the sharing
# stucture of `x` a... | 4e3a767af9dd64b119111860a039a99b2b210a0f | 25,990 |
def ec_cert(cert_dir):
"""Pass."""
return cert_dir / "eccert.pem" | 71cf6d98b05e4fc80515936d7aedc6f184fbe0a6 | 25,991 |
from datetime import datetime
def get_expiries(body):
"""
:type body: BeautifulSoup
"""
_ex = body.find_all('select', {'id': 'date', 'name': 'date'})
ex = []
for ch in _ex:
for _e in ch:
try:
ex.append(datetime.strptime(_e.text, '%d%b%Y').date())
... | 09d7f067aa283ff930151b129378785dcbc17b09 | 25,992 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.