content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _search(self, *query):
"""Search for a match between the query terms and a tensor's Id, Tag, or Description.
https://github.com/OpenMined/PySyft/issues/2609
Note that the query is an AND query meaning that every item in the list of strings (query*)
must be found somewhere on the tensor in order for it t... | 8ffd9ae2fc0eb9f5f01c9cd3d27123a316bad655 | 13,100 |
def _FindLockNames(locks):
""" Finds the ids and descriptions of locks that given locks can block.
@type locks: dict of locking level to list
@param locks: The locks that gnt-debug delay is holding.
@rtype: dict of string to string
@return: The lock name to entity name map.
For a given set of locks, some... | 9e98eb03a4a27d8af95b734453a0a2add8248fab | 13,101 |
import time
import subprocess
def runtime(command: list, show=True, env=None):
"""Runs the command and returns the runtime."""
print('START:', *command)
t_start = time()
if show:
r = subprocess.run(command, env=env)
else:
r = subprocess.run(command, stdout=subprocess.PIPE,
... | eae28156c04e99fd8c7868f2e6b123d6d6f8ce41 | 13,102 |
def val2str(val):
"""Writes values to a string.
Args:
val (any): Any object that should be represented by a string.
Returns:
valstr (str): String representation of `val`.
"""
# Return the input if it's a string
if isinstance(val,str ): valstr=val
# Handle types where sp... | c8f26553ceeeef841239c534815f86293f91086a | 13,103 |
def showItems(category_name):
"""Pulls all the Categories, the specific Category selected by the user
from the home page, all the items within that specific Category, and
then counts the number of items. All this information is displayed on the
items.html page.
"""
categories = session.query(Cat... | 0ef0c8dfca16a9f16a9d4a46c3d796e817710165 | 13,104 |
from datetime import datetime
import math
import calendar
def date_ranges():
"""Build date ranges for current day, month, quarter, and year.
"""
today = datetime.date.today()
quarter = math.floor((today.month - 1) / 3)
cycle = current_cycle()
return {
'month': (
today.repla... | 08feb47fe09d5a0d1c9e5e16bdcbd65d3e211e1e | 13,105 |
def FiskJohnsonDiscreteFuncBCKWD(r,F0,T):
"""Compute reverse Fourier-Bessel transformation via Fisk Johnson
procedure.
Compute reverse Fourier-Bessel transform (i.e. 0th order reverse Hankel
transform) using a rapidly convergent summation of a Fourier-Bessel
expansion fol... | f950323bcad980f8b0af94d5848b59cd3522adfc | 13,106 |
def make_waterfall_horizontal(data, layout):
"""Function used to flip the figure from vertical to horizontal.
"""
h_data = list(data)
h_data = []
for i_trace, trace in enumerate(list(data)):
h_data.append(trace)
prov_x = h_data[i_trace]['x']
h_data[i_trace]['x'] = list(h_data... | 0dacdefc4e36d10dea3404e1fc5e92ce6f7326be | 13,107 |
def parse_file(producer):
"""
Given a producer name, return appropriate parse function.
:param producer: NMR machine producer.
:return: lambda function that reads file according to producer.
"""
global path_to_directory
return {
"Agilent": (lambda: ng.agilent.read(dir=path_to_directo... | cdb8e5e6f506b6d393eeefc13e982f246ea527b6 | 13,108 |
from typing import Union
from typing import Optional
def get_lon_dim_name_impl(ds: Union[xr.Dataset, xr.DataArray]) -> Optional[str]:
"""
Get the name of the longitude dimension.
:param ds: An xarray Dataset
:return: the name or None
"""
return _get_dim_name(ds, ['lon', 'longitude', 'long']) | 7f063690d8835b7cdd3298e14a5c35bd32025acc | 13,109 |
def logout():
"""Log out user."""
session.pop('eventbrite_token', None)
return redirect(url_for('index')) | 449690645fc19d72ef85636776f8d853ca65f4f8 | 13,110 |
def search(query="", casesense=False, filterout=[], subscribers=0, nsfwmode=2, doreturn=False, sort=None):
"""
Search for a subreddit by name
*str query = The search query
"query" = results where "query" is in the name
"*query" = results where "query" is at the end of the name
"... | c623ee11d507dbd7de84b109c2aa40866bb06dda | 13,111 |
def is_xh(filename):
"""
Detects if the given file is an XH file.
:param filename: The file to check.
:type filename: str
"""
info = detect_format_version_and_endianness(filename)
if info is False:
return False
return True | f0c33e5eed11522210dbc64a556e77f1c68d63c1 | 13,112 |
import os
import psutil
def is_parent_process_alive():
"""Return if the parent process is alive. This relies on psutil, but is optional."""
parent_pid = os.getppid()
if psutil is None:
try:
os.kill(parent_pid, 0)
except OSError:
return False
else:
... | 35ea736de6e5aec32a300c52745ad760723ba314 | 13,113 |
from typing import Tuple
from typing import List
from typing import Union
from typing import Callable
from typing import Any
def validate_func_kwargs(
kwargs: dict,
) -> Tuple[List[str], List[Union[str, Callable[..., Any]]]]:
"""
Validates types of user-provided "named aggregation" kwargs.
`TypeError`... | 81475f1467546f31a63a021c05a0c5f1adfd28a8 | 13,114 |
def mni152_to_fslr(img, fslr_density='32k', method='linear'):
"""
Projects `img` in MNI152 space to fsLR surface
Parameters
----------
img : str or os.PathLike or niimg_like
Image in MNI152 space to be projected
fslr_density : {'32k', '164k'}, optional
Desired output density of ... | 07129a79bc51e4655516573f517c4270d89800ed | 13,115 |
def parse_record(raw_record, _mode, dtype):
"""Parse CIFAR-10 image and label from a raw record."""
# Convert bytes to a vector of uint8 that is record_bytes long.
record_vector = tf.io.decode_raw(raw_record, tf.uint8)
# The first byte represents the label, which we convert from uint8 to int32
# an... | 278998f8ee1a126c6c248d8124bba1a4abdf7621 | 13,116 |
def makeSSHTTPClient(paramdict):
"""Creates a SingleShotHTTPClient for the given URL. Needed for Carousel."""
# get the "url" and "postbody" keys from paramdict to use as the arguments of SingleShotHTTPClient
return SingleShotHTTPClient(paramdict.get("url", ""),
paramdict.ge... | e7172d849e9c97baf07b9d97b914bf3e05551026 | 13,117 |
import glob
def getFiles(regex, camera, mjdToIngest = None, mjdthreshold = None, days = None, atlasroot='/atlas/', options = None):
"""getFiles.
Args:
regex:
camera:
mjdToIngest:
mjdthreshold:
days:
atlasroot:
options:
"""
# If mjdToIngest is de... | 8d61d2e1900413d55e2cfc590fb6c969dd31b441 | 13,118 |
from typing import Sequence
from typing import Tuple
def chain(*args: GradientTransformation) -> GradientTransformation:
"""Applies a list of chainable update transformations.
Given a sequence of chainable transforms, `chain` returns an `init_fn`
that constructs a `state` by concatenating the states of the ind... | 089b30a4daec8be0033567da147be6dc4fab9990 | 13,119 |
def fibonacci_mult_tuple(fib0=2, fib1=3, count=10):
"""Returns a tuple with a fibonacci sequence using * instead of +."""
return tuple(fibonacci_mult_list(fib0, fib1, count)) | a43d1bd5bd2490ecbf85b305cc99929ac64a4908 | 13,120 |
import logging
def execute_in_process(f):
"""
Decorator.
Execute the function in thread.
"""
def wrapper(*args, **kwargs):
logging.info("Se ha lanzado un nuevo proceso")
process_f = Process(target=f, args=args, kwargs=kwargs)
process_f.start()
return process_f
... | 2a002ce48e07ec4b31066c1fad51cd271eaa6230 | 13,121 |
import copy
def castep_spectral_dispersion(computer, calc_doc, seed):
""" Runs a dispersion interpolation on top of a completed SCF calculation,
optionally running orbitals2bands and OptaDOS projected dispersion.
Parameters:
computer (:obj:`matador.compute.ComputeTask`): the object that will be c... | 0f84e9b4d7a044fd50512093b51ec20425c98cbd | 13,122 |
def return_limit(x):
"""Returns the standardized values of the series"""
dizionario_limite = {'BENZENE': 5,
'NO2': 200,
'O3': 180,
'PM10': 50,
'PM2.5': 25}
return dizionario_limite[x] | 92d40eaef7b47c3a20b9bcf1f7fd72510a05d9b2 | 13,123 |
def npaths(x, y):
"""
Count paths recursively. Memoizing makes this efficient.
"""
if x>0 and y>0:
return npaths(x-1, y) + npaths(x, y-1)
if x>0:
return npaths(x-1, y)
if y>0:
return npaths(x, y-1)
return 1 | 487a1f35b1bf825ffaf6bbf1ed86eb51f6cf18e9 | 13,124 |
from datetime import datetime
def sqlify(obj):
"""
converts `obj` to its proper SQL version
>>> sqlify(None)
'NULL'
>>> sqlify(True)
"'t'"
>>> sqlify(3)
'3'
"""
# because `1 == True and hash(1) == hash(True)`
# we have to do this the hard way...
... | 6342a4fc1b4450181cee5a6287036b1f4ed38883 | 13,125 |
def create_results_dataframe(
list_results,
settings,
result_classes=None,
abbreviate_name=False,
format_number=False,
):
"""
Returns a :class:`pandas.DataFrame`.
If *result_classes* is a list of :class:`Result`, only the columns from
this result classes will be returned. If ``N... | 638328936ee9207777fab504021efd83379ec93c | 13,126 |
def get_first_model_each_manufacturer(cars=cars):
"""return a list of matching models (original ordering)"""
first = []
for key,item in cars.items():
first.append(item[0])
return(first) | c6ec531ccc7a9bc48b404df34ec9c33066cd8717 | 13,127 |
def white(*N, mean=0, std=1):
""" White noise.
:param N: Amount of samples.
White noise has a constant power density. It's narrowband spectrum is therefore flat.
The power in white noise will increase by a factor of two for each octave band,
and therefore increases with 3 dB per octave.
"""
... | 874dd75b3cd735f6b5642cd5567d7d0218af615b | 13,128 |
import random
def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)):
"""Randomly crop src with size. Randomize area and aspect ratio"""
h, w, _ = src.shape
area = w*h
for _ in range(10):
new_area = random.uniform(min_area, 1.0) * area
new_ratio = random.uniform(*rati... | 76c64b91e03cb5cf65b164c10771bd78d13945ee | 13,129 |
import tqdm
def analyze_subject(subject_id, A, B, spheres, interpolate, mask, data_dir=None):
"""
Parameters
----------
subject_id : int
unique ID of the subject (index of the fMRI data in the input dataset)
A : tuple
tuple of (even_trials, odd_trials) for the first condition (A);
... | 9596de830bd554990dc286ea08c1ea967deb20a7 | 13,130 |
import re
def joinAges(dataDict):
"""Merges columns by county, dropping ages"""
popColumns = list(dataDict.values())[0].columns.tolist()
popColumns = [re.sub("[^0-9]", "", column) for column in popColumns]
dictOut = dict()
for compartmentName, table in dataDict.items():
table.columns = pop... | d83ee4883ba58f7090141c131c4e111a4805f15d | 13,131 |
def plot_graph_route(G, route, bbox=None, fig_height=6, fig_width=None,
margin=0.02, bgcolor='w', axis_off=True, show=True,
save=False, close=True, file_format='png', filename='temp',
dpi=300, annotate=False, node_color='#999999',
node_... | 19483338300d2f0fe9426942b5e0a196178cc036 | 13,132 |
from typing import Dict
def random_polynomialvector(
secpar: int, lp: LatticeParameters, distribution: str, dist_pars: Dict[str, int], num_coefs: int,
bti: int, btd: int, const_time_flag: bool = True
) -> PolynomialVector:
"""
Generate a random PolynomialVector with bounded Polynomial entries.... | 43d059c69f74f2ba91fec690cc6d9a86ca51cf2a | 13,133 |
def parse_module(file_name, file_reader):
"""Parses a module, returning a module-level IR.
Arguments:
file_name: The name of the module's source file.
file_reader: A callable that returns either:
(file_contents, None) or
(None, list_of_error_detail_strings)
Returns:
(ir, debug_info, ... | d7c7bc55e3020444473c7b1fd66214a9a2451cb5 | 13,134 |
def get_glare_value(gray):
"""
:param gray: cv2.imread(image_path) grayscale image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
:return: numrical value between 0-256 which tells the glare value
"""
blur = cv2.blur(gray, (3, 3)) # With kernel size depending upon image size
mean_blur = cv2.... | c019d79f47949a061e74129b56bfb3d413d03314 | 13,135 |
import torch
def makeCrops(image, stepSize, windowSize, true_center):
"""
"""
image = image.type(torch.FloatTensor)
crops = []
truths = []
c_x, c_y, orient = true_center
# TODO: look into otdering, why it's y,x !
margin = 15
# --> is x, but is the column
# to slide horizontally... | 26c813741c799a6f13c0afee3969a6a669064974 | 13,136 |
def generate_n_clusters(object_generator, n_clusters, n_objects_per_cluster, *, rng=None):
""" Creates n_clusters of random objects """
rng = np.random.default_rng(rng)
object_clusters = []
for i in range(n_clusters):
cluster_objects = generate_random_object_cluster(n_objects_per_cluster, object... | 1de8c3793abaf635e182b6b4640ddd8bd7d1ed28 | 13,137 |
def disp2vel(wrange, velscale):
""" Returns a log-rebinned wavelength dispersion with constant velocity.
This code is an adaptation of pPXF's log_rebin routine, simplified to
deal with the wavelength dispersion only.
Parameters
----------
wrange: list, np.array or astropy.Quantity
Inpu... | c15d5cf8dc3f26969f38e4f678441adeae710e77 | 13,138 |
def relabel(labels):
"""
Remaps integer labels based on who is most frequent
"""
uni_labels, uni_inv, uni_counts = np.unique(
labels, return_inverse=True, return_counts=True
)
sort_inds = np.argsort(uni_counts)[::-1]
new_labels = range(len(uni_labels))
uni_labels_sorted = uni_lab... | bc809781968387ec9de9de05f8d5cd990ede4c62 | 13,139 |
from typing import List
from typing import Tuple
def precision_at_threshold(
weighted_actual_names: List[Tuple[str, float, int]],
candidates: np.ndarray,
threshold: float,
distances: bool = False,
) -> float:
"""
Return the precision at a threshold for the given weighted-actuals and candidates... | 40c99830339418acee59c5364f1a70dc5639a475 | 13,140 |
def alias(*alias):
"""Select a (list of) alias(es)."""
valias = [t for t in alias]
return {"alias": valias} | b2ff51f33b601468b1ba4d371bd5abd6d013a188 | 13,141 |
def create_blueprint(request_manager):
"""
Creates an instance of the blueprint.
"""
blueprint = Blueprint('requests', __name__, url_prefix='/requests')
# pylint: disable=unused-variable
@blueprint.route('<request_id>/state')
def get_state(request_id):
"""
Retrieves the stat... | f31e386357dba3e890ea6c6acada4ef6f1bee143 | 13,142 |
import pathlib
import traceback
def parse_smyle(file):
"""Parser for CESM2 Seasonal-to-Multiyear Large Ensemble (SMYLE)"""
try:
with xr.open_dataset(file, chunks={}, decode_times=False) as ds:
file = pathlib.Path(file)
parts = file.parts
# Case
case = pa... | 791ecf41e4bc1b44ababbf35a021b4a48b46bc24 | 13,143 |
def get_shape(grid, major_ticks=False):
"""
Infer shape from grid
Parameters
----------
grid : ndarray
Minor grid nodes array
major_ticks : bool, default False
If true, infer shape of majr grid nodes
Returns
-------
shape : tuple
Shape of grid ndarray
... | 57f487260ca19257bd3f9891ce87c52c1eafe3bc | 13,144 |
def lorentz_force_derivative(t, X, qm, Efield, Bfield):
"""
Useful when using generic integration schemes, such
as RK4, which can be compared to Boris-Bunemann
"""
v = X[3:]
E = Efield(X)
B = Bfield(X)
# Newton-Lorentz acceleration
a = qm*E + qm*np.cross(v,B)
ydot = np.concaten... | 7a7aade5ece2363e177002bac0c18c4a0b59174f | 13,145 |
def copy_rate(source, target, tokenize=False):
"""
Compute copy rate
:param source:
:param target:
:return:
"""
if tokenize:
source = toktok(source)
target = toktok(target)
source_set = set(source)
target_set = set(target)
if len(source_set) == 0 or len(target_se... | 80b94e90ab43df2f33869660f4b83f41721826f0 | 13,146 |
import json
def read_json_info(fname):
"""
Parse info from the video information file.
Returns: Dictionary containing information on podcast episode.
"""
with open(fname) as fin:
return json.load(fin) | 1eed945ce2917cbca1fb807a807ab57229622374 | 13,147 |
def check_subman_version(required_version):
"""
Verify that the command 'subscription-manager' isn't too old.
"""
status, _ = check_package_version('subscription-manager', required_version)
return status | 33e14fd5cf68e170f5804ae393cb2a45878d19a6 | 13,148 |
import os
def create_output_directory(input_directory):
"""Creates new directory and returns its path"""
output_directory = ''
increment = 0
done_creating_directory = False
while not done_creating_directory:
try:
if input_directory.endswith('/'):
output_director... | b2496045e8c9fbd627c32ea40a7b77181b7f4c1d | 13,149 |
import random
def bigsegment_twocolor(rows, cols, seed=None):
"""
Form a map from intersecting line segments.
"""
if seed is not None:
random.seed(seed)
possible_nhseg = [3,5]
possible_nvseg = [1,3,5]
gap_probability = random.random() * 0.10
maxdim = max(rows, cols)
nhs... | 1df4861434b19d6bdebe926baad57e3a11f6a64b | 13,150 |
def first_order_smoothness_loss(
image, flow,
edge_weighting_fn):
"""Computes a first-order smoothness loss.
Args:
image: Image used for the edge-aware weighting [batch, height, width, 2].
flow: Flow field for with to compute the smoothness loss [batch, height,
width, 2].
edge_weighting_f... | 92e0eb047bb9d5d67a32c8ba7a601e4b7c0333b8 | 13,151 |
def where_is_my_birthdate_in_powers_of_two(date: int) -> int:
"""
>>> where_is_my_birthdate_in_powers_of_two(160703)
<BLANKLINE>
Dans la suite des
<BLANKLINE>
0 1 3 765
2 , 2 , 2 , …, 2
<BLANKLINE>
Ta date de naissance apparaît ici!:
<BLANKLINE>
…568720026062381... | 656e7c76c849ba4348a5499a1c5cbd02574db011 | 13,152 |
def make_df_health_all(datadir):
"""
Returns full dataframe from health data at specified location
"""
df_health_all = pd.read_csv(str(datadir) + '/health_data_all.csv')
return df_health_all | c9fe0efe65f4455bc9770aa621bed5aaa54fb47f | 13,153 |
def lothars_in_cv2image(image, lothars_encoders,fc):
"""
Given image open with opencv finds
lothars in the photo and the corresponding name and encoding
"""
# init an empty list for selfie and corresponding name
lothar_selfies=[]
names=[]
encodings=[]
# rgb image
rgb = cv2.... | be869c922299178dd3f4835a6fd547c779c4e11a | 13,154 |
def approx_nth_prime_upper(n):
""" approximate upper limit for the nth prime number. """
return ceil(1.2 * approx_nth_prime(n)) | 9cfebe3c1dbac176fe917f97664b287b8024c5d4 | 13,155 |
def wavelength_to_velocity(wavelengths, input_units, center_wavelength=None,
center_wavelength_units=None, velocity_units='m/s',
convention='optical'):
"""
Conventions defined here:
http://www.gb.nrao.edu/~fghigo/gbtdoc/doppler.html
* Radio V = c (c/l0 - c/l)/(c/l0) f(V) = (c/l0) ( 1... | ffa1c1bb69a7f6767efcd2f5494da43847a80d3b | 13,156 |
import json
def gen_api_json(api):
"""Apply the api literal object to the template."""
api = json.dumps(
api, cls=Encoder, sort_keys=True, indent=1, separators=(',', ': ')
)
return TEMPLATE_API_DEFINITION % (api) | d9acea9483199746a9c97d905f06b17f20bff18c | 13,157 |
import copy
from bs4 import BeautifulSoup
import re
def get_massage():
"""
Provide extra data massage to solve HTML problems in BeautifulSoup
"""
# Javascript code in ths page generates HTML markup
# that isn't parsed correctly by BeautifulSoup.
# To avoid this problem, all document.write frag... | b2a7555b48f4a208545ffb75a4cc36c8c43a1eb7 | 13,158 |
def generate_test_images():
"""Generate all test images.
Returns
-------
results: dict
A dictionary mapping test case name to xarray images.
"""
results = {}
for antialias, aa_descriptor in antialias_options:
for canvas, canvas_descriptor in canvas_options:
for fu... | d4de85956dfae0cc7d5405b55c21a5063c4dc2c6 | 13,159 |
from typing import Dict
from typing import Type
import copy
def registered_metrics() -> Dict[Text, Type[Metric]]:
"""Returns standard TFMA metrics."""
return copy.copy(_METRIC_OBJECTS) | 0311def576648d6e621d35e6ac89f8cda1302029 | 13,160 |
import os
def get_pcap_path(name):
"""Given a pcap's name in the test directory, returns its full path."""
return os.path.join(PCAPS_DIR, name) | 5c42a96a375202b042c41f546012084665d62371 | 13,161 |
def text_dataset_construction(train_or_test, janossy_k, task, janossy_k2, sequence_len, all_data_size=0):
""" Data Generation """
janossy_k = 1
janossy_k2 = 1
args = parse_args()
task = str(args.task).lower()
X = np.load('../data_'+str(task)+str(sequence_len)+'.npy')
output_X = np.load('../label_'+str(task)+str(... | d55cdade5e2b9bd8a4a2d3ee1e80f0e15f390fc8 | 13,162 |
def neo_vis(task_id):
"""
Args:
task_id:
Returns:
"""
project = get_project_detail(task_id, current_user.id)
return redirect(
url_for(
"main.neovis_page",
port=project["remark"]["port"],
pwd=project["remark"]["password"],
)
) | cb0af50364e857d8febb8771abd0222a6d993b2e | 13,163 |
def getfont(
fontname=None,
fontsize=None,
sysfontname=None,
bold=None,
italic=None,
underline=None):
"""Monkey-patch for ptext.getfont().
This will use our loader and therefore obey our case validation, caching
and so on.
"""
fontname = fontname or ... | 04f12244126efd8cf6f274991193a2d71f8797f5 | 13,164 |
def change_box(base_image,box,change_array):
"""
Assumption 1: Contents of box are as follows
[x1 ,y2 ,width ,height]
"""
height, width, _ = base_image.shape
new_box = [0,0,0,0]
for i,value in enumerate(change_array):
if value != 0:
new_box[i] = box[i] + valu... | 960b9f2c3ab1b65e9c7a708eac700dfaf65c67ac | 13,165 |
def fetchRepositoryFilter(critic, filter_id):
"""Fetch a RepositoryFilter object with the given filter id"""
assert isinstance(critic, api.critic.Critic)
return api.impl.filters.fetchRepositoryFilter(critic, int(filter_id)) | 76aa247ddf63838ff16131d0d7f1a04092ef3c41 | 13,166 |
def load_it(file_path: str, verbose: bool = False) -> object:
"""Loads from the given file path a saved object.
Args:
file_path: String file path (with extension).
verbose: Whether to print info about loading successfully or not.
Returns:
The loaded object.
Raises:
No... | 59795488dffbc1a69556b2619e8502cfa23d6d63 | 13,167 |
def connect_contigs(contigs, align_net_file, fill_min, out_dir):
"""Connect contigs across genomes by forming a graph that includes
net format aligning regions and contigs. Compute contig components
as connected components of that graph."""
# construct align net graph and write net BEDs
if align_net_fi... | dc262d7469f524d8b37eebc50787a6e687a1ff90 | 13,168 |
import torch
import time
def train(loader, model, crit, opt, epoch):
"""Training of the CNN.
Args:
loader (torch.utils.data.DataLoader): Data loader
model (nn.Module): CNN
crit (torch.nn): loss
opt (torch.optim.SGD): optimizer for every parameters with True
... | 64a8213d103f57b3305060b42f41c94a3d710759 | 13,169 |
import ostap.logger.table as T
def _h1_cmp_prnt_ ( h1 ,
h2 ,
head1 = '' ,
head2 = '' ,
title = '' ,
density = False ,
max_moment = 1... | 99757ebd016b5a7c9d63b431fc5aee92c08d90e5 | 13,170 |
def add_scatter(x, scatter, in_place=False):
"""
Add a Gaussian scatter to x.
Parameters
----------
x : array_like
Values to add scatter to.
scatter : float
Standard deviation (sigma) of the Gaussian.
in_place : bool, optional
Whether to add the scatter to x in place... | 27c1423441f7841284201afd873c2c6050812d5f | 13,171 |
def validate_job_state(state):
"""
Validates whether a returned Job State has all the required fields with the right format.
If all is well, returns True,
otherwise this prints out errors to the command line and returns False.
Can be just used with assert in tests, like "assert validate_job_state(st... | f108b7a80dee7777931aae994384d47f4a474d67 | 13,172 |
def get_urls(session):
"""
Function to get all urls of article in a table.
:param session: session establishes all conversations with the database and represents a “holding zone”.
:type session: sqlalchemy.session
:returns: integer amount of rows in table
"""
url = session.query(Article.url... | ad5e4797c1a41c63ef225becaee1a9b8814a3ea2 | 13,173 |
import pkg_resources
def check_min_package_version(package, minimum_version, should_trunc_to_same_len=True):
"""Helper to decide if the package you are using meets minimum version requirement for some feature."""
real_version = pkg_resources.get_distribution(package).version
if should_trunc_to_same_len:
... | 62bbed35905bf4aa38fb1596cf164a66eac30594 | 13,174 |
def bboxes_protection(boxes, width, height):
"""
:param boxes:
:param width:
:param height:
:return:
"""
if not isinstance(boxes, np.ndarray):
boxes = np.asarray(boxes)
if len(boxes) > 0:
boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, width - 1)
boxes[:, [1, 3]] ... | 8ab0c64788815f6ec66f42c90a4c2debc0627548 | 13,175 |
def mark_astroids(astroid_map):
"""
Mark all coordiantes in the grid with an astroid (# sign)
"""
astroids = []
for row, _ in enumerate(astroid_map):
for col, _ in enumerate(astroid_map[row]):
if astroid_map[row][col] == "#":
astroid_map[row][col] = ASTROID
... | 36ac179f1cbc040142bea8381c4c85f90c81ecba | 13,176 |
def process_player_data(
prefix, season=CURRENT_SEASON, gameweek=NEXT_GAMEWEEK, dbsession=session
):
"""
transform the player dataframe, basically giving a list (for each player)
of lists of minutes (for each match, and a list (for each player) of
lists of ["goals","assists","neither"] (for each mat... | dcbf210242509fa3df1ae5ca35614d802c460381 | 13,177 |
def copy_to_table(_dal, _values, _field_names, _field_types, _table_name, _create_table=None, _drop_existing=None):
"""Copy a matrix of data into a table on the resource, return the table name.
:param _dal: An instance of DAL(qal.dal.DAL)
:param _values: The a list(rows) of lists(values) with values to be ... | 765ae0310811fe64b063c88182726174411960a0 | 13,178 |
import os
def build_file_path(base_dir, base_name, *extensions):
"""Build a path to a file in a given directory.
The file may have an extension(s).
:returns: Path such as: 'base_dir/base_name.ext1.ext2.ext3'
"""
file_name = os.extsep.join([base_name] + list(extensions))
return os.path.expa... | 26e5998c5ba53fd9c99677991ff4cf2e82141f15 | 13,179 |
from scipy.optimize import minimize
def Uni(A, b, x=None, maxQ=False, x0=None, tol=1e-12, maxiter=1e3):
"""
Вычисление распознающего функционала Uni.
В случае, если maxQ=True то находится максимум функционала.
Parameters:
A: Interval
Матрица ИСЛАУ.
... | d81f8f38e4b2f196c79eaaa00c1b604cf119b1bb | 13,180 |
def boqa(alpha, beta, query, items_stat):
"""Implementation of the BOQA algorithm.
Args:
alpha (float): False positive rate.
beta (float): False negative rate.
query (dict): Dict of query terms (standard terms). Key: term name, value: presence value
items_stat (dict): Dictionnar... | 37ea565fa05b4a9bceeeb50f31e79394e9534966 | 13,181 |
from operator import inv
def d2c(sys,method='zoh'):
"""Continous to discrete conversion with ZOH method
Call:
sysc=c2d(sys,method='log')
Parameters
----------
sys : System in statespace or Tf form
method: 'zoh' or 'bi'
Returns
-------
sysc: continous system ss or tf
... | 41bb37fcf5b8726b5f20f54f492a568f508725fc | 13,182 |
import ipaddress
def ipv4(value):
"""
Parses the value as an IPv4 address and returns it.
"""
try:
return ipaddress.IPv4Address(value)
except ValueError:
return None | 499918424fe6a94d555379b5fc907367666f1cde | 13,183 |
from typing import Callable
from typing import Mapping
from typing import cast
from typing import Any
def test_from(
fork: str,
) -> Callable[
[Callable[[], StateTest]], Callable[[str], Mapping[str, Fixture]]
]:
"""
Decorator that takes a test generator and fills it for all forks after the
specifi... | 6c8704978c3ab37bb2ad8434b65359683bd76bbb | 13,184 |
import hashlib
def get_hash_name(feed_id):
"""
用户提交的订阅源,根据hash值生成唯一标识
"""
return hashlib.md5(feed_id.encode('utf8')).hexdigest() | edd1caf943635a091c79831cc6151ecfa840e435 | 13,185 |
from typing import TextIO
def _load_transition_probabilities(infile: TextIO) -> tuple[list, int]:
"""
For summary files with new syntax (post 2021-11-24).
Parameters
----------
infile : TextIO
The KSHELL summary file at the starting position of either of
the transition probability... | 9d0b8ebc4ffe78517cb548ae3bbd329b48868589 | 13,186 |
from typing import Dict
from typing import Counter
def merge_lineages(counts: Dict[str, int], min_count: int) -> Dict[str, str]:
"""
Given a dict of lineage counts and a min_count, returns a mapping from all
lineages to merged lineages.
"""
assert isinstance(counts, dict)
assert isinstance(min... | 3eea022d840e4e61d46041dffb188cbd73ed097b | 13,187 |
def str2bool(s):
"""特定の文字列をbool値にして返す。
s: bool値に変換する文字列(true, false, 1, 0など)。
"""
if isinstance(s, bool):
return s
else:
s = s.lower()
if s == "true":
return True
elif s == "false":
return False
elif s == "1":
return True
... | 54b991e234896c0ad684ce5f0f2ccceeada65d8e | 13,188 |
def merge_aoistats(main_AOI_Stat,new_AOI_Stat,total_time,total_numfixations):
"""a helper method that updates the AOI_Stat object of this Scene with a new AOI_Stat object
Args:
main_AOI_Stat: AOI_Stat object of this Scene
new_AOI_Stat: a new AOI_Stat object
... | 8bea60667fa2cc3c187a1fa288c4c3053ba6484e | 13,189 |
import six
from typing import OrderedDict
def catalog_xmatch_circle(catalog, other_catalog,
radius='Association_Radius',
other_radius=Angle(0, 'deg')):
"""Find associations within a circle around each source.
This is convenience function built on `~astropy.... | 1c56f35d7610c4f2d23e7eb5fd3007329f3dc298 | 13,190 |
def show_map_room(room_id=None):
"""Display a room on a map."""
return get_map_information(room_id=room_id) | 84c1e90ce5b0a210b75f104da429f03dff7b2ca1 | 13,191 |
import os
def color_enabled():
"""Check for whether color output is enabled
If the configuration value ``datalad.ui.color`` is ``'on'`` or ``'off'``,
that takes precedence.
If ``datalad.ui.color`` is ``'auto'``, and the environment variable
``NO_COLOR`` is defined (see https://no-color.org), then... | 5db8ac3de0fa8b3e452d82244208987c8816cfb4 | 13,192 |
def parse_line_regex(line):
"""Parse raw data line into list of floats using regex.
This regex approach works, but is very slow!! It also requires two helper functions to clean up
malformed data written by ls-dyna (done on purpose, probably to save space).
Args:
line (str): raw data line from... | b8b18a8d47f5f1c9a682ca86668bf311282b0439 | 13,193 |
def create_page_metadata(image_dir,
image_dir_path,
font_files,
text_dataset,
speech_bubble_files,
speech_bubble_tags):
"""
This function creates page metadata for a single page. It inclu... | 45499abf5374c8eaaa55a03f8ef0bb7fca6e18f5 | 13,194 |
def __merge_results(
result_list: tp.List[tp.Dict[str, tp.Dict[str, tp.Set[tp.Union[CVE, CWE]]]]]
) -> tp.Dict[str, tp.Dict[str, tp.Set[tp.Union[CVE, CWE]]]]:
"""
Merge a list of results into one dictionary.
Args:
result_list: a list of ``commit -> cve`` maps to be merged
Return:
t... | 685ce8e22483fc1dfe423763367857db22065a3c | 13,195 |
def compactness(xyz):
"""
Input: xyz
Output: compactness (V^2/SA^3) of convex hull of 3D points.
"""
xyz = np.array(xyz)
ch = ConvexHull(xyz, qhull_options="QJ")
return ch.volume**2/ch.area**3 | b1185e8aaec5962e39866594aeccdd5d5ae2807d | 13,196 |
import os
def is_posix():
"""Convenience function that tests different information sources to verify
whether the operating system is POSIX compliant.
.. note::
No assumption is made reading the POSIX level compliance.
:return: True if the operating system is MacOS, False otherwise.
:rtyp... | 7f40b0b6d785b63b0c7af6ac78272a4823994681 | 13,197 |
def guide(batch, z_dim, hidden_dim, out_dim=None, num_obs_total=None):
"""Defines the probabilistic guide for z (variational approximation to posterior): q(z) ~ p(z|q)
:param batch: a batch of observations
:return: (named) sampled z from the variational (guide) distribution q(z)
"""
assert(jnp.ndim(... | 1198ee7b12bed9118d7bb865ed45ff10eef917d4 | 13,198 |
def trip2str(trip):
""" Pretty-printing. """
header = "{} {} {} - {}:".format(trip['departureTime'],
trip['departureDate'], trip['origin'],
trip['destination'])
output = [header]
for subtrip in trip['trip']:
originstr = u'... | 67daf3feb6b81d40d3102a8c610b20e68571b131 | 13,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.