content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def frames_to_time(frames, sr=22050, hop_length=512, n_fft=None):
"""Converts frame counts to time (seconds)
"""
samples = frames_to_samples(frames,
hop_length=hop_length,
n_fft=n_fft)
return samples_to_time(samples, sr=sr) | a8abfabe5a3a577f0c6aa3fbd4c6dac14f282e20 | 79,823 |
import re
def course_item(soup):
"""
Gets the course items and lectures for the soup object.
"""
course_list_html = soup.find('div',class_='course-lectures-list')
topic_html = course_list_html.find_all('div',class_='course-item-list-header expanded')
view = []
for topics in topic_html:
... | 1d31abdee9a9d48d4484eabdfd838251e5b35fdb | 79,824 |
def validate_var_dict(value, _):
"""
Check that each key has 3 numbers associated.
"""
if value:
for k, v in value.get_dict().items():
if not isinstance(v, (tuple, list)):
return "the values for each key must be list or tuple."
if len(v) != 3:
... | c957903cb1bb13205c7dbed8bb2e5bf9a0c9822a | 79,825 |
def binary_search(array, x):
"""
Vanilla BS algorithm
Look for x in the sorted array
return the index if found
or else return None
[8, 9, 10]
"""
# A: init the low and high values
low, high = 0, len(array) - 1
# B: search the array
while low <= high:
# find the midd... | 99fb659774efabbbd5f53c91fd47d6e106542a4c | 79,826 |
def split_train_val_unlabeled(train_inputs, train_labels,
target_num_train_per_class, target_num_val,
seed=None):
"""Splits the training data into train, validation and unlabeled samples.
Arguments:
train_inputs: A numpy array containing the trainin... | 2be94c097646ab820c6cf902e45752478018f410 | 79,827 |
def _make_mako_template_dirs(settings):
"""
Derives the final Mako template directories list from other settings.
"""
if settings.ENABLE_COMPREHENSIVE_THEMING:
themes_dirs = get_theme_base_dirs_from_settings(settings.COMPREHENSIVE_THEME_DIRS)
for theme in get_themes_unchecked(themes_dirs... | c11a452b76d9c4ee08dab75b539f9a6967b571f7 | 79,828 |
def basic_preprocess(text):
"""
Realiza a atomização e remove as pontuações de um texto.
param : text : <str>
return : <list>
"""
sentences = sent_tokenize(text)
pre_processed_tokens = []
for sentence in sentences:
tokens = word_tokenize(sentence)
tokens = remove_punctua... | c4debc1cce592aac6320f23b8ee5d7d6d9df8344 | 79,829 |
from typing import Callable
import torch
def accuracy_fn_seg(nb_classes: int
) -> Callable[[torch.Tensor, torch.Tensor], torch.Tensor]:
"""
Returns function that computes IoU score
"""
def accuracy(y, y_prob, *args):
iou_score = IoU(
y, y_prob, nb_classes).e... | 881d5e4d7268292416154a770bb5187100213367 | 79,831 |
def create_symbolic_cell(
raw_source: str, calculated_result: dict, precision: int
) -> SymbolicCell:
"""
Returns a SymbolicCell
"""
comment_tag_removed = strip_cell_code(raw_source)
cell = SymbolicCell(
source=comment_tag_removed,
calculated_results=calculated_result,
li... | f74b3a3d02b0f6fca0bf198af8330d88ef1e8109 | 79,832 |
from typing import Dict
from typing import Callable
def snap_sink_registry(
file_pointer: h5py.File, name_map: Dict[str, str] = None
) -> Dict[str, Callable]:
"""Generate snap sink registry.
Parameters
----------
file_pointer
The h5py file pointer to the snap file.
name_map : optional... | bfe580ed7e1cc429e15cafa5ee9543c783d32ec1 | 79,833 |
def measure_statistics(measure,
nbins_for_ns = 53):
"""
This calculates the statistics of measures
Parameters
----------
measure : dictionay
measure for clusters.
nbins_for_ns : int
number of bins for calculation of cluster number density
Returns
... | 1472d0053da999179f8eb1663c24506a00a0d058 | 79,834 |
from corpkit.constants import transshow, transobjs
def make_name_to_query_dict(existing={}, cols=False, dtype=False):
"""
Make or add to dict of longhand and shorthand search bits
"""
if dtype and dtype != 'conll':
return {'None': 'None'}
for l, o in transobjs.items():
if cols... | 822bf1cffbf8ed80d4034659bd6fea98f433ec10 | 79,837 |
def TotalEvolution(tensor):
"""Calculates total communicability or flow over time for a network.
Parameters
----------
tensor : ndarray of rank-3
Temporal evolution of the network's dynamic communicability. A tensor
of shape timesteps x n_nodes x n_nodes, where n_nodes is the number of ... | c5e0bf65c98bc27783fcc2a3daeccb6d2b3e68a8 | 79,839 |
from re import T
def compute_f1(precision, recall):
"""
Computes the f1 score for the binary classification.
Computed as,
f1 = 2 * precision * recall / (precision + recall)
Parameters
----------
precision : Variable
Precision score of the binary decisions.
recall : Variable
... | 82e6c73e772d68884fa4e8561e34beb5679ec312 | 79,840 |
def test_apply_flows__with_function_flow__expect_flows_applied(backend, inf_pop, sus_pop, exp_flow):
"""
Expect a flow to occur proportional to the result of `get_flow_rate`.
"""
def get_flow_rate(flow, comps, comp_vals, flows, flow_rates, computed_values, time):
_, i_pop, _ = comp_vals
... | 72af28eac6e6385e997234c16daa2475958eef8b | 79,842 |
def maybeErrXcpt(fIsError, sText=None, cFrames=1):
""" Maybe error or maybe normal log exception entry. """
if fIsError is True:
return errorXcpt(sText, cFrames);
return logXcpt(sText, cFrames); | d78842d937931d90917ae0a6e1f8e2c03e5b0565 | 79,843 |
def clerk_logout(request):
"""
Logout currently logged in clerk.
"""
for key in ["clerk", "clerk_token", "counter"]:
request.session.pop(key, None)
return HttpResponse() | 240af18ce07683badaba3498a70e4afeb95f1a4a | 79,844 |
from typing import List
from typing import Dict
import json
def load_jsonl(filepath: str) -> List[Dict[str, str]]:
"""
Load data from a `.jsonl` file, i.e., a file with one dictionary per line
Args:
filepath (str): Path to `.jsonl` file.
Returns:
List[Dict[str, str]]: A list of dicti... | defed6436b4e6dd17aae7163db19a3558446fb34 | 79,845 |
def callInfoFromWSDL(port, name):
"""Return a SOAPCallInfo given a WSDL port and operation name."""
wsdl = port.getService().getWSDL()
binding = port.getBinding()
portType = binding.getPortType()
operation = portType.operations[name]
opbinding = binding.operations[name]
messages = wsdl.messa... | f4b0a0352133f6b0e636c2b24b6db4e6c4d1c46b | 79,846 |
def connect():
"""
Returns the list of compatible devices.
@return: device list
"""
ret = list()
ret += list(usb.core.find(find_all=True,
idVendor=0x04b4, idProduct=0xfd10))
ret += list(usb.core.find(find_all=True,
idVendor=0x04b4, idProduct=0xfd11))
ret += list(usb.core.find(find_all=True,
idVendor=0x04... | 9629e4042d3da326911dc324df0b21205e064a9a | 79,847 |
def configure_request_context(graph):
"""
Configure the flask context function which controls what data you want to associate
with your flask request context, e.g. headers, request body/response.
Usage:
graph.request_context()
"""
include_header_prefixes = graph.config.request_context.... | 5ff98c18ce1b3fabb85304728fdbc4f4175935d3 | 79,848 |
def get_nova_client(sess):
"""get OpenStack nova client"""
return novaClient('2', session=sess) | 7b17c00594f673552248a9af4d57ab7465fdf054 | 79,849 |
def is_pid_valid(pid: str) -> bool:
"""Passport Id"""
try:
int(pid)
except ValueError:
return False
else:
return len(pid) == 9 | cccf470c6118f81e689d6d21367303d2dc189b1b | 79,850 |
def _vasp5_lines_raw_coordinates(poscar_lines):
"""Return the coordinates of the sites and the corresponding
selective dynamics. Agnostic to Direct/Cartesian, this just converts
the lines into the appropriate type.
Parameters
----------
poscar_lines : list of str
Returns
-------
(n... | c08cf11f535d668e29428cd24b5a2a8856ca2caa | 79,851 |
def get_endpoint(endpoint: str, **kwargs) -> str:
"""Get a full endpoint on top of the base URL."""
return f"{base_url(**kwargs)}{endpoint}" | 14b631d8eff1b0100686ae95b313938e1d260984 | 79,852 |
def Nearest(point, vector):
"""
Find the position of the nearest vector's value from a given point
IMPUTS
point : value to need find the nearest point
vector: list or array with points to compare
OUPUTS
idx : Position of the original vector with less distance from the ginven point
"""
... | d69ec8cf5d98bcc62ee683419fd57e9e4c080100 | 79,853 |
def shell_sort(arr):
"""
Here lies the shell sort algorithm
"""
comp = 0
arr_len = len(arr)
gap = 1
# Get the gap number
while gap < arr_len/3:
gap = 3*gap + 1
while gap >= 1:
for i in range(gap, arr_len):
j = i
while (j >= gap):
... | 87774557017093d1152b45f29947ba5f2b8b33b6 | 79,855 |
def get_job_list():
"""Get a listing of jobs"""
query = {
"query": {
"match_all": {}
}
}
es_index = "job_status-current"
results = mozart_es.query(es_index=es_index, body=query, _source=False)
return sorted([result["_id"] for result in results]) | fd8ce94cea5d55bad4f14de8b12d847774711b2e | 79,856 |
def rouge_n_summary_level(summary_sentences, reference_sentences, n, alpha=None):
"""
Calculate summary level ROUGE-N using wrapper.
:param summary_sentences:
:param reference_sentences:
:param n:
:param alpha:
:return:
"""
rouge = _make_rouge_n(
summary=[summary_sentences],
... | bf3dda0523aa972531b99b4081323b31dd9d0149 | 79,857 |
def load_train_img_feature_vectors(IMAGE_FEATURE_TRAIN_PATH):
"""
Loading features of images from file
:return:
"""
print "Loading train features vectors ..."
features = np.loadtxt(IMAGE_FEATURE_TRAIN_PATH,dtype=float)
return features | aa5f1d4435e33bc5e517d948d410cedac927be7f | 79,858 |
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.core.numbers import comp
def verify_numerically(f, g, z=None, tol=1.0e-6, a=2, b=-1, c=3, d=1):
"""
Test numerically that f and g agree when evaluated in the argument z.
If z is None, all symbols will be tested. This r... | ae78ffc9b2f9f6c82854f04731f85c63616e8e39 | 79,859 |
def analyze(qpi, r0, method="edge", model="projection", edgekw={}, imagekw={},
ret_center=False, ret_pha_offset=False, ret_qpi=False):
"""Determine refractive index and radius of a spherical object
Parameters
----------
qpi: qpimage.QPImage
Quantitative phase image data
r0: floa... | 10e5ff26912793047a8a7f967f3ca6ad4be3fd27 | 79,860 |
def test_baumgartner_CC_emulator():
""" Test the Baumgartner Cross Coupling emulator"""
b = BaumgartnerCrossCouplingEmulator()
columns = [v.name for v in b.domain.variables]
values = {
("catalyst", "DATA"): "tBuXPhos",
("base", "DATA"): "DBU",
("t_res", "DATA"): 328.717801570892,... | acedecc712fb0df694b9f74c43ae649274977ce1 | 79,861 |
import math
def transformImage(img_in, mask, bbox):
"""takes Pix3D image, crops background and resizes to 124x124"""
# crop image to mask
img_white = Image.new('RGB', img_in.size, (255, 255, 255))
img_c = Image.composite(img_in, img_white, mask)
# crop image to bbox
img_c = img_c.crop(bbox)
... | 81ce8346fe5f24e5d9f0a7773a1a5426819178db | 79,862 |
from typing import Mapping
from typing import Any
from typing import List
import re
def extract_output_matchers_from_out(out: str, params: Mapping[str, Any], regex: bool) -> List[OutputMatcher]:
"""Transform output lines such as 'function:9: E: message'
The result is a list of output matchers
"""
mat... | b9ce5e8b1c77085310e2bf500841ee8bf20902fe | 79,863 |
def ccx(self, ctl1, ctl2, tgt):
"""Apply Toffoli to ctl1 and ctl2 to tgt."""
return self.append(ToffoliGate(), [ctl1, ctl2, tgt], []) | 04908253600b76552a9124a0ebaae505704aa9fc | 79,864 |
def delete_stack(stack_name):
"""
Delete a stack
"""
try:
delete_waiter = __client__.get_waiter('stack_delete_complete')
response = __client__.delete_stack(StackName=stack_name)
__logger__.info("Waiting for stack '%s' to be deleted...", stack_name)
delete_waiter.wait(Stac... | a7a9f54d9418d8c1f2ea008c8e0e1537499e3dc6 | 79,865 |
def loader():
"""Load the data from a csv file stored on S3
:return:
a dataframe that contains the data
"""
bucket = data_load_variables["bucket"]
if data_load_variables["use_lite_dataset"]:
dataset_name = data_load_variables["lite_dataset_name"]
else:
dataset_na... | 1dfeb6c7628cef3bf357a961a04ae74ca362ac07 | 79,866 |
def get_select_options(form):
"""
Return a dict or tags and descriptions based on the SELECT field in the
given form.
"""
tags = {}
selects = []
for input in form.inputs:
if not input.attrib.has_key('type'):
selects.append(input)
for select in selects:
tags[se... | 15773b1fd7483a71e6bae7d5d00647af788b8c8a | 79,867 |
import time
def is_in_bright_mask(targs, sourcemask, inonly=False):
"""Determine whether a set of targets is in a bright star mask.
Parameters
----------
targs : :class:`recarray`
A recarray of targets, skies etc., as made by, e.g.,
:func:`desitarget.cuts.select_targets()`.
source... | ad14504e3a3917544c1aa616d64ecf050f9cb3d3 | 79,868 |
def find_vswitch_map(oper, mgd_sys_uuid):
"""
Returns the mapping of vswitch names to IDs
:param oper: The operator to interact with the HMC.
:param mgd_sys_uuid: The unique identifier of the managed system.
:returns: vswitch_map
"""
if not oper:
return None
vswitch_map = {}
... | 9d64b0e17beb69b5a01fcaa92b9e447858c4ce05 | 79,870 |
def get_krogager_2018_dataframe():
"""
Return pandas dataframe for Krogager 2018
:return:
krogager_df :pandas.core.frame.DataFrame: dataframe containing Krogager 2018 data.
"""
print("Importing Krogager 2018 pandas dataframe.")
krogagerf = pd.ExcelFile('../data/source_data/MouseBrainProteom... | a69fca93c6147243e6fc2c8f5980d399448a64ad | 79,871 |
from datetime import datetime
def encode_refresh_jwt(user: str) -> str:
"""Generate a refresh JWT token
The token will expire based on the `jwt_refresh_expiration` option
in `config.py`.
:param user: User to use as a subject
:type user: str
:return: Return a JWT refresh token
:rtype: str... | 033b8696dafc114f850758a1eef749842a12791e | 79,872 |
import copy
def get_current_stack_trace():
"""Returns the stack trace of the current execution frame.
Returns:
A list of `StackTraceEntry` named tuples corresponding to the current stack
trace of the process, truncated to immediately before entry into
PyMJCF internal code.
"""
if _CURRENT_FROZEN_... | fbeb27b4e8e0e95d9b836f313eeddf307fd01224 | 79,873 |
def replace(string):
"""
>>> print(replace("L'horloge dit : « Quinze heures ? »."))
L’horloge dit\u00A0: «\u00A0Quinze heures\u202F?\u00A0».
>>> print(replace(" ; !« »“ ” /“ ”"))
\u00A0;\u202F!«\u00A0\u00A0»“\u00A0\u00A0”\u00A0/“\u00A0\u00A0”
"""
return TYPOGRAPHIC... | 2e4d35012f7d7eeff7af97a8fc56e64f7fd00fed | 79,874 |
def write_kpts_vasp(kpts):
"""
Write a list of kpoints to a vasp-formatted KPOINTS file.
"""
output = "Supercell_k-points_from_primitive_cell\n"
output += str(len(kpts))+"\n"
output += "reciprocal\n"
for i in range(len(kpts)):
for j in range(3):
output += str(kpts[i,j])+"... | 66a0f5b5128172d64c1e3d0af55695ffb10653b3 | 79,875 |
def normalize_0to1(batch):
"""
Normalize a batch such that every value is in the range 0 to 1.
Args:
batch: a batch first numpy array to be normalized.
Returns: A numpy array of the same size as batch, where each item in the
batch has 0 <= value <= 1.
"""
axis = tuple(range(1, len(batc... | 4607f1b1cd92490c52b9e7945204e820e005b6a5 | 79,876 |
def ambi_sieve(n):
"""Returns a list of primes < n"""
# http://tommih.blogspot.com/2009/04/fast-prime-number-generator.html
s = np.arange(3, n, 2)
for m in xrange(3, int(n ** 0.5) + 1, 2):
if s[(m - 3) / 2]:
s[(m * m - 3) / 2::m] = 0
return np.r_[2, s[s > 0]] | e3e70943449bf1d505b8c692944d74c909b5129d | 79,877 |
import numpy
def get_pop_v(image):
"""
calculate value if a pop window exit
:param image: image path
:return: mean of v channel
"""
img = cv2.imread('capture/'+image)
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(img_hsv)
return numpy.mean(v) | e039d017e93ff443d9d635b929eef7e607efc6b2 | 79,878 |
def docopt_cmdl(argd):
"""
Given a set of arguments, construct a command line
"""
argl = []
subcl = docopt_subcl()
for k in argd:
if argd[k] == True:
if k in subcl:
argl.insert(0, k)
else:
argl.append(k)
elif argd[k] is not ... | 576a4ce40c567ee1d1bc0dd6cd360fd3dbc734ac | 79,879 |
import torch
def kllossfunction(o, l: 'indicator'):
"""KL loss for DNN histogram output, labels represented as indicator arrays."""
return -torch.mean(2*torch.sum(torch.log(o)*l, dim=1)) | e777444949df58011b3d60b42248a7f9ef22e45e | 79,880 |
def flip(n, width):
"""Reverse the binary digits of integer `n`, which is `width` bits wide."""
s = bin(BIG + n)[-width:]
return int(s[::-1], 2) | 2e21bc2d6070702ec658674acf6c662dfa16910a | 79,881 |
def parse_entity_refs(clusters, ref_strings):
"""
Given the collection of configured clusters and a collection of entity ref strings, returns a pair
where the first element is a list of corresponding entity ref maps, and the second element is the
subset of clusters that are of interest.
"""
enti... | 2389d9c201304b4985086dc47cac5216f72f3afd | 79,882 |
def efetch_sequences(headers):
"""Retrieve protein sequences from NCBI for supplied accessions.
This function uses EFetch from the NCBI E-utilities to retrieve the sequences for
all synthases specified in `headers`. It then calls `fasta.parse` to parse the
returned response; note that extra processing ... | a2909fd452e450bc6a6cfb0d10cce2941969cd0e | 79,883 |
def ping_name(name, solr_mode='cores'):
"""ping_name: check if collection or core exists"""
this_api = 'admin/ping' if solr_mode == 'cores' else 'admin/ping?distrib=true'
this_error = None
try:
this_data = get_solr(name, api=this_api)
except (HTTPError, SolrError, ConnectionError) as error:
... | 4bc2d77d24d753560fb193ed10919483569187b4 | 79,884 |
def plot_line_params(line_params, header=None, vel_min=-200., vel_max=200.,
vdisp_max=300., flux_max=None, mask=None, flux_scale='arcsinh',
subplots=True):
"""
Function to plot the line intensity, velocity, and velocity dispersion in one figure
"""
int_flux_hdu... | 1bb85eccb33e96be609abfcbbc58b8fc72514ee3 | 79,885 |
def load_from_environ_as_json(metadata):
"""
Load configuration from environment variables as JSON
"""
return _load_from_environ(metadata, value_func=loads) | 42b007c81e572ea0f65463ae682c2efd8a870abc | 79,886 |
from typing import OrderedDict
def table_schema_builder(database):
"""
Returns a dictionary loaded with all of the tables available in the database.
``database`` must be an instance of DatabaseSchema.
.. note::
This function is automatically called for you and set to
``schema.databases[na... | 85b4cd959000c3c7039124428a28863eb10d2481 | 79,887 |
def _justify_and_indent(text, level, munge=0, width=72):
""" indent and justify text, rejustify (munge) if specified """
indent = " " * level
if munge:
lines = []
line = indent
text = text.split()
for word in text:
line = ' '.join([line, word])
if l... | dafa407bdf42832d92f8c3592ec9ab4f29711710 | 79,888 |
import random
def total():
"""Produce a random purchase amount."""
return round(random.random() * 1000, 2) | 5034ed943b1860384c3a19f129d0ab1b7d14629e | 79,889 |
def FormatParamsDictInfo(param_dict, actual, roman=False):
"""Formats a parameter dictionary.
@type param_dict: dict
@param param_dict: the own parameters
@type actual: dict
@param actual: the current parameter set (including defaults)
@rtype: dict
@return: dictionary where the value of each parameter is... | f3fb881ba4db6aea9a74bf4c8a385b17e3d59052 | 79,890 |
def nearby_agents(location: tuple, agents: dict[str, dict]) -> dict[str, dict]:
"""
Filter the non-nearby agents.
"""
neighbors = {label: agent for label, agent in agents.items()
if is_neighbor(agent['location'], location)}
return neighbors | 355bc0d9be3eaaea0569b7feb86be27a77b3bcb5 | 79,891 |
import atexit
def profile(func, columns=DEFAULT_COLUMNS):
"""Profile the CUDA memory usage of target function line by line
The profiling results will be printed at exiting, KeyboardInterrupt raised.
The CUDA memory is collected only on the **current** cuda device.
The columns are explained in the Py... | dee466e587caf87365614404d065d5098928558c | 79,893 |
def run_nonlincausality(
network_architecture,
x,
maxlag,
Network_layers,
Network_neurons,
Dense_layers,
Dense_neurons,
x_test,
run,
z,
z_test,
add_Dropout,
Dropout_rate,
epochs_num,
learning_rate,
batch_size_num,
verbose,
plot,
functin_type,
)... | 38f58c7008975b47b20818e3422adc53decc43aa | 79,895 |
def create_video(video: schemas.VideoCreate, db: Session = Depends(get_db)):
"""Creates new video."""
new_video = crud.videos.create_video(db, video)
return {
"video": new_video
} | bd3a5a5b86213daf37abea0dfe9def1a00eb8ed3 | 79,897 |
def v4_normal(Vert, Face):
"""
convert 3 vertices representation to 4 vertices with representation of normal
:param Vert: n * 3 matrix
:param Face: m * 3 matrix
:return: T N V F
"""
f1 = Face[:, 0] - 1
f2 = Face[:, 1] - 1
f3 = Face[:, 2] - 1
e1 = Vert[f2, :] - Vert[f1, :]
e2 ... | a861cdfb8ac9f6d2008d3ee4e92815cc8a5c139b | 79,898 |
import math
def density(altitude):
"""Corrects air density measurement for altitude"""
altitude_in_feet = altitude * 3.28084 # correct in standard [ft]
if altitude > STRATOS_SPLIT_ALTITUDE:
temperature = -205.05 + .00164 * altitude_in_feet # [F]
pressure = 51.97 * ((temperature + 459.7)/38... | d65deea5ab869ffd3cd82b6a8a0a83e6bd51be77 | 79,899 |
def get_date_string_with_tz(date_value) -> str:
"""Get date string with timezone."""
tz_offset = SUPPORTED_TIMEZONES[TIMEZONE]
main_str = date_value.strftime("%d %b %Y") + f" {TIMEZONE}"
return f"{main_str} ({tz_offset})" if tz_offset != "" else main_str | 30e978703e994688769f8daca921bfa9c9e88da5 | 79,900 |
def softranks(x, direction='ASCENDING', axis=-1, zero_based=True, **kwargs):
"""A differentiable argsort-like operator that returns directly the ranks.
Note that it behaves as the 'inverse' of the argsort operator since it returns
soft ranks, i.e. real numbers that play the role of indices and quantify the
rel... | 2522e0794ec05aecf4b45466901b4642c56b7a84 | 79,901 |
import time
def get_all_physical_tn(rt_info, with_tdw=True):
"""
获取result table id对应不同存储的物理表名称字典
:param rt_info: rt的配置信息
:param with_tdw: 是否返回tdw表规则
:return: rt的物理表名字典
"""
execute_begin_time = int(time.time() * 1000)
rt_id = rt_info[RESULT_TABLE_ID]
# 获取不同存储的默认表名规则
physical_tns... | 65e408b02fa67117debfdf7a9652f8e4f5a1a4b5 | 79,902 |
import itertools
def encrypt_repeating_key_xor(data, key):
"""Set 1 - Challenge 5"""
key_arr = np.array(list(itertools.islice(itertools.cycle(key), len(data))))
return data ^ key_arr | c6e471253999e934da92b1bb4be6e4874fee4767 | 79,903 |
def layered_medium( layers=water_layered_rock, **kwargs):
""" Friendly wrapper for instantiating the layered medium model. """
# Setup the defaults
model_config = dict(z_delta=None,
min_ppw_at_freq=(6,10.0), # 6ppw at 10hz
x_length=None, x_delta=None,
... | 9d8758bc581ddef1c26c3f91e6fb7ef6d754be32 | 79,904 |
def get_active_listings():
"""Returns a list of active listings from GetMyeBaySelling."""
outer_opts = {'OutputSelector': ['ItemID', 'SKU',
'ListingType', 'PaginationResult']}
inner_opts = {'Include': 'true',
'IncludeWatchCount': 'true'}
listings,... | 85c9f61f7348ae0806f1e6d3fc38f38da5384804 | 79,905 |
import copy
def validate(exif_dict_original):
"""
py:function:: piexif.validate(ifd_dict)
Return exif data as dict. Keys(IFD name), be contained, are "0th", "Exif", "GPS", "Interop", "1st", and "thumbnail". Without "thumbnail", the value is dict(tag name/tag value). "thumbnail" value is JPEG as bytes.
... | 87b41c865945bf183d70a3c0cc257137b652963f | 79,906 |
import csv
def open_test_file(input_file):
"""Read genes from the input file.
Args:
input_file: input file containing genes to find
(csv, tsv/tab, txt)
"""
test_genes_list = []
try:
with open(input_file) as csv_file:
csv_reader = csv.reader(csv_file... | 2cc8a9905e1a0896feea7550ab29e13591d045e0 | 79,908 |
def default_timetrace_weights(tx, rx):
"""
timetrace weights for TFM.
Consider a timetrace obtained by the transmitter i and the receiver j; this
timetrace is denoted (i,j). If the response matrix contains both (i, j) and (j, i),
the corresponding timetrace weight is 1. Otherwise, the timetrace wei... | f483f5a0e495f6a9e62f6d8a5e41b3559f4c23b1 | 79,909 |
def deep_merge_in(dict1: dict, dict2: dict) -> dict:
"""Deeply merge dictionary2 into dictionary1
Arguments:
dict1 {dict} -- Dictionary female
dict2 {dict} -- Dictionary mail to be added to dict1
Returns:
dict -- Merged dictionary
"""
if type(dict1) is dict and type... | 3f045a484dc4d65001f2e4ca3c6ac6123e4cd4a8 | 79,911 |
def is_jo(block):
"""Verify whether the block checks for OF, may also match JLE.
The location is bounded by set_key and its destination pushes.
Args:
block (list): a list of instructions (dict) belonging to one block
"""
recipe = [["set_key", []],
["d_push_imm", [0x12345678]]... | 5eb6a2c2db1ce191c5f9edcae554cd804757a844 | 79,912 |
from typing import Callable
from typing import Any
def get(identifier: OptStrOrCallable = None) -> Callable[..., Any]:
"""
Get activations by identifier
Args:
identifier (str or callable): the identifier of activations
Returns:
callable activation
"""
try:
return ker... | c997a5297008b7273970d9088c3a5d11bead4308 | 79,913 |
def prettyprint_binding(binding, indent_level=0):
"""Pretty print a binding with variable id and data."""
indent = " " * indent_level
if not binding:
return indent + "<>"
return "%s<v%d : %r>" % (indent, binding.variable.id, binding.data) | e1e196afd53027bbab076585dd8b6b6464b578bc | 79,914 |
def filter_by_likelihood(df, cname, common_names, threshold):
"""Filters imgs by likelihood of common_names appearing.
Args:
cname ([type]): Name of the likelihood column
common_names ([type]): common names
threshold ([type]): likelihood threshold
Returns:
[type]: df with i... | 7fb93937b16ac56afb78aec21b3b311de37c3d22 | 79,915 |
def workbook_lookup(item_type, multiple=False, **attributes):
"""
Given an item type and a set of attributes, looks up the workbook insert of that type matching
the given attribute details.
:param item_type: an item type (such as 'User' or 'Project')
:param multiple: True if the result should be a ... | 7658820157a6685b4eaa4edd50f9c84d6fd9707a | 79,916 |
def adapt_x(x, pyr_lvls=6):
"""Preprocess the input samples to adapt them to the network's requirements
Here, x, is the actual data, not the x TF tensor.
Args:
x: input samples in list[(2,H,W,3)] or (N,2,H,W,3) np array form
Returns:
Samples ready to be given to the network (w. same shap... | 5e47c102572baff6b471cd38fa7f49fe13adfeef | 79,918 |
def user_list(request, format=None):
"""
List all order, or create a server assets order.
"""
if request.method == 'GET':
snippets = User.objects.all()
serializer = UserSerializer(snippets, many=True)
return Response(serializer.data)
elif request.method == 'POST':
ser... | 2c5a6221bfe8889aea32274e87dde33d10d6e474 | 79,919 |
from typing import Callable
from typing import Any
def test_repr(sample_stopwatch: Stopwatch):
"""Test getting a string representation of the Stopwatch instance."""
def assert_repr_value(expected_value: str) -> Callable[[], Any]:
def perform_action():
assert repr(sample_stopwatch) == expe... | cc94cedb13f9761298d6dacdb46ec4c37c1f758d | 79,920 |
import yaml
def extract_yaml(yaml_files):
"""
Take a list of yaml_files and load them to return back
to the testing program
"""
loaded_yaml = []
for yaml_file in yaml_files:
try:
with open(yaml_file, 'r') as fd:
loaded_yaml.append(yaml.safe_load(fd))
... | 2d9dd60bff439a9654ae077f0dfaf0f60d9b839b | 79,921 |
def setup_table(connection, schema_name, table_name, sample_data=None, capture_instance_name=None):
"""Create table and insert the sample data into the table"""
table = create_table(connection, schema_name, table_name)
if capture_instance_name is None:
capture_instance_name = f'{schema_name}_{table_n... | 1a205c3b0bf31e28a35ddaea545e396719dbe1d9 | 79,923 |
from typing import List
def delete_bookmarks(connection, shortcut_id: str, bookmark_ids: List, error_msg=None):
"""Bulk deletion of bookmarks.
Args:
connection: MicroStrategy REST API connection object
shortcut_id: Shortcut ID
bookmark_ids: IDs of bookmarks to be deleted
error... | ab9b7c8a77af106d7eb8d5f3ab350c78c0d28883 | 79,924 |
async def get_auth_by_next_id(next_id):
"""Get user record from auth table using next_id."""
conn = await create_connection()
user_auth = (
await r.table("auth").filter({"next_id": next_id}).coerce_to("array").run(conn)
)
conn.close()
if not user_auth:
raise ApiNotFound("No user ... | 093be03858b915c6273e67988191a3811b6f380d | 79,925 |
def tropmapf(t, pos, el):
""" tropospheric mapping function Neil (NMF) """
if pos[2] < -1e3 or pos[2] > 20e3 or el <= 0.0:
return 0.0, 0.0
aht = nmf_aht
lat = np.rad2deg(pos[0])
# year from doy 28, add half a year for southern latitudes
y = (time2doy(t) - 28.0) / 365.25
y += 0.... | 6a1b9a1f5c4e654e128574c5e088e4e7de34a5a0 | 79,926 |
def nonzero_std(X, axis=0, ddof=0):
"""Compute the standard deviation of non-zero values in a given matrix.
Parameters
----------
X: array_like
axis: int
ddof: int
Returns
-------
np.ndarray
"""
return np.sqrt(nonzero_var(X, axis=axis, ddof=ddof)) | b6cbcdd312648d6e73d53c8e0c56b8d9279b07ef | 79,927 |
from typing import Tuple
from typing import Optional
def is_two_pair(hand: Tuple[Card]) -> Optional[Tuple[str, PokerHand, int]]:
""" If this hand contains two pair, return string representation of it """
rank_histogram, _ = create_cards_histogram(hand)
two_pair = []
highest_card = None
for rank i... | f1148c8bac9e2f4db74a8869ac2137be907e504e | 79,928 |
def purchaseFlexibleProduct(productId, amount, recvWindow=""):
"""# Purchase Flexible Product (USER_DATA)
#### `POST /sapi/v1/lending/daily/purchase (HMAC SHA256)`
### Weight:
1
### Parameters:
Name |Type |Mandatory |Description
--------|--------|--------|--------
productId |STRING |YES |
amount |DECIMAL |YES |
r... | 475c751fc8ea787cd254434198d9671c55e47002 | 79,929 |
def latlon2yx(plats, plons, glats, glons):
"""find y x coordinates """
if glons.ndim == 1 or glats.ndim == 1:
glons, glats = np.meshgrid(glons, glats)
combined = np.dstack(([glats.ravel(), glons.ravel()]))[0]
points = list(np.vstack((np.array(plats), np.array(plons))).transpose())
mytree ... | 2c3e586b29256e92e9139d9b2e9a1da9cc88a18d | 79,930 |
def run_params(molfile,tkin,cdmol,nh=0.0,nh2=0.0,op_ratio=3.0,ne=0.0,nhe=0.0,nhx=0.0,
linewidth=1.0,fmin=0.0,fmax=500.0,tbg=2.73,geometry=1, output_file=None):
"""
Run a single RADEX model from individual parameters
:param molfile: Either the full path, starting from . or / to a datafile in the Lam... | eaa0bf90f96b40aa95a7fe1abaf59d1baac27223 | 79,931 |
def policy_optimizer_app_and_usage_command(client: Client, args: dict) -> CommandResults:
"""
Gets the Policy Optimizer Statistics as seen from the User Interface
"""
rule_uuid = str(args.get('rule_uuid'))
raw_response = client.policy_optimizer_app_and_usage(rule_uuid)
stats = raw_response['re... | 30cd22e16095b82167f39986bd23c5edd3fd3c56 | 79,932 |
def MA(df, n):
"""简单移动平均线"""
if not isinstance(df, pd.DataFrame):
ma = list(df.rolling(n).mean()) #
df = pd.DataFrame(data=ma, columns=["ma"])
else:
df["ma"] = df["close"].rolling(n).mean() #
return df | 4dbdf7388ebed6dfece609c16efff2380de6c956 | 79,933 |
def database_oops(exc, _):
"""View triggered when the database falls over."""
return {
'no_database': True,
'exception': exc
} | f5fdaf887659f62c849a9beaa7a2cba5333ffe01 | 79,934 |
def get_surface_albedo() -> float:
"""
:return: 地面の日射反射率(アルベド), -
"""
return 0.2 | dc0bb08520d0858fdd6a95ab33932e7db4f710ef | 79,935 |
import requests
from bs4 import BeautifulSoup
def auth_session(username:str, password:str) -> (requests.Session, str):
"""自动通过用户名和密码认证登陆中央服务器,返回 Session 对象以及 PORTAL_TOKEN 密钥"""
basic_uri = "https://account.ccnu.edu.cn"
basic_uri_http = "http://account.ccnu.edu.cn"
test_uri = "http://one.ccnu.edu.cn"
... | f7b21b678e2e03ab8931b866a55010bd315521bc | 79,936 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.