content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import random
def generate_appskey():
"""Generate a random secret key"""
return "".join("{:02X}".format(x) for x in random.sample(range(255), 16)) | bd80160df997209981214201a3fac779ca4cdd60 | 71,119 |
def get_filters_visualization(psi, J, L, mode ='fourier'):
""" Visualizes the scattering filters input for different modes
parameters:
psi -- dictionnary that contains all the wavelet filters
L -- number of orientation
J -- scattering scale
mode -- mode between fourier... | 35009c4a4a83fa85168b028c2f2add4cc11038ad | 71,120 |
def unitchanger(unit):
"""
If unit is in unitdict, convert
otherwise, return the old unit
"""
if unit is None:
return None
lowerunit = unit.lower()
if lowerunit in unitdict:
return unitdict[lowerunit]
return unit | 6a1a6dcea7945d08a559b73a520c8d186693ac56 | 71,122 |
from airflow.models import DagRun
def latest_dag_runs():
"""Returns the latest DagRun for each DAG formatted for the UI. """
dagruns = DagRun.get_latest_runs()
payload = []
for dagrun in dagruns:
if dagrun.execution_date:
payload.append(
{
"dag_... | d69704810f26f7ea0dbe96b1339ebf2481578973 | 71,124 |
def detect(
A, threshold, is_excessive, min_group_edge_num=0,
):
"""
CIDRE algorithm
Parameters
-----------
A : scipy sparse matrix
Adjacency matrix
threshold : float
The algorithm seeks the groups of nodes that have a
donor score or a recipient score larger than o... | c8c4dce7a0b4e0f6a5196860f526bb981b98fa58 | 71,125 |
def can_fast_forward(repo, c1, c2):
"""Is it possible to fast-forward from c1 to c2?
Args:
repo: Repository to retrieve objects from
c1: Commit id for first commit
c2: Commit id for second commit
"""
if c1 == c2:
return True
# Algorithm: Find the common ancestor
paren... | d1e7a4925d8ef44de325a2d3fb3d0d7548ecb675 | 71,126 |
def get_sys_uptime():
"""
:return: (uptime, idle) in seconds
"""
f = open("/proc/uptime") # %f(uptime) %f(idle) , all in seconds
uptime = f.read()
f.close()
uptime, idle = uptime.split(" ")
return float(uptime), float(idle) | 71406d10728820680046a2137129a7410f16cd78 | 71,128 |
def calculate_image_precision(gts, preds, thresholds = (0.5, ), form = 'coco') -> float:
# https://www.kaggle.com/sadmanaraf/wheat-detection-using-faster-rcnn-train
"""Calculates image precision.
Args:
gts: (List[List[Union[int, float]]]) Coordinates of the available ground-truth boxes
pred... | fb6f232c3b7274b6281b912b48eb548a9b28ed37 | 71,129 |
from typing import List
from typing import Dict
def boolean_eval(exp: List[str], result: bool) -> int:
""" Counts the ways that parenthesis can be
arranged on exp that lead to result """
cache: Dict[str, int] = {}
return eval_amount(exp, result, cache) | e45a290873c6cd2a56073c6523f37fd0b648ba6f | 71,130 |
import json
def parse_fio_output_file(fpath: str) -> dict:
""" Read and parse json from fio json outputs """
lines = []
with open(fpath, 'r') as fiof:
do_append = False
for l in fiof:
if l.startswith('{'):
do_append = True
if do_append:
... | ce4efcd3f0508179971788a2c19a7f278d887a79 | 71,131 |
import platform
def is_win_platform():
"""
Checks if the current platform is Windows.
"""
WIN_PLATFORMS = ["windows", "cygwin", "cygwin_nt-10.0"]
return platform.system().lower() in WIN_PLATFORMS | c1e0eb0f57f69349c70470e6da13e687c1d72126 | 71,132 |
def get_full_name(participant):
"""Returns the full name of a given participant"""
return participant['fields']['First Name'].strip() + \
' ' + participant['fields']['Last Name'].strip() | 4292ea595d13e8093f6d221c40634e8fe74b8e91 | 71,133 |
def validator(req, template_name="buildmanager/validator.html"):
"""Validate an xform"""
def get(req, template_name):
return render_to_response(req, template_name, {})
def post(req, template_name):
xform_body = req.POST["xform"]
hq_validation = True if "hq-validate" in req.... | 19f5adf3d07d150e16bcfa4ccc7bb3c7761b1794 | 71,134 |
def config():
"""Get test config, extend to several scenarios"""
model = PowerLaw(
index=2, amplitude=1e-11 * u.Unit("cm-2 s-1 TeV-1"), reference=1 * u.TeV
)
pos = SkyCoord(83.63, 22.01, unit="deg", frame="icrs")
radius = Angle(0.11, "deg")
on_region = CircleSkyRegion(pos, radius)
f... | 940b1820d336d9f8caec8775a279c824d6ca7bcf | 71,135 |
def create_vpc(client, tag_name, cidr):
"""Method to create vpc based on the cidr and tag with tag_name.
Args:
client (boto client): Region specific boto client
tag_name (str): VPC tag name
cidr (str): CIDR string.
Returns:
VPC(Object): Newly created VPC object.
"""
v... | c572e97e2b28f6694b7d9ebb2921e53bbcdcab04 | 71,136 |
def sendHelp():
"""construct the help message to send to the user"""
message = "**Voilà un petit rappel des commandes que tu peux utiliser avec le PoGoBot en remplacant les valeurs `surlignées` : **\n*Ex: `pokemon` => pichu* \n\n"
for name, command in commandex.items():
message += str("**%s :**\t\... | 5796d23b8fd9e682366c2edbe11b870ebba48870 | 71,137 |
def tf_expm_dynamic(A, acc=1e-5):
"""
Matrix exponential by the series method with specified accuracy.
Parameters
----------
A : tf.tensor
Matrix to be exponentiated.
acc : float
Accuracy. Stop when the maximum matrix entry reaches
Returns
-------
tf.tensor
... | 0427f2366db06ffd9d88ad02350b288fdf31693a | 71,138 |
def minutes(m):
""" Create a time interval representing m minutes"""
return pd.tseries.offsets.Minute(m) | 3eb7200cfe21eae1e19b9619b8b67c0512a1d115 | 71,139 |
import math
def breit_wigner_random(rnd, mean, gamma) :
"""
Random Breit-Wigner distribution with specified mean and width
"""
rval = 2.*rnd - 1
displ = 0.5*gamma*atfi.tan(rval*math.pi/2.)
return mean + displ | 6c2d3a5b0e6201ee6d18bb766bb3f352dbb07460 | 71,140 |
def ftoj(instr):
"""
instr must be unicode
"""
return instr.translate(f2jtable) | 7655d82a4ed27ce5e002e07b5dd1704c646f95b4 | 71,141 |
def read_file(path: str) -> str:
"""Read a file and return its contents."""
try:
with open(path, encoding="ascii") as f:
return f.read()
except FileNotFoundError:
raise HERAError('file "{}" does not exist'.format(path))
except PermissionError:
raise HERAError('permiss... | cd3ea25915c265da487052862020d097fd231bc9 | 71,142 |
def WER(x, y):
"""
x, y : list of words for one sentence
output : wer
"""
d = np.zeros(((len(x) + 1), (len(y) + 1)), dtype='float32')
for i in range(len(x) + 1):
for j in range(len(y) + 1):
if i == 0:
d[0][j] = j
elif j == 0:
d[i]... | d29468d5f0a3e164600918c8c35d685c6f7729aa | 71,143 |
def get_gdrive_refresh_token(email):
""" Get user credentials from database
"""
print "inside get_gdrive_access_token() \nemail = ", email
# Get the refresh token from the DB
refresh_token = get_gdrive_token(email)
# print "refresh_token form db = ", refresh_token
if refresh_token:
return refresh_token
pr... | bcebbe0e05ef54a6ddd685beda63042f3af26a76 | 71,144 |
def generate_private_key(filename):
"""Generate private key.
:param filename: Path to generated private key.
"""
private_key = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_backend(),
)
alg = serialization.NoEncryption()
with open(filename, "wb")... | 8da108b8e84635da54e4382d49759f2bab4a87b0 | 71,145 |
import re
def user_has_harvard_email(failure_url='non-harvard-email'):
"""
Decorator to forward user if they don't have Harvard email. E.g.:
@user_has_harvard_email()
def my_view(request):
"""
return user_passes_test(
test_func=lambda u: bool(re.search(r'[.@]harvard.edu$',... | d26ccfe3e3d926b6a197364cbf047c1d90e7ff79 | 71,146 |
def create(large_person_group_id, name, user_data=None):
"""Create a new person in a specified large person group. A newly created
person have no registered face.
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
name: Name of the created per... | ce7a09fb554bedc40f87e26c124f76bcf2c98476 | 71,147 |
import time
def get_today_zero_time(now=time.time()):
"""
:param now: 时间轴
:return: 传入时间轴当天的零点时间轴
"""
midnight = now - (now % 86400) + time.timezone
return long(midnight) | 0f995cdf8f87ae30d2e3ab376868284f34206f98 | 71,149 |
def _get_categories_at_tier(project: Project, *, tier: int) -> set:
"""
Extracts categories at tier from a taxonomy associated with Project
Args:
project: Tamr project object
tier: integer specifying the tier to extract the categories;
-1 will return all leaf categories
R... | fa4e7515db8a9804393209352f6ac9ff7ef6621b | 71,150 |
import torch
def calc_squared_dice_loss(input, target, weight=None, eps=0.001):
"""Calculate the squared dice loss
Args:
input (torch.Tensor): The input tensor
target (torch.Tensor): The target tensor
eps (float): The smoothing term preventing division by 0
Return:
dice (... | dbb565861c90f8d505f227869574e9ba8120b8e9 | 71,151 |
import logging
def get_all_coins(client=None):
"""
Returns a dataframe of all available coins on Binance.US
"""
if client is None:
logging.info("No binance client found, attempting to establish connection.")
client = BinanceClient()
coins = client.get_all_tickers()
coins... | 194c4024f906f39775b1806dfbd7a981394654e8 | 71,152 |
def moveToPoseConstV(current_x, current_y, current_angle, current_V,
desired_x, desired_y, desired_angle,
k_alpha, k_beta, wheelbase):
"""Implements a simple proportional controller for Move to Pose
For stability with Ackermann style steering (bicycle model):
k_... | 9b1641fea54fd8935cc8dbbbe772cd9cf7b56739 | 71,153 |
def ioa(boxlist1, boxlist2):
"""Computes pairwise intersection-over-area between box collections.
Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).
Args:
boxl... | 4c16cf0ca8cf09a333f8ee520cdd716d609abe55 | 71,154 |
from typing import Iterable
from pathlib import Path
from typing import MutableMapping
from typing import Any
def read_toml_multi(filenames: Iterable[Path]) -> MutableMapping[str, Any]:
"""Read and parse multiple experiment configuration files with 'toml'."""
config: dict[str, Any] = {}
for filename in fi... | 3b7923288f147d124ae2640b06caec84387f4d2d | 71,155 |
import re
def join_list_item_to_content(snts):
"""
Evaluates a list of sentences to determininne if an itemized list is
present and then puts the number and list time into the same element of
the list.
:param snts: list of report sentences.
:return: List of sentences where list item and number... | 4cc33b7e9ab65c18b9dc0d587838bd5d56e9ffb6 | 71,156 |
def find_new_values(data, values, key):
"""Identify any new label/description values which could be added to an item.
@param data: the contents of the painting item
@type data: dict
@param values: the output of either make_labels or make_descriptions
@type values: dict
@param key: the type of v... | db56c07aedb38458be8aa0fc6bc4b5f4b49b4f4d | 71,157 |
def positional_encoding(pos, model_size):
""" Compute positional encoding for a particular position
Args:
pos: position of a token in the sequence
model_size: depth size of the model
Returns:
The positional encoding for the given token
"""
PE = np.zeros((1, model_size))... | c80d9dfb128d635d078e9f9b4ff38ceb9cbdd2ff | 71,159 |
def get_triples_from_bel_commons(network_id: str) -> np.ndarray:
"""Load a BEL document from BEL Commons by wrapping :func:`pybel.io.tsv.api.get_triples`.
:param network_id: The network identifier for a graph in BEL Commons
:return: A three column array with head, relation, and tail in each row
"""
... | b2d3e3d8dda74ad7886ce71a6bd9ae004f3560b2 | 71,160 |
from typing import Callable
def call_tf_no_ad(tf_fun: Callable, arg, *, result_shape):
"""The simplest implementation of calling to TF, without AD support.
We must use hcb.call because the TF invocation must happen outside the
JAX staged computation."""
def tf_to_numpy(t):
# Turn the Tensor to NumPy arr... | df423106f5e9d81427bd5ae26e388e3da9d83267 | 71,161 |
def evaluate_offsets(edges_list):
"""
Takes edges of rails graph with "Offsets" on Beziers, turns offset points into new
control points, finds new top control point (using curve tangents)
Uses: abstract_geometry.narrow_bezier()
Input: rails graph with "Offsets" (list of pythonic dicts)
Output: ... | d1293b3338602d237a9ca0e6de7e910871f5780d | 71,162 |
def _len_sans_ansi(text):
"""Computes the length of a string that might contain ANSI codes.
"""
return len(ANSI_ESCAPE.sub('', text)) | 3c5bca252c8068e00baaa2571e5a4d3cc8d22c00 | 71,163 |
def sceneViewer():
""" Returns an existing open Scene Viewer pane if there is one. A
Context viewer is also acceptable is no dedicated scene viewer
is found.
"""
return hou.SceneViewer | 3f75c04d35a5c7b9822a31c4e9926993a244320a | 71,164 |
import re
def _remove_handles_from_text(text: str) -> str:
"""
removes userhandles. ex: @JohnDoe
"""
return re.sub(r'(@[\w]*)', '', text) | c8f507d58d32ee3c1f38301255cd68fc2e36c666 | 71,165 |
import time
def inference_simple(cfg, blobs, net, num_test=10, scope=None, test_image=None, **net_args):
"""
Assumes blobs[i] is a list of blobs (crops).
Returns inference[i] = list of results for each crop.
"""
net.init_placeholders(**net_args)
if scope is None:
net.create_architectur... | 59441b00e9d1b1b48b35ebba812e2a4736e84420 | 71,166 |
def load_backends(backends, force_load=False):
"""
Load backends defined on SOCIAL_AUTH_AUTHENTICATION_BACKENDS, backends will
be imported and cached on BACKENDSCACHE. The key in that dict will be the
backend name, and the value is the backend class.
Only subclasses of BaseAuth (and sub-classes) ar... | 6e75e433fb3075569e00e6321a6a341d9d4a8ef6 | 71,167 |
from typing import Dict
def hausdorff_surface_distance(y_pred: itkImage, y_ref: itkImage) -> Dict[str, float]:
"""Compute symmetric surface distances between two binary masks
Args:
y_pred (itkImage): predicted segmentation
y_ref (itkImage): reference segmentation
Returns:
Dict[st... | 97c0c6c35e78fc0ee2595068586133d3a6da3049 | 71,168 |
def get_user_by_email(email):
"""Return a user by email."""
return User.query.filter(User.email == email).first() | a880409a65e1d1d3790caacd64089bec5e5f5a00 | 71,169 |
import typing
from typing import OrderedDict
def order_by_dependencies(dependency_mapper: typing.Dict[str, typing.Set[str]]) \
-> typing.Tuple[typing.List[str], typing.List[str]]:
"""
You have to make sure there's no cycle dependency.
"""
ordered_dict = OrderedDict()
for _ in range(1000):
... | 23bc887549a722612180b6720adaf4925e886752 | 71,170 |
def getattritem(o,a):
"""
Get either attribute or item `a` from a given object `o`. Supports multiple evaluations, for example
`getattritem(o,'one.two')` would get `o.one.two`, `o['one']['two']`, etc.
:param o: Object
:param a: Attribute or Item index. Can contain `.`, in which case the final value ... | 7b928b2405691dcb5fac26b7a3d7ebfcfa642f6d | 71,171 |
from xml.dom import minidom
def load_mountpoints(fpath):
"""Load mount points mapping from file
:fpath, file path to load
"""
if not fpath:
return
mount_maps = []
with open(fpath, 'r') as rf:
dom = minidom.parse(rf)
imgroot = dom.documentElement
for part in imgroot.g... | 06b11ddcec1d10addfa4ffa3dcd4c5a3ea4e2a9c | 71,172 |
def mesh2array(x_mesh, y_mesh):
"""Mesh to array converter.
Parameters
----------
x_mesh : array, shape = [n_samples, n_samples]
The x_axis mesh.
y_mesh : array, shape = [n_samples, n_samples]
The y_axis mesh.
Returns
-------
inputs : array, shape = [n_samples, 2]
... | d5905163ae884294c0d0d08e919888b5e44bca2b | 71,173 |
def publish_started(not_published, publishing_ip, manager):
""" Publish started services.
"""
publish_stats = []
for service_name in not_published:
def published_hook(sname):
publish_stats.append((sname, True, ["Published"]))
def already_published_hook(sname):
... | e1ee64e10a312bab8e5552689fce56f608ce7b51 | 71,174 |
def simplex_proj(y):
"""Projection of y onto simplex."""
m = len(y)
bget = False
s = sorted(y, reverse=True)
tmpsum = 0.0
for ii in range(m - 1):
tmpsum = tmpsum + s[ii]
tmax = (tmpsum - 1) / (ii + 1)
if tmax >= s[ii + 1]:
bget = True
break
... | 3c811f9c95629006b3f55db377ba42e84ba0b5a5 | 71,175 |
import re
def normalize_str(text: str) -> str:
"""Normalize str: Remove accent and white spaces from string and convert it into lower case."""
text = re.sub(r'\s+', '', text)
text = text.lower()
return remove_accent(text) | 8eb63a8f1fb70cbe582b0b94b7420334903d430a | 71,177 |
def filter_by_intersection_percent(df: gpd.GeoDataFrame,
geo: Polygon,
min_percent_overlap,
relative_to='geometry') -> gpd.GeoDataFrame:
"""Intersection area relative to dataframe or geometry"""
df_utm, geo... | f1667a024c058a61605433afabb4f2bd3cf17938 | 71,178 |
def handle_top():
""" app_page.route('/') """
return flask.redirect(flask.url_for("app_bp.handle_astutus")) | ffee1a670e3e70ad6fd4e783384746ea74191094 | 71,179 |
def parse_pdb(pdb_fname, base_fname=None):
"""Returns a graph object with available connectivity information"""
trj = md.load(pdb_fname).center_coordinates()
G = make_bondgraph(trj.top)
connect_dict = get_pdb_connect_dict(pdb_fname)
if len(connect_dict) != trj.top.n_atoms:
raise ValueError(... | 4d407f4c4e93945c92538a82baf2de2fe95e4f92 | 71,180 |
def _find_last_notified(location):
"""Find when an update for location was previously notified.
Returns notification time as datetime object or None if never notified.
"""
doc_ref = get_db().collection("locations").document(location)
doc = doc_ref.get()
if not doc.exists:
return None
... | 51c1f1d9eb19e2009c654c3bd6fecff96de1a50e | 71,181 |
from math import floor
def conv_output_shape(h_w, kernel_size=1, stride=1, padding=0, dilation=1):
"""
Utility function for computing output of convolutions
takes a tuple of (h,w) and returns a tuple of (h,w)
"""
if type(kernel_size) is not tuple:
kernel_size = (kernel_size, kernel_size)
... | 847899bba14ea18f2f0657c8c0e8b3b9cbf5327d | 71,182 |
def wgan_generator_loss(gen_noise, gen_net, disc_net):
"""
Generator loss for Wasserstein GAN (same for WGAN-GP)
Inputs:
gen_noise (PyTorch Tensor): Noise to feed through generator
gen_net (PyTorch Module): Network to generate images from noise
disc_net (PyTorch Module): Network to ... | 090de59ebc8e009b19e79047f132014f747972e7 | 71,183 |
def similarity(a, b):
"""
Returns the similarity between two strings.
Parameters
----------
a : str
String a
b : str
String b
Returns
-------
float
Similarity score (between 0-1)
"""
return SequenceMatcher(None, a, b).ratio() | 67bfea8333a489d130d2f10beb10ea12edd8f25d | 71,184 |
def add_parameter():
"""Add update user snmp info parameter"""
argget = utils.create_common_parameter_list()
add_helpmessage(argget)
args = argget.parse_args()
parameter_info = utils.parse_parameter(args)
parameter_info["username"] = args.username
parameter_info["authentication_protocol"] = ... | 3d5fd4720869c5a41bc6d6a12f021d776876da67 | 71,185 |
def find_project_root_and_manifest(project_items):
""" Given the contents of an archive, find a valid Pebble project.
:param project_items: A list of BaseProjectItems
:return: A tuple of (path_to_project, manifest BaseProjectItem)
"""
SRC_DIR = 'src/'
invalid_package_path = None
for item in ... | 119130f1e8b1c9d86c7558c313ec302962f85af0 | 71,186 |
import torch
def load_extended_vae(model_path, model_args, device=None, optimizer=None):
"""
Load the checkpoint of the extended model.
Args:
model_path: Path to the .pt checkpoint
model_args: Args to pass to the model class (kwargs are saved in the checkpoint)
device: Device of t... | 626bea17a047894766893e212293bcbdcc6c9158 | 71,187 |
def get_date_object(date = None):
"""takes an optional string date and returns a date object
if no argument a date object is returned with today's date"""
if date is None:
return dt.date.today()
if not isinstance(date, str):
raise TypeError('Input must be string')
date_obj ... | ac1c693fdae5503878d314c43cbc788aa9972826 | 71,188 |
import iso3166 #dbg
def _is_country(code):
"""
"""
if _is_region(code):
return False
if _is_income_level(code):
return False
try:
iso3166.countries.get(code.lower())
except:
if not in 'JG'
print '%s not in iso!?!' % code
return True | 40e70f53a6e1257ec47c4123b19d59360aed2157 | 71,190 |
def init_falff_wf(workdir=None, feature=None, fwhm=None, memcalc=MemoryCalculator()):
"""
Calculate Amplitude of low frequency oscillations(ALFF) and
fractional ALFF maps
Returns
-------
workflow : workflow object
ALFF workflow
Notes
-----
Adapted from
<https://github.c... | ac9429bef0b8d3f67d2acea2d74ac54ef055be81 | 71,191 |
def checkHistColumn(existingColNames):
"""
Check for the Histogram column in the attribute table. Return
its column number, and raise an exception if it is not present
"""
histColNdx = -1
for i in range(len(existingColNames)):
if existingColNames[i] == 'Histogram':
histColNdx... | 345311332f5522341b54670c1d626fd970b58b38 | 71,192 |
def esm1_t34_670M_UR50D():
"""34 layer transformer model with 670M params, trained on Uniref50 Dense.
Returns a tuple of (Model, Alphabet).
"""
return load_model_and_alphabet_hub("esm1_t34_670M_UR50D") | 451ad13716c147db3e53cdc74d6400290ff36e58 | 71,194 |
def remove_db_connection(profile_id, connection_id, web_session=None):
"""remove a db_connection by disassociating the connection from a profile
Args:
profile_id (int): The id of the profile
connection_id (int): The connection id to remove
web_session (object): The webserver session obj... | 64e42f5f96faa6b1883d19b0feb009ed89ed2497 | 71,195 |
def generate_model(**kwargs):
"""
Get ResNet3D with GloreUnit neural network.
"""
model = ResNet3D(Bottleneck, [3, 4, 6, 3], [64, 128, 256, 512], **kwargs)
return model | fd21e2346caaf5e82e7ef3d2814b5c8672bcea98 | 71,196 |
def cache_predict(smiles, model):
"""
use cache data for the same smiles
"""
mol = Chem.MolFromSmiles(smiles)
graphs = mol2dgl_single([mol])
test_bg = dgl.batch(graphs)
test_bg.set_e_initializer(dgl.init.zero_initializer)
test_bg.set_n_initializer(dgl.init.zero_initializer)
hidden = ... | 6b00a974b8a5dd8062c256404e1bf4953a98444e | 71,197 |
def makeItemList(pymarcResults, lib, lCode):
"""input: pymarc. return: list of config'd marc fields"""
lItem = []
try:#Extract the fields we want from the result set. Some fields we want may be unavailable
for r in pymarcResults:
lItem = []
lItem.append(lib)#the library sym... | a3de6fcc290cf8e60594113c4322f8781e39b218 | 71,199 |
def kinetic_local(omega_par, disp_vector, passive_el, ind_passive, coord, connect, E, v, rho, const_func):
""" Calculates the local kinetic energy function.
Args:
omega_par (:obj:`float`): 2 * pi * frequency.
disp_vector (:obj:`numpy.array`): Displacement.
passive_el (:obj:`numpy.array`... | d62f8ae304e82086cfd17136304e4844154ec337 | 71,200 |
def is_new_dbinit_notification(init_id, echoed_init_id):
"""Returns True if we have a received a new db initialisation notification
from a peer unit and we have not previously echoed it to indicate that we
have already performed the necessary actions as result.
Initialisation notification is expected t... | 3ff60ca786dd9e23e278d2e34d4e20f3e7b20985 | 71,201 |
def handle_NameError(exc, source):
"""Handles situation where a NameError is raise."""
_ = gettext_lang.lang
msg = exc.args[0]
var_name = msg.split("'")[1]
exc_name = exc.__class__.__name__
python_display = "{exc_name}: {msg}".format(exc_name=exc_name, msg=msg)
filename, linenumber = extrac... | 88a8026c206cebe6837f8aee7f345d1dc640e4e1 | 71,202 |
def logout():
"""Clear the current session, including the stored user id."""
logout_user()
return redirect(url_for("index")) | 0236e48025bf74eec9c56ee064d6dac985d9db59 | 71,203 |
import json
def get_dataframe():
"""Retrieve the dataframe from Redis
This dataframe is periodically updated through the redis task
"""
jsonified_df = redis_instance.hget(
tasks.REDIS_HASH_NAME, tasks.REDIS_KEYS["DATASETUP"]
).decode("utf-8")
# df = pd.DataFrame(json.loads(jsonified_df... | 465fcc3ece46428efa9e79b56dbd7a2fdd9f7bdd | 71,204 |
def pokemon_media_path(pokemon_species, prefix, ext, form=None):
"""Returns a path to a Pokémon media file.
form is not None if the form should be in the filename; it should be False
if the form should be ignored, e.g. for footprints.
"""
# Leave it as None if it's null; pass it by filename_from_n... | 7dd88cddaa0a6c158bf99dcfff9e82d26d7d2769 | 71,205 |
def option_select(prompt="", choices=None):
""" Bullet option select utility. """
return ScrollBar(
prompt=prompt,
choices=choices,
margin=2,
pointer="→"
).launch() | bceb101afdcc6332fd96911b4810feaf9093ae1b | 71,207 |
def dist_12x24(var_series, aggregation_method='mean', var_name_label=None, return_data=False):
"""
Accepts a variable series and returns a plot of 12x24 (12 months x 24 hours) for the 'mean' of the variable with
the table of data as an optional return. The aggregation_method 'mean' can be can be changed as ... | d4e7a79fe84ea9beb0139a8aabc0eecbc55b8b60 | 71,208 |
def mixer_l32_224(pretrained=False, **kwargs):
""" Mixer-L/32 224x224.
Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601
"""
model_args = dict(patch_size=32, num_blocks=24, embed_dim=1024, **kwargs)
model = _create_mixer('mixer_l32_224', pretrained=pretrained... | 009fdca7e1c1ddf743b42cdeb26866cec4a68b5e | 71,209 |
def projector(data, cube, mask=None, obstacle=None, nthread=0):
"""
Project a cubic map into a data cube using the Siddon algorithm.
The data cube is updated in-place, so you should make a copy before
calling projector.
Arguments
---------
data : 3d InfoArray
Contains a concatenation ... | b2a14ad97688451b53771296a0fcbec9194b5cf3 | 71,210 |
def parser_add_args_from_para(parser, para, usage):
"""Take the next Para as Lines of Args, if tagged as Positional Arguments"""
if para[0].startswith("positional arguments"):
for line in textwrap_para_unbreakdent_lines(para=para[1:]):
parser_add_arg_line(parser, usage=usage, line=line)
... | d6b4f1ac20b2e8f24daab069b4071e952c694ad0 | 71,211 |
def getDERIP(tracker,ID="deRIPseq",deGAP=True):
"""Write tracker object to sequence string.
Requires that all base values are strings."""
deRIPstr = ''.join([y.base for y in sorted(tracker.values(), key = lambda x: (x[0]))])
if deGAP:
deRIPstr = deRIPstr.replace("-", "")
deRIPseq = SeqRecord(Seq(deRIPstr, Gap... | 714ba32c38e363289d38f587285d22d1ede8a862 | 71,213 |
def part_b(data, **_) -> int:
"""
Solution for part b
Parameters
----------
data: str
Returns
-------
answer: int
"""
memory = {}
mask = None
for row in data.split('\n'):
if row.startswith('mask'):
mask = row.split(' = ')[1]
else:
... | f662862c001b9fc7c882b014915a4efc47d510a1 | 71,214 |
from typing import List
def get_worker_files(paths: List[str], env: CylonEnv, ext: str = None) -> List[str]:
"""
calculate the list of files that this worker will read
"""
all_files = get_files(paths=paths, ext=ext)
start, end = indices_per_worker(len(all_files), env.rank, env.world_size)
retu... | b6670ad3930826708254747ae1f10b97b77d4da5 | 71,215 |
import requests
import json
def modify_snmp_template(auth, url, snmp_template, template_name= None, template_id = None):
"""
Function takes input of a dictionry containing the required key/value pair for the modification
of a snmp template.
:param auth:
:param url:
:param ssh_template: Human ... | d4061820b588d8d1f2a6d77aa815022f21329b05 | 71,216 |
from typing import Sequence
from typing import Optional
def nodes_to_attach_risk_to(
nodes: Sequence[NodeView], risky_node_keys: Optional[Sequence[str]],
) -> Sequence[NodeView]:
"""
a None risky_node_keys means 'mark all as risky'
a [] risky_node_keys means 'mark none as risky'.
"""
if risky_... | 9677a6f4fe212614090e247c1f8171bd713f393c | 71,218 |
def foeppl_np_inkl_null(var_x, grenze_a, potenz_n):
"""Numpy Funktion für die Föppl Klammer mit ((var_x-a)==0) = 0"""
return np.where((var_x - grenze_a) <= 0, 0, (var_x - grenze_a) ** potenz_n) | 8f751529451ad19fa5a6b0bccfb322f8c75c28f8 | 71,221 |
def getDeploymentSections(deploymentInfos, nodesInformation):
"""
Combine deployments to the same nodes into lists in order to save on connect/disconnect time
:param deploymentInfos: deployment infos
:type: :class:`~storm.thunder.configuration.DeploymentInfos`
:param nodesInformation: nodes informa... | 3630f5ca0d7237fd2bdc0ce80026922eae20718f | 71,222 |
def sorted_eigenvector_matrix(M, numpy=False, increase=False, eps=1e-14, **kwargs):
"""
returns a matrix whose columns are the normalized eigenvectors of M
:M: square matrix (entries are assumed to be numbers)
:numpy: use numyp instead of sympy
:increase: sort in increasing order (defa... | ab895873d91cf114e6eecb5fd484528790faaec3 | 71,223 |
def _get_query_seqs(count_start, ref, ref_complement, srna_length):
"""
Get to correct length fwd and rvs query seq from the ref
:param count_start:
:param ref:
:param ref_complement:
:param srna_length:
:return:
"""
query_seq_fwd = DNA(ref[count_start:(count_start + srna_length)])
... | 27ec71b3ad0735ac792b77cb59f7b6a0b16ca436 | 71,224 |
import collections
def convert_examples_to_features(examples, tokenizer, max_seq_length,
doc_stride, max_query_length, is_training):
"""Loads a data file into a list of `InputBatch`s."""
unique_id = 1000000000
features = []
for (example_index, example) in enumerate(e... | 9cd255efd8daa611c9cccb6f33c39fe77c27f829 | 71,225 |
def find_val_percent(minval, maxval, x):
"""Find the percentage of a value, x, between a min and max number.
minval -- The low number of the range.
maxval -- The high number of the range.
x -- A value between the min and max value."""
if not minval < x < maxval:
print("\n" + " ERROR: X mu... | 13661bb2b6b230fa212ddd3ceb96c5b362d52f19 | 71,226 |
def class_delete():
"""
删除班级信息
:return:
"""
res = ResMsg()
obj = request.json
n_class = db.session.query(Class).filter(Class.id == obj["id"]).first()
n_stu_cls = db.session.query(StuCls).filter(StuCls.class_id == obj["id"]).all()
try:
db.session.delete(n_class)
db.ses... | fd247e9c2dd162b915ea9dab24ce942c1042af7d | 71,227 |
import json
def specific_area(region):
""" Shows the total number of COVID-19 positive test cases in specific \"region\""""
string = region.lower()
datas = json.loads(date_function.regional_data)
return datas.get(string,'The region name doesn\'t exist') | bef2a0dbf31cd82619fb36aa65a905244bd2e9f1 | 71,228 |
def ver_datos_basicos(request, extension_aulica_id):
"""
Visualización de los datos básicos de un extension_aulica.
"""
extension_aulica = __get_extension_aulica(request, extension_aulica_id)
try:
codigo = Establecimiento.get_parts_from_cue(extension_aulica.cue)['codigo_tipo_unidad_ed... | 303bf80b1a08102aad3a702ab4ec556885bf96f3 | 71,229 |
def name(who):
"""Return the name of player WHO, for player numbered 0 or 1."""
if who == 0:
return 'Player 0'
elif who == 1:
return 'Player 1'
else:
return 'An unknown player' | a553b64c7a03760e974b5ddeac170105dd5b8edd | 71,230 |
import requests
def jyfm_data_soybean_oil(indicator="豆油年度产能", headers=""):
"""
交易法门-数据-农产品-豆油
:param indicator: ["豆油年度产能", "压榨装置开工率", "油厂周度产量", "豆油现货成交",
"豆油商业库存", "豆油毛利润", "豆油月度产量", "豆油月度进口", "豆油月度消费", "豆油月度出口", "豆油月度库存"]
:type indicator: str
:param headers: headers with cookies
:type hea... | b321569aa34351c7f94dfe9d697e67c221278663 | 71,232 |
def segment(*args, **kwargs):
"""
Segment the map
"""
if len(args) > 0 and type(args[0]) == "str" or "input_map_filename" in kwargs:
func = mapfile_segment
else:
func = array_segment
return func(*args, **kwargs) | 0f1e3eca39a335031dcd6920f5c691086a1528db | 71,233 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.