content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
import pytz
def date_to_milliseconds(date_str):
"""Convert UTC date to milliseconds
If using offset strings add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/
:param date_str: date in r... | 2d9d4142627f10a8691280f10ead852ce5b1d2ee | 3,616,234 |
import re
def InstanceNameRegexpValidator():
"""Returns a function that validates an instance name using predefined rules.
Returns:
function: str -> str, usable as an argparse type
"""
# : and . are not valid characters, but we allow them through this regex so
# that we can give a better error message... | 57b8004a4023bb5011f1ecabb8658785c396cead | 3,616,236 |
def segmentation_metrics_blend(
isolated_images, detected_segmentations, matches, noise_threshold, meas_band_num
):
"""Calculates segmentation metrics given information from a single blend.
The true segmentation is obtained from the isolated images by setting to True
the pixels above the noise_threshol... | 8993780ab0d1c170bfc369d96cdc38f0b14ac087 | 3,616,237 |
def convert_RGB_to_OD(I):
"""
Convert from RGB to optical density (OD_RGB) space.
RGB = 255 * exp(-1*OD_RGB).
:param I: Image RGB uint8.
:return: Optical denisty RGB image.
"""
mask = (I == 0)
I[mask] = 1
return np.maximum(-1 * np.log(I / 255), 1e-6) | 5e22600f1985aebe10a2472fb98f664facbd0f0a | 3,616,238 |
def delete_profession(profession_id):
"""delete_profession
Delete profession # noqa: E501
:rtype: Response
"""
# Remove evidences of this profession
evidences = DBEvidence.query.filter(DBEvidence.evidence_profession == profession_id).all()
for evidence in evidences:
delete_evidenc... | 9195220969d759d57f5f4412b1772b51f205b7ee | 3,616,239 |
def process_remaining_mult_cases(chrom, positions, strand, edge_IDs, vertex_IDs,
transcript_dict, gene_starts, gene_ends, edge_dict,
locations, vertex_2_gene, run_info, cursor, tmp_gene):
""" This function is a catch-all for multiexonic transcripts t... | b1afa70df1f3e1836c6a05bd6b85d97c21f656fb | 3,616,240 |
def read_xlsx(filename: str, rows_count: int):
"""Читает документ xlsx и записывает данные в глобальную переменную названия телеграм каналов, локации и ссылки"""
tg = []
worksheet = xlrd.open_workbook(filename, on_demand=True).sheet_by_index(0)
for i in range(rows_count):
tg.append({'name': work... | 2ff498b9f942d0f91c8a4d4a679dcdfa9e4c0e3c | 3,616,241 |
def HammerProj( lonlat, lon0=0.0 ):
"""Takes a point at the (longitude, latitude) point in lonlat (arg 1,
in radians) and returns the (x,y) coordinates of the Hammer
projection of that point. lon0 is the central longitude for the
projection process (in radians). The x coordinate is in the range
[-2*... | 262623305e0ee794259446ecc5d470c39efd01ec | 3,616,242 |
def confusion_matrix_to_accuracy(conf_mat):
"""
Convert confusion matrix to accuracy
Parameters
conf_mat: np.ndarray | pd.DataFrame: confusion matrix, length of columns and that of rows must be same.
Returns
accuracy: float64: accuracy
"""
if type(conf_mat) is pd.DataFrame:
... | 2acb8bd8e2301b5f56c3371671a1ccb7c36848eb | 3,616,243 |
import shutil
def make_valid_param_card(path, restrictpath, outputpath=None):
""" modify the current param_card such that it agrees with the restriction"""
if not outputpath:
outputpath = path
cardrule = ParamCardRule()
cardrule.load_rule(restrictpath)
try :
cardrule.... | 1c2111eacaa8afb1748581e7ceb3d25724c849b2 | 3,616,244 |
import socket
from contextlib import closing
from typing import Generator
from typing import Any
import time
def multidevice_test_context(server_configuration: dict) -> Generator[MultiDeviceTestContext, None, None]:
"""Get generator for MultiDeviceTestContext."""
def _get_port() -> int:
with closing... | c6b1eb644133b8ed927729269fab45851495ab94 | 3,616,245 |
from typing import Optional
from typing import Any
def deeplabv3_mobilenet_v2(
pretrained: bool = False,
progress: bool = True,
num_classes: int = 21,
aux_loss: Optional[bool] = None,
**kwargs: Any
) -> nn.Module:
"""Constructs a DeepLabV3 model with a MobileNetV2 backbone.
Args:
... | 5a1dc413c3754d7b80aff584a7442ebd4af49564 | 3,616,246 |
import requests
def fetch_minion_pool() -> dict:
""" Fetch a new minion pool """
minions = [
minion
for minion in requests.get(settings.CARD_DB_ENDPOINT).json()
if minion.get("battlegroundsPremiumDbfId")
]
pool = defaultdict(list)
for minion in minions:
pool[minion.... | 92539fc27f3c55058be72c00e4b37498fd306d64 | 3,616,250 |
def API_StackDriver(config, auth, iterate=False):
"""StackDriver helper configuration for Google API.
Defines agreed upon version.
"""
api = {
'api': 'logging',
'version': 'v2',
'auth': auth,
'iterate': iterate
}
return API(config, api) | 1c7125dddf7e822b60082f755e0af6cfea3486bd | 3,616,253 |
def con_K(x, y, beta, method='cdist', return_d=False):
"""con_K constructs the kernel K, where K(i, j) = k(x, y) = exp(-beta * ||x - y||^2).
Arguments
---------
x: :class:`~numpy.ndarray`
Original training data points.
y: :class:`~numpy.ndarray`
Control points used t... | 6f608bb7958b5756456d3c6cf3d4b3223ec1aea5 | 3,616,255 |
import torch
def gin_predictor_nasbench_nlp(search_space,
num_init=10,
k=10,
total_queries=150,
acq_opt_type='mutation',
allow_isomorphisms=False,
... | 8025f8ec847531ef75213233d3f0df89c0db572f | 3,616,256 |
def main(request: Request):
"""
Responds to an HTTP request.
Parameters:
----------
request (flask.Request):
HTTP request object.
"""
a.generate()
return jsonify({"sucess": True}) | eeb2317faeafcb141844c2a0ef2e0d20963bdc73 | 3,616,257 |
def manage(request):
""" All-encompassing view for management stuff """
assert isinstance(request, HttpRequest)
return render(
request,
'app/manage.html',
{
'title':'Dashboard',
}
) | b5bf4b86c58d21b29ea6c81d105dcc05f0a0c9e5 | 3,616,258 |
def accuracy_score(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Accuracy classification score.
Args:
y_true (np.ndarray): correct target values.
y_pred (np.ndarray): estimated targets as returned by a classifier.
Returns:
float: proportion of correctly classified samples.
... | 24d5d6a113896d5c243ae492323c4d425179a8ec | 3,616,259 |
def setup_logging_server():
""" Gets a testing server ready to go
and returns the port being used"""
port_to_try = 5000
# Try to get an open port 32 times
for _ in range(0, 32):
try:
server = LoggingHTTPServer(('', port_to_try), UpdatingWebsite)
return server
... | 225a436ab95bb1ec4706a59020e67d8807a77d21 | 3,616,260 |
from typing import List
from typing import Tuple
def make_source_and_target_plates(target_df_list: List[pd.DataFrame],
max_volume_ul: float = MAX_WORKING_VOLUME_UL
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Generates optimized source and target pla... | d123584e9f4737809c77beb355c2dcd16f444b04 | 3,616,261 |
def path_along_circles(
arc_angle: float, circles_centers: np.ndarray, axis: np.ndarray = OUT
) -> PATH_FUNC_TYPE:
"""This function transforms each point by moving it roughly along a circle, each with its own specified center.
The path may be seen as each point smoothly changing its orbit from its starting... | 885e2e3770f9bc2e53d2062a43fe404cb192b529 | 3,616,262 |
def svn_wc_create_notify_url(*args):
"""svn_wc_create_notify_url(char url, svn_wc_notify_action_t action, apr_pool_t pool) -> svn_wc_notify_t"""
return apply(_wc.svn_wc_create_notify_url, args) | 36a42320c94f29516cdc401a9f0e0e35d477cd60 | 3,616,263 |
def make_model(n_size, n_output):
"""Create Keras model."""
model = Sequential()
model.add(LSTM(n_size))
model.add(Dense(n_output))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
ret... | 5c1c4bbc71f5b3fee81e7b3150c6277eb56c08c8 | 3,616,264 |
def humanize_seconds(total_seconds,
frmt='{hours:02d}:{minutes:02d}:{seconds:02d}',
negative_frmt=None):
"""Given time in int(seconds), return a string representing the time.
If negative_frmt is not given, a negative sign is prepended to frmt
and the result is wrap... | 86b58fe361382671f744529c676cc6cd16c877a6 | 3,616,265 |
def joint_residual(params, args):
"""
Residual for joint_fit
Input:
param_dict - suggested parameters of the functions Sigma and eta to be fit
args - arguments which remain fixed (e.g. r values)
Output:
residual - residual of the fit for the given parameters
"""
rA, Sigma... | 12b4ba12dad0ab8f97e721b73dede80987c2caab | 3,616,266 |
def _batch_gather(params, indices, axis, batch_dims):
"""Helper that implements the body for ragged gather() when batch_dims>0.
Args:
params: The tensor from which to gather values.
indices: The indices of values to gather.
axis: The axis in `params` to gather `indices` from.
batch_dims: The number... | a7a73514ce7382fd67e0471792a27bc6e4502819 | 3,616,267 |
import typing
import re
def search(pattern: typing.Union[str, int],
**kwargs):
"""Compare value to pattern using search."""
value = kwargs.pop('value')
# type adaptation only if value is int
if isinstance(value, int):
value = type(pattern)(value)
if config.TYPE_CHECK_LEVEL > 0... | e6989b053da4960f9cfb29fd4b0d21e8c2d31855 | 3,616,268 |
def get_base_info_for_selector(selection_dict, selector_type):
"""
Sets up the basic dictionary for data filters to be added on the data
:param selection_dict:
:param selector_type:
:return:
"""
base_info_dict_for_selector = {
OPTION_TYPE: selector_type,
COLUMN_NAME: selectio... | c08fc9a95517c3388da69e3f9935c255ce0d73c6 | 3,616,269 |
def make_datasets(dataset, train_batch=None, test_batch=None, train_transforms=None, test_transforms=None, num_workers=1, **custom_args):
""" Helper to make new instances of training and testing datasets.
Args:
dataset Case-sensitive dataset name
train_batch Training batch size, None or 0 for ... | 5c2090b9cbfb52c4cdb42f632dfe883c21465e9b | 3,616,270 |
def get_sentiment_by_id(sentiment_id):
"""
Returns the sentiment with given id
:param: sentiment_id
ID of the sentiment
:returns:
Sentiment with given ID
"""
sentiments = []
cursor = current_app.mongo.keywords.find({"request_id": sentiment_id})
for record in list(cursor... | 38fab08784267498fa09e1de35cd286c4a03f786 | 3,616,271 |
def clean_software_config(config):
"""Take an individual `config` data structure (as specified by
config_validation.SoftwareSchema) and return a 'clean' version suitable for
internal use. This allows for a simplified schema to be available to users
whilst preserving consistent internal data structures b... | c89ad5a4b61e4214d4b79ce6782e4fe5a86311bf | 3,616,272 |
def distance_A(A, D):
"""Takes distance matrix D and material attribute/category
matrix A and finds the sum of the pairwise distances of
each entry compared to D. This function should be used
in an optimizer to generate an optimal A matrix.
Implements first term of Equation 4
Parameters:
D... | dd896e36565a8daf5951fac3ceb29594c70707bb | 3,616,273 |
def get_word_by_name(name):
"""Get word detail by name
As title
---
tags: [word]
parameters:
- name: name
description: 单词名字
in: path
type: string
required: true
responses:
200:
description: Word matched.
schema:
$ref: '#/defin... | d76eacc085d24f6c71ffe8ced3fe55f0933ff153 | 3,616,274 |
def group_peaks_naive_1pass_centroid(df, ppmtol=1.0):
"""Compute groups of peaks, naive, one-pass, control distance to centroid ."""
# compute group indexes
glabel = 0
start = 0
glabels = [0]
reltol = ppmtol * 1.0e-6
m1 = df.loc[0, 'm/z']
samples = [df.loc[0, '_sample']]
masse... | 055f69644dc12d28fc6c477d497f2f32b6a8a593 | 3,616,275 |
import time
def run_firfilter(no_trick, duration=0.000001):
"""[summary]
Arguments:
no_trick ([type]): [description]
Keyword Arguments:
duration (float): [description] (default: {0.000001})
Raises:
Exception: [description]
"""
h0 = np.zeros(n) # initial x0
E = e... | fc2a223ce85113f8f8514cbae7e6688744b30214 | 3,616,276 |
def cdfinv_r(fName=None,pdf=None):
"""
Calculates the inverse of the cumulative distribution function for
probability as a function of r.
*** Arguments ***
* fName * File name for retrieving sigma(r). If None, the user must
define a function to calculate the inverse CDF. Otherw... | 498a2960cbede769eac396130ec5e306a0978bf3 | 3,616,277 |
def _base_down(x, base=10):
"""
Floor `x` to the nearest lower ``base^n``, where ``n`` is an integer.
Parameters
----------
x : float
Number to calculate the floor from.
base : float, optional
Base used to calculate the floor.
Return
------
float
The nearest... | 0489809838c9377b4114c751db34a4a81941ae57 | 3,616,278 |
def get_periodic_frame():
"""
Construct a simple periodic table dataframe organised by group and row. Note that
the lanthanides and actinides are each found in a single cell.
Returns
-------
:class:`pandas.DataFrame`
"""
table = pd.DataFrame(columns=np.arange(1, 19), index=np.arange(1,... | b5db8f2a0373c19fcea7ab0fe78cb8a4b7f0ade8 | 3,616,279 |
def miller_rabin_d(n: int) -> bool:
"""Check if n is a prime number via deterministic Miller-Rabin test.
Miller showed that it is possible to make the algorithm deterministic by
only checking all bases ≤ O(lg(n)^2). Bach later gave a concrete bound, it
is only necessary to test all bases a ≤ 2lg(n)^... | ac668cb55e417a6784ba52d1c5da1dc26d3693ad | 3,616,280 |
def get_path_upload_avatar(instance, file):
"""Построение пути к файлу, format: (media)/avatar/user_id/photo.jpg"""
return f"avatar/user_{instance.id}/{file}" | d3169d68e4abee31ee9649548892c2dc960717cc | 3,616,281 |
def is_category_url(url, ignore_exceptions=False):
"""This function identifies if a provided URL is for a category in the environment.
.. versionadded:: 2.1.0
:param url: The URL to be evaluated
:type url: str
:param ignore_exceptions: Determines if exceptions should not be raised
:type ignore... | 53127f4eaa23d5c8029ab0e6783be026d6a7328e | 3,616,282 |
import re
def maximum_time(time: str) -> str:
"""
Takes in a time with a single digit of either the hour part or minute part hidden with ?. The format of the time
is hh:mm. This returns the maximum possible time from the given input.
@param time: time of format hh:mm with a single digit of either the ... | 9bef83c27e7911c67172dbe41ca616c5adda1b17 | 3,616,283 |
def get_fd(file_or_fd, default=None):
"""Helper function for getting a file descriptor."""
fd = file_or_fd
if fd is None:
fd = default
if hasattr(fd, "fileno"):
fd = fd.fileno()
return fd | 7e8a5b91d010878bcc091fa9ef3b281431e34e19 | 3,616,284 |
from typing import List
from typing import Callable
def evaluate_predictions(preds: List[List[float]],
targets: List[List[float]],
metric_func: Callable) -> List[float]:
"""
Evaluates predictions using a metric function and filtering out invalid targets.
... | 7b7f550a0983cbb8af90f13b214a195cdb8cbfe3 | 3,616,285 |
def recommend_size(args, img):
""" Recommend size (in pixels) for populated image to reach 300 dpi"""
current_ppi = 72.0/img.scale
target_ppi = args.normal_ppi
scale = target_ppi/current_ppi
return (int(img.image.width*scale), int(img.image.height*scale)) | b32a0520586984124ba2134dc99ecc0b71cd01df | 3,616,286 |
def retain_top_pct(vals, pct_keep):
"""
Retain as many components as you need to capture `pct_keep` proportion
of the overall value
"""
if pct_keep > 1 or pct_keep <= 0:
raise ValueError(
"Must set pct_keep between 0 and 1 be when using "
"'retain_top_pct' retention ... | 6530550c8c31a708806e035196a59cb76010221b | 3,616,287 |
def test_curve_plot():
"""
Tests mpl image of curve.
"""
well = Well.from_las(FNAME)
fig = well.data['GR'].plot(return_fig=True)
return fig | 077ad46ea7012f032d85ebe92b9e9633b7228535 | 3,616,288 |
from pgdumplib import dump
def new(dbname: str = 'pgdumplib', encoding: str = 'UTF8',
converter=None):
"""Create a new :py:class:`pgdumplib.dump.Dump` instance
:param str dbname: The database name for the dump (Default: ``pgdumplib``)
:param str encoding: The data encoding (Default: ``UTF8``)
... | c41cffcc961b7a273bf9b7402af7a22401a738db | 3,616,289 |
def audio(sec=3):
""" Record audio for a given duration """
display(Javascript(RECORD_AUDIO))
s = output.eval_js('record(%d)' % (sec*1000))
b = b64decode(s.split(',')[1])
return Audio(b) | c4b6c43aa75a44a785b9f920e5e276a3d318847a | 3,616,290 |
def isinstalled(name: str,
lib_loc=None):
"""
Find whether an R package is installed
:param name: name of an R package
:param lib_loc: specific location for the R library (default: None)
:rtype: a :class:`bool`
"""
instapack = InstalledPackages(lib_loc)
return instapack... | a05dce14c5280aa96113933bf9dfd0141ffd2d5b | 3,616,294 |
import math
def create_experiment(run_config,
hparams,
model_name,
problem_name,
data_dir,
train_steps,
eval_steps,
min_eval_frequency=2000,
s... | 31cbb1ba9948af5a3e84e864271e0888f4fdf448 | 3,616,295 |
def quit_hermit():
"""usage: quit
Exit Hermit.
"""
clear_screen()
return True | 1b27fdcb6a1fe69541f5f388e05e70b3731a5239 | 3,616,296 |
from typing import Union
def flatten(x: Union[list, tuple]) -> list:
"""
Flattening function for nested lists and tuples
Args:
x: List or tuple
Returns:
object (list): Flat list
"""
if not isinstance(x, list) and isinstance(x, tuple):
raise TypeError("input must be a ... | 36c35dfbef4214ccf0f6d355f36865996fd6d88e | 3,616,297 |
from typing import Mapping
def update_nested(original_dict, update_dict):
"""Update a nested dictionary with another nested dictionary.
Has equivalent behaviour to :obj:`dict.update(self, update_dict)`.
Args:
original_dict (dict): The original dictionary to update.
update_dict (dict): The... | a1a372ac4d26066c3fe32cd4ee1a49fff6972cd9 | 3,616,298 |
def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001,
num_epochs = 1500, minibatch_size = 32, print_cost = True):
"""
Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.
Arguments:
X_train -- training set, of shape (input size = 1... | c45624090d044dcafaa254f8fb3c5a5340c3efaf | 3,616,299 |
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3):
"""
Compute c_v coherence for various number of topics
Parameters:
----------
dictionary : Gensim dictionary
corpus : Gensim corpus
texts : List of input texts
limit : Max num of topics
Returns:
--... | bcbf01aca76aea445e74ddbda9cf3facd8c44dd2 | 3,616,301 |
def on_launch(launch_request, session):
""" Called when the user launches the skill without specifying what they want
"""
print("on_launch requestId=" + launch_request['requestId'] + ", sessionId=" + session['sessionId'])
# Dispatch to your skill's launch
return get_welcome_response() | 9d0cd9c03b06e8b77dd702b80a7e217f1c4d2a68 | 3,616,302 |
def remove_comment(line):
"""Remove trailing comments from one line."""
start = 0
while True:
loc = line.find('#', start)
if loc == -1:
return line.replace('\\#', '#')
elif not (loc and line[loc - 1] == '\\'):
return line[:loc].replace('\\#', '#')
star... | e2ab53813efd17e00240f747709330c44c875235 | 3,616,303 |
import ee
def GEEsmos(ptsFile,metric,timeStep,buf,poly,username,folderOut, scalePix = 25000,startYear = None,endYear = None):
"""
Calculates soil moisture at point OR mean within buffer of point if buf > 0 OR mean within polygon if poly = 1
Requires:
ptsfile - file name of uploaded shapefile... | 405641924be284e924285e872dd795beb9932df8 | 3,616,304 |
def sphinx_license(opts):
"""
Template of license.rst
:param opts: mapping parameters as dictionary
:return: file content as string
"""
template = get_template("sphinx_license")
return template.substitute(opts) | b12a177497fd7b857dce04e9a59c9ccca39cb9ed | 3,616,305 |
def entailment_internalization(df):
"""
new_ p = ''
new_h = 'p implies that h' (1,0)
new_h = 'p and h' (-1)
"""
contra_combine = " , "
not_contra_combine = " implies that "
df_not_contra = df.query("label!='contradiction'").copy()
df_contra = df.query("label=='contradiction'").copy()... | 502613bc15a7764e5ee9643c500ec3ada8ab5c45 | 3,616,306 |
def tcl_findprd_prepdict(prddict):
"""
Prepare dict of center:[ends] entries.
:param prddict: Device:PRD dictionary.
:type prddict: dict(str: list)
"""
prda = tcl_findprd_prepd_start(prddict)
prdx = tcl_findprd_prepd_middle(prda)
prdfinal = tcl_findprd_prepd_end(prdx)
return prdfina... | 9da3dfab8f44166cb353cf667ff51c2256755b78 | 3,616,307 |
def create_nn_cat(input_dim, nr_units, nr_layers, nr_classes):
"""Compile NN model with categories as outputs"""
print('Compiling NN model with {0} layers, {1} units, input dimension {2}...'.format(nr_layers, nr_units, input_dim))
model = keras.models.Sequential()
model.add(keras.layers.Dense(nr_units, ... | 450fc1eb7c7c0d712da0fb803149b646970e5700 | 3,616,308 |
def augment(cls):
"""Add `time` to kwargs list."""
class New(cls):
@staticmethod
def _myfun(x, *args, time=0, **kwargs):
return super(New,New)._myfun(x)
return New | cf08f753ba3af3ff2d2c11ca24c5796d2b0a4c12 | 3,616,309 |
async def led(command: Command[JaegerActor], fps: FPS, level: int):
"""Sets the level of the FVC LED."""
fvc_ieb = FVC_IEB.create()
led = fvc_ieb.get_device("LED1")
raw_value = 32 * int(1023 * (level / 100))
await led.write(raw_value)
await command.send_command("jaeger", "fvc status")
re... | e3427b9175c079912cb48326da792bb325d776c9 | 3,616,310 |
def ReverseSequence(a, seq_lengths, seq_dim, batch_dim):
"""
Sequential reverse op.
"""
r = np.copy(a)
invidxs = (len(r.shape) - 1) * [slice(None)]
if seq_dim < batch_dim:
invidxs[seq_dim] = slice(None, None, -1)
else:
invidxs[seq_dim - 1] = slice(None, None, -1)
_invidxs... | ffac61cf7e793167033aff28dbfefc59e69580a0 | 3,616,311 |
def handle_none(func):
"""A decorator function to handle cases where partition values are `None` or "__HIVE_DEFAULT_PARTITION__"
Args:
func (Callable): A function registered to the singledispatch function `partition_to_py`
"""
def wrapper(primitive_type, value_str):
if value_str is Non... | 23db0c46a35f2e433735c4a863d5619bf4c3cc55 | 3,616,312 |
from datetime import datetime
def encode_dexcode(dexid: str, effort: int, due: datetime.datetime, importance: int, status: str, flags: list) -> str:
"""
Create a dexcode from python objects which are easy to work with.
Args:
dexid (str): The dex ID (single letter followed by a number).
ef... | cbed3d4840a8473b79345b9c38e861cf922a0424 | 3,616,315 |
def _to_kql(obj: ExpressionType, parentheses: bool = False) -> KQL:
"""
Convert the given expression to KQL. If this is a subexpression of a greater expression, neighboring operators might
take precedence over operators included in this expression, causing an incorrect evaluation order. This might not be a ... | c03f304183876dfb0c84f181afc3dffc6987c5e6 | 3,616,316 |
import torch
def sphere_mesh(n=512, radius=1.0, device="cpu"):
"""Return a unit sphere mesh discretization with *at least* n vertices.
Initially this returns a standard uv sphere but in the future we could
change it to return a more sophisticated discretization.
Code adapted from github.com/caos... | c691af3b7a89da0b142bc0e9a3ef271cf22d157a | 3,616,317 |
def asInteger(epsg):
""" convert EPSG code to integer """
return int(epsg) | 18a14944f5f29ec09585757f0edc912b896a12ba | 3,616,318 |
def monitor_cb(ud, msg):
"""Callback for the MonitorStates, listening to /click/start_button"""
# Return False when you want the MonitorState to terminate
return False | 34f5065aadf8ec96bbe0fb54b791f7a4385a55b5 | 3,616,319 |
def email_image_attribution(request, id=None, *args, **kwargs):
"""
GET request with an ID in the request that links to a notification ID (or other field),
and will mark that notification as having been opened.
"""
# mark the email
mark_email_as_read(id)
# create an image
img = Image.n... | be678affd751a7e0f09b4710d57a7e3d3e4a941e | 3,616,321 |
def angular_distance_fast(ra1, dec1, ra2, dec2):
"""
Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at
their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for
antipodes.
:param lo... | 16962f59775faa928d45d802a4b77a0bacb2df6d | 3,616,322 |
def resnet50(**kwargs):
"""
ResNet-50 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in ... | c8246e1f3302ed5be611a27fd3885d4a167e5197 | 3,616,323 |
def get_node_rb(graph, k=3, approx=np.inf):
"""
Get k nodes to defend based on Recalculated Betweenness (RB) Removal :cite:`holme2002attack`
:param graph: an undirected NetworkX graph
:param k: number of nodes to defend
:param approx: number of nodes to approximate the betweenness centrality, k=0.1... | 835353e8369f83e6fa7fe96b53f0c45c187ab7e2 | 3,616,324 |
def excluir_usuario():
""" Exclui um usuario com id especificado pela url """
try:
if current_user.is_administrator():
cod_id = request.args.get('id')
usuario = Usuario.query.filter_by(cod_usuario = cod_id).one()
db.session.delete(usuario)
db.session.commi... | 811016c34ebcc1450fa9679bb15ee336576f9334 | 3,616,325 |
def make_model():
"""
Generate the model used to make the saved test data.
"""
props = {'density': 1, 'magnetization': utils.ang2vec(1, 25, -10)}
return [Sphere(x=-100, y=200, z=500, radius=400, props=props)] | 9f7f366c8552b7079cb5201d059304de79aa4cb4 | 3,616,326 |
def metarthunter_parse(driver: webdriver.Firefox) -> tuple[list[str], int, str]:
"""Read the html for hetarthunter.com"""
# Parses the html of the site
soup = soupify(driver)
image_list = soup.find("ul", class_="list-justified2").find_all("a")
images = [image.get("href") for image in image_list]
... | 178db60ec8cee91505f6b6d8038788a44d52d3f8 | 3,616,329 |
def mag(initial, current):
"""
Calculates the magnification of a specified value
**Parameters**
intial: *float*
initial value (magnificiation of 1)
current: *float*
current value
**Returns**
magnification: *float*
the magnification of the current value
"""
... | abc8d3603f11e62f57a62c47dc372b4b9ea19b0c | 3,616,330 |
def conv2d(x, dim, stride=1, bn=True):
"""二维卷积
Args:
x ([type]): 输入数据
dim ([type]): 维度,一般为卷积核数量,一般为输出维度
stride (int, optional): 步长. Defaults to 1.
bn (bool, optional): 是否使用BN层. Defaults to True.
Returns:
[type]: slim.conv2d 默认pad模式是SAME ,卷积后的数据会变成和原来大小一样,比如n*m*w*h*c... | 38f4d9ce1bb64bc7aba01e07d28df1deb26c8579 | 3,616,331 |
def divergence(f):
"""Take the divergence of a vector array
Parameters
----------
f : np.ndarray
Vector array whose divergence should be taken.
Returns
-------
out : np.ndarray
Scalar array of divergence. Dimensionality one less
than the vector array.
"""
... | 3ce65111bd6815b6597b4cb7915acd3b8d0e6f88 | 3,616,332 |
import re
def capitalize(word):
"""Only capitalize the first letter of a word, even when written in
CamlCase.
Args:
word (str): Input string.
Returns:
str: Input string with first letter capitalized.
"""
return re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), word, 1) | 4f254696e00c24a85a20ea74fc66a32fceb541c6 | 3,616,333 |
from pathlib import Path
from re import T
from datetime import datetime
def read_ini(fn: Path) -> dict[str, T.Any]:
"""parse .ini file
DEPRECATED
"""
fn = find.config(fn)
with fn.open("rt") as f:
date = list(map(int, f.readline().split()[0].split(",")))[::-1]
sec = float(f.readli... | d26e4527a2eb1b12d6268da17252f9eb3424b564 | 3,616,334 |
import re
def cassandra_ddl_repr(data):
"""Generate a string representation of a map suitable for use in Cassandra DDL."""
if isinstance(data, str):
return "'" + re.sub(r"(?<!\\)'", "\\'", data) + "'"
elif isinstance(data, dict):
pairs = []
for k, v in data.items():
if ... | c81ad24c0185ef10646644b82399c202c2261a1a | 3,616,335 |
import json
import requests
def gconnect():
"""Handles the data sent by the google signin ajax"""
# First validate state token to protect from CSRF
if request.args.get('state') != login_session['state']:
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers... | d3a5c414345be246c17daf05368519f99ba27f9b | 3,616,336 |
import itertools
def primes_up_to(n, ps = None):
"""Prime numbers <= n."""
if ps is None: ps = mprimes()
return itertools.takewhile(lambda p: p <= n, ps) | 070dbd97d56583d5d7baa85467e442e1b01dcb7f | 3,616,338 |
def _IsNestedSet(field: descriptor.FieldDescriptor) -> bool:
"""If this is a nested field that translates to a set."""
return _IsNestedElement(field, Schema_pb2.ColumnInfo.TYPE_SET) | 4ae82bc9ccdb0c35b04135781f49119840300d0f | 3,616,341 |
def get_unit(coordinate):
"""
Get the `unit` identifier of **coordinate**, if **coordinate** has a valid
`unit` identifier appended, else returns `None`.
"""
if isinstance(coordinate, (int, float)):
return None
result = pattern.coordinate.match(coordinate)
if result:
return ... | 4e16a67acd4d480761a7523046642130054d6d93 | 3,616,342 |
def GetVnodeLocksSummary(vnode):
""" Internal function to get summary of advisory locks for the given vnode
params: vnode - value representing the vnode object
return: str - formatted output information for the summary of advisory locks
"""
out_str = ''
if vnode:
lockf_list =... | 353922932696cfc0e1cc4f48a78e4c90fea2d960 | 3,616,343 |
def pct_similarity(results, map_probes_to_genes_first=False, top=None):
""" Read each file in a list and return the percent overlap of their top genes.
See pct_similarity_matrix_raw for calculation details
:param results: a list of paths to tsv-formatted result files or a list of lists of probes for co... | 1f77b14171a35e9197ab2c35f798223c0d2fba17 | 3,616,344 |
def check_lights_opposite(light_a, light_b):
""" Checks if the two given lights are opposite to each other or not. """
def get_forward_vector(light):
light_vector = light.get_transform().get_forward_vector()
return [light_vector.x, light_vector.y, light_vector.z]
light_a_vector = get_forwar... | 5fb8befa1e366151c6447088c24c8218b32b4394 | 3,616,345 |
from pathlib import Path
def _make_ls5_scene_datasets(geotiffs, tmpdir):
"""
Create directory structures like::
LS5_TM_NBAR_P54_GANBAR01-002_090_084_01
|---scene01
| |----- report.txt
| |----- LS5_TM_NBAR_P54_GANBAR01-002_090_084_01_B10.tif
| |----- LS5_TM... | c4f4b217b621061eefc750475da5aa881ebc73e6 | 3,616,346 |
def rsc_bounds(rsc_data):
"""Uses the x/y and step data from a .rsc file to generate LatLonBox for .kml"""
north, south, east, west = rsc_nsew(rsc_data)
return {"north": north, "south": south, "east": east, "west": west} | acc149486f75bce102b0e509371eed815665a60d | 3,616,348 |
import tempfile
def build_dir():
"""Test build dir for the sphinx compiled docs."""
return tempfile.mkdtemp() | aef168b1031a9ebc15d502a3aedb89da004caffa | 3,616,349 |
def tag_edit(tag_id):
"""Edit Tag"""
tag = Tag.get_item_by_id(tag_id)
if tag is None:
abort(404)
else:
if request.method == "POST":
tag.name = request.form["name"]
tag.slug = request.form["slug"]
db.session.add(tag)
db.session.commit()
... | 365f99779d398e4269bed7e38f4ba259e49b56e2 | 3,616,351 |
def _get_project_title():
"""Get project title"""
title = None
puts("")
while not title:
title = raw_input("What is the project's full title? (e.g. My awesome project) ")
return title | 64c3c7c66d48a519ff6ecc274e5d01234987e6aa | 3,616,352 |
import csv
def read_csv_file(file_name):
"""
Given a CSV file, read the data into a nested list
Input: String corresponding to comma-separated CSV file
Output: Nested list consisting of the fields in the CSV file
"""
with open(file_name, newline='') as csv_file: # don't need to ... | 65f9d2edb9ecf020d773a8d8516f31247fa680ed | 3,616,354 |
def asymptomatic_duration_00():
"""
Real Name: b'asymptomatic duration 00'
Original Eqn: b'5'
Units: b'Day'
Limits: (None, None)
Type: constant
b''
"""
return 5 | 8c29fa4db3c950daf5e0fb1f4cfe3a2e98d32583 | 3,616,355 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.