content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_all_migrations(ctxt, inactive=0):
"""Get all non-deleted source hypervisors.
Pass true as argument if you want deleted sources returned also.
"""
return db.migration_get_all(ctxt, inactive) | c8e8ae084ca42d560e79412e4ff56d79059055a6 | 3,651,154 |
def extract(input_data: str) -> tuple:
"""take input data and return the appropriate data structure"""
rules = input_data.split('\n')
graph = dict()
reverse_graph = dict()
for rule in rules:
container, contents = rule.split('contain')
container = ' '.join(container.split()[:2])
... | f71cdc23fdfaf6ef0d054c0c68e513db66289c12 | 3,651,155 |
def get_total_indemnity(date_of_joining, to_date):
"""To Calculate the total Indemnity of an employee based on employee's Joining date.
Args:
date_of_joining ([date]): Employee's Joining Date
to_date ([data]): up until date
Returns:
total_allocation: Total Indemnity Allocation calc... | 1b09d0dc7971ab4c3d63c303a93f64da924dcfa4 | 3,651,156 |
def api_2_gamma_oil(value):
"""
converts density in API(American Petroleum Institute gravity) to gamma_oil (oil relative density by water)
:param value: density in API(American Petroleum Institute gravity)
:return: oil relative density by water
"""
return (value + 131.5) / 141.5 | 20e625f22092461fcf4bc2e2361525abf8051f97 | 3,651,158 |
def compute_metrics(pred, label):
"""Compute metrics like True/False Positive, True/False Negative.`
MUST HAVE ONLY 2 CLASSES: BACKGROUND, OBJECT.
Args:
pred (numpy.ndarray): Prediction, one-hot encoded. Shape: [2, H, W], dtype: uint8
label (numpy.ndarray): Ground Truth, one-hot encoded.... | be8415c997197c06a5998671ffe09e70c6d3719c | 3,651,159 |
import jinja2
def expand_template(template, variables, imports, raw_imports=None):
"""Expand a template."""
if raw_imports is None:
raw_imports = imports
env = jinja2.Environment(loader=OneFileLoader(template))
template = env.get_template(template)
return template.render(imports=imports, variables=varia... | c5ebe1610a6e2fa9e0b18afa7d23652c1f7c25ba | 3,651,160 |
from typing import Any
from operator import truth
def __contains__(container: Any, item: Any, /) -> bool:
"""Check if the first item contains the second item: `b in a`."""
container_type = type(container)
try:
contains_method = debuiltins._mro_getattr(container_type, "__contains__")
except Att... | b58a5f400895df472f83a5e2410dff9cd112fc91 | 3,651,161 |
def generate_search_url(request_type):
"""Given a request type, generate a query URL for kitsu.io."""
url = BASE_URL_KITSUIO.format(request_type)
return url | 9508d909fb8eb018770b2191f7d62ccb3881f285 | 3,651,162 |
from typing import Callable
def register_magic(func: Callable[[Expr], Expr]):
"""
Make a magic command more like Julia's macro system.
Instead of using string, you can register a magic that uses Expr as the
input and return a modified Expr. It is usually easier and safer to
execute metaprogrammin... | 06d93f8a48758dc39679af396c10a54927e3696e | 3,651,163 |
def ValidatePregnum(resp):
"""Validate pregnum in the respondent file.
resp: respondent DataFrame
"""
# read the pregnancy frame
preg = nsfg.ReadFemPreg()
# make the map from caseid to list of pregnancy indices
preg_map = nsfg.MakePregMap(preg)
# iterate through the respondent pre... | a51f3af130cbad4a5cd3d3c9707788f783302000 | 3,651,165 |
def is_super_admin(view, view_args, view_kwargs, *args, **kwargs):
"""
Permission function for things allowed exclusively to super admin.
Do not use this if the resource is also accessible by a normal admin, use the is_admin decorator instead.
:return:
"""
user = current_user
if not user.is_... | 503550fcd52e62053d42a3059aba298009d3eb01 | 3,651,166 |
def normalize_depth(val, min_v, max_v):
"""
print 'nomalized depth value'
nomalize values to 0-255 & close distance value has high value. (similar to stereo vision's disparity map)
"""
return (((max_v - val) / (max_v - min_v)) * 255).astype(np.uint8) | 431cda7af30ef1127c60069b6958ef4d8234eaae | 3,651,167 |
def parse_iori_block(block):
"""Turn IORI data blocks into `IoriData` objects.
Convert rotation from Quaternion format to Euler angles.
Parameters
----------
block: list of KVLItem
A list of KVLItem corresponding to a IORI data block.
Returns
-------
iori_data: IoriData
... | b9ad59677e51c30b2bec51a0503fc2718cde0f7d | 3,651,168 |
def ungap_all(align):
"""
Removes all gaps (``-`` symbols) from all sequences of the :class:`~data.Align`
instance *align* and returns the resulting ~data.Container instance.
"""
result = data.Container()
for n,s,g in align:
result.append(n, s.translate(None, '-'), g)
... | 511b6aeb7fc262b733a97b5180a23c7f044fea06 | 3,651,169 |
def expandBcv(bcv):
"""If the bcv is an interval, expand if.
"""
if len(bcv) == 6:
return bcv
else:
return "-".join(splitBcv(bcv)) | abfb1bf31acca579fecb526d571b32cefa7ecd61 | 3,651,170 |
def cluster_profile_platform(cluster_profile):
"""Translate from steps.cluster_profile to workflow.as slugs."""
if cluster_profile == 'azure4':
return 'azure'
if cluster_profile == 'packet':
return 'metal'
return cluster_profile | 0a01f566562002fe43c3acbb00d5efcc09d25314 | 3,651,172 |
def get_price_lambda_star_lp_1_cvxpy(w: np.ndarray, c_plus: np.ndarray, psi_plus: np.ndarray) \
-> float:
"""
Computes lambda_star based on dual program of the projection of w_star.
:param w: current state in workload space.
:param c_plus: vector normal to the level set in the monotone region '... | 0a1a658cd86a0253fe3caf8a5e162393926b351a | 3,651,173 |
import typing
import random
def _get_nodes(
network: typing.Union[NetworkIdentifier, Network],
sample_size: typing.Optional[int],
predicate: typing.Callable,
) -> typing.List[Node]:
"""Decaches domain objects: Node.
"""
nodeset = [i for i in get_nodes(network) if predicate(i)]
if samp... | f3be401c2fd0adf58f10b679d254ff2075f4546b | 3,651,174 |
def cdl_key():
"""Four-class system (grain, forage, vegetable, orchard. Plus 5: non-ag/undefined"""
key = {1: ('Corn', 1),
2: ('Cotton', 1),
3: ('Rice', 1),
4: ('Sorghum', 1),
5: ('Soybeans', 1),
6: ('Sunflower', 1),
7: ('', 5),
8: (''... | 634a35d2962695dd0ef1b38a0c353498ca3dea89 | 3,651,175 |
def colmeta(colname, infile=None, name=None, units=None, ucd=None, desc=None,
outfile=None):
"""
Modifies the metadata of one or more columns. Some or all of the name,
units, ucd, utype and description of the column(s),
identified by "colname" can be set by using some or all of the listed ... | 15fc5b53e4ebd3563b00ef771a707d2ad2473ad7 | 3,651,176 |
def get_confusion_matrix_chart(cm, title):
"""Plot custom confusion matrix chart."""
source = pd.DataFrame([[0, 0, cm['TN']],
[0, 1, cm['FP']],
[1, 0, cm['FN']],
[1, 1, cm['TP']],
], columns=["actual valu... | 28884c46a51f3baf51dc5a6f3c0396a5c8f24e10 | 3,651,177 |
def get_ppo_plus_eco_params(scenario):
"""Returns the param for the 'ppo_plus_eco' method."""
assert scenario in DMLAB_SCENARIOS, (
'Non-DMLab scenarios not supported as of today by PPO+ECO method')
if scenario == 'noreward' or scenario == 'norewardnofire':
return md(get_common_params(scenario), {
... | 26bb3db0cf14eceea86cd659332c9bbc0195ab9b | 3,651,178 |
def field_display(name):
"""
Works with Django's get_FOO_display mechanism for fields with choices set. Given
the name of a field, returns a producer that calls get_<name>_display.
"""
return qs.include_fields(name), producers.method(f"get_{name}_display") | 7fbc17dddfa398934496099f605f6cee97a802ad | 3,651,179 |
from typing import Dict
from typing import List
def extract_attachments(payload: Dict) -> List[Image]:
"""
Extract images from attachments.
There could be other attachments, but currently we only extract images.
"""
attachments = []
for item in payload.get('attachment', []):
# noinspe... | afb9d959e680c51fc327d6c7e5f5e74fdc5db5e6 | 3,651,181 |
from ...model_zoo import get_model
def yolo3_mobilenet1_0_custom(
classes,
transfer=None,
pretrained_base=True,
pretrained=False,
norm_layer=BatchNorm, norm_kwargs=None,
**kwargs):
"""YOLO3 multi-scale with mobilenet base network on custom dataset.
Parameters
... | 2da86fe66538e3cd9a21c456c00312a217ab5ca0 | 3,651,182 |
def calculate_levenshtein_distance(str_1, str_2):
"""
The Levenshtein distance is a string metric for measuring the difference between two sequences.
It is calculated as the minimum number of single-character edits necessary to transform one string into another
"""
distance = 0
buffer_re... | 949d54fbcbd2169aa06cedc7341e98c12412d03c | 3,651,183 |
from datetime import datetime
def make_datetime(value, *, format_=DATETIME_FORMAT):
"""
>>> make_datetime('2001-12-31T23:59:59')
datetime.datetime(2001, 12, 31, 23, 59, 59)
"""
return datetime.datetime.strptime(value, format_) | 5c6d79ae0ddc9f4c47592a90ed3232f556df0a49 | 3,651,184 |
import inspect
def named_struct_dict(typename, field_names=None, default=None, fixed=False, *, structdict_module=__name__,
base_dict=None, sorted_repr=None, verbose=False, rename=False, module=None, qualname_prefix=None,
frame_depth=1):
"""Returns a new subclass of Stru... | 465ac4783697b749c092d96fa8af498e67f15d51 | 3,651,185 |
from .pytorch.pytorch_onnxruntime_model import PytorchONNXRuntimeModel
def PytorchONNXRuntimeModel(model, input_sample=None, onnxruntime_session_options=None):
"""
Create a ONNX Runtime model from pytorch.
:param model: 1. Pytorch model to be converted to ONNXRuntime for inference
... | d925b67c3628995d75d1ea6c687e5beb022fdbd8 | 3,651,186 |
def intensity_variance(mask: np.ndarray, image: np.ndarray) -> float:
"""Returns variance of all intensity values in region of interest."""
return np.var(image[mask]) | e967b4cd3c3a896fba785d8c9e5f8bf07daa620d | 3,651,188 |
def permute_array(arr, axis=0):
"""Permute array along a certain axis
Args:
arr: numpy array
axis: axis along which to permute the array
"""
if axis == 0:
return np.random.permutation(arr)
else:
return np.random.permutation(arr.swapaxes(0, axis)).swapaxes(0, axis) | ce5f6d571062f36888d22836579332034f4fe924 | 3,651,189 |
def dsmatch(name, dataset, fn):
"""
Fuzzy search best matching object for string name in dataset.
Args:
name (str): String to look for
dataset (list): List of objects to search for
fn (function): Function to obtain a string from a element of the dataset
Returns:
First e... | 0835c0da3773eedab95c78e1b4f7f28abde0d8fd | 3,651,191 |
def f(q):
"""Constraint map for the origami."""
return 0.5 * (np.array([
q[0] ** 2,
(q[1] - q[0]) ** 2 + q[2] ** 2 + q[3] ** 2,
(q[4] - q[1]) ** 2 + (q[5] - q[2]) ** 2 + (q[6] - q[3]) ** 2,
q[4] ** 2 + q[5] ** 2 + q[6] ** 2,
q[7] ** 2 + q[8] ** 2 + q[9] ** 2,
(q[7... | 77c3617a76cb2e184b1f22404f1db8be8212a4c9 | 3,651,193 |
def resize(clip, newsize=None, height=None, width=None):
"""
Returns a video clip that is a resized version of the clip.
Parameters
------------
newsize:
Can be either
- ``(height,width)`` in pixels or a float representing
- A scaling factor, like 0.5
- A fu... | 5a8541e1320d37bd47aa35978794d849af358cb6 | 3,651,194 |
def calc_rt_pytmm(pol, omega, kx, n, d):
"""API-compatible wrapper around pytmm
"""
vec_omega = omega.numpy()
vec_lambda = C0/vec_omega*2*np.pi
vec_n = n.numpy()
vec_d = d.numpy()
vec_d = np.append(np.inf, vec_d)
vec_d = np.append(vec_d, np.inf)
vec_kx = kx.numpy().reshape([-1,1])... | def2fb22d2e72a873794838601bc74a7c65cb9c3 | 3,651,195 |
def statistic_bbox(dic, dic_im):
""" Statistic number of bbox of seed and image-level data for each class
Parameters
----------
dic: seed roidb dictionary
dic_im: image-level roidb dictionary
Returns
-------
num_bbox: list for number of 20 class's bbox
num_bbox_im: list for numb... | 782314baeab7fbec36c9ea56bcec57d5a508a918 | 3,651,196 |
def github_youtube_config_files():
"""
Function that returns a list of pyGithub files with youtube config channel data
Returns:
A list of pyGithub contentFile objects
"""
if settings.GITHUB_ACCESS_TOKEN:
github_client = github.Github(settings.GITHUB_ACCESS_TOKEN)
else:
... | 166ca3653173feee7513097c9313ebb5ab3b4d17 | 3,651,197 |
def reverse_uint(uint,num_bits=None):
"""
This function takes an unsigned integer and reverses all of its bits.
num_bits is number of bits to assume are present in the unsigned integer.
If num_bits is not specified, the minimum number of bits needed to represent the unsigned integer is assumed.
If n... | a3197aa3f199a5677a15e053c0455c0216d07827 | 3,651,198 |
def min_by_tail(lhs, ctx):
"""Element ↓
(any) -> min(a, key=lambda x: x[-1])
"""
lhs = iterable(lhs, ctx=ctx)
if len(lhs) == 0:
return []
else:
return min_by(lhs, key=tail, cmp=less_than, ctx=ctx) | 88fce303e6ff95f89e57ebd05c575810238497ea | 3,651,199 |
def SecureBytesEqual( a, b ):
"""Returns the equivalent of 'a == b', but avoids content based short
circuiting to reduce the vulnerability to timing attacks."""
# Consistent timing matters more here than data type flexibility
# We do NOT want to support py2's str type because iterating over them
# (below) pro... | 1ba46089d94f544b53a47e09dbbcf95dd5b594a0 | 3,651,200 |
import base64
import pickle
def encode(something):
"""
We encode all messages as base64-encoded pickle objects in case
later on, we want to persist them or send them to another system.
This is extraneous for now.
"""
return base64.b64encode(pickle.dumps(something)) | 89c9c855b8b66aadc55c1602e133906d3220691a | 3,651,201 |
def installRecommendation(install, uninstall, working_set=working_set, tuples=False):
"""Human Readable advice on which modules have to be installed on
current Working Set.
"""
installList = []
for i in install:
is_in = False
for p in working_set:
if i[0] == p.key and i[1... | bf3083d4bcb50bdc27c382ccd9ea1dfc7b8cdb71 | 3,651,203 |
def obsangle(thetas, phis, alpha_obs):
"""
Return the cosine of the observer angle for the different shockwave segments and and
and observer at and angle alpha_obs with respect to the jet axis
(contained in yz plane)
"""
#u_obs_x, u_obs_y, u_obs_z = 0., sin(alpha_obs), co... | 6fc03a386a97f63d3ad10d291d1528bf7fb45720 | 3,651,204 |
def _image_tensor_input_placeholder(input_shape=None):
"""Returns input placeholder and a 4-D uint8 image tensor."""
if input_shape is None:
input_shape = (None, None, None, 3)
input_tensor = tf.placeholder(
dtype=tf.uint8, shape=input_shape, name='image_tensor')
return input_tensor, inp... | bd3c339da4b8f0eea482687cecf28a4625d3f84c | 3,651,205 |
def _load_top_bonds(f, topology, **kwargs):
"""Take a mol2 file section with the heading '@<TRIPOS>BOND' and save to the topology.bonds attribute."""
while True:
line = f.readline()
if _is_end_of_rti(line):
line = line.split()
bond = Bond(
connection_membe... | e6605428a99720ff0d773a1db2a8363d61e38ca3 | 3,651,206 |
def timelength_to_phrase(
timelength: spec.Timelength,
from_representation: spec.TimelengthRepresentation = None,
) -> spec.TimelengthPhrase:
"""convert Timelength to TimelengthPhrase
## Inputs
- timelength: Timelength
- from_representation: str representation name of input timelength
## R... | a840b69625c968cda4a1e686a61298e2809ffde0 | 3,651,207 |
def order_columns(self: DataFrame, order: str = "asc", by_dtypes: bool = False):
"""
Rearrange the columns in alphabetical order.
An option of rearrangement by dtypes is possible.
:param self:
:param by_dtypes: boolean to rearrange by dtypes first
"""
if order not in ['asc', 'desc']:
... | c05f4b13b26b041c86816c15a375943713a6dcdb | 3,651,208 |
import random
def reorderWithinGroup(players_by_wins):
"""Shuffle players with the same score.
Args:
players_by_wins: a dictionary returned by splitByScore().
Returns a list of the re-ordered player ids.
"""
for score in players_by_wins.keys():
random.shuffle(players_by_win... | bd0afe4db36bf815ab7861e53cd674bd49e81775 | 3,651,210 |
def selection(population, method):
"""Apply selection method of a given population.
Args:
population: (list of) plans to apply the selection on.
method: (str) selection method:
- rws (Roulette Wheel Selection)
- sus (Stochastic Universal Selection)
- ts (Tou... | e5b05c62530babfd48b5061152b9f88e4a463456 | 3,651,211 |
def PSL_prefix(row, cols):
"""Returns the prefix a domain (www.images for www.images.example.com)"""
psl_data = psl.search_tree(row[cols[0]])
if psl_data:
return(psl_data[1], psl_data[0])
return (None, None) | e5e7809acae3be60eca9f0cd65aec7a93ac087de | 3,651,212 |
def build_model(sess,t,Y,model='sde',sf0=1.0,ell0=[2,2],sfg0=1.0,ellg0=[1e5],
W=6,ktype="id",whiten=True,
fix_ell=False,fix_sf=False,fix_Z=False,fix_U=False,fix_sn=False,
fix_ellg=False,fix_sfg=False,fix_Zg=True,fix_Ug=False):
"""
Args:
sess: TensowFlow session ne... | f5d691aca815df25d1c34ae9c7fa9810c3aae1ab | 3,651,213 |
import re
def paginatedUrls(pattern, view, kwargs=None, name=None):
"""
Takes a group of url tuples and adds paginated urls.
Extends a url tuple to include paginated urls.
Currently doesn't handle url() compiled patterns.
"""
results = [(pattern, view, kwargs, name)]
tail = ''
mtail ... | 2102309434e02e0df49888978d41ffce2de0e2dc | 3,651,214 |
from typing import Tuple
def _to_intraday_trix(date: pd.Timestamp, provider: providers.DataProvider,
period: int)-> Tuple[nd.NDArray, nd.NDArray]:
"""
Returns an ndarray containing the TRIX for a given +data+ and +provider+,
averaged across a given +period+.
"""
# First, get ... | 14c621afa6128fb3b33058b357e2ca79723a42f9 | 3,651,215 |
def _decode(integer):
"""
Decode the given 32-bit integer into a MAX_LENGTH character string according
to the scheme in the specification. Returns a string.
"""
if integer.bit_length() > 32:
raise ValueError("Can only decode 32-bit integers.")
decoded_int = 0
# Since each byte has ... | 156b75e8907bbcf6ae69f0a3429fb29777651f8e | 3,651,216 |
def register(name):
"""Registers a new data loader function under the given name."""
def add_to_dict(func):
_LOADERS[name] = func
return func
return add_to_dict | ea672cdf3c8d34f090d98e2498b77ea929aee6e6 | 3,651,217 |
def get_api_host(staging):
"""If 'staging' is truthy, return staging API host instead of prod."""
return STAGING_API_HOST if staging else PROD_API_HOST | d2b0003669422ef4481ffe4db76497de1485d0f7 | 3,651,218 |
def delete_user(auth, client):
"""
Delete a user
:auth: dict
:client: users_client object
"""
log("What user you want to delete?")
user_to_delete = find_user_by_username(auth, client)
if user_to_delete is False:
log("Could not find user.", serv="ERROR")
return False
... | db51c7d7d9f5fbd164bde010f3887f43e998fbef | 3,651,220 |
def remove_empty(s):
"""\
Remove empty strings from a list.
>>> a = ['a', 2, '', 'b', '']
>>> remove_empty(a)
[{u}'a', 2, {u}'b']
"""
while True:
try:
s.remove('')
except ValueError:
break
return s | 98778e4cc90f11b9b74ac6d26b203cbfc958fd7b | 3,651,222 |
import math
from typing import Tuple
from typing import Any
import itertools
def quantum_ia(nb_stick: int, past: list, backend_sim: Aer) -> list:
"""Quantum IA.
Args:
nb_stick: nb of stick left
past: past turn
backend_sim: backend for quantum
Return: Prediction to use
... | 7e13f554e6eb901ec43ec80bf346005f17ec55d5 | 3,651,223 |
def construct_model_cnn_gram(num_classes, input_shape):
"""
construct model architecture
:param num_classes: number of output classes of the model [int]
:return: model - Keras model object
"""
model = Sequential()
model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_unifo... | ddffb66efe6b4f94a9c2a0ccc976206eebb503a6 | 3,651,224 |
def get_basic_data(match_info, event):
"""input: dictionary | output: dictionary updated"""
match_info['status'] = event['status']['type']['name']
match_info['start_time'] = event['date']
match_info['match_id'] = event['id']
match_info['time'] = event['status']['displayClock']
match_info['period... | fae755e195b5bbf12c9fccf20b9ba2c2f9e700c6 | 3,651,225 |
def convert_blockgrad(node, **kwargs):
""" Skip operator """
return create_basic_op_node('Identity', node, kwargs) | 12803d387a30884da08779b878e9cdf3e06226a7 | 3,651,227 |
def is_complete(node):
"""
all children of a sum node have same scope as the parent
"""
assert node is not None
for sum_node in reversed(get_nodes_by_type(node, Sum)):
nscope = set(sum_node.scope)
if len(sum_node.children) == 0:
return False, "Sum node %s has no childr... | a92741f4770757518e91a44e757e4d8037958066 | 3,651,228 |
import torch
def step_inplace(Ts, ae, target, weight, depth, intrinsics, lm=.0001, ep=10.0):
""" dense gauss newton update with computing similiarity matrix """
pts = pops.inv_project(depth, intrinsics)
pts = pts.permute(0,3,1,2).contiguous()
# tensor representation of SE3
se3 = Ts.data.perm... | 9f1fc6911d1fb11bc6956d63dda8f59b8f6654cd | 3,651,229 |
def _compute_extent_axis(axis_range, grid_steps):
"""Compute extent for matplotlib.pyplot.imshow() along one axis.
:param axis_range: 1D numpy float array with 2 elements; axis range for plotting
:param grid_steps: positive integer, number of grid steps in each dimension
:return: 1D numpy float array w... | e83a251b4055639435342d19960d1e75a6d33ba8 | 3,651,230 |
import hashlib
def md5_hash_file(fh):
"""Return the md5 hash of the given file-object"""
md5 = hashlib.md5()
while True:
data = fh.read(8192)
if not data:
break
md5.update(data)
return md5.hexdigest() | f572ec27add8024e5fa8b9a82b5d694905e4d0f8 | 3,651,233 |
def rule(request):
"""Administration rule content"""
if request.user.is_authenticated():
return helpers.render_page('rule.html', show_descriptions=True)
else:
return redirect('ahmia.views_admin.login') | 514f767235660b812126c5cfc2dabeec40a7b22a | 3,651,234 |
def get_tenant_info(schema_name):
"""
get_tenant_info return the first tenant object by schema_name
"""
with schema_context(schema_name):
return Pharmacy.objects.filter(schema_name=schema_name).first() | 388d51c50fec60a331822bd157da1d53c88cc170 | 3,651,235 |
def get_lr(curr_epoch, hparams, iteration=None):
"""Returns the learning rate during training based on the current epoch."""
assert iteration is not None
batches_per_epoch = int(hparams.train_size / hparams.batch_size)
if 'svhn' in hparams.dataset and 'wrn' in hparams.model_name:
lr = step_lr(hp... | 42df4a185dd41d0eb02845d78dbd061f4658fba8 | 3,651,236 |
def delete_page(shortname):
"""Delete page from the database."""
# Check page existency
if get_page(shortname) is None:
abort(404)
if shortname is None:
flash("No parameters for page deletion!")
return redirect(url_for("admin"))
else:
query_db("DELETE FROM pages WHER... | b1bb9526832209e1cddf1c86851aeef7c6701d3d | 3,651,238 |
def has_property(name, match=None):
"""Matches if object has a property with a given name whose value satisfies
a given matcher.
:param name: The name of the property.
:param match: Optional matcher to satisfy.
This matcher determines if the evaluated object has a property with a given
name. I... | a5c562b1f5a36fc2c591d700d84b5ee9ca54ccde | 3,651,239 |
import glob
def gain_stability_task(run, det_name, fe55_files):
"""
This task fits the Fe55 clusters to the cluster data from each frame
sequence and writes a pickle file with the gains as a function of
sequence number and MJD-OBS.
Parameters
----------
run: str
Run number.
de... | a285879fc963342ed51b61ec9fae8ac08c089bc6 | 3,651,240 |
from datetime import datetime
def get_datetime(timestamp):
"""Parse several representations of time into a datetime object"""
if isinstance(timestamp, datetime.datetime):
# Timestamp is already a datetime object.
return timestamp
elif isinstance(timestamp, (int, float)):
try:
... | d8277a1de3876106de02b9d75e02369061261996 | 3,651,241 |
def conda_installed_files(prefix, exclude_self_build=False):
"""
Return the set of files which have been installed (using conda) into
a given prefix.
"""
res = set()
for dist in install.linked(prefix):
meta = install.is_linked(prefix, dist)
if exclude_self_build and 'file_hash' i... | e81051e19f7829bf149c71f0533bd51c80c7e2a1 | 3,651,242 |
def computeStarsItembased(corated, target_bid, model):
"""
corated - {bid: star, ...}
"""
if corated == None:
return None
corated.pop(target_bid, None)
bid_cor = list(corated.keys())
collect = []
for b in bid_cor:
pair = None
if b < target_bid:
pair = ... | 7b3cd5bd103d35fe09477be96b5cbcc378927c65 | 3,651,243 |
import psutil
import re
def beacon(config):
"""
Monitor the memory usage of the minion
Specify thresholds for percent used and only emit a beacon
if it is exceeded.
.. code-block:: yaml
beacons:
memusage:
- percent: 63%
"""
ret = []
_config = {}
li... | ac10e85d47fef403148ad2e00c4e10ced2cc226c | 3,651,244 |
def get_surrounding_points(search_values, point_set):
"""
#for each value p[i] in search_values, returns a pair of surrounding points from point_set
the surrounding points are a tuplet of the form (lb[i], ub[i]) where
- lb[i] < p[i] < ub[i] if p[i] is not in point_set, and p[i] is within range
- lb[... | d4ec055946c19b999ed9523aa260d7bd28ffd269 | 3,651,245 |
def _scriptable_get(obj, name):
""" The getter for a scriptable trait. """
global _outermost_call
saved_outermost = _outermost_call
_outermost_call = False
try:
result = getattr(obj, '_' + name, None)
if result is None:
result = obj.trait(name).default
finally:
... | 53da00cb49d73065281306c90a51a95e1670e14e | 3,651,246 |
def Iq(q, intercept, slope):
"""
:param q: Input q-value
:param intercept: Intrecept in linear model
:param slope: Slope in linear model
:return: Calculated Intensity
"""
inten = intercept + slope*q
return inten | af3e580e6061089b431ef25f1f08def6f29c8ef6 | 3,651,247 |
def get_optimizer(library, solver):
"""Constructs Optimizer given and optimization library and optimization
solver specification"""
options = {
'maxiter': 100
}
if library == 'scipy':
optimizer = optimize.ScipyOptimizer(method=solver, options=options)
elif library == 'ipopt':
... | be72fc9115abf0d087049debe470139b248ef47f | 3,651,251 |
def _cast_query(query, col):
"""
ALlow different query types (e.g. numerical, list, str)
"""
query = query.strip()
if col in {"t", "d"}:
return query
if query.startswith("[") and query.endswith("]"):
if "," in query:
query = ",".split(query[1:-1])
return [... | 4b6cfc823f8b2e78f343e73683b418112e66f43d | 3,651,252 |
import torch
def binary_loss(pred_raw,
label_raw,
loss_func,
weight=None,
class_weight=None,
class_weight_norm=False,
reduction='mean',
avg_factor=None,
smooth=1.0):
"""
:param pred:... | 9154c8e46a48485e643de496554d302f9db294ac | 3,651,253 |
def showerActivityModel(sol, flux_max, b, sol_max):
""" Activity model taken from: Jenniskens, P. (1994). Meteor stream activity I. The annual streams.
Astronomy and Astrophysics, 287., equation 8.
Arguments:
sol: [float] Solar longitude for which the activity is computed (radians).
... | 0a4cc6d8c490b36412140cfeeca0c30464c11577 | 3,651,255 |
import json
def request_slow_log(db_cluster_id, start_datetime, end_datetime, page_number, page_size):
"""
请求慢SQL日志
:param db_cluster_id:
:param start_datetime:
:param end_datetime:
:param page_number:
:param page_size:
:return:
"""
request = DescribeSlowLogRecordsRequest()
... | e49a006e59f04067eb43f72dfcd29fd71def4fb1 | 3,651,257 |
def pad_omni_image(image, pad_size, image_dims=None):
"""Pad an omni-directional image with the correct image wrapping at the edges.
Parameters
----------
image
Image to perform the padding on *[batch_shape,h,w,d]*
pad_size
Number of pixels to pad.
image_dims
Image dimen... | e54d732508bea3f969eb2a78ec3238e88e33a30f | 3,651,258 |
from typing import Any
def add_film(
film: FilmCreate,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
) -> Any:
"""
Add new film
"""
if not user.role.can_add_films:
raise ForbiddenAction
db_film = db.query(Film).filter(Film.name == film.name).first()
... | 510f80969570e186233a6313277093b6d939a9ea | 3,651,259 |
def load_cube_file(lines, target_mode=None, cls=ImageFilter.Color3DLUT):
"""Loads 3D lookup table from .cube file format.
:param lines: Filename or iterable list of strings with file content.
:param target_mode: Image mode which should be after color transformation.
The default is No... | bf87c0e686b689a429297bae4ec84402dd12dc3d | 3,651,260 |
import torch
def vector_to_Hermitian(vec):
"""Construct a Hermitian matrix from a vector of N**2 independent
real-valued elements.
Args:
vec (torch.Tensor): (..., N ** 2)
Returns:
mat (ComplexTensor): (..., N, N)
""" # noqa: H405, D205, D400
N = int(np.sqrt(vec.shape[-1]))
... | 8bd32d93e9865305a8f75711d72990beaea5d897 | 3,651,261 |
def view_payment(request):
""" A view that renders the payment page template """
user = request.user
# Check if user has already paid and redirect them to definitions app.
if user.has_perm('definitionssoftware.access_paid_definitions_app'):
return redirect(reverse('view_definitionssoftware'))
... | fc86a79c759bc4e4005d634b5c9a204473a3a3a7 | 3,651,263 |
def augment_bag(store, bag, username=None):
"""
Augment a bag object with information about it's policy type.
"""
if not bag.store:
bag = store.get(bag)
if not username:
username = bag.policy.owner
policy_type = determine_tank_type(bag, username)
bag.icon = POLICY_ICONS[polic... | 1fbda85f3db346e46e52b86d2d4b5784f8c4d2ab | 3,651,264 |
from typing import Dict
def province_id_to_home_sc_power() -> Dict[utils.ProvinceID, int]:
"""Which power is this a home sc for?"""
content = get_mdf_content(MapMDF.STANDARD_MAP)
home_sc_line = content.splitlines()[2]
tag_to_id = _tag_to_id(get_mdf_content(MapMDF.STANDARD_MAP))
# Assume powers are ordered ... | f87081ce053e3a50bb48deaae28b0e919e224216 | 3,651,265 |
def evaluate_cubic_spline(x, y, r, t):
"""Evaluate cubic spline at points.
Parameters:
x : rank-1 np.array of np.float64
data x coordinates
y : rank-1 np.array of np.float64
data y coordinates
r : rank-1 np.array of np.float64
output of solve_coeffs()... | 52d6c4ac0440da88ee908bc0a6cfa2b755ca606f | 3,651,266 |
def get_username(host, meta_host, config):
"""Find username from sources db/metadata/config."""
username = host.username or meta_host.get("username")
if is_windows_host(meta_host):
username = username or "Administrator"
default_user = get_config_value(config["users"], meta_host["os"])
usern... | 4e220816442e64d43f1da15aa0bd19508e186f19 | 3,651,267 |
def get_all_tests():
"""
Collect all tests and return them
:return: A test suite as returned by xunitparser with all the tests
available in the w3af framework source code, without any selectors.
"""
return _get_tests('all.xml') | 11acff501fb717ac5c9bdc16343742f124f2a120 | 3,651,268 |
def main():
"""Builds OSS-Fuzz project's fuzzers for CI tools.
Note: The resulting fuzz target binaries of this build are placed in
the directory: ${GITHUB_WORKSPACE}/out
Returns:
0 on success or nonzero on failure.
"""
return build_fuzzers_entrypoint() | cd7c386c2a5d126c0abc1504a1cb3dfe6026173c | 3,651,269 |
def find_first_img_dim(import_gen):
"""
Loads in the first image in a provided data set and returns its dimensions
Intentionally returns on first iteration of the loop
:param import_gen: PyTorch DataLoader utilizing ImageFolderWithPaths for its dataset
:return: dimensions of image
"""
for x,... | 3ccaccdfb20d7b2ca4d339adacd3c706a460fdef | 3,651,270 |
def restaurantJSON():
""" Returns all restaurants by JSON call """
restaurants = session.query(Restaurant)
return jsonify(Restaurants=[r.serialize for r in restaurants]) | 350df909de7798da9567a7fe0a972d660c40ff8c | 3,651,271 |
def _to_histogram_plotgroup(use_spec, plotgroup_id, plot_id, read_type, bincounts, output_dir, png_name):
"""
Create a histogram of length distribution.
"""
plot_spec = use_spec.get_plot_spec(plotgroup_id, plot_id)
png_file = op.join(output_dir, png_name)
png, thumb = plot_read_lengths_binned(bi... | 18ae412af24800098ec2c01c9ba5c456455540f5 | 3,651,272 |
def prepare_string(x, max_length=None):
""" Converts a string from LaTeX escapes to UTF8 and truncates it to max_length """
# data = latex2text(x, tolerant_parsing=True)
try:
data = latex_to_unicode(filter_using_re(x))
if max_length is not None:
data = (data[:max_length-5] + '[..... | 043d0d063e22ef18943459a7ba0a8928244bca12 | 3,651,273 |
import math
def q_b(m0, m1, m2, n0, n1, n2):
"""Stretch"""
return math.sqrt((m0 - n0)**2 + (m1 - n1)**2 + (m2 - n2)**2) | 61cf1b5eec6c89be7f822cbdbc03564b805a1920 | 3,651,274 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.