content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import functools
def single(window, config):
"""Single theme
===== Header =====
= items =
==================
"""
cordx = round(config.get('cordx', 0))
color = config.get('color', red)
icon = config.get('icon', '=')
align = config.get('align', 'left')
term = window.ter... | 61f481ff43100bcd1b4f88c087dfdecdc7336681 | 61,100 |
def keepWindowSize(key, window, defaultSize=None, defaultPosition=POSITION_NONE):
""" You should call keepWindowSize before show on your windows """
key = key + "window"
def savePosition(window, *event):
log.debug("keepWindowSize.savePosition: %s" % window.get_title())
width = window.get_a... | 41d99330458034910ceed4230bd925f4ca9db59e | 61,101 |
def table_exists(table_or_name):
"""
Determines if a table exists in the database
:param table_or_name: a sqlalchemy table object or the name of a table to query
:return: True if table exists, otherwise False
"""
if isinstance(table_or_name, str):
table = get_table(table_or_name, ignore... | bda7243311ba83771575eb0cfa66ea34a978e94c | 61,102 |
def vectorCosine(v, u):
"""
Calculates the cosine between two vectors
(because they are both normal and have length 1).
"""
cosine = np.dot(v, u)
return cosine | 130ea9d8dd57c0988efee6491449a7270ff6c97a | 61,103 |
def get_segment_probs(all_b_samples, all_masks, segment_id):
"""Get segment probabilities for a particular segment ID."""
neg_cumsum = 1 - jnp.cumsum(all_b_samples[segment_id], axis=1)
if segment_id > 0:
return neg_cumsum * all_masks[segment_id - 1]
else:
return neg_cumsum | 1684a2daaf9c59f23eaf8af5f325c3457eed4627 | 61,104 |
def find_and_instantiate_clazz(obj, instancelize_clazz_fce=None):
"""
Got through json-like object and find all classes definitions and instantiate them.
Class definition is dict with `class` key and optionally `args` and `kwargs` keys.
"""
if instancelize_clazz_fce is None:
instancelize_cl... | f06c346e333bb8d8d70a84050d1baecc0d5c77a5 | 61,105 |
def flow_to_rgb(flow):
"""Compute an RGB visualization of a flow field."""
shape = tf.cast(tf.shape(flow), tf.float32)
height, width = shape[-3], shape[-2]
scaling = _FLOW_SCALING_FACTOR / (height**2 + width**2)**0.5
# Compute angles and lengths of motion vectors.
motion_angle = tf.atan2(flow[Ellipsis, 1],... | 0cdef99bf519b83640923096b474d5de1e37a4c8 | 61,106 |
from typing import Callable
from typing import Any
from typing import OrderedDict
def multimap(f: Callable, *xs: Any) -> Any:
"""
Each x in xs is a tree of the same structure.
Apply f at each leaf of the tree with len(xs) arguments.
Return a tree of the same structure, where each leaf contains f's ret... | 7c81deab0875b2396a2127b504a4ce8773ab356c | 61,107 |
def partition_for_vitis_ai(mod, params=None, dpu=None, **opts):
"""Partition the Relay expression for offloading operators to Vitis AI DPU
Parameters
----------
mod : Module
The module to run passes on.
params : Optional[Dict[str, NDArray]]
Constant input parameters.
dpu : str
... | 56a485f36513d459c5e6c445815060fd0f237947 | 61,108 |
def serialize_user_list_default(user: User, context: Context):
"""
Actually, roles are serialized as users (with minimal information)
:param role:
:param context:
:return:
"""
result = DictLikeClass()
result['id'] = user.user_id
result['name'] = user.get_display_name()
result['em... | fe718642bb059853bcdd0735b5f1fd340e79d51b | 61,109 |
def rooms_n9():
"""
Complicated arrangement of rooms
"""
rooms = []
rooms.append(Room('rm1', 1e3, [[0,0], [5,0], [5,5], [0,5]]))
rooms.append(Room('rm2', 2e3, [[5,0], [10,0], [10,2], [10,4], [10,5], [5,5]]))
rooms.append(Room('rm3', 3e3, [[0,5], [5,5], [10,5], [10,6], [10,8], [10,10]]))
... | 1ac6c1817b6e82304c251bcaa2281125794f8629 | 61,110 |
def transitive_reduction(G):
""" Returns transitive reduction of a directed graph
The transitive reduction of G = (V,E) is a graph G- = (V,E-) such that
for all v,w in V there is an edge (v,w) in E- if and only if (v,w) is
in E and there is no path from v to w in G with length greater than 1.
Para... | bd7b31648b013bea07e01f74ccacdcb23f001d48 | 61,111 |
def parse_addr_file(filename):
"""Parse an address file, called filename.
An address file is in the form:
<name>: <base0>,<end0> <base1>,<end1>
<name>: <base0>,<end0> <base1>,<end1>
Each line represents a set of disjoint set of memory with
a particular name. The each item in the set is a range ... | dcf79cfd3d7c2272f5407f2fabe4d77fe3d81eff | 61,112 |
import random
def generate_palette(
count, ranges, offset_angles, saturation_range, luminance_range):
"""
-Analogous: Choose second and third ranges 0
-Complementary: Choose the third range 0, and first offset angle 180
-Split Complementary: Choose offset angles 180 +/- a small angle. The
seco... | 645d6f309c9446bd6a97007662ca56d0cddb7d73 | 61,113 |
def xml_reader(fh, filesize):
"""Read XML from file and return as xml.ElementTree root Element."""
xml = unicode(stripnull(fh.read(filesize)), 'utf-8')
return etree.fromstring(xml) | c17639a38b0cca8e9d48d57763ad23b7c971772a | 61,114 |
from typing import Optional
from typing import List
import torch
def push1d(inp, g, shape: Optional[List[int]], bound: List[Bound],
extrapolate: int = 1):
"""
inp: (B, C, iX, iY) tensor
g: (B, iX, iY, 2) tensor
shape: List{2}[int], optional
bound: List{2}[Bound] tensor
extrapolate: ... | d6175e1b27d0d5d3e4f0eaeafbe9e1851f5129f2 | 61,115 |
def superuser(db) -> "User":
"""Gets the sample super user
:param db: Database connection
:return: Super User model
"""
return _get_user(db, "superuser@email.com") | 80ca0e9a00892b4a2dae9cd180caf1d685b26b3d | 61,116 |
def default(value, default):
"""
Returns a specified default value if the provided value is None.
Args:
value (object): The value.
default (object): The default value to use if value is None.
Returns:
object: Either value, or the default.
"""
return value if value is no... | 99fddb624594c837218d6b1ca7f6d49d94e05031 | 61,117 |
def String_Rules_From_Binary(node_rules_binary_dictionary):
"""Convert from binary dictionary rule format to BooleanNet format.
Parameters
----------
node_rules_binary_dictionary : dictionary
Binary dictionary representation of rules.
Returns
-------
str
BooleanNet represen... | deffbfc51d4fc5d35cb8e1a24f8aa9a65c08039b | 61,118 |
import numpy
def sqft_homes_select(data, sel):
"""Extract and restructure home count or square footage for a microsegment
Similar to nrg_stock_select, for the microsegment identified by
'sel,' this function extracts the corresponding house count (total
homes or new homes) or square footage from the E... | 1b896a67e11fa687a7de3f008db1f0722175b1f8 | 61,119 |
def mat_list_to_iq_array(mats_list: list) -> (np.ndarray, dict):
"""Make an IQ array from a list of mats"""
parameters = open_parameters(mats_list[0])
iq_array = np.array(
[open_iq(x) for x in mats_list]
)
# todo: fix horizontal flipping in final... | dd2a4113e7536f70c0e0ac23078ffb85b15c624e | 61,120 |
def crscode_to_string(codetype, code, format):
"""
Lookup crscode and return in specified format.
Uses epsg.io for epsg code, or spatialreference.org for esri or sr codes.
Arguments:
- *codetype*: "epsg", "esri", or "sr-org".
- *code*: The code.
- *format*: The crs format of the returned s... | 4cc61c5c89d2edd417dfc47dc8edf9d530dabc5f | 61,121 |
def get_atom_target_index(target_index, input_index, resindices):
"""get target indices of input atom
Arguments:
target_index {array} -- target(native) residue index
input_index {array} -- input residue index
resindices {array} -- target residue index of input atoms
Returns... | 5fd414cc147e1fe5c6c51b6c6e655a11b8bec8db | 61,122 |
def array_from_where(process, where):
"""Get array of scannables from provided parameter"""
if where == 'all':
return process.pages
if where == 'pages':
return process.pages
if where == 'modules':
return process.modules
if not where is None:
return [module for module ... | 9e312cbd2b890ec976ba42f524ee57d501c30efa | 61,123 |
import tqdm
def get_tqdm(**kwargs):
""" Similar to :func:`get_tqdm_kwargs`,
but returns the tqdm object directly. """
return tqdm(**get_tqdm_kwargs(**kwargs)) | 4905c3196f06b2f490b2dc53a97c698e85da2b4c | 61,124 |
import random
def get_rnd_kpts_per_samples(num_batch, num_kpts, nMaps_shuffled):
"""
This method gets num_batch, num_kpts, nMaps_shuffled
and for each example in num_batch, selects as many as
'nMaps_shuffled' random UNIQUE samples in the range [0, num_kpts)
and returns them
"""
# building ... | b61d24b4cd4967b32bc38511413c0bb405290746 | 61,125 |
def conv_reduce_sum(x, result_shape, padding, strides):
"""Sums along the output dimensions in line with an N-D convolution.
For example, with a kernel size of 3, padding=`VALID`, and stride of 1, then
with respect to each spatial dimension of the convolution (and disregarding
class, batch and channel dimensio... | bfc0fa2d84d3658a74486b2f2193ca6f0d8e10a6 | 61,126 |
def inside_string(i, j, string_ranges):
"""Returns true if the range described by i and j is contained within a range in the list string_ranges"""
for s, e in string_ranges:
if i >= s and j <= e:
return True
return False | aea2ac8a777914c2e86aea40cf43f4d01b2ef8b0 | 61,127 |
import re
def clean_txt(txt):
"""clean txt from e.g. html tags"""
cleaned = re.sub(r'<.*?>', '', txt) # remove html
cleaned = cleaned.replace('<', '<').replace('>', '>') # retain html code tags
cleaned = cleaned.replace('"', '"')
cleaned = cleaned.replace('’', "'")
cleaned = c... | 6eb173f7f06794fc2e9220c15b3743fc27e11904 | 61,128 |
def rgbd(depth,rgb):
"""
return 32x32x4 array
"""
d=misc.imread(depth)
c=misc.imread(rgb)
r=c[:,:,0]
g=c[:,:,1]
b=c[:,:,2]
img=np.zeros([r.shape[0],r.shape[1],4])
img[:,:,0]=r
img[:,:,1]=g
img[:,:,2]=b
img[:,:,3]=d
return img | 8224d740cdd32b9b208c2d58c2c669103119f065 | 61,129 |
def filter_items(items, *args, **kwargs):
"""Filters an iterable using lookup parameters
:param items : iterable
:param args : ``Q`` objects
:param kwargs : lookup parameters
:rtype : lazy iterable (generator)
"""
q1 = list(args) if args is not None else []
q2 = [Q(**kwargs)]... | 4f2cd17f8f64b063956a15e1fb177fa407e919b2 | 61,130 |
def _create_validation_data_loader(img_path, batch_size, img_size, n_cpu):
"""
Creates a DataLoader for validation.
:param img_path: Path to file containing all paths to validation images.
:type img_path: str
:param batch_size: Size of each image batch
:type batch_size: int
:param img_size:... | 63109318fba9f224e802be8e2296b6bc3c78ac99 | 61,131 |
def cast_ext(ext: str) -> str:
"""Convert ext to a unified form."""
ext = ext.lower()
if ext == 'jpeg':
ext = 'jpg'
return ext | 7b4894e035a3b785b017c9794e494ff7b78e7c1b | 61,132 |
import logging
def setup_logger(name, log_file, formatter_text):
"""To setup as many loggers as you want"""
handler = logging.FileHandler(log_file)
handler.setFormatter(logging.Formatter(formatter_text))
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
logger.addHandler(handler... | 6f80c4abbc33c20a60e919a3a03bc4d75eae917e | 61,133 |
def filter_reply_msg(top_indices, top_cosine, cosine_cut_off, count_cutoff):
"""
Filter out responses
1. cosine similarity < cosine_cut_off
2. too short replies (word count <= count_cutoff)
3. replies contain other special characters
:type pandas DataFrame: response_df
:type float: cosi... | 4915c71f64cc2a676a3f7da458a73ff8a165aee0 | 61,134 |
from datetime import datetime
def process_issue(
start, day_to_process, message_index, drive_by, issue_owner, messages,
user):
"""Calculates 'latency', 'lgtms' and 'review_type' for a reviewer on an Issue.
Arguments:
- start: moment to use to calculate the latency. Can be either the moment a
... | 7c6589976ea95d3e2998d7546a90dbb84b5e6958 | 61,135 |
import math
from eiscat_toolkit import loc2gg
def find_coord_alt_2(loc, elRange, elProject, az, alt, range_start=None, accuracy=1):
"""same as find_coord_alt, but lets you find the proper range using one
elevation elRange and then project to another elevation elProject."""
# find starting guess for rang... | bf99399a87770eda65634397b635fceb40291abb | 61,136 |
def create_app(mbtiles=None, cache_config=None):
"""Initialize the application with a given configuration.
mbtiles must be a path to the MBTiles sqlite file.
"""
app = Flask(__name__)
app.config.update({
'MBTILES_PATH': mbtiles
})
app.register_blueprint(frontend)
cache.init_app... | 46fb9db09d567474ebeaa936f2dcd573a0d1a354 | 61,137 |
def get_xaligned_axes(ax, y_distance, height, factor=1., **kwargs):
"""
:param ax:
:param y_distance: negative distance in y direction to the x axis
:param height: height of the new axes
:param factor: factor for scaling the fig_width_inch of the new axes
:param kwargs: kwargs passed to matplot... | 768b7bcd93e5c363a80049c76fa0e761ffc940db | 61,138 |
def get_tracing_strat(quarantine_infect_mult, other_infect_mults) -> Stratification:
"""
Contact tracing stratification to represent those detected actively through screening of first order contacts of
symptomatic COVID-19 patients presenting passively.
"""
tracing_strat = Stratification("tracing",... | a92256fa5fb8bb3629cb590eae2ff6baed59c95d | 61,139 |
import string
def decode(digits, base):
"""Decode given digits in given base to number in base 10.
digits: str -- string representation of number (in given base)
base: int -- base of given number
return: int -- integer representation of number (in base 10)"""
# Handle up to base 36 [0-9a-z]
as... | e803563c7c8f0ec3f32aae6c95d1db111b4b9b10 | 61,140 |
def main_add(args):
"""Add variables main."""
return add_variables(args.directory, args.env_spec, args.vars_to_add, args.default) | ffae73e612874d3ed73102e7ac85dd9202d74fa8 | 61,141 |
from typing import Optional
def make_range(
index: pd.DatetimeIndex, other_index: pd.DatetimeIndex = None
) -> Optional[Range1d]:
"""Make a 1D range of values from a datetime index or two. Useful to share axis among Bokeh Figures."""
index = tz_index_naively(index)
other_index = tz_index_naively(other... | 25acbc625cef95b01e5e48010c0af0280bd0f104 | 61,142 |
import re
def parse_issue_comment(username, body, sha, botname, hooks=[]):
"""
Parse an issue comment looking for commands that Homu should handle
Parameters:
username: the username of the user that created the issue comment.
This is without the leading @
body: the full body of the com... | c9087b204bfde84d32e8fca21c3186d99436e7ca | 61,143 |
def applyPrecession(ra, dec, epoch=2000.0, mjd=None):
"""
applyPrecession() applies precesion and nutation to coordinates between two epochs.
Accepts RA and dec as inputs. Returns corrected RA and dec (in degrees).
Assumes FK5 as the coordinate system
units: ra_in (degrees), dec_in (degrees)
... | 984c99010190011a93d0e31824f801c80089ff9a | 61,144 |
def oriented_bounds_2D(points, qhull_options='QbB'):
"""
Find an oriented bounding box for a set of 2D points.
Parameters
----------
points: (n,2) float, 2D points
Returns
----------
transform: (3,3) float, homogenous 2D transformation matrix to move the
input points so... | 3585e86d9522822816908c2c5f5a484720ad04ea | 61,145 |
def filter_map(df_map, df_samp, sample_col):
"""Filtering df_sample to just destination position,
then adding values to df_map
"""
# formatting sample table
df_samp = filter_samp(df_samp, sample_col)
# formatting mapping table
df_map = df_map.drop_duplicates(subset='#SampleID')
# joinin... | 9f1d2400f06e4e3a6036448052c7ebe4c77f1495 | 61,146 |
def low_frequency_accuracy(sent_test_tags, sent_pred_tags, counter):
"""
sent_test_tags: # [[{'start_idx': 7, 'end_idx': 12, 'text': '東芝キヤリア'}, {'start_idx': 14, 'end_idx': 19, 'text': 'ダイキン工業'}],
[{'start_idx': 0, 'end_idx': 1, 'text': '東芝'}, {'start_idx': 27, 'end_idx': 32, 'text': 'ダイキン工... | 49d40fd41ace2a25be35d0a2d764bd23b4cad0b8 | 61,147 |
def _set_concatenate(sets):
"""concatenate indexable objects.
Parameters
----------
sets : iterable of indexable objects
Returns
-------
indexable object
handles both arrays and tuples of arrays
"""
def con(set):
# if not all():
# raise ValueError('concaten... | 36bec5766d636f381d4e399918ca25b989bd752e | 61,148 |
from typing import List
from typing import Tuple
def count_chunks(alignment: List[Tuple[int, int]]) -> int:
"""
Find the minimum number of chunks the alignment can be grouped into.
"""
alignment = sorted(alignment)
num_chunks = 0
last_h, last_r = -2, -2
for (h, r) in alignment:
if... | 41429e2e725b32edadc066ce4a2748cc3933cc50 | 61,149 |
def create_basic_vector(num_qubits: int):
"""Generate list of basic vectors
Args:
num_qubits (int): number of qubits
Returns:
np.ndarray: |00...0>, |00...1>, ..., |11...1>
"""
bs = []
for i in range(0, 2**num_qubits):
b = np.zeros((2**num_qubits, 1))
b[i] = 1
... | 2fb39fec815a9ea250dd687eb796f93e5972899f | 61,150 |
def intersection(box1, box2):
"""Compute pairwise intersection areas between boxes.
Args:
box1: a float Tensor with [N, 4].
box2: a float Tensor with [M, 4].
Returns:
a float tensor with shape [N, M] representing pairwise intersections
"""
with tf.name_scope('Intersection'):
y_min1, x_min1, ... | 3eddb5c7aa7e85e233d595569f0d5f2c479f44d8 | 61,151 |
def _get_converter(orig, target):
"""get funtion 'convert_{}_to_{}' when available for coverage """
try:
func = getattr(utils, f'convert_{orig}_to_{target}')
except AttributeError:
func = partial(convert_unit, orig=orig, to=target)
return func | 5d08c1f13b56720f12ca5d875b13138f3eee4601 | 61,152 |
import operator
def get(ind, seq, default=no_default):
""" Get element in a sequence or dict
Provides standard indexing
>>> get(1, 'ABC') # Same as 'ABC'[1]
'B'
Pass a list to get multiple values
>>> get([1, 2], 'ABC') # ('ABC'[1], 'ABC'[2])
('B', 'C')
Works on any value th... | 7c98f4f5db3d1b2ccf43ddf3546bc5cd7bfc312a | 61,153 |
from typing import Any
from typing import List
from typing import Optional
def verify_trim(trims: Any) -> List[Optional[int]]:
"""Basically just to satisfy mypy. My trims should *always* be a tuple."""
return list(trims) if isinstance(trims, tuple) else [None, None] | 1c3f738fd0b77388999c5de34d71ead90d39543e | 61,154 |
def get_reference_output_files(reference_files_dict: dict,
file_type: str) -> list:
""" Returns list of files matching a file_type from reference files
Args:
reference_files_dict: A validated dict model from reference
file_type: a file type string, e.g. vcf, fasta... | 7050c39a8116f8874dbc09bcf7ff2908dcd13ff8 | 61,155 |
import requests
from bs4 import BeautifulSoup
import time
import random
def get_stock_names(code, retry=3):
"""
从新浪财经中爬去上市公司的名称以及简称。
需要的输入:
code: 股票代码
retry:错误发生之后重新尝试的次数
"""
stock_info = {'code': code}
URL = "http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CorpInfo/stockid/%s.pht... | cf1cd00e42bc3ae668d70a4574f0ff3b1769ed3b | 61,156 |
def sanitizeSmarts(smarts, outrxn):
""" It works both with the smiles string or a rxn file """
try:
try:
rxn = AllChem.ReactionFromSmarts(smarts, useSmiles=True)
except:
rxn = AllChem.ReactionFromSmarts(smarts)
smi = AllChem.ReactionToSmiles(rxn)
with open... | 99a4dbe01c27e9eaf2a5d4486bdbf72de9dde508 | 61,157 |
def draw_line_param_abc(line, min_x=0, max_x=100, min_y=0, max_y=100):
"""draw line a*x + b*y + c = 0, line=[a, b, c]"""
a, b, c = line[0], line[1], line[2]
pts = []
if a == 0 and b == 0:
print('Warning, line parameters error!')
return pts
if b == 0:
pts = [[get_line_ABC_x(... | 9f28fb42a29a77a0ed5aa3c321e6f939f7fa1c15 | 61,158 |
def close_noscript(tag):
"""Return a string with each closing parent tags for escaping a noscript"""
s = ""
if tag.findParent("noscript"):
curr = tag.parent
while True:
s += "</{0}>".format(curr.name)
if curr.name == "noscript":
break
curr ... | 8082f609ff4c98059d728eeed8fb1f87a5fda48f | 61,159 |
def rev_comp(seq):
"""
"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'}
return "".join(complement[base] for base in seq)[::-1] | f5876955ee1bec0eb393d306870a8c388fce7762 | 61,160 |
import click
def test_function(ctx):
"""
Simple single-function test
"""
config_filename = ctx.obj['config_filename']
config = pywren.wrenconfig.load(config_filename)
wrenexec = pywren.default_executor()
def hello_world(x):
return "Hello world"
fut = wrenexec.call_async(hell... | 32200dd3b03addcc321c366c62aff4f6e21bf153 | 61,161 |
def _pooling(net, stride, operation, use_bounded_activation):
"""Parses operation and performs the correct pooling operation on net."""
padding = 'SAME'
pooling_type, pooling_shape = _operation_to_pooling_info(operation)
if use_bounded_activation:
net = tf.nn.relu6(net)
if pooling_type == 'avg':
net =... | 5d58ed2bbfca4432dbb2442e7ebbfaf7498df264 | 61,162 |
import hashlib
def testfunc(res, i):
"""Return a hash of the index plus the other results."""
m = hashlib.md5()
m.update(str(i).encode('utf-8'))
for r in res:
m.update(r.encode('utf-8'))
return m.hexdigest() | f19a38d99bf50c33614134dec0d8184f35b27d60 | 61,163 |
def has_group_permission(user, thing, permission, grp_prop, user_grp_prop='groups'):
"""Convenience function for checking group permissions."""
# If group does not have permission, fail early.
if not permission:
raise ForbiddenError()
# Check if user is a group member and group has permission.
model_group... | 35326d4a5e49216d6ae5c869df1e196f75ed6ce6 | 61,164 |
import sys
import torch
def init_quants(node_rank, gpu, gpus, world_size, params):
"""
Initialize some parallelization quantities.
Args:
node_rank (int): rank of the node
gpu (int): local rank of the current gpu
gpus (int): number of gpus per node
world_size (int): total nu... | eed39dc43cdc61b88156f87d862ae1c8a8e9b9d1 | 61,165 |
def clasificar(a1: float, a2: float, a3: float) -> str:
"""
Retorna 'Equilatero' si el triángulo es equilatero, 'Isóceles'
si es isóceles y 'Escaleno' si es escaleno.
"""
if a1 == a2 and a1 == a3 and a2 == a3:
retorno = "Equilatero"
elif a1 == a2 or a1 == a3 or a2 == a3:
retorno ... | e44104b58ab5fa24ab37831920e4d1c855eb25f3 | 61,166 |
from sys import path
import tempfile
import os
import sys
import subprocess
def with_setup_command(root, *args, **kwds):
"""
Run `setup.py build_sphinx` with args and kwargs,
pass it to the test and clean up properly.
"""
def generator(func):
@wraps(func)
def deco(*args2, **kwargs2... | 7162c7f2a276d935313ff94921362f9dc9fed248 | 61,167 |
def _list_to_html(list_, html=None):
"""Convert JSON-LD list to HTML."""
if html is None:
html = []
if len(list_) == 1:
_to_html(list_[0], html)
else:
html.append('<ul>\n')
for item in list_:
html.append('<li>')
_to_html(item, html)
htm... | 15c7c4d5174e5d5f6a471bf41debb370b05b176d | 61,168 |
def pretty_print_prime_rules(primes):
"""Prints pyboolnet a prime dictionary as Boolean rules
The output format is of the form:
A* = B & C | !D, for example.
Parameters
----------
primes : pyboolnet primes dictionary
Update rules to print.
"""
if primes is None:
return... | f72f5b9a2c9b3c90c6682e253dffd1d22f78fa0c | 61,169 |
def to_pil_image(pic, mode=None):
"""Convert a tensor or an ndarray to PIL Image.
Args:
pic (Tensor or numpy.ndarray): Image(HWC format) to be converted to PIL Image.
mode (`PIL.Image mode`_): color space and pixel depth of input data (optional).
.. _PIL.Image mode: https://pillow.readthedoc... | 10debe47ed2a32565d7aad4c45441890b1cd2eac | 61,170 |
import pprint
def safe_execute_code(inputcode,
language="python",
protocol=PROTOCOL,
port=PORT,
address=ADDRESS,
url=None
):
""" Ask Camisole to execute the <inputcode> written in <language>, and returns the JSON result from Camisole."""
data = {
"lang": st... | 691cefa62478f183efe5d4a49c1b32cf3a718464 | 61,171 |
def generate_objective_or_constraint_expr(columns, tokens, variables,
result_value_name, group_by,
variable_str, data_str, value_str,
index_str):
"""
Generate the model expression for th... | cd19f7b881f77b031c8ab4c844e6167b6190e983 | 61,172 |
def norm(im):
"""Normaliza una imagen de números reales a [0,1]"""
return cv2.normalize(im, None, 0.0, 1.0, cv2.NORM_MINMAX) | 9da7a5c503dd8bdc191c6c55273e0183157d159a | 61,173 |
def getServerCEASettingsId(nodename, servername):
"""Returns the Object ID for CEA Settings in a server, or None"""
m = "getServerCEASettingsId:"
#sop(m,"Entry. nodename=%s servername=%s" % (nodename, servername))
cea_settings_id = AdminConfig.getid( '/Node:%s/Server:%s/CEASettings:/' % ( nodename, serv... | ea7dddd4f4c44216fd1b67705b880dd00059e13b | 61,174 |
def validate_all_blocks_have_trips(rating):
"""
Validate that all blocks have at least one revenue trip.
Exceptions:
- RAD/WAD blocks
"""
previous_block = None
has_revenue_trips = False
revenue_trips = {
trip.trip_id
for trip in rating["trp"]
if isinstance(trip,... | 071adfac3f3ff6c791ac154b826629f3be8b1d97 | 61,175 |
import math
def param2stroke(param, H, W, meta_brushes):
"""
param2stroke
"""
b = param.shape[0]
param_list = paddle.split(param, 8, axis=1)
x0, y0, w, h, theta = [item.squeeze(-1) for item in param_list[:5]]
sin_theta = paddle.sin(math.pi * theta)
cos_theta = paddle.cos(math.pi * thet... | 81c4260db0ea94a8a05ba3e42385266604bc945c | 61,176 |
def _sort_key(k):
"""Sort key for common paths. Ensures the correct order for processing,
without having to care about offsetting indices.
Heavily inspired by the natsort package:
Copyright (c) 2012-2016 Seth M. Morton
Permission is hereby granted, free of charge, to any person obtaining a copy o... | 92c2281458511415ecd547edbb1a8b843ce8bfd8 | 61,177 |
def additive_noise(s, snr):
"""Additive white noise with a given SNR relative to the input signal"""
additive_noise = np.random.randn(len(s))
Es = np.std(s)
En = np.std(additive_noise)
return additive_noise / En * Es * 10**(snr/20) | 2426738acf146f72937fd3a05e3d2491c9f4b4b2 | 61,178 |
async def events(city: str, state: str, country: str) -> quart.Response:
"""Returns current weather event."""
player = {
"name": "Jeff the player",
"city": city,
"state": state,
"country": country,
}
if not player:
quart.abort(404)
return quart.jsonify(player) | d8ba520a85d75b9d6fe73980f112bee37aa6f462 | 61,179 |
import os
def createfolders(foldername_list):
"""Create the folder structure specified by the list."""
path = ''
for s in foldername_list:
if s != '/':
path = path + s + '/'
try:
os.makedirs(path)
except OSError as e:
if os.path.exists(path):
print... | 9b9ebf3c29dce52b05a885019f7a3e2092856605 | 61,180 |
def optimal_q_u(kzzinv, noise_covar, x_mean, psi_1, psi_2, ns=nt.NumpyLinalg):
"""
Computes optimal q(u)
:param kzzinv: [M*M]
:param noise_covar: scalar
:param x_mean: [N*D] means of GP mappinf outpot x_t: GP(x_minus_t) -> f_t -> x_t
:param psi_1: [N*M]
:param psi_2: [N*M*M]
:return: u_m... | eb4ae3178faf63f028853688413b41f429322b80 | 61,181 |
def leak_nt_base_palette(manager_palette, worker_palette):
"""
Function to leak the NT base via TEB
Based on:
https://github.com/FuzzySecurity/PSKernel-Primitives/blob/master/Pointer-Leak.ps1
and
https://www.blackhat.com/docs/us-17/wednesday/us-17-Schenk-Taking-Windows-10-Kernel-Exploitation-To-The-Next-Level%E2%... | d88aca2ce85ddfe67bea2b202c40bf6953d42640 | 61,182 |
def generate_export(config: Config, fmt: str) -> str:
"""
Generate a configuration export in the specified format.
Args:
config (``fica.config.Config``): the config object to export
fmt (``str``): the format to export it to
Returns:
``str``: the exported config object
"""
... | b90be4da10ed41be802bc8cbd2806746cde91b8e | 61,183 |
from typing import Dict
def get_pygments_style_colors(
style: Style, *, fallbacks: Dict[str, str]
) -> Dict[str, str]:
"""Get background/foreground colors for given pygments style."""
background = style.background_color
text_colors = style.style_for_token(Text)
foreground = text_colors["color"]
... | 63975fc72e073df98e508eb54ae1cb97bc98c62f | 61,184 |
def leaver_cf_inv_lentz_old(omega, a, s, m, A, n_inv,
tol=1.e-10, N_min=0, N_max=np.Inf):
""" Legacy function. Same as :meth:`leaver_cf_inv_lentz` except
calling :meth:`qnm.contfrac.lentz`. We do not jit this function
since lentz is not jitted. It remains here for testing purpo... | 2c1eb0bd983e16b38368bdc60377a3da373b646a | 61,185 |
import time
def import_droid_vm_template(session, host_ref, creds=None):
"""Import VM template from Dom0 for use in tests"""
sr_refs = find_storage_for_host(session, host_ref)
if not sr_refs:
raise Exception(
"Error: could not find any available SRs for host '%s'" % host_ref)
sr_... | 7bf1d4469f34572af5a0638821e755b4f48b4ffe | 61,186 |
def normalize_ext_data(data):
"""
Combine and normalize Extension data. Passing a tuple for an item will ignore defaults.
"""
normlist = ('sources', 'include_dirs', 'library_dirs', 'runtime_library_dirs')
data.update({k: normalize(_build_list(k, v)) for k, v in data.items() if k in normlist})
r... | b600509ac3340d180f2429df21c0f126c6309337 | 61,187 |
def is_gzip_file(view):
"""
Given a view, determine if that view (probably) contains a gzipped file
or not. This is currently based on a combination of the extension and the
file being a binary file with the right magic bytes.
"""
return (view.encoding() == "Hexadecimal" and
view.sub... | f457e373d59d7688a9ec3e5e64b2ab6c92115d25 | 61,188 |
import os
def create_gazebo_files(pkg_path, model_info):
"""
Create a world and launch file to bringup the current terrain model
in a otherwise empty Gazebo world.
"""
# Relevant paths
temp_path = os.path.join(pkg_path, "scripts/templates")
world_path = os.path.join(pkg_path, "worlds... | 94423541fd4f4fa4e5346dd5378e159a2f7b4472 | 61,189 |
from typing import Callable
import functools
def get_v_panel_from_i(cell_param=np.array([6.48000332e+00, 6.37762333e-10,
8.45318984e-04, 1.65194938e+03,
3.14194723e-02]),
I_min: float = -4, I_max: float = 7,... | 6fa736bffc1f32df41364442249195a0b066ac4a | 61,190 |
import json
def get_project(project_id: int) -> json:
"""
:param project_id:
:return:
"""
query_result = db.session.query(Project).filter(Project.id == project_id).all()
if len(query_result) == 1:
info = {
"name": query_result[0].name,
"description": query_result[0].description
}
return j... | d25670cad7d2ce74ddc5706d333d570b090c2006 | 61,191 |
def fetchone_to_dict(sql, params=None, db='default'):
"""
返回一行数据
:param sql: sql语句
:param params: sql语句参数
:param db: Django数据库名
:return: 例如:{"id": id, "username": 'username', "first_name": 'first_name'}
"""
cursor = connections[db].cursor()
cursor.execute(sql, params)
desc = curs... | 79ef4f0c9e66fda994aa5d4e223a6872f92e515e | 61,192 |
def make_zip_handler(zipfilename, max_age=None, public=None):
"""Factory function to construct a custom ZipHandler instance.
Args:
zipfilename: The filename of a zipfile.
max_age: Optional expiration time; defaults to ZipHandler.MAX_AGE.
public: Optional public flag; defaults to ZipHandler.PUBLIC.
... | a9833e0a07f36060efbb06099493d0a87202ce55 | 61,193 |
def rotmatrix(ang, raxis, axis=0):
"""Construct a 3d rotation matrix representing a rotation of
ang degrees around the specified rotation axis raxis, which can be "x", "y", "z"
or 0, 1, 2. If ang is a scalar, the result will be [3,3]. Otherwise,
it will be ang.shape + (3,3)."""
ang = np.asarray(ang)
raxis = raxi... | 767484648c70ff961d223e23d226ce44dabd1afe | 61,194 |
def watershed_group_add(request):
"""
Controller for adding a watershed_group.
"""
if request.is_ajax() and request.method == 'POST':
#get/check information from AJAX request
post_info = request.POST
watershed_group_name = post_info.get('watershed_group_name')
watershed_g... | ad18b5667f0effe6fb8bd9dd787ce967d418816e | 61,195 |
def is_trivial_pair(p):
"""Is the critical pair trivial?"""
u, v = p; return u == v | ee4b42a9f1345c7260c3992db4c2445b32273a01 | 61,196 |
def update_api_key(api_key, permission_set):
"""Update (and/or add) an API key and permissions.
Args:
api_key (str): any string representing an api key
permission_set (set): set of "catalog:READ/WRITE" permission strings
to add to the key.
Returns:
new/updated API key o... | 3dc6f37abbc35d7a53afbf99d0b66b1adabe5d73 | 61,197 |
def multiplicativeAttraction(vGamble,pGamble,timePressure,neta,framing,x,need,c):
"""Here we assume time prssure with enhance the framing effect, and an additive risk attraction term """
expectation = pGamble * vGamble + 0
varGamble = pGamble * (vGamble - expectation) ** 2 + (1 - pGamble) * (0 - expectation... | c1c96ac867162c1c78033550641719be430e468b | 61,198 |
def pairs_to_dict(response, decode_keys=False, decode_string_values=False):
"""Create a dict given a list of key/value pairs"""
if response is None:
return {}
if decode_keys or decode_string_values:
# the iter form is faster, but I don't know how to make that work
# with a str_if_byt... | 3303d4549e23bc2c1b360091f8f2d97cf50d0f65 | 61,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.