content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _min(group_idx, a, size, fill_value, dtype=None):
"""Same as aggregate_numpy.py"""
dtype = minimum_dtype(fill_value, dtype or a.dtype)
dmax = np.iinfo(a.dtype).max if issubclass(a.dtype.type, np.integer)\
else np.finfo(a.dtype).max
ret = np.full(size, fill_value, dtype=dtype)
if fill_val... | a11d1e5bcf0c3aca81cdc6081fc0dfd186fa499e | 3,649,396 |
def find_word(ch, row, boggle_lst, used_positions_lst, current, ans):
"""
:param ch: int, index for each character in a row
:param row: int, index for each row in the boggle list
:param boggle_lst: list, list for all rows
:param used_positions_lst: tuple, index of ch and row that indicates the position of an used ... | c896c4b4ac7b6816d0d4a35135ea2c87891f214e | 3,649,397 |
def lazy_tt_ranks(tt):
"""Returns static TT-ranks of a TensorTrain if defined, and dynamic otherwise.
This operation returns a 1-D integer numpy array of TT-ranks if they are
available on the graph compilation stage and 1-D integer tensor of dynamic
TT-ranks otherwise.
Args:
tt: `TensorTrain` object.
... | 6792b269c9c27dc7ad83202b7920f44ae8ee3ff8 | 3,649,398 |
def word_errors(reference, hypothesis, ignore_case=False, delimiter=' '):
"""Compute the levenshtein distance between reference sequence and
hypothesis sequence in word-level.
:param reference: The reference sentence.
:type reference: str
:param hypothesis: The hypothesis sentence.
:type hypoth... | 11473b01bd222c4550403afb07303a14cd123720 | 3,649,399 |
def augment_note_matrix(nmat, length, shift):
"""Pitch shift a note matrix in R_base format."""
aug_nmat = nmat.copy()
aug_nmat[0: length, 1] += shift
return aug_nmat | a1ff855266e44012e05347a95abfa5324fd6e4e6 | 3,649,400 |
def breed_list(request):
""" Фикстура возвращает список всех пород собак """
return request.param | 29394d8a97444680acc3a0b7ff0f1b2949a5609d | 3,649,401 |
def norm_layer(norm_type, nc):
"""tbd"""
# normalization layer 1d
norm = norm_type.lower()
if norm == 'batch':
layer = batch_norm_1d(nc)
elif norm == 'layer':
layer = nn.LayerNorm(nc)
else:
raise NotImplementedError('normalization layer [%s] is not found' % norm)
retu... | 05207a65ca4afd551230b3b3f2e87bce58905b6d | 3,649,402 |
def tail(file, n=1, bs=1024):
""" Read Last n Lines of file
credit:
https://www.roytuts.com/read-last-n-lines-from-file-using-python/
https://github.com/roytuts/python/blob/master/read-lines-from-last/last_lines_file.py
"""
f = open(file)
f.seek(0, 2)
l = 1-f.read(1).count('\n')
B ... | db7443e4af1028565491cb06944717488506b2b7 | 3,649,404 |
import random
def create_hparams(state, FLAGS): # pylint: disable=invalid-name
"""Creates hyperparameters to pass into Ray config.
Different options depending on search or eval mode.
Args:
state: a string, 'train' or 'search'.
FLAGS: parsed command line flags.
Returns:
tf.hparams object.
"... | b61c4d21dbc232700d4eb50aadd0e4699ed43b96 | 3,649,405 |
def resources_match(resource_one, resource_two):
"""
Checks if resource_one and resource_two match. If two folders, recursively compares contents.
If two files, compares versions.
"""
if resource_one['type'] == FOLDER:
match = recursively_compare_folders(resource_one, resource_two)
else... | 824200e5a107b612981dab9c77e34386f191d8ab | 3,649,406 |
def read():
"""Read content of predefined numpy archive file."""
return _read(tml.value('numpy', section='data', subkey='fname')) | decee54289f532e6f5c385336b1a98536595139a | 3,649,407 |
def elexon_b1630(args):
""" Actual or forecast Wind & Solar Generation """
if not check_api_key(args):
return None
api = B1630(args.apikey)
if args.settlement_period is None:
print("A settlement period should be supplied using the --settlement-period flag (range 1 to 50)."
... | 151d2cd7aa44d90fd46e647d69131f6ac4b37270 | 3,649,408 |
def null_count(df):
"""
df is a dataframe
Check a dataframe for nulls and return the number of missing values.
"""
return df.isnull().sum().sum() | 6e3eb91a3eaec456bb828b44be0780b64470e823 | 3,649,409 |
def rpy2r(roll, pitch=None, yaw=None, *, unit="rad", order="zyx"):
"""
Create an SO(3) rotation matrix from roll-pitch-yaw angles
:param roll: roll angle
:type roll: float
:param pitch: pitch angle
:type pitch: float
:param yaw: yaw angle
:type yaw: float
:param unit: angular units:... | 2e9217396408452f54a663697d317a7fd7807c81 | 3,649,410 |
def plot3d_embeddings(dataset, embeddings, figure=None):
"""Plot sensor embedding in 3D space using mayavi.
Given the dataset and a sensor embedding matrix, each sensor is shown as
a sphere in the 3D space. Note that the shape of embedding matrix is
(num_sensors, 3) where num_sensors corresponds to the... | 49194f7ea6dee85dc84dd1c9047d21140a5e7a38 | 3,649,411 |
def geometry(cnf_save_fs, mod_thy_info, conf='sphere', hbond_cutoffs=None):
""" get the geometry
"""
assert conf in ('minimum', 'sphere')
# Read the file system
if conf == 'minimum':
geom = _min_energy_conformer(
cnf_save_fs, mod_thy_info, hbond_cutoffs=hbond_cutoffs)
elif ... | 9805baa4479ebcafa158b26ef4e19ea31109e8eb | 3,649,412 |
def exportToVtk(gridFunction, dataType, dataLabel, fileNamesBase, filesPath=None, type='ascii'):
"""
Export a grid function to a VTK file.
*Parameters:*
- gridFunction (GridFunction)
The grid function to be exported.
- dataType ('cell_data' or 'vertex_data')
Determines w... | 04efb88c7870ec46d793bb6bbdd40b7ef70ae8ce | 3,649,413 |
def get_fullname(user):
""" Get from database fullname for user
"""
data = frappe.db.sql("""
SELECT full_name FROM `tabUser` WHERE name=%s and docstatus<2""", user, True)
return data | 51d8c0115964cc3159340e2fdc1356d922bc5ae0 | 3,649,414 |
def greedy_inference(original, protein_column = 'Protein Accession', peptide_column = 'Base Sequence'):
"""
Greedy protein inference algorithm for matching peptids to corresponding proteins
Notaion:
G : original graph
Gi : inferred graph
Gr : remaining graph
Gd: dropped graph
p : greedi... | aa43950c859bcac0371ce4e845c26bdb13182897 | 3,649,415 |
import requests
def deploy_droplet(token):
"""
deploy a new droplet. return the droplet infos so that it can be used to
further provision.
"""
droplet_info = {
'name': 'marian',
'region': 'sfo2',
'size': '4gb',
'image': 'ubuntu-18-04-x64',
'ssh_keys[]': get... | 34d9fa31f686936a1c0abb4b5eafcb8eaaac1b11 | 3,649,416 |
from typing import Dict
from typing import Any
def _convert_run_describer_v1_like_dict_to_v0_like_dict(
new_desc_dict: Dict[str, Any]) -> Dict[str, Any]:
"""
This function takes the given dict which is expected to be
representation of `RunDescriber` with `InterDependencies_` (underscore!)
obje... | b5d4126f0b480a90323df24dda1d7ecb0c84d712 | 3,649,417 |
from io import StringIO
import textwrap
def download_sequences(request):
"""Download the selected and/or user uploaded protein sequences."""
selected_values = request.session.get("list_names", [])
list_nterminal = request.session.get("list_nterminal", [])
list_middle = request.session.get("list_middl... | a5f063d4323290b939ccb635f0db175f6fe48ce0 | 3,649,419 |
def resize_to_fill(image, size):
"""
Resize down and crop image to fill the given dimensions. Most suitable for thumbnails.
(The final image will match the requested size, unless one or the other dimension is
already smaller than the target size)
"""
resized_image = resize_to_min(image, size)
... | 977b9a1e84a0a2125aa60cea09e7d2bea520cccf | 3,649,420 |
def extract_dual_coef(num_classes, sv_ind_by_clf, sv_coef_by_clf, labels):
""" Construct dual coefficients array in SKLearn peculiar layout,
as well corresponding support vector indexes
"""
sv_ind_by_class = group_indices_by_class(
num_classes, sv_ind_by_clf, labels)
sv_ind_mapping = map_sv_... | cd64c5df3b6e633a482271e82b53b5d1f431bf7a | 3,649,421 |
def namespaces_of(name):
"""
utility to determine namespaces of a name
@raises ValueError
@raises TypeError
"""
if name is None:
raise ValueError('name')
try:
if not isinstance(name, basestring):
raise TypeError('name')
except NameError:
if not isinst... | 7226d0540963f021b5a0bcf34763ab60942094d0 | 3,649,423 |
def create_c3d_sentiment_model():
"""
C3D sentiment Keras model definition
:return:
"""
model = Sequential()
input_shape = (16, 112, 112, 3)
model.add(Conv3D(64, (3, 3, 3), activation='relu',
padding='same', name='conv1',
input_shape=input_shape))
... | 77de7bc69c848b6b1efdd222161e2e471186cd41 | 3,649,424 |
def notch_filter(data: FLOATS_TYPE,
sampling_freq_hz: float,
notch_freq_hz: float,
quality_factor: float) -> FLOATS_TYPE:
"""
Design and use a notch (band reject) filter to filter the data.
Args:
data: time series of the data
sampling_freq_... | 4a7fc2c41343258e9951503fb5579b3283f14e31 | 3,649,426 |
def get_trail_max(self, rz_array=None):
"""
Return the position of the blob maximum. Either in pixel or in (R,Z) coordinates if rz_array
is passed.
"""
if (rz_array is None):
return self.xymax
# Remember xycom[:,1] is the radial (X) index which corresponds to R
return rz_array[self.... | 5456c95ba4cb02352aa69398f9fa5307f3dc8e06 | 3,649,427 |
def create_action_type(request):
"""
Create a new action type
"""
# check name uniqueness
if ActionType.objects.filter(name=request.data['name']).exists():
raise SuspiciousOperation(_('An action with a similar name already exists'))
description = request.data.get("description")
labe... | c8101eb8721a63771484ae16a39783338d7ad7a5 | 3,649,428 |
def ec_chi_sq(params,w,y,weights,model,normalize='deg'):
"""
Chi squared for equivalent circuit model.
Parameters:
-----------
params: dict of model parameters
w: frequencies
y: measured impedance data: nx2 matrix of Zreal, Zimag
weights: weights for squared residuals (n-vector)
model: equivalent circuit mo... | 3d108f79aec530cc375443001902cd8f3797cd95 | 3,649,429 |
def synthesize_genre_favs(xn_train_df):
"""
Making synthetic user-genre favorite interactions
We're going to just count the genres watched by each user.
Subsample from a random top percentile of genres and
consider those the user's favorites. We will then subsample again
-- simulating the volun... | f0be8bf6441efda1c27f0f03df644c5fab408ca5 | 3,649,430 |
def mfa_to_challenge(mfa):
""" Convert MFA from bastion to internal Challenge
param mfa: MFA from bastion
:rtype: Challenge
:return: a converted Challenge
"""
if not mfa.fields:
return None
message_list = []
echos = [False for x in mfa.fields]
fields = mfa.fields
if hasa... | 903bbc7f82e624d2dac0fbc1c0711742de57e876 | 3,649,431 |
def put_vns3_controller_api_password(
api_client, vns3_controller_id, api_password=None, **kwargs
): # noqa: E501
"""Update VNS3 Controller API password # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> respo... | b24f43b047c0b96ff41b628de7d2efbd3bd71f12 | 3,649,432 |
def create_pod(interface_type=None, pvc_name=None, desired_status=constants.STATUS_RUNNING, wait=True):
"""
Create a pod
Args:
interface_type (str): The interface type (CephFS, RBD, etc.)
pvc (str): The PVC that should be attached to the newly created pod
desired_status (str): The s... | 6d8142a71e187efa194ac8c492f004bbc9e126b8 | 3,649,433 |
from typing import Tuple
from typing import List
def create_annotation(annotation_id: int, image_id: int, category_id: int, is_crowd: int, area: int,
bounding_box: Tuple[int, int, int, int], segmentation: List[Tuple[int, int]]) -> dict:
"""
Converts input data to COCO annotation informat... | 715a6204ed5dd9b081ac6e87541df3cd46d329a1 | 3,649,435 |
def check_sequence_is_valid(seq, alignment=False):
"""
Parameters
--------------
seq : str
Amino acid sequence
alignment : bool
Flag that defines if this alignment sequence rules
should be applied or not.
Returns
------------
Tuple
Returns a tuple of si... | eeae8e65e068a8c94b63e70eec2cc84e0fb5c85c | 3,649,436 |
import torch
def get_device():
"""Pick GPU if available, else CPU"""
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu') | 6b1a9baa0c7a98c31bdfebba513565fedc9335af | 3,649,437 |
from scipy.stats import chisquare
from sklearn.feature_extraction import DictVectorizer
def extension_chisquare(x, y=None, lower=True):
"""Calculates a one-way chi square test for file extensions.
:param x: Paths to compare with y.
:type x: list, tuple, array of WindowsFilePath or PosixFilePath objects
... | e181c119c85ce2914f66c2064863d8eaa43754d4 | 3,649,438 |
def kuster_toksoz_moduli(
k1, mu1, k2, mu2, frac2, inclusion_shape="spheres", alpha=None
):
"""Kuster-Toksoz Moduli for an inclusion to a material. Best used for low-porosity materials.
To add multiple inclusions to a model use this function recursively substituting the output for
k1 and mu1 after the ... | 42f50effa180abfefe83c0c9c4a67c102d5a7d88 | 3,649,439 |
def fetchResearchRadius(chatId: str, reachableByFoot: bool) -> tuple:
"""Given a chat id and a distance type, returns the user distance preference.
Args:
chatId (str) - the chat_id of which the language is required
reachableByFoot (bool) - true if the preferred_distance_on_foot param has to be ... | 9a5c83b25b50ba31e0e9376bef5a3cc8dc38d08d | 3,649,440 |
def build_train_valid_test_datasets(tokenizer, data_class, data_prefix, data_impl, splits_string,
train_valid_test_num_samples,
enc_seq_length, dec_seq_length, seed, skip_warmup, prompt_config):
"""Build train, valid, and test datasets."""
... | 48e2528007e34f668dc34052db2e150646bb42ec | 3,649,441 |
def _scal_sub_fp(x, scal):
"""Subtract a scalar scal from a vector or matrix x."""
if _type_of(x) == 'vec':
return [a - scal for a in x]
else:
return [[a - scal for a in x_row] for x_row in x] | ef431b7dcceb9339381b623c957a860ee789e2bd | 3,649,442 |
def asset_name(aoi_model, model, fnf=False):
"""return the standard name of your asset/file"""
prefix = "kc_fnf" if fnf else "alos_mosaic"
filename = f"{prefix}_{aoi_model.name}_{model.year}"
if model.filter != "NONE":
filename += f"_{model.filter.lower()}"
if model.rfdi:
filename... | e7211bec70739e53280ce424e1cb3c4c4304ac54 | 3,649,443 |
from nipype.interfaces import ants
from collections import (
OrderedDict,
) # Need OrderedDict internally to ensure consistent ordering
from nipype.interfaces.semtools.segmentation.specialized import BRAINSROIAuto
from nipype.interfaces.semtools.segmentation.specialized import (
... | fe742ccf65da1935614867b3ea5823054fbfbcc9 | 3,649,444 |
def get_partition_info_logic(cluster_name):
"""
GET 请求集群隔离区信息
:return: resp, status
resp: json格式的响应数据
status: 响应码
"""
data = ''
status = ''
message = ''
resp = {"status": status, "data": data, "message": message}
partition_info = SfoPartitionsInfo.query.fi... | ee0b08fddc8dcb19bd226aca51a918e48af036e3 | 3,649,445 |
def choice_group_name(identifier: Identifier) -> Identifier:
"""
Generate the XML group name for the interface of the given class ``identifier``.
>>> choice_group_name(Identifier("something"))
'something_choice'
>>> choice_group_name(Identifier("URL_to_something"))
'urlToSomething_choice'
... | 6eb9b40154dd4c1f38e6a22dda2ebfccf6180506 | 3,649,446 |
def init_all_sources_wavelets(observation, centers, min_snr=50, bulge_grow=5, disk_grow=5,
use_psf=True, bulge_slice=slice(None,2), disk_slice=slice(2, -1), scales=5, wavelets=None):
"""Initialize all sources using wavelet detection images.
This does not initialize the SED and morpholgy parameters, so
... | 777d0be59a9cab19c91bc8ec1eb956beecdd5066 | 3,649,447 |
def init_coreg_conversion_wf(name: str = "coreg_conversion_wf") -> pe.Workflow:
"""
Initiate a workflow to convert input files to NIfTI format for ease of use
Parameters
----------
name : str, optional
Workflow's name, by default "nii_conversion_wf"
Returns
-------
pe.Workflow... | 411e19083a243e1f38b8243e4bae1384aaba190e | 3,649,448 |
def rgb2hex(rgb_color):
""" 'rgb(180, 251, 184)' => '#B4FBB8' """
rgb = [int(i) for i in rgb_color.strip('rgb()').split(',')]
return '#{:02x}{:02x}{:02x}'.format(rgb[0], rgb[1], rgb[2]) | 40a01ccc5695266aebaf63a169c1039a6f42a724 | 3,649,449 |
def validate_tax_request(tax_dict):
"""Return the sales tax that should be collected for a given order."""
client = get_client()
if not client:
return
try:
tax_data = client.tax_for_order(tax_dict)
except taxjar.exceptions.TaxJarResponseError as err:
frappe.throw(_(sanitiz... | 5f6dc961595d766548c348149cc988346dcfdbbe | 3,649,450 |
def union_with(array, *others, **kargs):
"""This method is like :func:`union` except that it accepts comparator
which is invoked to compare elements of arrays. Result values are chosen
from the first array in which the value occurs.
Args:
array (list): List to unionize with.
others (lis... | dd1ee10763f826e9cc94c4ab4a11df20b1d2da3f | 3,649,451 |
def CalculateMoranAutoVolume(mol):
"""
#################################################################
Calculation of Moran autocorrelation descriptors based on
carbon-scaled atomic van der Waals volume.
Usage:
res=CalculateMoranAutoVolume(mol)
Input: mol is a molecule obj... | 28aa0db26041ccddbf12c7d371b06183b9f14fac | 3,649,452 |
def execute(cursor, query):
"""Secure execute for slow nodes"""
while True:
try:
cursor.execute(query)
break
except Exception as e:
print("Database query: {} {}".format(cursor, query))
print("Database retry reason: {}".format(e))
return cursor | b46338ab7304737d3b12cb1bd4d4dff9665d0f60 | 3,649,453 |
import zipfile
def zip_to_gdal_path(filepath):
"""
Takes in a zip filepath and if the zip contains files
ascii files, prepend '/viszip' to the path
so that they can be opened using GDAL without extraction.
"""
zip_file_list = []
if zipfile.is_zipfile(filepath):
try:
... | 9e9e44d6eb3022ebe982cc44284da76f56a4ddeb | 3,649,454 |
def calculateMACD(prices_data):
"""Calculate the MACD of EMA15 and EMA30 of an asset
Args:
prices_data (dataframe): prices data
Returns:
macd (pandas series object): macd of the asset
macd_signal (pandas series object): macd signal of the asset
"""
ema15 = pd.Series(prices_... | 4a35619a1abf1f9e984cd334641d3f1f765ec352 | 3,649,455 |
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Logitech Squeezebox component."""
return True | ca111ab23656110623567eea043ee2bfe4db83e5 | 3,649,456 |
def generateDwcaExportFiles(request):
""" Generates DarwinCore-Archive files for the 'Export formats' page. """
error_message = None
#
if request.method == "GET":
form = forms.GenerateDwcaExportFilesForm()
contextinstance = {'form' : form,
'error_message' : e... | cd8cda559bc13d8203a73655fd1c2b2f919c4b9a | 3,649,457 |
def treeFromList(l):
"""
Builds tree of SNode from provided list
Arguments:
l: the list with tree representation
Return:
the tuple with root node of the tree and the sentence index of last leaf node
"""
root = SNode("S")
s_index = 0
for child in l:
node = SNode(ch... | 4c08f87f9b0d3872574ef28b2eb15dbc51181ea6 | 3,649,458 |
import asyncio
def with_event_loop(func):
"""
This method decorates functions run on dask workers with an async function call
Namely, this allows us to manage the execution of a function a bit better, and especially, to exit job execution if things take too long (1hr)
Here, the function func is run i... | 7a977a47e6e20742767c71ab5c78d00d11896b90 | 3,649,459 |
from datetime import datetime
import pytz
def get_current_time():
"""Retrieve a Django compliant pre-formated datetimestamp."""
datetime_tz_naive = datetime.datetime.now()
django_timezone = settings.TIME_ZONE
datetime_tz = pytz.timezone(django_timezone).localize(datetime_tz_naive)
return datetim... | 60ee3acf1b7e805cf6f44cc066e5b452099a6306 | 3,649,460 |
def is_eval_epoch(cfg, cur_epoch):
"""
Determine if the model should be evaluated at the current epoch.
Args:
cfg (CfgNode): configs. Details can be found in
sgs/config/defaults.py
cur_epoch (int): current epoch.
"""
return (
cur_epoch + 1
) % cfg.TRAIN.EVAL_P... | d8abb04409879b88bdfd32cf323bcbea037ae630 | 3,649,461 |
def get_app_run_sleep():
"""Returns the entrypoint command that starts the app."""
return get(cs.ODIN_CONF, cs.APP_SECTION, cs.RUN_SLEEP) | bf7fd5ce98823e3d2ccb1a80addb1d5eb4b85241 | 3,649,462 |
def plot_sphere(Radius, Point, part="Part::Feature", name="Sphere", grp="WorkObjects"):
"""
makeSphere(radius,[pnt, dir, angle1,angle2,angle3]) -- Make a sphere with a given radius
By default pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0, angle2=90 and angle3=360
"""
if not(App.ActiveDocument.g... | be6a2d82d8a2a7268bfc203c0b15fa6d7b711ed2 | 3,649,463 |
async def my_job_async_gen(my_job_manager):
"""Fixture provides the job definition (async generator).
Returns:
The object yielded by the fixture `my_job_manager` with one
extra attribute: `job` - job function decorated with `@job` and
wrapped into `sync_to_async` for convenience (tests ... | cb3bb924e798ddd976a44ecddd8bcec700de7a99 | 3,649,464 |
def cluster(self, net_cvg, net_boxes):
"""
Read output of inference and turn into Bounding Boxes
"""
batch_size = net_cvg.shape[0]
boxes = np.zeros([batch_size, MAX_BOXES, 5])
for i in range(batch_size):
cur_cvg = net_cvg[i]
cur_boxes = net_boxes[i]
if (self.is_groundt... | 7f30a79911db3bcc1a09e4197f4f1d1adb73aaa2 | 3,649,466 |
def _getMissingResidues(lines):
"""Returns the missing residues, if applicable."""
try:
missing_residues = []
for i, line in lines['REMARK 465']:
if len(line.split()) == 5 and int(line.split()[4]) > 0:
missing_residues.append("{0:<3s} {1}{2:>4d}".format(line.split()[... | 071c6d792bc703d0379774eb19c09d9599f17c66 | 3,649,467 |
def register_single_sampler(name):
"""
A decorator with a parameter.
This decorator returns a function which the class is passed.
"""
name = name.lower()
def _register(sampler):
if name in _registered_single_sampler:
raise ValueError("Name {} already chosen, choose a differe... | 7511e4da51a4078df17f6733855f879b1afb2ca8 | 3,649,468 |
def export_txt(obj, file_name, two_dimensional=False, **kwargs):
""" Exports control points as a text file.
For curves the output is always a list of control points. For surfaces, it is possible to generate a 2-D control
point output file using ``two_dimensional`` flag. Please see the supported file format... | e3d2cfa787502190ae3897e67b3daed1a0becacb | 3,649,469 |
from .client import PostgresDialect
from ibis.sql.alchemy import to_sqlalchemy
def compile(expr):
"""
Force compilation of expression for the Postgres target
"""
return to_sqlalchemy(expr, dialect=PostgresDialect) | 32d6c8e6c7fe9cfd56824e7591a88617833479c7 | 3,649,470 |
def build_bar_chart(x_axis_name, request, **kwargs):
"""This abstract function is used to call submethods/specific model"""
base_query = request.GET.get("base_query", None)
bar_chart_input = []
if base_query == 'group_users':
bar_chart_input = group_users_per_column(x_axis_name)
elif base_q... | b23c0ce360c5022dfcb5edf36f3aef90b5ea8ed9 | 3,649,471 |
def diff_hours(t1,t2):
""" Number of hours between two dates """
return (t2-t1).days*hours_per_day + (t2-t1).seconds/seconds_per_hour | de674b6fca138da49291af4e85a043259d32e525 | 3,649,472 |
def fatorial(num=1, show=False):
"""
Calcula o fatorial de um número:
:param n: O número a ser calculado.
:param show: (opcional) Mostrar ou não os cálculos.
:return: O valor do fatorial.
"""
f = 1
c = num
if show==True:
while c > 0:
print(c, end='')
... | 0755528d43731a47a43950d5be62f265d9941488 | 3,649,473 |
def get_season(msg, info_fields):
"""find season in message"""
seasonDICT = {'2016':['二零一六球季', '二零一六賽季', '2016球季', '2016賽季', '2016年', '2016'],
'2017':['二零一七球季', '二零一七賽季', '2017球季', '2017賽季', '2017年', '2017'],
'2018':['二零一八球季', '二零一八賽季', '2018球季', '2018賽季', '2018年', '2018'],
... | 8b5dfceafe45d9ba325c519b24dde03a20d37655 | 3,649,474 |
import numpy
def gray_img(img:'numpy.ndarray'):
"""
对读取的图像进行灰度化处理
:param img: 通过cv2.imread(imgPath)读取的图像数组对象
:return: 灰度化的图像
"""
grayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
return grayImage
pass | e0497d3ec5fa4aed4def293de5981bb0e73ef3e7 | 3,649,475 |
def class_acc(label_threshold_less):
"""
Wrapper function to return keras accuracy logger
Args:
label_threshold_less (int): all label IDs strictly less than this number
will be ignored in class accuracy calculations
Returns:
argument_candidate_acc (function)
"""
def arg... | 6a5dc2806fb223c4f625aa033db808d367676a45 | 3,649,476 |
def reduce_30Hz(meas_run_30Hz, ref_run_30Hz, ref_data_60Hz, template_30Hz, scan_index=1, template_reference=None):
"""
Perform 30Hz reduction
@param meas_run_30Hz: run number of the data we want to reduce
@param ref_run_30Hz: run number of the reference data, take with the same config
... | b58dc7a344ca84800935993f4d747cdee9245fbe | 3,649,477 |
def sRGB_to_sd_Mallett2019(RGB):
"""
Recovers the spectral distribution of given *sRGB* colourspace array using
*Mallett and Yuksel (2019)* method.
Parameters:
-----------
RGB : array_like, (3,)
*sRGB* colourspace array. Do not apply a transfer function to the
*RGB* values.
... | 8251c864db23d50ad54c35ffc306cf0c5d279fc7 | 3,649,478 |
def stationary_traffic_matrix(topology, mean, stddev, gamma, log_psi, n,
max_u=0.9,
origin_nodes=None, destination_nodes=None):
"""
Return a stationary sequence of traffic matrices.
The sequence is generated by first generating a single matrix ass... | ec1267820804dfaec09a9cd0a4fc5c30f5cac329 | 3,649,479 |
def lsst_exposure_time(bands=''):
"""
Sample from the LSST exposure time distribution
"""
dist = {'u': 15.0, 'g': 15.0, 'r': 15.0, 'i': 15.0, 'z': 15.0, 'Y': 15.0}
return [dist[b] for b in bands.split(',')] | 1374512a73b9a0eaf3b1757b09cfdd519fba520c | 3,649,480 |
def bin2hexstring(bin_str):
"""
二进制串转十六进制串,按照 4:1 比例转换
:param bin_str: 二进制串
:return: 十六进制串
"""
bin_len = len(bin_str)
left = 0
right = 4
re_str = hex(int(bin_str[left:right], 2))[2:]
for i in range(right, bin_len, 4):
left = right
right += 4
re_str += hex(... | 823ba4ef86ebcf7e30a29c3718768c6a654acad5 | 3,649,481 |
def check_dict_word(word, target):
"""
Check dict word. If one character not in searching word, then not add the word to python_dict.
:param word: str, word in dictionary.txt.
:param target: str, the searching word
:return: True, all character within are in searching word.
"""
# Level one: c... | 91751f580aa74b7340946f0642c24e11dc19ff32 | 3,649,482 |
def get_memory_in_GB(memory_str):
"""Returns the memory value in GB from a given string in kB"""
try:
return '{0} GB'.format(int(memory_str[:-2]) / 1000000)
except (ValueError, TypeError):
return '' | 4c94c00a5e800ed807f4c3a31fe89e90f28260fe | 3,649,483 |
def get_slot_dict(token_present=False):
"""Compiles a dictionary of the available slots
:returns: A python dictionary of the available slots
"""
ret, slot_list = c_get_slot_list(token_present)
if (ret != 0):
return ret
slot_dict = {}
ret = CKR_OK
for slot in slot_list:
... | 11fd85b408dbbd50e003c9458f865c24ca6f4677 | 3,649,484 |
def load_segment_by_patient(patient):
"""
Load the pixels for a patient and segment all of them
"""
pixels = load_pixels_by_patient(patient)
segments = []
for pixel in pixels:
segments.append(segment(pixel))
return np.array(segments) | f032eb68109707197a05ad1a457d52b36a2f99ed | 3,649,485 |
def filehash(thisfile, filesha):
"""
First parameter, filename
Returns SHA1 sum as a string of hex digits
"""
try:
filehandle = open(thisfile, "rb")
except:
return ""
data = filehandle.read()
while data != b"":
filesha.update(data)
data = filehandle.read(... | bb6c965d5a0c5f332320d2426b066b4fa85f77e3 | 3,649,486 |
def show_date(
enode,
_shell='vtysh',
_shell_args={
'matches': None,
'newline': True,
'timeout': None,
'connection': None
}
):
"""
Display system date information
This function runs the following vtysh command:
::
# show date
:param dict kw... | f7b650deca043834caa90fecba1d4b25d5e8b1cc | 3,649,488 |
def show_score(connection, amt):
"""
show_score
:param connection: :class:`sqlite3`
:param amt: int
:return: int
"""
sand = read_sum(connection, "sand", amt)
putt = read_sum(connection, "putt", amt)
return sand + putt | 26ff2fe98cd24d8480c7b4172cd2fcfc2b1d85fd | 3,649,489 |
import time
def current_time():
""" current_time() -> str
>>> current_time()
14:28:04
Returns the current local time in 24 clock system.
"""
return time.strftime('%X', (time.localtime())) | 9ab4ed21d1480e1923c8a55b8f213ff47cb8adcc | 3,649,490 |
def kernel_s_xz2(y, x, z, zc, yp, xp, zp):
"""
Kernel for xz-component of stress in the semi-infinite space domain
(2nd system)
"""
# Y = y - yp
# X = x - xp
# Z = z - zp - 2 * zc
Y = yp - y
X = xp - x
Z = zp - z + 2 * zc
rho = np.sqrt(Y ** 2 + X ** 2 + Z ** 2)
kernel = (... | c4b4e89584acf5a6af2c91686cbfe542d5942a33 | 3,649,491 |
def prepare_hex_string(number, base=10):
"""
Gets an int number, and returns the hex representation with even length padded to the left with zeroes
"""
int_number = int(number, base)
hex_number = format(int_number, 'X')
# Takes the string and pads to the left to make sure the number of characte... | e6efeca87d5f0a603c8fdb65fd7e2d07cc491766 | 3,649,492 |
def parse_function(image_size, raw_image_key_name):
"""Generate parse function for parsing the TFRecord training dataset.
Read the image example and resize it to desired size.
Args:
image_size: int, target size to resize the image to
raw_image_key_name: str, name of the JPEG image in each TFRecord entry... | 549651d152836b8703eaac70b635fbb12158f429 | 3,649,493 |
def clean_coverage(x):
"""
Cleans the coverage polygons by remove small multipolygon shapes.
Parameters
---------
x : polygon
Feature to simplify.
Returns
-------
MultiPolygon : MultiPolygon
Shapely MultiPolygon geometry without tiny shapes.
"""
# if its a sing... | a6a82975aabc3ceb90f4b1eab5a0978df048f647 | 3,649,494 |
def send():
"""For testing: Example of activating a background task."""
log.info("executing a background task")
bgtasks.send_email.spool(email="tomi@tomicloud.com",
subject="Hello world!", template="welcome.html")
return jsonify({"reply":"background task will start"}), 200 | 5d5fad2025b55e1751c99ef3260a0883795bf469 | 3,649,495 |
from datetime import datetime
def get_today_month_and_day() -> str:
"""Returns today's month and day in the format: %m-%d"""
return datetime.date.today().strftime("%m-%d") | 8358a443c7fec2a7a832c55281f297d8b3573579 | 3,649,496 |
def climate_zone_to_tmy3_stations(climate_zone):
"""Return TMY3 weather stations falling within in the given climate zone.
Parameters
----------
climate_zone : str
String representing a climate zone.
Returns
-------
stations : list of str
Strings representing TMY3 station i... | 8ad2d6a378d7350221655cf323ec42ca66271fb9 | 3,649,497 |
from pathlib import Path
import re
def artist_html_file_path(artist) -> Path: # Used
"""Return absolute artists HTML file path.
Parameters
----------
artist
Artist name.
Returns
-------
:cod:`Path`
Absolute artists HTML file path.
"""
artist_file_name = re.sub(r"... | 9f6ae1849905f820febd8d45bd7583d2911fcaf2 | 3,649,498 |
def _deepfoolx_batch(model, epochs, eta, clip_min, clip_max):
"""DeepFool for multi-class classifiers in batch mode.
"""
original_model_X = model.X
y0 = tf.stop_gradient(model.prob)
B, ydim = tf.shape(y0)[0], y0.get_shape().as_list()[1]
k0 = tf.argmax(y0, axis=1, output_type=tf.int32)
k0 =... | 346e7fc18c634bfe240c85301b6c54ce0f4201a7 | 3,649,499 |
import re
def tokenize(text):
"""
The function to tokenize and lemmatize the text.
Inputs:
text: the text which needs to be tokenized
Outputs:
tokens: tokens which can be used in machine learning
"""
stop_words = stopwords.words("... | b41e66c4a065d898b2c3cf05fa261f6100d0f413 | 3,649,500 |
def remove_task(name: str):
"""
Delete a task based on information "name":
- **name**: each tasks must have a name
"""
name_idx = _db_has_name(name)
if name_idx == None:
raise HTTPException(status_code = 400, detail = {"message" : "name doesn't exists"})
else:
del db["tasks... | 4190e3e6a0ac55defe5ba6dcac3036f7c7df290b | 3,649,501 |
def set_dj_definition(cls, type_map: dict = None) -> None:
"""Set the definition property of a class by inspecting its attributes.
Params:
cls: The class whose definition attribute should be set
type_map: Optional additional type mappings
"""
# A mapping between python types and DataJoi... | 9335e1b4413ce03f98ca885bcf4a888af9d014a1 | 3,649,502 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.