content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def get_pd_metrics(data):
"""Function for create physical disks metrics files."""
create_dir(LLD_METRICS_PATH)
for ctrl, ctrl_value in data.items():
if isinstance(ctrl_value, dict):
for ar_key, ar_value in ctrl_value.items():
match = re.search(ARRAY_NAME_PATT... | 5b073b0ec045ac3df5de74c6d2454b6775ffac78 | 3,630,457 |
def svn_stream_read(*args):
"""svn_stream_read(svn_stream_t stream, char buffer) -> svn_error_t"""
return _core.svn_stream_read(*args) | 1c9657c2b65b8b30fc20bc62f9002f8f6578cc63 | 3,630,458 |
import random
def create_pipes(pipes, pipe_assets):
"""
Creates the pipes. Generates them randomly and appends them to the pipe list.
Args:
pipes(list): A list containing the pipe rects
pipe_assets(list): A list containing the pipe images images (rotated and non-rotated)
Returns:
... | f5740d13b8524063c736de38cabaf0132d8d0f6d | 3,630,459 |
def shell_short(unordered, ordered):
"""
Startig at the bottom of the stack:
1 - If the name is in the correct position move to the next
2 - If it is not in the position remove it, move all other names
one positions down and got to 1
sort all the removed positions, these nam... | df57eb0bee03159ac6b698bf0377efec48355e76 | 3,630,460 |
def render_latest_entries_links(context, request=None):
"""
Renders the links to the 5 latest entries.
"""
qs = NewsEntry.objects.published()
context.update({
'entries': qs[:5]
})
return context | ea5afb238162d565bf00977c146ddd79a59fb3b4 | 3,630,461 |
def __standard_cand_fun(candidates):
"""
Convert candidates from the forms accepted by :py:fun:`recommend` into
a standard form, a function that takes a user and returns a candidate
list.
"""
if isinstance(candidates, dict):
return candidates.get
elif candidates is None:
retu... | ad206802bfbcd0ec8f4601ebc043f8d468709c75 | 3,630,462 |
def diff(obj1, obj2):
"""Prints a simple human-readable difference between two Python objects."""
result = []
diffAny(obj1, obj2, result)
return '\n'.join(result) | 9f898a17ee6e447e5aca9edcba8b4b6151aa6e3c | 3,630,464 |
import torch
def get_static_features(
inputs,
num_windows,
stream_sizes=None,
has_dynamic_features=None,
streams=None,
):
"""Get static features from static+dynamic features."""
if stream_sizes is None:
stream_sizes = [180, 3, 1, 15]
if has_dynamic_features is None:
has... | 4767c0a480b04047b16d01d7e994fb09c61b543c | 3,630,465 |
def _l4_parameterize_ ( l4 ,
tree ,
xvar ,
yvar ,
zvar ,
uvar ,
cut = '' , first = 0 , last = _large ) :
"""Parameterize 4D unbinned ddistribuition from TTree in terms of... | 6e4448450feb7063fb8ef8bb540a6b2af3fcfd5f | 3,630,466 |
import textwrap
def welcome():
"""
Welcomes the player, brief intro to the game, and returns hand size as integer
ranging from 4 to 9
"""
version = '0.1'
m01 = "Welcome to the MIT 6.00.1x Wordgame (etherwar's mod)"
m02 = "Build " + version
m03 = "The Game: "
m04 = "First, you must ... | 0a89b38c1b9636e78d7299b8d3c6051717ab7fd7 | 3,630,467 |
def check():
"""Do the database check."""
icursor.execute("""
SELECT datname, age(datfrozenxid) FROM pg_database
ORDER by age DESC LIMIT 1
""")
row = icursor.fetchone()
return row | cc2584d2d049aa25745c67ccc90a65f4dbb227ec | 3,630,469 |
import random
def sample_multi_ellipsoid(key, mu, radii, rotation, unit_cube_constraint=True):
"""
Sample from a set of overlapping ellipsoids.
When unit_cube_constraint=True then during the sampling when a random radius is chosen, the radius is constrained.
u(t) = R @ (x + t * n) + c
u(t) == 1
... | 9b507adc2d485dc036718879e2de1a174e9713eb | 3,630,470 |
def auto_dataset(dataset, label) -> pd.DataFrame:
"""Prepares a dataset object."""
semantics = infer_semantic_from_dataframe(dataset)
def extract_by_semantic(semantic):
return [k for k, s in semantics.items() if s == semantic and k != label]
categorical_features = extract_by_semantic(Semantic.CATEGORICAL... | c58d1f6a7ca0a9aa36b93531c26b20deb23c7974 | 3,630,471 |
def chuz_top(input):
"""
:type input: ndarray
:return:
"""
return K.argmax(input, 1) | 009bea44ccb6a26e39fe9eb9bcd79afab1174fd7 | 3,630,472 |
def dBrickId(brickId):
"""Return box id if valid, raise an exception in other case"""
if brickId >= 0 and brickId <= 15:
return brickId
else:
raise ValueError(
'{} is not a valid Brick Id, Brick Id must be between 0-15'.format(
brickId)) | 10e0f27f179dcd54c5cc4967ea960b77a4c5a924 | 3,630,474 |
def vibrational_density_state(path_to_mass_weighted_hessian: str, eps_o: float = 3e12, nq: int = 2e4):
"""
Compute the vibrational density of state from hessian matrix
:arg
path_to_mass_weighted_hessian: str
Point to the mass weighted hessian file
eps_o: float
Th... | 4fbb92ad08174ab77d6df078876bcbdfc6786a92 | 3,630,475 |
import hashlib
def hash(text, digest_alg = 'md5'):
"""
Generates hash with the given text using the specified
digest hashing algorithm
"""
if not isinstance(digest_alg,str):
h = digest_alg(text)
else:
h = hashlib.new(digest_alg)
h.update(text)
return h.hexdigest() | 386268086a55b8e622c00b407cabd3207bb94ffb | 3,630,476 |
def box2d_iou(box1, box2):
"""Compute 2D bounding box IoU.
Input:
box1: tuple of (xmin,ymin,xmax,ymax)
box2: tuple of (xmin,ymin,xmax,ymax)
Output:
iou: 2D IoU scalar
"""
return get_iou(
{"x1": box1[0], "y1": box1[1], "x2": box1[2], "y2": box1[3]},
{"x1": box... | 8f291f5a1dd9d6c2278a0ecb00d7b6b3d581e028 | 3,630,477 |
def merge_params(params, config):
"""Merge CLI params with configuration file params. Configuration params
will overwrite the CLI params.
"""
return {**params, **config} | a1dc002a900968e6cf7c5ba401519759e6ef485e | 3,630,479 |
def init_rate():
""" This rate indicates the recorded positions' intervals. """
rate = float(0.1) # (Hz)
return rate | e6e9c6439fe4288c24be18bb098f1844aed9fc64 | 3,630,480 |
import time
import json
import base64
import requests
def doge_response(event, context):
""" Background Cloud Function to be triggered by Pub/Sub.
Takes the image URL passed in a Slack request and dogeifies it
by overlaying text generated by Cloud Vision.
Args:
event (dict): The data associate... | bc4120633ac278dbbdd11f6577bb72b3e953266e | 3,630,481 |
def get_gamma(y1, y2, gamma1, gamma2):
"""一般部位及び大部分がガラスで構成されていないドア等の開口部における日除けの効果係数 (-)
Args:
y1(float): 日除け下端から一般部及び大部分がガラスで構成されていないドア等の開口部の上端までの垂直方向距離 (mm)
y2(float): 一般部及び大部分がガラスで構成されていないドア等の開口部の高さ寸法 (mm)
gamma1(float): データ「日除けの効果係数」より算出した値
gamma2(float): データ「日除けの効果係数」より算出した値
Re... | 6503a957bc7d5daee1926aaa23694b4550733f6d | 3,630,482 |
import io
import pprint
def show(files, repo):
"""Show the commit dialog.
Args:
files: files for pre-populating the dialog.
repo: the repository.
Returns:
The commit msg.
"""
if IS_PY2:
# wb because we use pprint to write
cf = io.open(_commit_file(repo), mode='wb')
else:
cf = io.... | 48a6e77c40ebbe87870a425613a01f3376232230 | 3,630,483 |
def download_clip_wrapper(row, output_filename):
"""Wrapper for parallel processing purposes. label_to_dir"""
#print(row, type(row))
#print(output_filename)
downloaded, log = download_clip(row['video-id'], output_filename, row['start-time'], row['end-time'])
status = tuple([str(downloaded), out... | f7715c075b2f59078c2af3e17928ddd9591f00fd | 3,630,484 |
def staff_user_id():
"""Creates a staff user and returns its ID."""
staff = factories.UserStaff()
return staff.pk | 57e582056f130a91c1cbdaabaf0744d6959bc5ab | 3,630,485 |
def isNumber(s):
"""returns True if string s can be cast to a number, False otherwise"""
try:
float(s)
return True
except ValueError:
return False | fdee7992541ce42fb05e3202e63fc5bac04d43bc | 3,630,488 |
def tasks(tmpdir):
"""
Set up a project with some tasks that we can test displaying
"""
task_l = [
"",
" ^ this is the first task (released)",
" and it has a second line",
" > this is the second task (committed)",
" . this is the third task (changed, not yet com... | 64104bde2aab55021cf0d49fbb1d47670d0e4e0d | 3,630,489 |
def user_login(username, password):
"""
用户登录api(手机登录)
Args:
username: 用户账号,手机号
password: 密码
Returns:
result: a json obj of user data
"""
base_url = 'https://music.163.com/weapi/login/cellphone'
login_url = 'https://music.163.com/weapi/login/'
password = hashlib.m... | d4e8ff4cce3e5606c59ebddb6c3ee2ec5275e4a4 | 3,630,490 |
def validate_search_string(cls, value):
"""Strip search_field for evil chars used in XSS/SQL injection."""
return escape(value, quote=True) if value is not None else value | 4b77aea29d75d7ecc180514e44b1156c202be172 | 3,630,492 |
import torch
def get_topo(logbook):
"""Return a network for the experiment and the loss function for training."""
# create the network
net_config = logbook.config['indiv']['net']
if net_config['class'] not in logbook.module.__dict__:
raise ValueError('Network topology {} is not defined for pro... | 03977bb5d3520c913245b0e5bda56f6cad91a4bc | 3,630,493 |
def contact_length(roll_pass: RollPass, roll: Roll):
"""
Contact length between rolls and stock calculated using Siebel's approach
"""
height_change = roll_pass.in_profile.height - roll_pass.height
return np.sqrt(roll.min_radius * height_change - height_change ** 2 / 4) | 230914ec015ee84f6d3e4ece57d39357396b57f7 | 3,630,494 |
def swagger_url(self):
"""Patch for HTTPS"""
return url_for(self.endpoint('specs'), _external=True, _scheme='https') | 827ce733aef5a62ceb80a0ceb1fac7fd2d4a7b44 | 3,630,495 |
def read_matrix_as_image(path):
"""Read every channel of a fusion npy matrix.
Args
path: Path to the image.
"""
image = np.load(path)
#img = np.zeros((image.shape[0], image.shape[1],6))
#img[:,:,:5] = image
#return img[:, :, ::-1].copy()
return image[:, :, ::-1].copy() | 00ab043e5aff02f6e6de6aa1e1ac8aa52a6ddbc3 | 3,630,496 |
def home(request):
"""Mock home view"""
return HttpResponse('home') | 017be5073942202030c627a8a62393f49ef7d526 | 3,630,497 |
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the bpost component."""
hass.data.setdefault(DOMAIN, {})
return True | 69e7ea1d542f5aca3b7a6685b49761bc989b6985 | 3,630,498 |
from typing import List
def merge_subgroups(subgroup_list: List[Subgroup]) -> List[Subgroup]:
"""Post-processing the clusters by merging long names with short sub-name.
For example, `male canadian lynx` is merged with `canadian lynx`"""
if len(subgroup_list) <= 1:
return subgroup_list
# sort... | 01fdfcd7c89a0e65eb9118d0b97748298a0c8f70 | 3,630,499 |
def singer_map(pop, rate):
"""
Define the equation for the singer map.
Arguments
---------
pop: float
current population value at time t
rate: float
growth rate parameter values
Returns
-------
float
scalar result of singer map at time t+1
"""
return... | 84aba1d96304b67fba1b4a0e7a909e23121a3d6b | 3,630,500 |
def initialize_embedding_from_dict(vector_map, dim, vocabulary, zero_init=False, standardize=False):
"""
Initialize a numpy matrix from pre-exi\sting vectors with indices corresponding to a given vocabulary. Words in vocabulary
not in vectors are initialized using a given function.
:param vector_map: di... | 0af00d66f8c14909e5e447f2b8eb4bd68c551c97 | 3,630,501 |
def get_wall_status_data_by_simplified_calculation_no_01() -> pd.DataFrame:
"""
通気層を有する壁体の総当たりパラメータを取得し、簡易計算法案No.1(簡易版の行列式)による計算結果を保有するDataFrameを作成する
:param: なし
:return: DataFrame
"""
# パラメータの総当たりリストを作成する
parameter_name = ['theta_e', 'theta_r', 'j_surf', 'a_surf', 'C_1', 'C_2', 'l_h', 'l_w... | dafe25b6b484c0116da0f7837555a3b29cc5b068 | 3,630,503 |
def get_audio_embedding(audio, sr, model=None, input_repr="mel256",
content_type="music", embedding_size=6144,
center=True, hop_size=0.1, batch_size=32,
verbose=True):
"""
Computes and returns L3 embedding for given audio data.
Embeddi... | 2a2448c46cbe31c0631ccd049eca796e94a5f973 | 3,630,504 |
import json
def format_rpc_response(data, exception=None):
"""
Formats a response from a RPC Manager.
It provides the data and/or a serialized exception so it can be
re-created by the caller.
:param Any data: A JSON Serializable object.
:param Exception exception: An Exception object
:ret... | c900e2512fd486c91789ab4312883061553a2fb1 | 3,630,505 |
def AbsoluteError(U, Uold):
"""Return absolute error.
Absolute error is calculated to track the changes or deviation in
the numerical solution. This is done by subtracting the solution
obtained at the current time step from the solution at previous
time step within the entire domain.
The compu... | 179cbe81cee92a01e12509b42f6a8800a6c05976 | 3,630,506 |
import typing
def safe_redirect(endpoint: str,
**params: str | bool | None) -> typing.RouteReturn | None:
"""Redirect to a specific page, except if we are already here.
Avoids infinite redirection loops caused by redirecting to the
current request endpoint.
It also automatically ad... | 9cca685ae4e7476be6759d9b4721d7f3e1b7b89f | 3,630,510 |
import scipy
def interpolate_with_ot(p0, p1, tmap, interp_frac, size):
"""
Interpolate between p0 and p1 at fraction t_interpolate knowing a transport map from p0 to p1
Parameters
----------
p0 : 2-D array
The genes of each cell in the source population
p1 : 2-D array
The genes... | 419635d2f6db9a8b95eada62221b1242ceecb80f | 3,630,511 |
import functools
def db_session(func) -> Session:
"""
gets a connection from the pool, create an orm session and passes it as first parameter to `func`
after finish the connection is returned to the pool
no transaction handling
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
... | 1ea1f3850b4c062c91b2a33302a23040c9d2d72b | 3,630,512 |
import torch
def get_attention(preds, temp):
""" preds: Bs*C*W*H """
N, C, H, W = preds.shape
value = torch.abs(preds)
# Bs*W*H
fea_map = value.mean(axis=1, keepdim=True)
print("fea_map = ", fea_map.shape)
S_attention = (
H * W * F.softmax((fea_map/temp).view(N, -1), dim=1)).view(... | 0c257ca2fbc17a5e56702c15a138567e7ed81bec | 3,630,513 |
import logging
def select_best_haplotype_match(all_matches):
"""Returns the best HaplotypeMatch among all_matches.
The best matching HaplotypeMatch is the one with the lowest match_metrics
score.
Args:
all_matches: iterable[HaplotypeMatch]. An iterable of HaplotypeMatch objects
we want to select t... | 0e40fef830055e5cd297b0f00672d8b0caedc62e | 3,630,514 |
def get_tokens_list_from_column_list(column_name_list: list,
delimiter: str = '!!') -> list:
"""Function that returns list of tokens present in the list of column names.
Args:
column_name_list: The list of column name strings.
delimiter: delimiter seperating tok... | 66e2c3c280188d2cc3e8df35e0112095f3244918 | 3,630,515 |
def solve(task: str, preamble_length=25) -> int:
"""What is the first invalid number?"""
data = [int(num) for num in task.strip().split("\n")]
return first_invalid(data, preamble_length) | e574aeaba225010e0538d0298a198e37d2272e74 | 3,630,516 |
def schedule(course_list):
"""
Given a list of courses, return a dictionary of the possible schedules
['BT 353','CS 135','HHS 468','BT 181','CS 146','CS 284'] -->
{1:
{'url': 'https://web.stevens.edu/scheduler/#2015F=10063,10486,10479,11840,12011,11995,10482,10487',
'list': "('BT 181A', ... | 8c9c5db6e49b1ae106e7d83a38dde0fc2e7617e7 | 3,630,517 |
def get_repository_instance(conf=None):
"""
Helper function to get a database Repository model instance based on CLA configuration.
:param conf: Same as get_database_models().
:type conf: dict
:return: A Repository model instance based on configuration specified.
:rtype: cla.models.model_interf... | 33b49af8dd1db0af572b6ddc0d3ad5d919e06eb8 | 3,630,518 |
import operator
def _setup_RepeatingContainer_special_names(repeating_class):
"""This function is run when the module is imported--users should
not call this function directly. It assigns magic methods and
special attribute names to the RepeatingContainer class.
This behavior is wrapped in a function... | 83909835d62599f190e26d3e72c40a9759cfbbf4 | 3,630,519 |
def set_up_nircam():
"""
Return a configured instance of the NIRCam simulator on JWST.
Sets up the Lyot stop and filter from the configfile, turns of science instrument (SI) internal WFE and zeros
the OTE.
:return: Tuple of NIRCam instance, and its OTE
"""
nircam = webbpsf.NIRCam()
nir... | b994561fe00f34e704f4ffc06f162da1bc060425 | 3,630,520 |
def _dens0(S,T):
"""Density of seawater at zero pressure"""
# --- Define constants ---
a0 = 999.842594
a1 = 6.793952e-2
a2 = -9.095290e-3
a3 = 1.001685e-4
a4 = -1.120083e-6
a5 = 6.536332e-9
b0 = 8.24493e-1
b1 = -4.0899e-3
b2 = 7.6438e-5
b3 = -8.2467e-7
... | a0df8ba385c18fbb7f51088cac2ec842bdef308f | 3,630,521 |
import warnings
import ctypes
def convolve(array, kernel, boundary='fill', fill_value=0.,
nan_treatment='interpolate', normalize_kernel=True, mask=None,
preserve_nan=False, normalization_zero_tol=1e-8):
"""
Convolve an array with a kernel.
This routine differs from `scipy.ndimag... | b4ec7a5e8f8e7b1ddd9fd14f50efda96ffb548fd | 3,630,523 |
from pathlib import Path
from typing import Optional
def get_k_best_and_worst_performing(val_metrics_csv: Path, test_metrics_csv: Path, k: int,
prediction_target: str = MetricsDict.DEFAULT_HUE_KEY) -> Optional[Results]:
"""
Get the top "k" best predictions (i.e. correct cla... | 5aaa2510f72649be280859793e0959def07d6e0a | 3,630,524 |
def flow_experiment_from_csv(filename):
"""
Initialise a flow experiment from a formatted .csv file.
Parameters
----------
filename: str
Name of a formatted configuration file.
Returns
-------
experiment: Classes.FlowExperiment
"""
with open(filename, "r", encoding="ut... | 9e37a4392eb3f96dfbd3b8947badb9009e252513 | 3,630,525 |
def get_int(value, allow_sign=False):
"""Convert a value to an integer.
Args:
value: String value to convert.
allow_sign: If True, negative values are allowed.
Return:
int(value) if possible.
"""
try:
# rstrip needed when 0. is passed via [count]
int_val = in... | a50b23cac634d4cf414fa18a68f5a926c0702735 | 3,630,526 |
from typing import Union
def calculate_weights(
performance: Union['xr.DataArray', None],
independence: Union['xr.DataArray', None],
performance_sigma: Union[float, None],
independence_sigma: Union[float, None]) -> 'xr.DataArray':
"""Calculate normalized weights for each model N.
... | 2a5e578b80fb4cff7e8d90ce0d8c7a98d777342f | 3,630,527 |
def validate_state(state):
"""
State validation rule.
Property: LifecyclePolicy.State
"""
VALID_STATES = ("ENABLED", "DISABLED")
if state not in VALID_STATES:
raise ValueError("State must be one of : %s" % ", ".join(VALID_STATES))
return state | 5dcc3d2c8bf9242d8090aef0933f26d2ffa1821d | 3,630,528 |
def load_variable_config(project_config):
"""Extract the variable configuration out of the project configuration.
Args:
project_config (dict-like): Project configuration.
Returns:
dict: Variable dictionary with name: [levels] (single level will have a list containing None.)
"""
# ... | 37caccfa5f9c3a724e61233610c3e4a3e9938695 | 3,630,529 |
from typing import Union
from typing import List
def absolute_simulations_distance_for_tables(
simulation_dfs: Union[List[pd.DataFrame], pd.DataFrame],
gt_simulation_dfs: Union[List[pd.DataFrame], pd.DataFrame]):
"""Compute absolute normalized distance between simulations.
Parameters
----... | e7090bc60bc9da4aed070e7c0af78e91aad7504d | 3,630,530 |
def _experiment_fn(run_config, hparams):
"""Outputs `Experiment` object given `output_dir`.
Args:
run_config: `EstimatorConfig` object fo run configuration.
hparams: `HParams` object that contains hyperparameters.
Returns:
`Experiment` object
"""
estimator = learn.Estimator(
... | aebf6b7586ece3a995f29b8f7f52283e3d29a478 | 3,630,531 |
import torch
def cross_op_torch(r):
"""
Return the cross operator as a matrix
i.e. for input vector r \in \R^3
output rX s.t. rX.dot(v) = np.cross(r, v)
where rX \in \R^{3 X 3}
"""
if len(r.shape) > 1:
rX = torch.zeros(r.shape[0], 3, 3).to(r)
rX[..., 0, 1] = -r[..., 2]
rX[..., 0, 2] = ... | 04f926f00f6ed58bee3feae80ef573f5a8822d20 | 3,630,532 |
from datetime import datetime
def apply_internal(user_id, job_id, resume, comment):
"""
Basic logic for applying to internal job postings.
Arguments:
`user_id`: ID of the user applying
`job_id`: ID of the job a user is applying for
`resume`: Handy tool for applying to jobs
"""
if not ... | af7ebb2e9a31c4ee41514d6330a416018e85999e | 3,630,533 |
def check_acls(user, obj, acl_type):
"""Check ACLs."""
if acl_type == 'moz_contact':
try:
return user.email in obj.addon.get_mozilla_contacts()
except AttributeError:
return user.email in obj.thread.addon.get_mozilla_contacts()
if acl_type == 'admin':
return a... | 6d00906484479c918280e92cc61168aa5959e066 | 3,630,534 |
def variable_labels():
"""Dictionaries that contain Variables objects."""
_phi = r'$\phi$'
_eta = r'$\eta$'
_T = r'$_\text{T}$ [GeV]'
_mass = 'Mass [GeV]'
variables = {}
variables['ljet_C2'] = Variable(binning=hist1d(10, 0., 0.6), label=r'Large-R Jet C$_2^{\beta\text{=1}}$')
v... | 38cf74c3c4a1a136adfa81ee8ff675062caf1f7e | 3,630,535 |
def _calcDistance(fiberMatrix1, fiberMatrix2):
""" *INTERNAL FUNCTION*
Computes average Euclidean distance
INPUT:
fiberMatrix1 - 3D matrix containing fiber spatial infomration
fiberMatrix2 - 3D matrix containing fiber spatial information for
comparison
OUTPUT:
... | d50fef85c6a682c093ba62394103d525d23f58b7 | 3,630,536 |
from typing import Dict
def filter_topology(model: Dict[str, str], operator: str, value: str,
component: str):
"""Check whether model should be included according to the user input. The
model should be added if the its topology is consistent with the components
requested by the user (n... | c4e26a89a271e5f70b0ca1afae47a78a3e6acca0 | 3,630,538 |
def getAuctionPrice(the_auction: models.DutchAuction, bid: Transaction[BidParameter, TezlandDutchAuctionsStorage]):
"""Returns current price in mutez.
More or less pasted from dutch auction contract."""
granularity = int(bid.storage.granularity)
op_now = bid.data.timestamp
# return start price if ... | 4503fe0212935a2b37a15000448dd0fe8b5674a4 | 3,630,539 |
def __all_paths_between_acceptance_states(Dfa):
"""Generates for each front acceptance state a copy of the complete
graph which can be reached inside 'Dfa' starting from it until the next
acceptance state.
RETURNS: List of DFAs containing a tail for each found acceptance states.
"""
def _get_br... | 136ea0a999bff3b930ad4e05107042da36262d13 | 3,630,540 |
def hello():
"""
An op definition. This example op outputs a single string.
For more hints about writing Dagster ops, see our documentation overview on Ops:
https://docs.dagster.io/concepts/ops-jobs-graphs/ops
"""
return "Hello, Dagster!" | cf701323e751122823f22bad864f7b1f0d700a97 | 3,630,541 |
def vtk_clean_polydata(surface):
"""
Clean surface by merging
duplicate points, and/or
removing unused points
and/or removing degenerate cells.
Args:
surface (vtkPolyData): Surface model.
Returns:
cleanSurface (vtkPolyData): Cleaned surface model.
"""
# Clean surfac... | 340d1e9377b378ff007a6fd115508e7c25890de2 | 3,630,542 |
def custom_exception_handler(exc, context):
"""
A custom exception handler that makes sure errors are returned with a fixed format.
Django, django-rest-framework, and the jwt framework all throw exceptions in slightly
different ways. This has to be caught and each type of exception has to be converted
... | fbb3e8934851b53ea0e771b39d0d5e0fc992ff3e | 3,630,543 |
def fetch_svc(k8s_host, **kwargs):
"""
Fetch named service definition from Kubernetes (output: dict)
"""
pass_headers = {}
if 'k8s_api_headers' in kwargs:
headers = kwargs.pop('k8s_api_headers')
pass_headers.update(headers)
namespace = kwargs['namespace']
service_name = kwargs[... | c302f0cbaf7026356e9f6f9adae2820bb9d17ae5 | 3,630,544 |
def mentionable():
"""
:return: boolean
True, if there is something mentionable to notify about
False, if not
"""
# need to be implemented
return False | d1dac607efb512771677aa7e8dd42a2c21251833 | 3,630,545 |
def cmp_ver(a, b):
"""Compare versions in the form 'a.b.c'
"""
for (i, j) in zip(split_ver(a), split_ver(b)):
if i != j:
return i - j
return 0 | d774235354c613cec15e2d438bc6a1e60e678ae7 | 3,630,546 |
def delete_buckets(buckets) -> list:
"""Deletes all buckets from a list
Args:
buckets (list): A list of s3 buckets
Returns:
A list of terminated buckets
"""
terminated_buckets = []
for bucket in buckets:
bucket_name = bucket["Name"]
if helpers.check_in_whitelist... | 17c1eaf5b277a3343fd4d0403150b571fa462ee9 | 3,630,549 |
def box_fusion(
bounding_boxes,
confidence_score,
labels,
mode='wbf',
image_size=None,
weights=None,
iou_threshold=0.5):
"""
bounding boxes:
list of boxes of same image [[box1, box2,...],[...]] if ensemble many models
list of boxes of sing... | 59622e278e6805b1a726871bec089a90a68c1d4f | 3,630,550 |
def get_worker_class(global_conf, message):
"""Returns class of worker needed to do message's work"""
worker_type = 'worker-%s' % (message.body['worker_type'])
if worker_type not in global_conf:
raise RuntimeError("Invalid worker type '%s'" % (worker_type))
conf = global_conf[worker_type]
im... | 3f975caf97827fcfaf7d74141ea651c302e4781c | 3,630,551 |
def isConsistant(spectrum,kmer):
"""Checks whether a given kmer is consistent with a given spectrum or not.
INPUT :
spectrum: array-like. The spectrum required to check the given kmer against.
kmer: string. The given kmer required to check its consistency.
OUTPUT:
.: bool. The consist... | 0403fdcb324d40d10bdc4555f3d8eb26faebe8ed | 3,630,554 |
def validate_java_file(java_file):
"""Validates a java file.
Args:
java_file_path: the path to the java file.
Returns:
a list of errors.
"""
file_status, java_file_path = java_file
with open(java_file_path, "r") as fp:
contents = fp.read()
if not contents:
return ["[ERROR] Errors exist in " + java_fi... | a0bde1c13ef1d7b5056fe47fefe05bfd8bbcf7b1 | 3,630,555 |
def convertVoltage(raw_voltage):
""" Ground is 1
1.8 is 4095
"""
converted_voltage = (raw_voltage/4095)*1.8
return "%.3f" % converted_voltage | 4f404ff02449a231521f80a2b9a4ae443880e1b3 | 3,630,556 |
def fast_ica(image, components):
"""Reconstruct an image from Fast ICA compression using specific number of components to use
Args:
image: PIL Image, Numpy array or path of 3D image
components: Number of components used for reconstruction
Returns:
Reconstructed image
Example:
... | 49ade88a8d1fe6a7addf8eb35be326088b916846 | 3,630,557 |
from typing import Callable
from typing import Optional
from typing import Union
from typing import Tuple
from typing import Iterable
def solve_nr(
f: Callable[[float], float],
df: Callable[[float], float],
estimate: float,
eps: Optional[float]=1.0e-6,
max_num_iter=100,
throw_if_failed_converge=True,
re... | c6ab8b6bb27f8b9be9c31fe7cbd58300637d9fef | 3,630,558 |
import json
def get_data(source):
"""fungsi ambil data pegawai, jadwal, judul, liburan"""
with open(source, 'r') as srce:
return json.load(srce) | 964efdabcbd21486985bbc9189c5d07dbc800dd6 | 3,630,559 |
def unpack_request(data):
"""Take a buffer and return a pair of the RequestHeader and app data"""
start = MSG_TYPE_SIZE + REQUEST_HEADER_SIZE
return (unpack_request_header(data), data[start:]) | ed0e2baf9aa510e6460eb3a9b4e5e95295389bfe | 3,630,561 |
def basic_pl_stats(degree_sequence):
"""
:param degree sequence of individual nodes
"""
results = Fit(degree_sequence,discrete=True)
return (results.alpha,results.sigma) | a079169a328547a2f43eb6ed9431202895cd75f9 | 3,630,562 |
def merge_config_dictionaries(*dicts):
"""
Merges n dictionaries of configuration data
:param list<dicts>:
:return dict:
"""
res_dict = {}
if isinstance(dicts, list):
if len(dicts) == 1 and isinstance(dicts[0], dict):
return dicts[0]
else:
for diction... | c9711e897d5c7caa47a21f3e901025c91862327f | 3,630,563 |
def op_catalog_size() -> int:
"""
Return number of entries in the operational-data catalog
@return: integer
"""
return sum(len(entries) for entries in _op_catalog.values()) | 844519ec9afa3b06138128f5559acc2090ad4452 | 3,630,564 |
import json
def worker_recv_export_job(request):
"""Worker进程(集群节点)请求接受给定ID(taskSettingId)的导出任务"""
try:
datas = json.loads(request.body.decode())
taskSettingId = int(datas["params"]["taskSettingId"])
# Worker进程可以有多个,为了防止并发请求导致job更新不及时被两个Worker消费,这里需要这样处理
updateRows = PlExportJob... | 084526b0021e7fb31d5edb041fde2c734729a5cc | 3,630,565 |
def add_host_log_history(
host_id, exception_when_existing=False,
filename=None, user=None, session=None, **kwargs
):
"""add a host log history."""
host = _get_host(host_id, session=session)
return utils.add_db_object(
session, models.HostLogHistory, exception_when_existing,
host.id,... | 511213a6f00660c8e5921cf23974842e413e1725 | 3,630,566 |
def get_main_window():
"""Return the tkinter root window that Porcupine is using."""
if _root is None:
raise RuntimeError("Porcupine is not running")
return _root | 8c4ff2126f3f9c3367214ff1fe186106e15e7f57 | 3,630,569 |
def calculate_cluster_spatial_enrichment(all_data, dist_mats, fovs=None,
bootstrap_num=1000, dist_lim=100):
"""Spatial enrichment analysis based on cell phenotypes to find significant interactions between different
cell types, looking for both positive and negative enric... | 62cef02346e1461c03a46dad81cb5814010cc8c7 | 3,630,570 |
import calendar
import pytz
def epoch(dt):
"""
Returns the epoch timestamp of a timezone-aware datetime object.
"""
return calendar.timegm(dt.astimezone(pytz.utc).timetuple()) | 027ea75bf75b6bb6b4da14b2bed1afc363a9121a | 3,630,571 |
def main():
"""Implements the main method running this smoke test."""
defaults = {
'TEST_STACK': str(OpenStackSmokeTestScenario.DEFAULT_TEST_ID),
'TEST_APP': 'openstack-smoketest' + OpenStackSmokeTestScenario.DEFAULT_TEST_ID
}
return citest.base.TestRunner.main(
parser_inits=[OpenStackSm... | 02e542c2337f9582e38bedec6067c4290d0317f6 | 3,630,572 |
def is_pandas_series(value):
"""
Check if an object is a Pandas DataFrame
:param value:
:return:
"""
return isinstance(value, pd.Series) | 3ea667302f4a60f68569555c650a297e6b7b3a18 | 3,630,573 |
from typing import Union
import copy
import numpy
def copy_visibility(vis: Union[Visibility, BlockVisibility], zero=False) -> Union[
Visibility, BlockVisibility]:
"""Copy a visibility
Performs a deepcopy of the data array
:param vis: Visibility or BlockVisibility
:returns: Visibility or BlockVisi... | 451d0d365611d3538d8bc3e9d90fc82771df8290 | 3,630,574 |
def set_produce_compilation_cache(enabled: bool) -> dict:
"""Forces compilation cache to be generated for every subresource script.
Parameters
----------
enabled: bool
**Experimental**
"""
return {"method": "Page.setProduceCompilationCache", "params": {"enabled": enabled}} | 3d2dd7fa6c8d04713ace26c666d9b00407a5a586 | 3,630,575 |
def raw_input(prompt=None): # real signature unknown; restored from __doc__
"""
raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled... | ad09db4416e3705a34e4fc88c7df569693608c80 | 3,630,577 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.