content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def conjugate_term(term: tuple) -> tuple:
"""Returns the sorted hermitian conjugate of the term."""
conj_term = [conjugate_field(field) for field in term]
return tuple(sorted(conj_term)) | d21834ff5c2abe5ff6ec85304db962d809b07637 | 3,650,200 |
def create_notify_policy_if_not_exists(project, user, level=NotifyLevel.involved):
"""
Given a project and user, create notification policy for it.
"""
model_cls = apps.get_model("notifications", "NotifyPolicy")
try:
result = model_cls.objects.get_or_create(project=project,
... | 3d2eec3e3a5f12a4cbba3c3c111608f38133cf94 | 3,650,201 |
def parse_table(soup, start_gen, end_gen):
"""
- Finds the PKMN names in the soup object and puts them into a list.
- Establishes a gen range.
- Gets rid of repeated entries (formes, e.g. Deoxys) using an OrderedSet.
- Joins the list with commas.
- Handles both Nidorans having 'unmappable' chara... | 1bb1ce6135f162e532b02e2d95eabd675540878d | 3,650,202 |
import torch
def get_expert_parallel_src_rank():
"""Calculate the global rank corresponding to a local rank zero
in the expert parallel group."""
global_rank = torch.distributed.get_rank()
local_world_size = get_expert_parallel_world_size()
return (global_rank // local_world_size) * local_world_si... | 0022f953707f26f9a3b3b021422ebc16e1d14213 | 3,650,203 |
from typing import Dict
from typing import Any
from typing import Optional
def _add_extra_kwargs(
kwargs: Dict[str, Any], extra_kwargs: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Safely add additional keyword arguments to an existing dictionary
Parameters
----------
kwargs : dic... | cfc4c17f608c0b7fe1ae3046dc220d385c890caa | 3,650,204 |
import random
import math
def Hiker(n,xLst,yLst,dist):
"""
Hiker is a function to generate lists of x and y
coordinates of n steps for a random walk of n steps
along with distance between the first and last point
"""
x0=0
y0=0
x=x0
y=y0
xLst[1] = x0
yLst[1] = y0
... | abe341c8ecdc579de2b72f5af1ace3f07dd40dc3 | 3,650,205 |
def extractdata(csvName='US_SP_Restructured.csv'):
"""
Parameters
----------
:string csvName: Name of csv file. e.g. 'US_SP_Restructured.csv'
"""
df = pd.read_csv(csvName)
df['index'] = df.index
# extract alternative specific variables
cost = pd.melt(df, id_vars=['quest', 'index'],
value_vars=['Ca... | e0a3f405da0e31e252b6110f84f81363c692d66a | 3,650,206 |
def has_field(entry: EntryType, field: str) -> bool:
"""Check if a given entry has non empty field"""
return has_data(get_field(entry, field)) | e13d973fde62e36764871fd3b565552ff46b359b | 3,650,207 |
import timeit
import json
import logging
def generate_random_fires(fire_schemas, n=100):
"""
Given a list of fire product schemas (account, loan, derivative_cash_flow,
security), generate random data and associated random relations (customer,
issuer, collateral, etc.)
TODO: add config to set numb... | 1a9425287d0a2eeccb83b86330751f12801d73d9 | 3,650,208 |
def open_file(app_id, file_name, mode):
# type: (int, str, int) -> str
""" Call to open_file.
:param app_id: Application identifier.
:param file_name: File name reference.
:param mode: Open mode.
:return: The real file name.
"""
return _COMPSs.open_file(app_id, file_name, mode) | 7c38d219d4a867e72d90b873412ec7d5e5aad78a | 3,650,209 |
import logging
def is_valid_network(name, ip_network, **kwargs):
"""Valid the format of an Ip network."""
if isinstance(ip_network, list):
return all([
is_valid_network(name, item, **kwargs) for item in ip_network
])
try:
netaddr.IPNetwork(ip_network)
except Excepti... | ce1c36badc5ce3176a75d7787acf19addc0a5c20 | 3,650,210 |
def correct_repeat_line():
""" Matches repeat spec above """
return "2|1|2|3|4|5|6|7" | b9c1e48c5043a042b9f6a6253cba6ae8ce1ca32c | 3,650,211 |
from typing import Tuple
def get_byte_range_bounds(byte_range_str: str, total_size: int) -> Tuple[int, int]:
"""Return the start and end byte of a byte range string."""
byte_range_str = byte_range_str.replace("bytes=", "")
segments = byte_range_str.split("-")
start_byte = int(segments[0])
# chrome... | f376f5af0771901d9850e06f08ebd32b13243176 | 3,650,212 |
def privmsg(recipient, s, prefix='', msg=None):
"""Returns a PRIVMSG to recipient with the message msg."""
if conf.supybot.protocols.irc.strictRfc():
assert (areReceivers(recipient)), repr(recipient)
assert s, 's must not be empty.'
if minisix.PY2 and isinstance(s, unicode):
s = s.en... | 1ff0087794732a06c7e2151ad6c255ca863ffb37 | 3,650,213 |
def char_decoding(value):
""" Decode from 'UTF-8' string to unicode.
:param value:
:return:
"""
if isinstance(value, bytes):
return value.decode('utf-8')
# return directly if unicode or exc happens.
return value | b8054b4a5012a6e23e2c08b6ff063cf3f71d6863 | 3,650,214 |
def inv2(x: np.ndarray) -> np.ndarray:
"""矩阵求逆"""
# np.matrix()废弃
return np.matrix(x).I | 9b1b18dc0cbd248c977fd0ae0c35a65b4cd5b797 | 3,650,215 |
def clean_remaining_artifacts(image):
"""
Method still on development. Use at own risk!
Remove remaining artifacts from image
:param image: Path to Image or 3D Matrix representing RGB image
:return: Image
"""
img, *_ = __image__(image)
blur = cv2.GaussianBlur(img, (3, 3), 0)
# conve... | 54473dcce5eb5764e80304836f0ca16ce4d82a77 | 3,650,216 |
def max_simple_dividers(a):
"""
:param a: число от 1 до 1000
:return: самый большой простой делитель числа
"""
return max(simple_dividers(a)) | 3fc2fb51e2940ed07db97285886e7cb30e99d5a0 | 3,650,217 |
def to_light_low_sat(img, new_dims, new_scale, interp_order=1 ):
"""
Turn an image into lightness
Args:
im : (H x W x K) ndarray
new_dims : (height, width) tuple of new dimensions.
new_scale : (min, max) tuple of new scale.
interp_order : interpolation order, de... | 2aca96378551a2a083f1762f30582efe1560f2fb | 3,650,218 |
def get_slug_blacklist(lang=None, variant=None):
"""
Returns a list of KA slugs to skip when creating the channel.
Combines the "global" slug blacklist that applies for all channels, and
additional customization for specific languages or curriculum variants.
"""
SLUG_BLACKLIST = GLOBAL_SLUG_BLAC... | e06dd582812ddd8d2d2e929c733dc957abb748d6 | 3,650,219 |
def get_level_rise(station):
"""For a MonitoringStation object (station), returns a the rate of water level rise, specifically
the average value over the last 2 days"""
#Fetch data (if no data available, return None)
times, values = fetch_measure_levels(station.measure_id, timedelta(days=2))
#O... | 59de80a5bdb5b24711f45395ec9cbc282ad6ad44 | 3,650,220 |
def get_mask_indices(path):
"""Helper function to get raster mask for NYC
Returns:
list: returns list of tuples (row, column) that represent area of interest
"""
raster = tiff_to_array(path)
indices = []
it = np.nditer(raster, flags=['multi_index'])
while not it.finished:
if i... | ff957ffac0f79635e729f8880457d8aa33379185 | 3,650,221 |
def about(isin:str):
"""
Get company description.
Parameters
----------
isin : str
Desired company ISIN. ISIN must be of type EQUITY or BOND, see instrument_information() -> instrumentTypeKey
Returns
-------
TYPE
Dict with description.
"""
params = {'isin': is... | 86554c393087670637859d991bd2ae740ea4ff86 | 3,650,222 |
def aesEncrypt(message):
"""
Encrypts a message with a fresh key using AES-GCM.
Returns: (key, ciphertext)
"""
key = get_random_bytes(symmetricKeySizeBytes)
cipher = AES.new(key, AES.MODE_GCM)
ctext, tag = cipher.encrypt_and_digest(message)
# Concatenate (nonce, tag, ctext) and return ... | 06a13bb605f9038d8096f73681932a09022107b1 | 3,650,223 |
from contextlib import suppress
def pyro_nameserver(host=None,
port=None,
auto_clean=0,
auto_start=False):
"""Runs a Pyro name server.
The name server must be running in order to use distributed cameras with POCS. The name server
should be start... | 1cf986688a9b5184e2e147fe3a9f5a8aa0379d60 | 3,650,224 |
import os
import sys
def _get_library_path() -> str:
"""Find library path for compiled IK fast libraries.
Look for sub-package 'linux_so', or '.reach/third_party/ikfast/linux-so'
Only supports Linux "so" file.
Returns:
Library path.
"""
if _is_running_on_google3:
return "./"
current_folder =... | d227349fb3cfd4caa7938a7bd9da78c846c40fc0 | 3,650,225 |
from pathlib import Path
import os
def view_img(
stat_map_img,
bg_img="MNI152",
cut_coords=None,
colorbar=True,
title=None,
threshold=1e-6,
annotate=True,
draw_cross=True,
black_bg="auto",
cmap=cm.cold_hot,
symmetric_cmap=True,
dim="auto",
vmax=None,
vmin=None,
... | 5891758ec6baac825345435afece645fb8b24e42 | 3,650,226 |
def getType(o):
"""There could be only return o.__class__.__name__"""
if isinstance(o, LispObj):
return o.type
return o.__class__.__name__ | a3602469d8a7d5f6372c6e74d868a903651f85f7 | 3,650,227 |
import shutil
import os
import subprocess
def cr2_to_pgm(
cr2_fname,
pgm_fname=None,
overwrite=True, *args,
**kwargs): # pragma: no cover
""" Convert CR2 file to PGM
Converts a raw Canon CR2 file to a netpbm PGM file via `dcraw`. Assumes
`dcraw` is installed on the system... | 62ebda213ff919904aa5d84e32c8b6f204de8c24 | 3,650,228 |
def failed_revisions_for_case_study(
case_study: CaseStudy, result_file_type: MetaReport
) -> tp.List[str]:
"""
Computes all revisions of this case study that have failed.
Args:
case_study: to work on
result_file_type: report type of the result files
Returns:
a list of fail... | 2e9d5ab3818343e7a07fc3ff7242206f4b231e89 | 3,650,229 |
def _removeTwoSentenceCommonNode(syncSrc1, syncSrc2, matchListT1, matchListT2, prefix):
"""
Identify and remove a node that appears to be in both of the target sentences,
and is also a currently active link
"""
raise DeprecationWarning, "Now finding split points before individual pairs"
# a usef... | 4496f2ab8bf00833d3b5a11818994332df48f893 | 3,650,230 |
def bytes_load(path):
"""Load bytest from a file."""
with open(path, 'rb') as f:
return f.read() | ebbeb4bfcecfb94a1fa1ef8640f4e749bfa0dfcb | 3,650,231 |
def get_relationship_length_fam_mean(data):
"""Calculate mean length of relationship for families DataDef 43
Arguments:
data - data frames to fulfill definiton id
Modifies:
Nothing
Returns: added_members
mean_relationship_length - mean relationship length of families
"""
families... | 4d9b76c4dca3e1f09e7dd2684bd96e25792177fd | 3,650,232 |
def convert_hapmap(input_dataframe, recode=False, index_col=0):
""" Specifically deals with hapmap and 23anMe Output
"""
complement = {'G/T': 'C/A', 'C/T': 'G/A', "G/A" : "G/A", "C/A": "C/A", "A/G" : "A/G",
"A/C": "A/C"}
dataframe = input_dataframe.copy()
if recode:
recode = data... | c328cfe41e25f7fd3ff2274861fb6fc89effa181 | 3,650,233 |
def to_base64(message):
"""
Returns the base64 representation of a string or bytes.
"""
return b64encode(to_bytes(message)).decode('ascii') | d3f091f7dbf04850e8c40bca8e7fb0ec06f2848f | 3,650,234 |
import traceback
def create_alerts():
"""
Function to create alerts.
"""
try:
# validate post json data
content = request.json
print(content)
if not content: raise ValueError("Empty value")
if not 'timestamp' in content or not 'camera_id' in content or not 'c... | ca824f0f356cf2b42e7a598810dc89f7121664ba | 3,650,235 |
import os
def read_envs():
"""Function will read in all environment variables into a dictionary
:returns: Dictionary containing all environment variables or defaults
:rtype: dict
"""
envs = {}
envs['QUEUE_INIT_TIMEOUT'] = os.environ.get('QUEUE_INIT_TIMEOUT', '3600')
envs['VALIDATION_TIMEOUT'] = os.environ.ge... | 2d357796321d561a735461d425fa7c703082434c | 3,650,236 |
import platform
import os
def get_platform():
""" Get system platform metadata.
"""
detected_os = platform.system()
detected_distro = platform.platform()
if detected_os == "Darwin":
return PlatformDescription(detected_os=detected_os,
detected_distro=dete... | d54d93bf95e9d746ba33d38e1dfe2e74c7ab54d8 | 3,650,237 |
import numpy
def load_catalog_npy(catalog_path):
"""
Load a numpy catalog (extension ".npy")
@param catalog_path: str
@return record array
"""
return numpy.load(catalog_path) | 912281ad17b043c6912075144e6a2ff3d849a391 | 3,650,238 |
def pgd(fname, n_gg=20, n_mm=20, n_kk=20, n_scale=1001):
"""
:param fname: data file name
:param n_gg: outer iterations
:param n_mm: intermediate iterations
:param n_kk: inner iterations
:param n_scale: number of discretized points, arbitrary
:return:
"""
n_buses, Qmax, Qmin, Y, V_... | 5a00b6992ecf5c4f3b89fcf5151cae71c4a36298 | 3,650,239 |
def find_first_empty(rect):
"""
Scan a rectangle and find first open square
@param {Array} rect Board layout (rectangle)
@return {tuple} x & y coordinates of the leftmost top blank square
"""
return _find_first_empty_wrapped(len(rect[0]))(rect) | d266805761cda903733cef7704baff6d38576b04 | 3,650,240 |
import re
def parseArticle(text: str) -> str:
"""
Parses and filters an article. It uses the `wikitextparser` and custom logic.
"""
# clear the image attachments and links
text = re.sub("\[\[Податотека:.+\]\][ \n]", '', text)
text = wikipedia.filtering.clearCurlyBrackets(text)
# repl... | 7a17e31ec960b568debb9c6e7ccb8018bba19218 | 3,650,241 |
import torch
def exp2(input, *args, **kwargs):
"""
Computes the base two exponential function of ``input``.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.exp2(ttorch.tensor([-4.0, -1.0, 0, 2.0, 4.8, 8.0]))
tensor([6.2500e-02, 5.0000e-01, 1.0... | 17cbc0917acf19932ec4d3a89de8d78545d02e31 | 3,650,242 |
def list_default_storage_policy_of_datastore(
datastore,
host=None,
vcenter=None,
username=None,
password=None,
protocol=None,
port=None,
verify_ssl=True,
):
"""
Returns a list of datastores assign the storage policies.
datastore
Name of the datastore to assign.
... | caf729c258a4ece895d14fdd93ba1f23879453e8 | 3,650,243 |
import numpy
def action_stats(env, md_action, cont_action):
"""
Get information on `env`'s action space.
Parameters
----------
md_action : bool
Whether the `env`'s action space is multidimensional.
cont_action : bool
Whether the `env`'s action space is continuous.
Returns
-------
n_actions_per_dim : list of len... | 8a08b3fe5be20f274680fe33df9ca02456bb511f | 3,650,244 |
def count(pred: Pred, seq: Seq) -> int:
"""
Count the number of occurrences in which predicate is true.
"""
pred = to_callable(pred)
return sum(1 for x in seq if pred(x)) | 09726935174d7590030331da62322da870e216aa | 3,650,245 |
def lambda_k(W, Z, k):
"""Coulomb function $\lambda_k$ as per Behrens et al.
:param W: Total electron energy in units of its rest mass
:param Z: Proton number of daughter
:param k: absolute value of kappa
"""
#return 1.
gammak = np.sqrt(k**2.0-(ALPHA*Z)**2.0)
gamma1 = np.sqrt(1.-(ALPHA... | 9f6a59bd730460c09a3c7f855550254ffb5cdc66 | 3,650,246 |
import pprint
import json
def tryJsonOrPlain(text):
"""Return json formatted, if possible. Otherwise just return."""
try:
return pprint.pformat( json.loads( text ), indent=1 )
except:
return text | 2431479abf6ab3c17ea63356ec740840d2d18a74 | 3,650,247 |
import aiohttp
import websockets
import random
def create_signaling(args):
"""
Create a signaling method based on command-line arguments.
"""
if args.signaling == "apprtc":
if aiohttp is None or websockets is None: # pragma: no cover
raise Exception("Please install aiohttp and web... | f9fe4ed35555381468dbf15379ab70a4af289ac9 | 3,650,248 |
def get_corpus_gene_adjacency(corpus_id):
"""Generate a nugget table."""
corpus = get_corpus(corpus_id)
data = get_gene_adjacency(corpus)
return jsonify(data), 200 | 9dd86e11eba5e5bc5094d89bd15dd9315df40480 | 3,650,249 |
def get_pool_health(pool):
""" Get ZFS list info. """
pool_name = pool.split()[0]
pool_capacity = pool.split()[6]
pool_health = pool.split()[9]
return pool_name, pool_capacity, pool_health | 1a9dbb8477d8735b225afc2bdd683f550602b36e | 3,650,250 |
def resize_short(img, target_size):
""" resize_short """
percent = float(target_size) / min(img.shape[0], img.shape[1])
resized_width = int(round(img.shape[1] * percent))
resized_height = int(round(img.shape[0] * percent))
resized_width = normwidth(resized_width)
resized_height = normwidth(resi... | ca9a71dc97a57c5739419c284514466e86dc3fa1 | 3,650,251 |
def _scale(aesthetic, name=None, breaks=None, labels=None, limits=None, expand=None, na_value=None, guide=None,
trans=None, **other):
"""
Create a scale (discrete or continuous)
:param aesthetic
The name of the aesthetic that this scale works with
:param name
The name of the ... | c8d98a52f2b87340e0a1df46b9f36ca811c18d5d | 3,650,252 |
def logsubexp(x, y):
"""
Helper function to compute the exponential
of a difference between two numbers
Computes: ``x + np.log1p(-np.exp(y-x))``
Parameters
----------
x, y : float or array_like
Inputs
"""
if np.any(x < y):
raise RuntimeError('cannot take log of nega... | a0b0434fb2714f3d1dec24b88ce0fa9ff0110bc0 | 3,650,253 |
def is_sequence_of_list(items):
"""Verify that the sequence contains only items of type list.
Parameters
----------
items : sequence
The items.
Returns
-------
bool
True if all items in the sequence are of type list.
False otherwise.
Examples
--------
>... | e53e5d31e1c4f5649b2f03edf792f810bc398446 | 3,650,254 |
def sum_fib_dp(m, n):
"""
A dynamic programming version.
"""
if m > n: m, n = n, m
large, small = 1, 0
# a running sum for Fibbo m ~ n + 1
running = 0
# dynamically update the two variables
for i in range(n):
large, small = large + small, large
# note that (i + 1)... | 5be6e57ddf54d185ca6d17adebd847d0bc2f56fc | 3,650,255 |
def fibo_dyn2(n):
"""
return
the n-th fibonacci number
"""
if n < 2:
return 1
else:
a, b = 1, 1
for _ in range(1,n):
a, b = b, a+b
return b | e8483e672914e20c6e7b892f3dab8fb299bac6fc | 3,650,256 |
import time
import math
def build_all(box, request_list):
"""
box is [handle, left, top, bottom] \n
request_list is the array about dic \n
****** Attention
before running the function, you should be index.
After build_all, function will close the windows about train tr... | 59db695f802867e85a5e920f2efa8f652ac12823 | 3,650,257 |
def select_results(results):
"""Select relevant images from results
Selects most recent image for location, and results with positive fit index.
"""
# Select results with positive bestFitIndex
results = [x for x in results['items'] if x['bestFitIndex'] > 0]
# counter_dict schema:
# counter... | 85940fe93b33d79ca0a799ca52a9e68439e7e822 | 3,650,258 |
def dc_session(virtual_smoothie_env, monkeypatch):
"""
Mock session manager for deck calibation
"""
ses = endpoints.SessionManager()
monkeypatch.setattr(endpoints, 'session', ses)
return ses | 06876e5ce2d599086efcb37688f5181f32392068 | 3,650,259 |
def is_available(_cache={}):
"""Return version tuple and None if OmnisciDB server is accessible or
recent enough. Otherwise return None and the reason about
unavailability.
"""
if not _cache:
omnisci = next(global_omnisci_singleton)
try:
version = omnisci.version
... | 0edcbfcd1ecb6a56b4b4a6f55907271c9094b8d8 | 3,650,260 |
import copy
def pitch_info_from_pitch_string(pitch_str: str) -> PitchInfo:
"""
Parse a pitch string representation. E.g. C#4, A#5, Gb8
"""
parts = tuple((c for c in pitch_str))
size = len(parts)
pitch_class = register = accidental = None
if size == 1:
(pitch_class,) = parts
e... | cc1b6c0fe64834fe3fdc5249078e10e8f3af1434 | 3,650,261 |
def determine_word_type(tag):
"""
Determines the word type by checking the tag returned by the nltk.pos_tag(arr[str]) function.
Each word in the array is marked with a special tag which can be used to find the correct type of a word.
A selection is given in the dictionaries.
Args:
tag : String tag from the nltk... | 4505d2cf69f961ecdec4e3c693ea85b916acce96 | 3,650,262 |
def get_normalized_map_from_google(normalization_type, connection=None, n_header_lines=0):
"""
get normalized voci or titoli mapping from gdoc spreadsheets
:param: normalization_type (t|v)
:param: connection - (optional) a connection to the google account (singleton)
:param: n_header_lines - (optio... | 61056536cae2da9053f21d2739488c5512546a68 | 3,650,263 |
import io
def parse_file(fname, is_true=True):
"""Parse file to get labels."""
labels = []
with io.open(fname, "r", encoding="utf-8", errors="igore") as fin:
for line in fin:
label = line.strip().split()[0]
if is_true:
assert label[:9] == "__label__"
... | ea6cbd4b1a272f472f8a75e1cc87a2209e439205 | 3,650,264 |
from datetime import datetime
import os
import json
def main(event, context):
"""
Args:
package: Python Package to build and deploy
return:
execution_arn: ARN of the state machine execution that is building the package
"""
packages = get_config.get_packages()
execution_arns =[]
... | a73abef29b0fd98e878ee71b9fbc30fa8f204bb9 | 3,650,265 |
def make_mesh(object_name, object_colour=(0.25, 0.25, 0.25, 1.0), collection="Collection"):
"""
Create a mesh then return the object reference and the mesh object
:param object_name: Name of the object
:type object_name: str
:param object_colour: RGBA colour of the object, defaults to a shade of g... | 73fd8d13d471c55258a06feb71eec51ca51f23f9 | 3,650,266 |
import optparse
def _OptionParser():
"""Returns the options parser for run-bisect-perf-regression.py."""
usage = ('%prog [options] [-- chromium-options]\n'
'Used by a try bot to run the bisection script using the parameters'
' provided in the auto_bisect/bisect.cfg file.')
parser = optpars... | 7485db294d89732c2c5223a3e3fe0b7773444b49 | 3,650,267 |
def calc_radiance(wavel, Temp):
"""
Calculate the blackbody radiance
Parameters
----------
wavel: float or array
wavelength (meters)
Temp: float
temperature (K)
Returns
-------
Llambda: float or arr
monochromatic radiance (W/m^2/m/sr)
... | 9a957b42e0e92614709f7157765f0185e1dd532a | 3,650,268 |
import json
import os
def load_config(filename):
"""
Returns:
dict
"""
config = json.load(open(filename, 'r'))
# back-compat
if 'csvFile' in config:
config['modelCategoryFile'] = config['csvFile']
del config['csvFile']
required_files = ["prefix", "modelCategoryFil... | af9f6cb02925d38077652703813b9fec201f12f7 | 3,650,269 |
def _JMS_to_Fierz_III_IV_V(C, qqqq):
"""From JMS to 4-quark Fierz basis for Classes III, IV and V.
`qqqq` should be of the form 'sbuc', 'sdcc', 'ucuu' etc."""
#case dduu
classIII = ['sbuc', 'sbcu', 'dbuc', 'dbcu', 'dsuc', 'dscu']
classVdduu = ['sbuu' , 'dbuu', 'dsuu', 'sbcc' , 'dbcc', 'dscc']
if... | 5629a4e88996bd3ba30bd68cc8758b3d55abd093 | 3,650,270 |
from typing import Any
def get_parsed_args() -> Any:
"""Return Porcupine's arguments as returned by :func:`argparse.parse_args`."""
assert _parsed_args is not None
return _parsed_args | 9e4dc1eadc3c68d8a8e5a5a885fecf7c0ec89856 | 3,650,271 |
def get_license_description(license_code):
"""
Gets the description of the given license code. For example, license code '1002' results in 'Accessory Garage'
:param license_code: The license code
:return: The license description
"""
global _cached_license_desc
return _cached_license_desc[lic... | 3de38be73d303036872b285c2dd7c0048ba5660f | 3,650,272 |
import pickle
import getpass
def db_keys_unlock(passphrase) -> bool:
"""Unlock secret key with pass phrase"""
global _secretkeyfile
try:
with open(_secretkeyfile, "rb") as f:
secretkey = pickle.load(f)
if not secretkey["locked"]:
print("Secret key file is already u... | 4d1af86143384ff6228ad086d92f797b7529c73e | 3,650,273 |
def list_domains():
"""
Return a list of the salt_id names of all available Vagrant VMs on
this host without regard to the path where they are defined.
CLI Example:
.. code-block:: bash
salt '*' vagrant.list_domains --log-level=info
The log shows information about all known Vagrant e... | af04859c5d6e0cd2edb3d3cec88ebebd777c93d6 | 3,650,274 |
def get_old_options(cli, image):
""" Returns Dockerfile values for CMD and Entrypoint
"""
return {
'cmd': dockerapi.inspect_config(cli, image, 'Cmd'),
'entrypoint': dockerapi.inspect_config(cli, image, 'Entrypoint'),
} | eed75800ae3afdc99fdcd5c0f5dc36504d5db96c | 3,650,275 |
def line_crops_and_labels(iam: IAM, split: str):
"""Load IAM line labels and regions, and load line image crops."""
crops = []
labels = []
for filename in iam.form_filenames:
if not iam.split_by_id[filename.stem] == split:
continue
image = util.read_image_pil(filename)
... | f223ded3c2dc9254985ad450995f8dc598dc5411 | 3,650,276 |
def convert(chinese):
"""converts Chinese numbers to int
in: string
out: string
"""
numbers = {'零':0, '一':1, '二':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '壹':1, '贰':2, '叁':3, '肆':4, '伍':5, '陆':6, '柒':7, '捌':8, '玖':9, '两':2, '廿':20, '卅':30, '卌':40, '虚':50, '圆':60, '近':70, '枯':80, '无':90}
... | cf2ece895698e2d99fde815efa0339687eadda97 | 3,650,277 |
def computeZvector(idata, hue, control, features_to_eval):
"""
:param all_data: dataframe
:return:
"""
all_data = idata.copy()
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
m_indexes = list(all_data[hue].unique().astype('str'))
query_one = ""
for el in contr... | d80e6a9fe754cb8558598c72ab2f076fab329750 | 3,650,278 |
def getjflag(job):
"""Returns flag if job in finished state"""
return 1 if job['jobstatus'] in ('finished', 'failed', 'cancelled', 'closed') else 0 | bf0c0a85cb1af954d25f4350e55b9e3604cf7c79 | 3,650,279 |
import copy
def json_parse(ddict):
"""
https://github.com/arita37/mlmodels/blob/dev/mlmodels/dataset/test_json/test_functions.json
https://github.com/arita37/mlmodels/blob/dev/mlmodels/dataset/json/benchmark_timeseries/gluonts_m5.json
"deepar": {
"model_pars": {
"model_... | 30b037531ac129a2a597b146c935fe344566a547 | 3,650,280 |
def read_viz_icons(style='icomoon', fname='infinity.png'):
""" Read specific icon from specific style
Parameters
----------
style : str
Current icon style. Default is icomoon.
fname : str
Filename of icon. This should be found in folder HOME/.dipy/style/.
Default is infinity... | 8d97ebb450b94dce5c4feb3f631cd9deebcdb1c1 | 3,650,281 |
def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="12345",
domain=DOMAIN,
data={CONF_API_KEY: "tskey-MOCK", CONF_SYSTEM_ID: 12345},
unique_id="12345",
) | cb2a5b8d7e84d1b825e79a9b4e3aebc8f8c60783 | 3,650,282 |
import datasets
def get_mnist_loader(batch_size, train, perm=0., Nparts=1, part=0, seed=0, taskid=0, pre_processed=True, **loader_kwargs):
"""Builds and returns Dataloader for MNIST and SVHN dataset."""
transform = transforms.Compose([
transforms.Grayscale(),
transform... | 2181ffa0abd4f1357ec7cc8cdf52b0eb86a2d13c | 3,650,283 |
def read_data(filename):
"""
Reads orbital map file into a list
"""
data = []
f = open(filename, 'r')
for line in f:
data += line.strip().split('\n')
f.close()
return data | 7c2f5669735e39352b0b655425a70993baae32ef | 3,650,284 |
from typing import Union
def _form_factor_pipi(
self, s: Union[float, npt.NDArray[np.float64]], imode: int = 1
) -> Union[complex, npt.NDArray[np.complex128]]:
"""
Compute the pi-pi-V form factor.
Parameters
----------
s: Union[float,npt.NDArray[np.float64]
Square of the center-of-mas... | 92438400debb52bff6480791631e2b60043c758f | 3,650,285 |
import os
def lecture():
"""
lecture()
Lee archivos "tmdb_5000_credits.csv" y "tmdb_5000_movies.csv"
para luego transformarlos en pandas.DataFrame.
Parameters
----------
None.
Returns
-------
credits, movies : [pandas.Data... | 710c66c98d9af344afa883c9efb551e9e68c991c | 3,650,286 |
import re
import click
def string_to_epoch(s):
"""
Convert argument string to epoch if possible
If argument looks like int + s,h,md (ie, 30d), we'll pass as-is
since pushshift can accept this. Per docs, pushshift supports:
Epoch value or Integer + "s,m,h,d" (i.e. 30d for 30 days)
:param s: ... | b45db1d589cbe71eec5f11d53d2851dee258da8f | 3,650,287 |
import array
def spline_filter(Iin, lmbda=5.0):
"""Smoothing spline (cubic) filtering of a rank-2 array.
Filter an input data set, `Iin`, using a (cubic) smoothing spline of
fall-off `lmbda`.
"""
intype = Iin.dtype.char
hcol = array([1.0,4.0,1.0],'f')/6.0
if intype in ['F','D']:
I... | ee606bdceaf974671ccf36b9d498204613c12f51 | 3,650,288 |
def _construct_aline_collections(alines, dtix=None):
"""construct arbitrary line collections
Parameters
----------
alines : sequence
sequences of segments, which are sequences of lines,
which are sequences of two or more points ( date[time], price ) or (x,y)
date[time] may be ... | 863fd8c6e8d0b1a39c5a79bca7a0eaa5b2204aea | 3,650,289 |
def is_mergeable(*ts_or_tsn):
"""Check if all objects(FermionTensor or FermionTensorNetwork)
are part of the same FermionSpace
"""
if isinstance(ts_or_tsn, (FermionTensor, FermionTensorNetwork)):
return True
fs_lst = []
site_lst = []
for obj in ts_or_tsn:
if isinstance(obj... | de5f4fc47874e328bcdd078e2bdf8d6f53d6d4e6 | 3,650,290 |
import urllib
import http
def fetch_file(url, config):
"""
Fetch a file from a provider.
"""
# pylint: disable=fixme
# FIXME: the handled checking should be in each handler module (possibly handle_file(parsed_url,
# config) => bool)
parsed_url = urllib.parse.urlparse(url)
if parsed_... | 0be30bb953f3d0dedc36eaf89e4b7d0a6ac48ad9 | 3,650,291 |
def query_for_account(account_rec, region):
""" Performs the public ip query for the given account
:param account: Account number to query
:param session: Initial session
:param region: Region to query
:param ip_data: Initial list. Appended to and returned
:return: update ip_data list
"""... | 61055939990175c6e2cb850ede7d448a261ccdff | 3,650,292 |
from typing import List
def filter_list_of_dicts(list_of_dicts: list, **filters) -> List[dict]:
"""Filter a list of dicts by any given key-value pair.
Support simple logical operators like: '<,>,<=,>=,!'. Supports
filtering by providing a list value i.e. openJobsCount=[0, 1, 2].
"""
for key, val... | f926b7c478400d3804d048ced823003e48fd5ef1 | 3,650,293 |
def construct_pos_line(elem, coor, tags):
"""
Do the opposite of the parse_pos_line
"""
line = "{elem} {x:.10f} {y:.10f} {z:.10f} {tags}"
return line.format(elem=elem, x=coor[0], y=coor[1], z=coor[2], tags=tags) | 21ca509131c85a2c7bc24d00a28e7d4ea580a49a | 3,650,294 |
def compute_pcs(predicts, labels, label_mapper, dataset):
"""
compute correctly predicted full spans. If cues and scopes are predicted jointly, convert cue labels to I/O labels depending on the
annotation scheme for the considered dataset
:param predicts:
:param labels:
:return:
"""
def ... | 5f046c1599617ad7620ea9a618f85f02dd93e28c | 3,650,295 |
def pentomino():
"""
Main pentomino routine
@return {string} solution as rectangles separated by a blank line
"""
return _stringify(
_pent_wrapper1(tree_main_builder())(rect_gen_boards())) | 07e448efdbfe5cb43ce943f33f24a7887878001f | 3,650,296 |
def do_login(request, username, password):
""" Check credentials and log in """
if request.access.verify_user(username, password):
request.response.headers.extend(remember(request, username))
return {"next": request.app_url()}
else:
return HTTPForbidden() | f7c076c6f4a6ac51bf5a3ea39116166002ce1833 | 3,650,297 |
from tokenize import Token
import re
def _interpolate(format1):
"""
Takes a format1 string and returns a list of 2-tuples of the form
(boolean, string) where boolean says whether string should be evaled
or not.
from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee)
"""
def ma... | 9af06b91f0ad2e15fd7479ac2e1dedc5443b6e34 | 3,650,298 |
def approxIndex(iterable, item, threshold):
"""Same as the python index() function but with a threshold from wich values are considerated equal."""
for i, iterableItem in rev_enumerate(iterable):
if abs(iterableItem - item) < threshold:
return i
return None | 45ec7b816674231a5efa8a559e9f9416a81987f5 | 3,650,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.