content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def check_cn_match(sv_list, cn_increase, cn_decrease, final_cn):
"""
Check that the CNV combination produces the right final copy number.
"""
if sv_list == []:
return False
initial_cn = 2
for sv in sv_list:
if sv in cn_increase:
initial_cn += 1
if sv in cn_dec... | a9d45b1421b5b6f5ce085df7e2f0c8040bffd163 | 39,500 |
def rotateMatrix(m):
"""
rotate matrix
:param m: matrix
:type m: list of list of integers
:return: rotated matrix
:rtype: list of list
"""
for i in range(int(len(m) / 2)):
last_layer = len(m) - i - 1
for j in range(i, last_layer):
offset = j - i
to... | 198c8c28c29c49fee1d26d603e52ec2da43d82a5 | 39,501 |
def get_beautiful_base_image_map(df_flux, thin=False):
""" Create the beautiful folium map containing routes, with blur effect """
# Initialize folium map parameters
folium_map = folium.Map(location = sgs._location_map,
zoom_start = sgs._zoom_map,
... | ca4a1c63bc9ca01283719600385eb78ce9f0072f | 39,502 |
def lambda_handler(event, context):
"""Main Lambda Handler."""
print 'event ', event
LOG.debug('event %s', event)
namespace = event['directive']['header']['namespace']
if namespace == 'Alexa.Discovery':
return handle_discovery(context, event)
elif namespace == 'Alexa.RemoteVideoPlayer':
... | 2fc3babc56ae5cfc9dfd5ea0e7ec9d31b7ab72e8 | 39,503 |
def u_crit_switch_lat_hh80(thermal_ro):
"""Where RCE and AMC winds are equal in Held Hou 1980 model."""
return np.rad2deg(np.arccos((((1 + 2*thermal_ro)**-0.25)))) | 998d183e56fd3d423fa7b8f227558030f02ac9cb | 39,504 |
import re
def GetUniqueName(context, name):
""" Fixup any sbsar naming collision """
foundName = False
nameCount = 1
lastChar = ''
for sb in context.scene.loadedSbsars:
if sb.name.startswith(name):
foundName = True
# find the highest value suffix on the name
... | fe8b868ec791af091eb0e78abea2549b7e724adf | 39,505 |
def _make_text_table(
explainer_values,
normalized_values,
pipeline_features,
original_features,
top_k,
include_explainer_values=False,
algorithm="shap",
):
"""Make a table displaying the explainer values for a prediction.
Args:
explainer_values (dict): Dictionary mapping th... | 78a5c4422958bfac20c1ff4c05f26dee155bd4c5 | 39,506 |
def find_best_ncut(G, x, y, cell_to_idx=None, mut_to_idx=None):
"""
Given bipartite graph G, 1-dimensional representation x of "left" vertices, 1-dimensional representation y of "right" vertices, exhaustively finds the cut-points in these 1D representations that minimizes the normalized cut.
"""
i2... | 2b9b11a9f892fbfcec2fae3befe9833db87834a7 | 39,507 |
from .constants import a_cc, beta
def triaxial_strain(magnetic_field):
"""Triaxial strain corresponding to a homogeneous pseudo-magnetic field
Parameters
----------
magnetic_field : float
Intensity of the pseudo-magnetic field to induce.
"""
def field_to_strain(field):
return... | 6435017f83c84a7880b808c717fa66016c707893 | 39,508 |
import os
import torch
def read_data( x_range, y_range, geoboundary, batch_size=0, set_size=0, data_dir=os.path.abspath(''), rand_seed=1234,
normalize_input=True, test_ratio=0.2):
"""
:param set_size: input size of sets
:param input_size: input size of the arrays
:param output_siz... | cbaeefa0c52ab58162b1910ef042597f87ae254e | 39,509 |
def get_least_sig_bit(band):
"""Return the least significant bit in color value"""
mask = 0x1
last_bit = band & mask
return str(last_bit) | 9d56bc5fdbf613f31bf7b21ee08f4f753b3a92db | 39,510 |
def _str(val):
"""
Ensures that the val is the default str() type for python2 or 3
"""
if str == bytes:
if isinstance(val, str):
return val
else:
return str(val)
else:
if isinstance(val, str):
return val
else:
return str... | d1c56751d2b7ef732a0048749e01f4c08e88d0f8 | 39,511 |
def CurrentColumn():
"""Returns the 0-based current column. Do NOT access the CurrentColumn in
vim.current.line. It doesn't exist yet when the cursor is at the end of the
line. Only the chars before the current column exist in vim.current.line.
"""
# vim's columns are 1-based while vim.current.line... | 98e2a1f5ef572d9cdacc63289ba23f3eac6f755f | 39,512 |
def sort_data_mnist(
x_train,
y_train,
x_test,
y_test,
num_points_per_task,
test_points_per_task,
n_tasks=10,
shift=1,
):
"""
Sorts data into training and testing data sets for each task.
Generalized for MNIST datasets and different task numbers.
"""
# reformat data
... | 50ddd8031ba47001e0d098ed80bfc87cf2eaca8a | 39,513 |
def show_confmap_grid(net, X, Y, plot=True, save_path=None, show_figure=False):
"""
Shows predictions from the model using every channel in the confmap.
"""
if X.ndim == 2:
X = X[None,...,None]
if X.ndim == 3:
if X.shape[0] == 1: # missing singleton channel
X = X[..., No... | 2a58de790069636732abebec39020e2110721f8c | 39,514 |
def make_sign_from_network(Network):
"""
Make an NxN numpy array describing the interaction sign between edges
Input:
Network - DSGRN network object
Output:
numpy array with 1 if j->i, -1 if j-|i, and 0 otherwise.
"""
N = Network.size()
sign = np.zeros([N,N])
for j in ra... | 96fc6c9ac72c62f8c8927b188df26235f9c58ab3 | 39,515 |
def open_file(filename, mode):
"""Open json file for the current user and given filename, and mode."""
return open('users/' + user_info['username'] + '/' + filename + '.json', mode, encoding='utf-8') | e71f3c722ba11a6f88e9e6cfb7fd329a62f3e1d7 | 39,516 |
def rc4(data, key):
"""RC4 encryption and decryption method."""
S, j, out = list(range(256)), 0, []
for i in range(256):
j = (j + S[i] + ord(key[i % len(key)])) % 256
S[i], S[j] = S[j], S[i]
i = j = 0
for ch in data:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[... | 8c77874bcf3be7f5a01bf23b33f8a1cce0d18630 | 39,517 |
def test(img, r=3, d=8, option="single"):
"""Standardized Tester
Parameters
----------
img : np.array
Input binary image to run DBScan on
Keyword Arguments
-----------------
r : int
Ball radius for DBScan
d : int
Density threshold; how many neighbors must be pre... | 3142dc5351d86a732615bf15ab1ce9931c1eb713 | 39,518 |
import logging
import sys
def create_logger(name, silent=False, to_disk=True, log_file=None):
"""Logger wrapper
"""
# setup logger
log = logging.getLogger(name)
log.setLevel(logging.DEBUG)
log.propagate = False
formatter = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%m/%d/%Y ... | d6ee71d33db3af55fdf87042c3d458ccb327cc31 | 39,519 |
def binomial_ci(series, alpha=0.05, method="wilson", side="both"):
"""Returns a binomial confidence interval
Computes a binomial confidence interval based on boolean data. A symbolic
wrapper for statsmodels.stats.proportion.proportion_confint.
Args:
series (pandas.Series): Column to summarize;... | fc528d05d5eceded41ed68b81d63fd61c35456fa | 39,520 |
def _redirect_func_check_failed(request):
"""
跳转功能权限检测失败的提示页面
"""
url = '%saccount/check_failed/?code=func_check' % settings.SITE_URL
if request.is_ajax():
# ajax跳转页面,需要借助settings.js实现页面跳转或redirect跳转。
resp = HttpResponse(status=402, content=url)
return resp
else:
... | 176336045ae27bab92a9286743bb01d9c4fae51b | 39,521 |
def I(box):
"""
Integrate even function over a box
"""
level = 0
ub = []
return Ir(box, level, ub) | 0611e2d89ea4421c34b74dcf84a1552c98131d9e | 39,522 |
import importlib
def register_models(app):
"""All database models need to be registered for Flask-Migrate to see them"""
for model in [
"biography",
"comments",
"contacts",
"downloads",
"guestbook",
"news",
"people",
"photos",
"releases",... | 51e134fb5bce61fd4dba12d815561cd4ebf63396 | 39,523 |
def encode_data(data, tokenizer, punctuation_enc):
"""
Converts words to (BERT) tokens and puntuation to given encoding.
Note that words can be composed of multiple tokens.
"""
X = []
Y = []
for line in data:
word, punc = line.split()
punc = punc.strip()
tokens = tok... | ad1a866f8f165f037cf6c85c8f60a4fd15eb570f | 39,524 |
import os
import json
import subprocess
import re
def get_status(jobdir, jobid=None):
"""
Given list of jobs, returns status of each.
"""
cmd_template = "aws batch describe-jobs --jobs {}"
if jobid is None:
print(("Describing jobs in {}/ids/...".format(jobdir)))
jobs = os.listdir(... | 665ca433ca90ed7d0851bfd4d0d1a1e800fcc4ad | 39,525 |
import torch
def superpixel_mask(img, mod_specific = True):
"""
assume dim 0 of img is the batch_size
SLIC - K-Means based image segmentation
https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_segmentations.html
:param input: Input image, which can be 2D or 3D, and grayscale or mult... | da422b706eecd2b44d96e5b5d5fbce4d4ddfe382 | 39,526 |
def get_experiment_random_states_data():
"""Get the data for random states experiment
Params:
episode: int
The episode for which the data of an
experiment instance shall be returned
Returns:
exp_data: dict
The experiment data. For further explanation
... | 85c8ca47e1a6423a86e7cf7bc3d1694b9c63957d | 39,527 |
import os
import sys
import errno
def openpty():
"""
Call :func:`os.openpty`, raising a descriptive error if the call fails.
:raises mitogen.core.StreamError:
Creating a PTY failed.
:returns:
`(master_fp, slave_fp)` file-like objects.
"""
try:
master_fd, slave_fd = os.... | 38da225a6cb6ca9d6894479e2c50fc715f172795 | 39,528 |
def _private_key_filename(file_prefix):
"""
Construct the name of a file for use in storing a private key.
:param str file_prefix: base file name for the private key (without the
extension)
:return: private key filename
:rtype: str
"""
return file_prefix + ".key" | 66f0bf0dfb3250c81c56220f50438debd74852bf | 39,529 |
import itertools
def possible_jp(decay_chain, max_J=2):
"""get possible resonances jp of J <= max_J"""
ret = []
A = decay_chain.top
outs = decay_chain.outs
jp_list = [jp_seq(max_J) for _ in decay_chain.inner]
ret = {}
for jps in itertools.product(*jp_list):
res_map = {}
fo... | b3722316ed07c854e452a7b3995245b0778d9d0a | 39,530 |
import socket
def set_mock_context(msg, monkeypatch, writerfqdn='test.bar.example.com'):
"""
establish the mock context for our testing
"""
print("================ %s ================" % msg)
# pylint: disable=bad-continuation
props = {
'writerfqdn': writerfqdn,
'use_existing': False,
'readerf... | b5243906f711837a54bd16444c5ede07f7639928 | 39,531 |
def default(mol, gerebtzoff = True):
"""
Calculates the QED descriptor using average descriptor weights and Gregory Gerebtzoff parameters.
"""
return weights_mean(mol, gerebtzoff) | e6e8ec956bdc365101a9c54cb5e65ae9326c8a03 | 39,532 |
def build_context_residual(offxml, molfile, dihedrals):
"""Builds context for the openmm calculation keeping the dihedral frozen and the
specific energy contributions from the dihedral zeroed out
Parameters
----------
offxml: forcefield file
molfile: molecule file in sdf format
dihedrals: li... | 9973eded35fbe6aa468ec4c32559b16e7dc70afc | 39,533 |
import torch
def sparse_tensor_to_sparse_adj(x: torch.Tensor) -> sp.csr_matrix:
"""Converts a SparseTensor to a Scipy sparse matrix (CSR matrix)."""
x = x.coalesce()
data = x.values().detach().cpu().numpy()
indices = x.indices().detach().cpu().numpy()
shape = tuple(x.size())
return sp.csr_matr... | 3480c0a10d1dcd28b8c75693d305c86cee45bb04 | 39,534 |
def preprocess(question):
"""Do all steps of question preprocessing.
Args:
question (str): Original question in natural language.
ctx_entities (list): Context entities.
Returns:
str: Question lower, without punctuation and with stopwords
replaced by wildcards.
"""
... | 745542ae9117f7381d4952f5ffebbdf98de161bd | 39,535 |
import os
def _genome_asset_path(
genomes, gname, aname, tname, seek_key, enclosing_dir, no_tag=False
):
"""
Retrieve the raw path value for a particular asset for a particular genome.
:param Mapping[str, Mapping[str, Mapping[str, object]]] genomes: nested
collection of key-value pairs, keyed... | 2e3293f80291418ed1e565e10617af452c1c6069 | 39,536 |
def create_body(arch, pretrained=True, cut=-2):
""" Cut off the body of a typically pretrained `model` at `cut` or as specified by `body_fn` """
model = arch(pretrained)
if pretrained:
freeze(model)
return nn.Sequential(*list(model.children())[:cut]) | ed984542e204e93401e6de5872e8f25772a94a06 | 39,537 |
from io import StringIO
def get_stock_basics(date=None):
"""
获取沪深上市公司基本情况
Parameters
date:日期YYYY-MM-DD,默认为上一个交易日,目前只能提供2016-08-09之后的历史数据
Return
--------
DataFrame
code,代码
name,名称
industry,细分行业
area,地区
pe,市盈率
... | c2c296b311630637df7cf5c2991b08cb4af72210 | 39,538 |
def _RunWorkload(vm, num_threads):
"""Runs stress-ng on the target vm.
Args:
vm: The target vm to run on.
num_threads: Number of instances of stressors to launch.
Returns:
A list of sample.Sample objects.
"""
metadata = {
'duration_sec': FLAGS.stress_ng_duration,
'threads': num_thre... | f58ccd2525881668ad1069a9bbed920bd41eb1ff | 39,539 |
def denormalize_image(image):
""" Undo normalization of image. """
image = (image / 2) + 0.5
return image | c49a1465d89e317a1c8013969fbee913bf705f4a | 39,540 |
def find_overlapping_selections(selections, selection_strings):
"""
Given a list of atom selections (:py:class:`scitbx.array_family.flex.bool`
arrays) and corresponding selection strings, inspect the selections to
determine whether any two arrays overlap. Returns a tuple of the first pair
of selection string... | fffd25a98cbb2184d372c5904718f30cd7c97d1a | 39,541 |
from meerschaum.config._edit import general_write_yaml_config
from meerschaum.config._sync import sync_files
def write_stack(
debug : bool = False
):
"""
Write Docker Compose configuration files
"""
general_write_yaml_config(get_necessary_files(), debug=debug)
return sync_files(['stac... | 1e0ebea2836e7f300e8698585ed2a0736d6480a6 | 39,542 |
def compute_pdf(obs, histogram):
"""
Compute the PDF of the given observable histogram
"""
(_, _, bin_size) = constants.HISTOG_PARAM_TABLE[obs]
pdf = histogram / sum(histogram) / bin_size
return pdf | b7fb65e02838edcf264a332c1969904aeb954c05 | 39,543 |
from typing import Any
def day_lte(query: int, field_name: str, object: Any) -> bool:
"""
Check if value of object is less than or equal to value of query
"""
return _datetime_lte(query, getattr(object, field_name).day) | ce0466aae8825366db0ec0c65fb8bb6311f0f800 | 39,544 |
def dot(x,y):
""" dot product of two vectors """
return tf.reduce_sum(tf.multiply(x,y)) | 3a08ad41b0e04760b583f8146c4ecdb4db706f08 | 39,545 |
import imghdr
def check_bmp(input_file_name):
""" Check if filename is a BMP file
:param input_file_name: input file name
:type input_file_name: string
:return whether the file is .bmp
:rtype boolean
"""
return 'bmp' == imghdr.what(input_file_name) | 3a8749832418d3976825a79a0bd89c7a77649fe8 | 39,546 |
def mediapackage_channels(region):
"""
Return the MediaPackage channels for the given region.
Tags included.
"""
items = []
service_name = 'mediapackage'
if region in boto3.Session().get_available_regions(service_name):
service = boto3.client(service_name, region_name=region, config=... | 2f59c573b9bec22ddc9badc57abd407bb9a8c61f | 39,547 |
def doc_fb_threshold_filter(threshold, session, docs = None, with_fb = True):
"""
Filter documents by feedback value
threshold: float, the threshold value
session: Session,
docs: DocumentList, the documents to be considered
with_fb: Boolean, if True, then those without feedback values are ... | 3eec4e7e2716869eaa573c78f53bbd2085c55913 | 39,548 |
import os
import logging
def save_df(args: dict, df: pd.DataFrame) -> bool:
"""Save Pandas DataFrame to a file in excel or CSV format (depending on extension)"""
if args['outfile']:
base, ext = os.path.splitext(args['outfile'])
if ext == '.xlsx':
df['datetime'] = df.index.to_series... | 68850764f67fa613f033f2ec93dce2335631e3f1 | 39,549 |
def time2char(qr_time, dico):
"""
Calcule le code alphanumérique à partir d'un datetime.
Parameters:
qr_time (dt): le datetime à convertir
dico (str): le dictionnaitre pour décoder le code (correspondance entre lettre et chiffre)
Returns:
str: Code alphanumérique
"""
... | b3b5542d3b9a2c3fed38fd031b1520beaa00499f | 39,550 |
from typing import List
from re import T
from typing import Callable
from typing import Tuple
def enumerate_spans(
sentence: List[T],
offset: int = 0,
max_span_width: int = None,
min_span_width: int = 1,
filter_function: Callable[[List[T]], bool] = None,
) -> List[Tuple[int, int]]:
"""
Giv... | 7e832fb700ed142e136d3cb0e19b78f44ba14ad9 | 39,551 |
import requests
def create_quay_org(endpoint, token, org_name):
"""
Creates an organization in quay
Args:
endpoint (str): Quay endpoint url
token (str): Super user token
org_name (str): Organization name
Returns:
bool: True in case org creation is successful
"""
... | edcda0b836fc72283fa042af831e9dcdbf726adb | 39,552 |
async def create_recipe_tag(
tag: TagIn, session: Session = Depends(generate_session), current_user=Depends(get_current_user)
):
""" Creates a Tag in the database """
return db.tags.create(session, tag.dict()) | 7456d32724b4b3d4f305952978c065c802c099a5 | 39,553 |
def update_weights(point_to_weight, misclassified_points, error_rate):
"""Given a dictionary mapping training points to their old weights, a list
of training points misclassified by the current weak classifier, and the
error rate of the current weak classifier, returns a dictionary mapping
training poin... | 176570f92f56a37581c9ef2b53c1db001d0ae897 | 39,554 |
def edge_intersect(p1, q1, edge):
"""Return True if edge from A, B interects edge.
http://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/"""
p2 = edge.p1
q2 = edge.p2
o1 = ccw(p1, q1, p2)
o2 = ccw(p1, q1, q2)
o3 = ccw(p2, q2, p1)
o4 = ccw(p2, q2, q1)
# General case... | 6a46d9fbce89f980008ae2049920177178dda7b9 | 39,555 |
def get_reversibles_in_direction(color, size, board, x, y, direction):
"""
Get Reversibles in Direction
"""
ret = []
next_x, next_y = x, y
dx, dy = direction
while True:
next_x, next_y = next_x + dx, next_y + dy
if in_range(size, next_x, next_y):
next_value = bo... | 525d1bf08c67195036933b824afeb4f8bfd71fc7 | 39,556 |
def full_batch_mc(N):
"""Build computations to use the full batch and the GGN-MC."""
return BaseComputations(
extension_cls_directions=SqrtGGNMC,
extension_cls_second=SqrtGGNMC,
subsampling_first=None,
subsampling_directions=None,
subsampling_second=None,
verbose=... | ed33c598885f95d59b437997786155b15f64a33d | 39,557 |
def enabled(serviceName):
"""Return True if serviceName is enabled in the run level 3"""
return hasRunLevel(serviceName, 3) | eb8b0913c5d06626fa8c10e9c94e849f60a137fc | 39,558 |
def as_mb(in_size: int) -> int:
"""
Converter functions to convert the size in bytes to megabytes.
"""
conv = 1024 * 1024
return in_size // conv | af771ea9da7b7d6285cc5a2d3f6ba8873298b9ac | 39,559 |
def _mp_ParameterGrid_getitem(self, ind):
"""Get the parameters that would be ``ind``th in iteration
Parameters
----------
ind : int
The iteration index
Returns
-------
params : dict of str to any
Equal to list(self)[ind]
"""
# This is used to make discrete sampling... | a7c6edb9aa3c3101d0f622701c844032dfafa591 | 39,560 |
def mycv2_cvt_gray(img):
"""
将图片转换为灰度图
:param img: numpy.ndarray()
:return:
"""
channels = img.shape[2]
if channels == 3:
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
elif channels == 4:
return cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
else: # channels == 2... | a44d0a4e9a1fb78a3fc940cd6b60a79a7c618fa3 | 39,561 |
def find_cea_coord(header,phi_c,lambda_c,nx,ny,dx,dy):
"""Convert the index to CCD coordinate (xi,eta)"""
nx = int(nx)
ny = int(ny)
# Array of CEA coords
x = []
y = []
for j in range(ny):
col = []
row = []
for i in range(nx):
col.append(np.radians((i-(nx... | 7cb7df07df8c2d4962ec52d4ac574fe242e57f6a | 39,562 |
import socket
def allowed_gai_family():
"""
https://github.com/shazow/urllib3/blob/master/urllib3/util/connection.py
"""
return socket.AF_INET #* this to force use ipv4 (issue with ipv6, get 2s delay) | 97d983d7c573ba73a2833ca07513a37ce17b521d | 39,563 |
from typing import Callable
def build_dict_from_file(path: PosixPath, value_func: Callable = str) -> dict:
"""Build dictionary from file of key, value pairs separated by tab character.
Args:
path (PosixPath): Path to dictionary-containing text file
value_func (Callable): Function to run over each value
Retur... | d2d4f6504f0115c7a8fa22bd115b2bf65f3c5130 | 39,564 |
def _get_list_pairs(pairs, idx_class_dict, num_feature):
"""Creates flattened list of (repeated) pairs.
The indexing corresponds with the flattened list of T values and the
flattened list of p-values obtained from _get_list_signif_scores().
Arguments:
pairs: [(int, int)]
list of pa... | fbdff91f18587894a15a9eeb77fc1427779bc6ae | 39,565 |
def sign_out(addon_id):
"""
Usage:
addon.xml
---
<import addon="plugin.video.youtube" version="6.1.0"/>
---
.py
---
import youtube_registration
import youtube_authentication
youtube_registration.register_api_keys(addon_id='plugin.video.example',
... | 9c6b8fd9d66e603e6efc7828a239d0a660e75ec0 | 39,566 |
def ldns_dnssec_rrsets_contains_type(*args):
"""LDNS buffer."""
return _ldns.ldns_dnssec_rrsets_contains_type(*args) | edd31e9608c16acd2523e6310f59901acf3a0153 | 39,567 |
import typing
from typing import List
def parameters_from_proto(msg: Parameters) -> typing.Parameters:
"""."""
tensors: List[bytes] = list(msg.tensors)
return typing.Parameters(tensors=tensors, tensor_type=msg.tensor_type) | 2986010677112746ee830fe540e43e8f262a81e3 | 39,568 |
def create_loopback_interface(interface_name, vrf="default", ipv4=None, interface_desc=None, **kwargs):
"""
Perform a PUT and/or POST call to create a Loopback Interface table entry for a logical L3 Interface. If the
Loopback Interface already exists and an IPv4 address is given, the function will update th... | a9161ad8c75ad92ac54bdf760fd34c7a0cf0e5ff | 39,569 |
from typing import Tuple
def _detail_collection_tuple(worker: AbstractWorker, my_tuple: Tuple) -> Tuple:
"""
This function is designed to operate in the opposite direction of
_simplify_collection. It takes a tuple of simple python objects
and iterates through it to determine whether objects in the col... | 1e6b01fcb8826aece99a1d4cdf07f37833d80ddf | 39,570 |
def fake_check(name='fake_check', tags=None, is_active=True, run_return=None, run_exception=None,
run_logs=None, run_files=None, changed=False, get_var_return=None):
"""Returns a new class that is compatible with OpenShiftCheck for testing."""
_name, _tags = name, tags
class FakeCheck(objec... | 1524269a81a9389e17f8d597e040f7165281aef9 | 39,571 |
def hasScript(s):
"""Dig out evil Java/VB script inside an HTML attribute.
>>> hasScript('script:evil(1);')
True
>>> hasScript('expression:evil(1);')
True
>>> hasScript('http://foo.com/ExpressionOfInterest.doc')
False
"""
s = decode_htmlentities(s)
s = ''.join(s.split()).lower()
for t ... | ed44770e256e01d26e6795e6bd7aaeb77f5270f9 | 39,572 |
from typing import Tuple
def add_link_data(
link_proto: core_pb2.Link,
) -> Tuple[InterfaceData, InterfaceData, LinkOptions, LinkTypes]:
"""
Convert link proto to link interfaces and options data.
:param link_proto: link proto
:return: link interfaces and options
"""
iface1_data = link_i... | fb692b81ad3504b6524791f04d4193c54923e570 | 39,573 |
def _create_sender(net_type, msg_queue_size=2*1024*1024*1024):
"""Create a Sender communicator via C api
Parameters
----------
net_type : str
'socket' or 'mpi'
msg_queue_size : int
message queue size (2GB by default)
"""
assert net_type in ('socket', 'mpi'), 'Unknown network... | bdf22c799cb5348087897821c8805ab9bf996d37 | 39,574 |
def evaluate_predictions_per_char(predictions, original_sentences, answers):
"""Evaluates predictions per char, returning the accuracy and lists of correct and incorrect sentences."""
predicted_chars = []
sentences_with_preds = []
errors = set()
correct_sentences = []
total = 0
correct = 0
... | fb27ce85ad0843e474930802b06ab89849d87aba | 39,575 |
def n2es(x):
"""None/Null to Empty String
"""
if not x:
return ""
return x | cf73dd72230040cfc1c71b248b4cdd490004a213 | 39,576 |
def eval_loss_and_grads(generated):
"""
Computes the loss and gradients
:param generated: The generated image
:return: The loss and the gradients
"""
generated = generated.reshape((1, img_height, img_width, 3))
outs = f_outputs([generated])
loss_value = outs[0]
grad_values = outs[1].... | d0801878afe142b7e9b3d262449616f5fc630fc4 | 39,577 |
def rand_no_gen(seed, a, c, m, no_of_randnos):
"""
This function generates a numpy array of random numbers (positive integers) using Linear congruent method
If r_i is initial random number, the next random number in the sequence is given by
r_i+1 = (a*r_i + c) % m
The random numbers generated will ... | a817d65825bff623f56706edd737f88cf07ec3ef | 39,578 |
def get_genes(db, location=None, use_strand=False, overlap=True):
"""
Get Gene objects
"""
gene_ids = get_genes_ids(db, location, use_strand, overlap)
genes = {}
for i, gene_id in enumerate(gene_ids):
genes_temp = get_gene(db, gene_id)
if genes_temp:
for ensembl_id, ... | 29a225bdcee15fdf0a9ca36a7e40618924aa922f | 39,579 |
def proc_frac(cases, lcl, frac=True):
"""fraction or sum of process occurrences per case"""
cl_sum = cases.case.apply(lambda x: 0)
for cl in lcl:
cl_sum += cases.case.apply(lambda x: cl_frac_in_case(x, cl, frac=False))
if frac:
sizes = cases.case.apply(lambda x: x.classes.size)
r... | 269259a34dc98625f8df3e0eb3a7448b756763a8 | 39,580 |
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Table, TableStyle
from reportlab.lib import colors
from reportlab.platypus import Paragraph
from reportlab.lib.styles import getSampleStyleSheet
import os.path
import collections
import json
from datetim... | 9ad7833b9fd23839e0d2f0c78be22a63ee263e6b | 39,581 |
def get_source_version(service_name = None, default_version=None):
"""
Gets the source (from) version of a service participating in an upgrade. If there is no
upgrade or the specific service is not participating, this will return None.
:param service_name: the service name to check for, or None to extract it f... | 86038eee166e48124c94d960b7ef76802e01165f | 39,582 |
def strict_match_data(payload):
"""
Takes in explanation data, and a source of unlabeled data and will annotate the unlabeled data
with the explanations provided. Converts explanations into binary labeling functions and if an
explanation applies to a datapoint the label associated with the e... | 53982cbc0f14b55e82d5c6a7bf48d14fba714754 | 39,583 |
def CollectProcesses_NoCache():
"""Collect raw data here, which can be formatted in Parse(). Called from Parse()"""
metrics = []
# Get our rolled-up parent processes for creating metrics
for info in GetParentProcessItems():
is_system_process = False
if not info['cmdline']:
... | fc36ec948fdbff889e4e747ba608a45f5b50f6ef | 39,584 |
import time
def stop_mdsd():
"""
Stop mdsd process
:return: None
"""
pids = get_lad_pids()
if not pids:
return 0, "Already stopped"
kill_cmd = "kill " + " ".join(pids)
hutil.log(kill_cmd)
RunGetOutput(kill_cmd)
terminated = False
num_checked = 0
while not term... | d3e97ff8f799401d8c813fda51982dc0b664f9ff | 39,585 |
def get_translation_matrix(translation_vector):
"""Convert a translation vector into a 4x4 transformation matrix
"""
T = mx.nd.zeros(translation_vector.shape[0], 4, 4).as_in_context(
context=translation_vector.context)
t = translation_vector.contiguous().view(-1, 3, 1)
T[:, 0, 0] = 1
T... | 5d029dbb8725714e6d6b359a7094fc47484a1c46 | 39,586 |
def task_install_node_certificates(ca_cert, node_cert, node_key):
"""
Install certificates and private key required by a node.
:param FilePath ca_cert: Path to CA certificate on local machine.
:param FilePath node_cert: Path to node certificate on
local machine.
:param FilePath node_key: Pa... | 7fe5fa8cc21a47f1d362395bcd6dc3fced203275 | 39,587 |
def json_subscription_property(request, user_profile, subscription_data=REQ(
validator=check_list(
check_dict([["stream", check_string],
["property", check_string],
["value", check_variable_type(
[check_string, check_bool])]... | 0d8601e6ada68c7af9a5d80e66314507a0f0ad27 | 39,588 |
def _get_int_axis_extra_coords(cube_list, axis_coord_names, axis_coord_units, axis):
"""
Retrieve all extra coord names and units assigned to a data axis along a
sequence of cubes.
Parameters
----------
cube_list: `list` of `ndcube.NDCube`
The sequence of cubes from which to extract the ... | c83e9f119fea87a55fea0cdd773d596e551fd459 | 39,589 |
def est_shape( bg, tracking_settings_frame=None ):
"""Estimate fly shape from a bunch of sample frames."""
interactive = params.feedback_enabled and tracking_settings_frame is not None
if interactive:
progressbar = \
wx.ProgressDialog('Computing Shape Model',
... | 05cb1bd4bb3639acc312ef335fd982a60829c06b | 39,590 |
from types import FunctionType
def get_class_methods(class_item=None):
"""
Returns the class methods of agiven class object
:param class_item: Class item to introspect
:type class_item: object
:returns: list -- Class methods
"""
_type = FunctionType
return [x for x, y in iteritems(cla... | 3b43e27264ac6d13698250c6ed43bc9cc38463c1 | 39,591 |
def get_default_benchmark_simulated_datasets():
"""Default parameter sets to generate simulated data for benchmarking.
The training periods and forecast horizon are chosen to complement default real datasets.
Every tuple has the following structure:
(data_name, frequency, training_periods, forecast_hori... | aa0d7017fc693e71c016d80f7e50cc1c9a6cdc24 | 39,592 |
import os
import json
def load_config(cfg_path):
"""Load the config from a json file"""
if not os.path.exists(cfg_path):
raise RuntimeError('file {} does not exists!'.format(cfg_path))
with open(cfg_path, 'r') as f:
cfg = json.load(f)
return cfg | dcb1f309f7868191854203994b91cb28f759b5dd | 39,593 |
def all_reduce_v2(t,
group_size,
group_key,
instance_key,
merge_op='Add',
final_op='Id',
communication_hint='auto',
timeout=0):
"""Reduces tensors collectively, across devices.
Args:
t:... | b6bbe60f560f1c16266e13eea77d1f9eaecbcd98 | 39,594 |
def get_actions(chunkstart, chunkstop, grid):
"""Updates policy for a subsection of the grid with greedy actions.
Input should be the first and last row of the subsection."""
actions = ['up', 'down', 'left', 'right']
new_actions = []
for i in range(chunkstart, chunkstop):
... | 3a6a5c521404e6fc942e2860e1be74825e561d50 | 39,595 |
import uuid
import inspect
def log(func):
"""Decorator for functions, to log start/end times"""
@wraps(func)
async def wrapper(*args, **kwargs):
_id = uuid.get_and_increment()
args_text = truncate(args, 2000)
kwargs_text = truncate(kwargs, 2000)
logger.debug(f"{func.__name... | 46c79fb9c76e7f772d9bdbff8f39398e7f9e5329 | 39,596 |
import os
def getFirstFrame(video, name):
"""
The function saves the video file's first frame in the current folder.
Params:
video (string): Path to the video file
name (string): Name of the new image
Returns:
name (string): name of the created image
"""... | ae84a94db6d3ad99e66ad07ed410b859cb7ec357 | 39,597 |
import math
def deconv_size(input_height, input_width, stride=2):
"""
Compute the feature size (height and width) after filtering with
a specific stride. Mostly used for setting the shape for deconvolution.
Args:
input_height (int): height of input feature
input_width (int): width of ... | d7e3df3087142f6ccea3c6ed8ea3724b12b8ce89 | 39,598 |
def G(x, alpha, shift=0):
""" Return Gaussian line shape at x with HWHM alpha """
return np.sqrt(np.log(2) / np.pi) / alpha\
* np.exp(-((x - shift) / alpha)**2 * np.log(2)) | b89afb23564f15a2d798708977fb8c82890190c1 | 39,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.