content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_dist_genomic(genomic_data,var_or_gene):
"""Get the distribution associated to genomic data for its characteristics
Parameters: genomic_data (dict): with UDN ID as key and list with dictionaries as value,
dict contaning characteristics of the considered genomic data
... | ada0b7ecd57ace9799102e97bc9173d888c23565 | 3,648,580 |
def get_gmb_dataset_train(max_sentence_len):
"""
Returns the train portion of the gmb data-set. See TRAIN_TEST_SPLIT param for split ratio.
:param max_sentence_len:
:return:
"""
tokenized_padded_tag2idx, tokenized_padded_sentences, sentences = get_gmb_dataset(max_sentence_len)
return tokeniz... | 762800a0b986c74037e79dc1db92d5b2f6cd2e50 | 3,648,581 |
def is_answer_reliable(location_id, land_usage, expansion):
"""
Before submitting to DB, we judge if an answer reliable and set the location done if:
1. The user passes the gold standard test
2. Another user passes the gold standard test, and submitted the same answer as it.
Parameters
--------... | 3aa510d68115ef519ec2a1318102d302aae81382 | 3,648,582 |
import numpy
def _polyfit_coeffs(spec,specerr,scatter,labelA,return_cov=False):
"""For a given scatter, return the best-fit coefficients"""
Y= spec/(specerr**2.+scatter**2.)
ATY= numpy.dot(labelA.T,Y)
CiA= labelA*numpy.tile(1./(specerr**2.+scatter**2.),(labelA.shape[1],1)).T
ATCiA= numpy.dot(label... | 9398fa2072625eb66ea8df2f79008577fe6aaabe | 3,648,583 |
def colorize(data, colors, display_ranges):
"""Example:
colors = 'white', (0, 1, 0), 'red', 'magenta', 'cyan'
display_ranges = np.array([
[100, 3000],
[700, 5000],
[600, 3000],
[600, 4000],
[600, 3000],
])
rgb = fig4.colorize(data, colors, display_ranges)
... | efb6ff9c0573da4a11cbfdbf55acaccbb69de216 | 3,648,585 |
import itertools
def multi_mdf(S, all_drGs, constraints, ratio_constraints=None, net_rxns=[],
all_directions=False, x_max=0.01, x_min=0.000001,
T=298.15, R=8.31e-3):
"""Run MDF optimization for all condition combinations
ARGUMENTS
S : pandas.DataFrame
Pandas DataFrame... | 3496105b764bc72b1c52ee28d419617798ad72cc | 3,648,586 |
def nufft_adjoint(input, coord, oshape=None, oversamp=1.25, width=4.0, n=128):
"""Adjoint non-uniform Fast Fourier Transform.
Args:
input (array): Input Fourier domain array.
coord (array): coordinate array of shape (..., ndim).
ndim determines the number of dimension to apply nuff... | d3d03ebe3d905cb647fab7d801592e148023709e | 3,648,587 |
def get_bustools_version():
"""Get the provided Bustools version.
This function parses the help text by executing the included Bustools binary.
:return: tuple of major, minor, patch versions
:rtype: tuple
"""
p = run_executable([get_bustools_binary_path()], quiet=True, returncode=1)
match ... | 7de14349b9349352c3532fbcc0be58be0f9756c7 | 3,648,588 |
def request_from_url(url):
"""Parses a gopher URL and returns the corresponding Request instance."""
pu = urlparse(url, scheme='gopher', allow_fragments=False)
t = '1'
s = ''
if len(pu.path) > 2:
t = pu.path[1]
s = pu.path[2:]
if len(pu.query) > 0:
s = s + '?' + pu.query... | aff334f8358edcae028b65fa1b4cf5727638eaad | 3,648,590 |
def enable_pause_data_button(n, interval_disabled):
"""
Enable the play button when data has been loaded and data *is* currently streaming
"""
if n and n[0] < 1: return True
if interval_disabled:
return True
return False | 4257a2deb9b8be87fe64a54129ae869623c323e8 | 3,648,592 |
import scipy
def dProj(z, dist, input_unit='deg', unit='Mpc'):
"""
Projected distance, physical or angular, depending on the input units (if
input_unit is physical, returns angular, and vice-versa).
The units can be 'cm', 'ly' or 'Mpc' (default units='Mpc').
"""
if input_unit in ('deg', 'arcmi... | 13610816dfb94a92d6890d351312661b04e8604f | 3,648,593 |
def savgoldiff(x, dt, params=None, options={}, dxdt_truth=None, tvgamma=1e-2, padding='auto',
optimization_method='Nelder-Mead', optimization_options={'maxiter': 10}, metric='rmse'):
"""
Optimize the parameters for pynumdiff.linear_model.savgoldiff
See pynumdiff.optimize.__optimize__ and pynu... | cb6da1a5fe3810ea1f481450667e548a9f64dae2 | 3,648,594 |
import base64
def credentials(scope="module"):
"""
Note that these credentials match those mentioned in test.htpasswd
"""
h = Headers()
h.add('Authorization',
'Basic ' + base64.b64encode("username:password"))
return h | 4f0b1c17da546bfa655a96cfe5bcf74719dff55d | 3,648,595 |
def _set_bias(clf, X, Y, recall, fpos, tneg):
"""Choose a bias for a classifier such that the classification
rule
clf.decision_function(X) - bias >= 0
has a recall of at least `recall`, and (if possible) a false positive rate
of at most `fpos`
Paramters
---------
clf : Classifier
... | bbc903752d9abc93f723830e5c6c51459d18d0a5 | 3,648,597 |
from typing import Type
from typing import Dict
from typing import Any
def get_additional_params(model_klass: Type['Model']) -> Dict[str, Any]:
"""
By default, we dont need additional params to FB API requests. But in some instances (i.e. fetching Comments),
adding parameters makes fetching data simpler
... | 1b4c934a06870a8ae1f2f999bab94fb286ee6126 | 3,648,598 |
def thread_loop(run):
"""decorator to make the function run in a loop if it is a thread"""
def fct(self, *args, **kwargs):
if self.use_thread:
while True:
run(*args, **kwargs)
else:
run(*args, **kwargs)
return fct | a68eee708bc0a1fe0a3da01e68ec84b6a43d9210 | 3,648,599 |
from typing import Dict
def rand_index(pred_cluster: Dict, target_cluster: Dict) -> float:
"""Use contingency_table to get RI directly
RI = Accuracy = (TP+TN)/(TP,TN,FP,FN)
Args:
pred_cluster: Dict element:cluster_id (cluster_id from 0 to max_size)| predicted clusters
target_cluster: Dict... | 19ccbd6708abe6b3a05dc23843fa21e0f6d804e9 | 3,648,600 |
import re
import time
from datetime import datetime
def _strToDateTimeAndStamp(incoming_v, timezone_required=False):
"""Test (and convert) datetime and date timestamp values.
@param incoming_v: the literal string defined as the date and time
@param timezone_required: whether the timezone is required (ie, ... | fa0362976c3362e32c4176b4bd4c84ae0c653080 | 3,648,601 |
def get_price_for_market_stateless(result):
"""Returns the price for the symbols that the API doesnt follow the market state (ETF, Index)"""
## It seems that for ETF symbols it uses REGULAR market fields
return {
"current": result['regularMarketPrice']['fmt'],
"previous": result['regularMark... | 6afb9d443f246bd0db5c320a41c8341953f5dd7a | 3,648,602 |
def jump(current_command):
"""Return Jump Mnemonic of current C-Command"""
#jump exists after ; if ; in string. Always the last part of the command
if ";" in current_command:
command_list = current_command.split(";")
return command_list[-1]
else:
return "" | 2530ae99fcc4864c5e529d783b687bfc00d58156 | 3,648,604 |
def get_veterans(uname=None):
"""
@purpose: Runs SQL commands to querey the database for information on veterans.
@args: The username of the veteran. None if the username is not provided.
@returns: A list with one or more veterans.
"""
vet = None
if uname:
command = "SELECT * FROM v... | df97dee334332613b52c745c3f20c4509c0e0cb9 | 3,648,605 |
def mock_movement_handler() -> AsyncMock:
"""Get an asynchronous mock in the shape of an MovementHandler."""
return AsyncMock(spec=MovementHandler) | 85579588dc5d8e6cb37bc85bc652f70d3fca8022 | 3,648,607 |
def compute( op , x , y ):
"""Compute the value of expression 'x op y', where -x and y
are two integers and op is an operator in '+','-','*','/'"""
if (op=='+'):
return x+y
elif op=='-':
return x-y
elif op=='*':
return x*y
elif op=='/':
return x/y
else:
r... | dbdf73a91bdb7092d2a18b6245ce6b8d75b5ab33 | 3,648,608 |
def list_arg(raw_value):
"""argparse type for a list of strings"""
return str(raw_value).split(',') | 24adb555037850e8458cde575ed360265a20cea5 | 3,648,609 |
def create_tracking(slug, tracking_number):
"""Create tracking, return tracking ID
"""
tracking = {'slug': slug, 'tracking_number': tracking_number}
result = aftership.tracking.create_tracking(tracking=tracking, timeout=10)
return result['tracking']['id'] | 4f5d645654604787892f1373759e5d40ce01b2fe | 3,648,610 |
def get_indentation(line_):
"""
returns the number of preceding spaces
"""
return len(line_) - len(line_.lstrip()) | 23a65ba620afa3268d4ab364f64713257824340d | 3,648,611 |
def main():
"""
Find the 10001th prime main method.
:param n: integer n
:return: 10001th prime
"""
primes = {2, }
for x in count(3, 2):
if prime(x):
primes.add(x)
if len(primes) >= 10001:
break
return sorted(primes)[-1] | 3d4f492fe3d0d7e4991003020694434145cd5983 | 3,648,612 |
def launch(context, service_id, catalog_packages=""):
""" Initialize the module. """
return EnvManager(context=context, service_id=service_id,
catalog_packages=catalog_packages) | ba22d106efca9014d118daf4a8880bbcfe0c11fa | 3,648,615 |
def handle_verification_token(request, token) -> [404, redirect]:
"""
This is just a reimplementation of what was used previously with OTC
https://github.com/EuroPython/epcon/pull/809/files
"""
token = get_object_or_404(Token, token=token)
logout(request)
user = token.user
user.is_acti... | f369dc743d875bee09afb6e2ca4a2c313695bcbc | 3,648,616 |
def multi_perspective_expand_for_2d(in_tensor, weights):
"""Given a 2d input tensor and weights of the appropriate shape,
weight the input tensor by the weights by multiplying them
together.
"""
# Shape: (num_sentence_words, 1, rnn_hidden_dim)
in_tensor_expanded = tf.expand_dims(in_tensor, axis=... | 3d153e0bd9808dcd080f3d0ba75ee3bdd16123d3 | 3,648,617 |
import base64
def generateBasicAuthHeader(username, password):
"""
Generates a basic auth header
:param username: Username of user
:type username: str
:param password: Password of user
:type password: str
:return: Dict containing basic auth header
:rtype: dict
>>> generateBasicAu... | 835b3541212e05354a5573a5b35e8184231c7a6c | 3,648,619 |
def correlation(df, target, limit=0, figsize=None, plot=True):
"""
Display Pearson correlation coefficient between target and numerical features
Return a list with low-correlated features if limit is provided
"""
numerical = list(df.select_dtypes(include=[np.number]))
numerical_f = [n for n i... | 044f4708ad691ad4d275c58ff6dbd5a57a6a978d | 3,648,620 |
def fasta_to_raw_observations(raw_lines):
"""
Assume that the first line is the header.
@param raw_lines: lines of a fasta file with a single sequence
@return: a single line string
"""
lines = list(gen_nonempty_stripped(raw_lines))
if not lines[0].startswith('>'):
msg = 'expected the... | e75bd1f08ab68fa5a2a0d45cb23cba087e078d30 | 3,648,621 |
def pc_proj(data, pc, k):
"""
get the eigenvalues of principal component k
"""
return np.dot(data, pc[k].T) / (np.sqrt(np.sum(data**2, axis=1)) * np.sqrt(np.sum(pc[k]**2))) | 768a4a9eba6427b9afda8c34326c140b360feec3 | 3,648,622 |
from datetime import datetime
def compare_time(time_str):
""" Compare timestamp at various hours """
t_format = "%Y-%m-%d %H:%M:%S"
if datetime.datetime.now() - datetime.timedelta(hours=3) <= \
datetime.datetime.strptime(time_str, t_format):
return 3
elif datetime.datetime.now() - datet... | b3d6d85e4559fa34f412ee81825e4f1214122534 | 3,648,623 |
def trendline(xd, yd, order=1, c='r', alpha=1, Rval=True):
"""Make a line of best fit,
Set Rval=False to print the R^2 value on the plot"""
#Only be sure you are using valid input (not NaN)
idx = np.isfinite(xd) & np.isfinite(yd)
#Calculate trendline
coeffs = np.polyfit(xd[idx], yd[idx], order... | af10643b0d74fd5f7a82f803bcef0bd9e379f086 | 3,648,624 |
import collections
def groupby(key, seq):
""" Group a collection by a key function
>>> names = ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank']
>>> groupby(len, names) # doctest: +SKIP
{3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']}
>>> iseven = lambda x: x % 2 == 0
... | bfbec3f25d1d44c9ff2568045508efbf2a2216d2 | 3,648,625 |
def evo():
"""Creates a test evolution xarray file."""
nevo = 20
gen_data = {1: np.arange(nevo),
2: np.sin(np.linspace(0, 2*np.pi, nevo)),
3: np.arange(nevo)**2}
data = {'X1': np.linspace(0.1, 1.7, nevo)*_unit_conversion['AU'],
'X2': np.deg2rad(np.linspace(6... | 5873a3ee7a66d338a8df6b8cf6d26cf4cfeb41a3 | 3,648,626 |
from typing import List
from typing import Any
from typing import Optional
def jinja_calc_buffer(fields: List[Any], category: Optional[str] = None) -> int:
"""calculate buffer for list of fields based on their length"""
if category:
fields = [f for f in fields if f.category == category]
return max... | c1f619acd8f68a9485026b344ece0c162c6f0fb0 | 3,648,627 |
def get_delete_op(op_name):
""" Determine if we are dealing with a deletion operation.
Normally we just do the logic in the last return. However, we may want
special behavior for some types.
:param op_name: ctx.operation.name.split('.')[-1].
:return: bool
"""
return 'delete' == op_name | 508a9aad3ac6f4d58f5890c1abc138326747ee51 | 3,648,628 |
def random_radec(nsynths, ra_lim=[0, 360], dec_lim=[-90, 90],
random_state=None, **kwargs):
"""
Generate random ra and dec points within a specified range.
All angles in degrees.
Parameters
----------
nsynths : int
Number of random points to generate.
ra_lim : list-l... | 4649d5f8e42ada28ba45c46fac1174fc66976f16 | 3,648,630 |
def warmUp():
"""
Warm up the machine in AppEngine a few minutes before the daily standup
"""
return "ok" | f7c83939d224b06db26570ab8ccc8f04bd69c1d6 | 3,648,631 |
def _map_dvector_permutation(rd,d,eps):
"""Maps the basis vectors to a permutation.
Args:
rd (array-like): 2D array of the rotated basis vectors.
d (array-like): 2D array of the original basis vectors.
eps (float): Finite precision tolerance.
Returns:
RP (list): The perm... | 3060cb093d769059f2af0635aafc0bd0fe94ad86 | 3,648,633 |
import re
def varPostV(self,name,value):
""" Moving all the data from entry to treeview """
regex = re.search("-[@_!#$%^&*()<>?/\|}{~: ]", name) #Prevent user from giving special character and space character
print(regex)
if not regex == None:
tk.messagebox.showerror("Forbidden Entry","The var... | 07e108df0ff057ee42e39155562b32fa651ba625 | 3,648,635 |
def _mysql_int_length(subtype):
"""Determine smallest field that can hold data with given length."""
try:
length = int(subtype)
except ValueError:
raise ValueError(
'Invalid subtype for Integer column: {}'.format(subtype)
)
if length < 3:
kind = 'TINYINT'
... | 3a0e84a3ac602bb018ae7056f4ad06fe0dcab53b | 3,648,636 |
def get_ci(vals, percent=0.95):
"""Confidence interval for `vals` from the Students' t
distribution. Uses `stats.t.interval`.
Parameters
----------
percent : float
Size of the confidence interval. The default is 0.95. The only
requirement is that this be above 0 and at or below 1.
... | 1d5e311aab4620e070efcf685505af4a072e56eb | 3,648,637 |
from typing import OrderedDict
from datetime import datetime
def kb_overview_rows(mode=None, max=None, locale=None, product=None, category=None):
"""Return the iterable of dicts needed to draw the new KB dashboard
overview"""
if mode is None:
mode = LAST_30_DAYS
docs = Document.objects.filte... | 768d9aacf564e17b26beb53f924575202fea3276 | 3,648,638 |
def test_query_devicecontrolalert_facets(monkeypatch):
"""Test a Device Control alert facet query."""
_was_called = False
def _run_facet_query(url, body, **kwargs):
nonlocal _was_called
assert url == "/appservices/v6/orgs/Z100/alerts/devicecontrol/_facet"
assert body == {"query": "B... | 6a0182a7b9ad15e5194bcc80aba19ab386e71f35 | 3,648,639 |
def regularity(sequence):
"""
Compute the regularity of a sequence.
The regularity basically measures what percentage of a user's
visits are to a previously visited place.
Parameters
----------
sequence : list
A list of symbols.
Returns
-------
float
1 minus th... | e03d38cc3882ea5d0828b1f8942039865a90d49d | 3,648,641 |
from typing import List
def _make_tick_labels(
tick_values: List[float], axis_subtractor: float, tick_divisor_power: int,
) -> List[str]:
"""Given a collection of ticks, return a formatted version.
Args:
tick_values (List[float]): The ticks positions in ascending
order.
tick_d... | 13aaddc38d5fdc05d38a97c5ca7278e9898a8ed1 | 3,648,642 |
import pickle
def load_coco(dataset_file, map_file):
"""
Load preprocessed MSCOCO 2017 dataset
"""
print('\nLoading dataset...')
h5f = h5py.File(dataset_file, 'r')
x = h5f['x'][:]
y = h5f['y'][:]
h5f.close()
split = int(x.shape[0] * 0.8) # 80% of data is assigned to the training ... | b924b13411075f569b8cd73ee6d5414a4f932a17 | 3,648,643 |
def eval_rule(call_fn, abstract_eval_fn, *args, **kwargs):
"""
Python Evaluation rule for a numba4jax function respecting the
XLA CustomCall interface.
Evaluates `outs = abstract_eval_fn(*args)` to compute the output shape
and preallocate them, then executes `call_fn(*outs, *args)` which is
the... | 6e52d9bdeda86c307390b95237589bd9315829ad | 3,648,644 |
def bev_box_overlap(boxes, qboxes, criterion=-1):
"""
Calculate rotated 2D iou.
Args:
boxes:
qboxes:
criterion:
Returns:
"""
riou = rotate_iou_gpu_eval(boxes, qboxes, criterion)
return riou | 4614a3f8c8838fc4f9f32c2ef625274239f36acf | 3,648,645 |
def filter_shape(image):
"""画像にぼかしフィルターを適用。"""
weight = (
(1, 1, 1),
(1, 1, 1),
(1, 1, 1)
)
offset = 0
div = 9
return _filter(image, weight, offset, div) | f16c181c0eb24a35dfc70df25f1977a04dc9b0f5 | 3,648,646 |
def makeTriangularMAFdist(low=0.02, high=0.5, beta=5):
"""Fake a non-uniform maf distribution to make the data
more interesting - more rare alleles """
MAFdistribution = []
for i in xrange(int(100*low),int(100*high)+1):
freq = (51 - i)/100.0 # large numbers of small allele freqs
for j in r... | 4210fffbe411364b2de8ffbc1e6487c8d3a87a09 | 3,648,648 |
def contains_whitespace(s : str):
"""
Returns True if any whitespace chars in input string.
"""
return " " in s or "\t" in s | c5dc974988efcfa4fe0ec83d115dfa7508cef798 | 3,648,650 |
import itertools
def get_files_to_check(files, filter_function):
# type: (List[str], Callable[[str], bool]) -> List[str]
"""Get a list of files that need to be checked based on which files are managed by git."""
# Get a list of candidate_files
candidates_nested = [expand_file_string(f) for f in files]... | 6b508745aa47e51c4b8f4b88d7a2dff782289206 | 3,648,651 |
def main(argv):
"""Parse the argv, verify the args, and call the runner."""
args = arg_parse(argv)
return run(args.top_foods, args.top_food_categories) | bb2da95cec48b1abfa0e1c0064d413e55767aa89 | 3,648,652 |
import requests
def _failover_read_request(request_fn, endpoint, path, body, headers, params, timeout):
""" This function auto-retries read-only requests until they return a 2xx status code. """
try:
return request_fn('GET', endpoint, path, body, headers, params, timeout)
except (requests.exceptions.Request... | 731a14e72ff4fa88f160215f711fcca2199c736c | 3,648,653 |
def GenerateConfig(context):
"""Generates configuration."""
image = ''.join(['https://www.googleapis.com/compute/v1/',
'projects/google-containers/global/images/',
context.properties['containerImage']])
default_network = ''.join(['https://www.googleapis.com/compute/v1/projec... | 4dbf579c780b0305b4a0b5dcfb3860a086867cbb | 3,648,654 |
from typing import Optional
from typing import List
async def read_all_orders(
status_order: Optional[str] = None,
priority: Optional[int] = None,
age: Optional[str] = None,
value: Optional[str] = None,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
db: AsyncIOMotorClien... | 28200a5dd9c508690ad3234c3080f0bb44a425c4 | 3,648,655 |
def read_log_file(path):
"""
Read the log file for 3D Match's log files
"""
with open(path, "r") as f:
log_lines = f.readlines()
log_lines = [line.strip() for line in log_lines]
num_logs = len(log_lines) // 5
transforms = []
for i in range(0, num_logs, 5):
meta_data... | dcd010f27c94d5bcd2287cb83765fe0eca291628 | 3,648,656 |
import math
def divide_list(l, n):
"""Divides list l into n successive chunks."""
length = len(l)
chunk_size = int(math.ceil(length/n))
expected_length = n * chunk_size
chunks = []
for i in range(0, expected_length, chunk_size):
chunks.append(l[i:i+chunk_size])
for i in range(le... | bad7c118988baebd5712cd496bb087cd8788abb7 | 3,648,657 |
def sigma(n):
"""Calculate the sum of all divisors of N."""
return sum(divisors(n)) | 13dd02c10744ce74b2a89bb4231c9c055eefa065 | 3,648,658 |
def ATOMPAIRSfpDataFrame(chempandas,namecol,smicol):
"""
AtomPairs-based fingerprints 2048 bits.
"""
assert chempandas.shape[0] <= MAXLINES
molsmitmp = [Chem.MolFromSmiles(x) for x in chempandas.iloc[:,smicol]]
i = 0
molsmi = []
for x in molsmitmp:
if x is not None:
x... | cb2babbebd60162c4cc9aa4300dba14cc2cf7ce8 | 3,648,659 |
def filter_by_minimum(X, region):
"""Filter synapses by minimum.
# Arguments:
X (numpy array): A matrix in the NeuroSynapsis matrix format.
# Returns:
numpy array: A matrix in the NeuroSynapsis matrix format.
"""
vals = np.where((X[:,2] >= i[0])*(X[:,3] >= i[1])*(X[:,4]... | 6af135d7ecc716c957bf44ed17caab4f9dd63215 | 3,648,660 |
import tqdm
def gen_graphs(sizes):
"""
Generate community graphs.
"""
A = []
for V in tqdm(sizes):
G = nx.barabasi_albert_graph(V, 3)
G = nx.to_numpy_array(G)
P = np.eye(V)
np.random.shuffle(P)
A.append(P.T @ G @ P)
return np.array(A) | 6decd819a5e2afad9744270c616a60c532f2e6fd | 3,648,661 |
def daemonize(identity: str, kind: str = 'workspace') -> DaemonID:
"""Convert to DaemonID
:param identity: uuid or DaemonID
:param kind: defaults to 'workspace'
:return: DaemonID from identity
"""
try:
return DaemonID(identity)
except TypeError:
return DaemonID(f'j{kind}-{id... | 8cd08d9d8a558b9f78de60d2df96db553fbca8bf | 3,648,662 |
from typing import Counter
def count_gender(data_list:list):
"""
Contar a população dos gêneros
args:
data_list (list): Lista de dados que possui a propriedade 'Gender'
return (list): Retorna uma lista com o total de elementos do gênero 'Male' e 'Female', nessa ordem
... | 9e8a05067a617ca0606eec8d216e25d3f937e097 | 3,648,663 |
async def card_balance(request: Request):
""" 返回用户校园卡余额 """
cookies = await get_cookies(request)
balance_data = await balance.balance(cookies)
return success(data=balance_data) | 09e2b7e84743a0ed5625a6cc19dda0e97eb6df10 | 3,648,664 |
def _grid_vals(grid, dist_name, scn_save_fs,
mod_thy_info, constraint_dct):
""" efef
"""
# Initialize the lists
locs_lst = []
enes_lst = []
# Build the lists of all the locs for the grid
grid_locs = []
for grid_val_i in grid:
if constraint_dct is None:
... | a401632285c9ac48136239fcfa7f3c2eb760734c | 3,648,665 |
import vtool as vt
def group_images_by_label(label_arr, gid_arr):
"""
Input: Length N list of labels and ids
Output: Length M list of unique labels, and lenth M list of lists of ids
"""
# Reverse the image to cluster index mapping
labels_, groupxs_ = vt.group_indices(label_arr)
sortx = np.... | 9bdc83f2a9a5810b5d3cf443dcd72852dd35c26b | 3,648,666 |
from typing import Optional
def ask_user(prompt: str, default: str = None) -> Optional[str]:
"""
Prompts the user, with a default. Returns user input from ``stdin``.
"""
if default is None:
prompt += ": "
else:
prompt += " [" + default + "]: "
result = input(prompt)
return ... | 7803d7e71b2cc3864440cd99c276784cebf81f91 | 3,648,667 |
def tensor_index_by_tuple(data, tuple_index):
"""Tensor getitem by tuple of various types with None"""
if not tuple_index:
return data
op_name = const_utils.TENSOR_GETITEM
tuple_index = _transform_ellipsis_to_slice(data, tuple_index, op_name)
data, tuple_index = _expand_data_dims(data, tupl... | 4a32d9f4028f4ac57d1e523c946bb4a4d349b120 | 3,648,668 |
import scipy
def are_neurons_responsive(spike_times, spike_clusters, stimulus_intervals=None,
spontaneous_period=None, p_value_threshold=.05):
"""
Return which neurons are responsive after specific stimulus events, compared to spontaneous
activity, according to a Wilcoxon test.
... | b5b835113644d7c42e7950cc8fc5699e62d631fa | 3,648,669 |
def _get_book(**keywords):
"""Get an instance of :class:`Book` from an excel source
Where the dictionary should have text as keys and two dimensional
array as values.
"""
source = factory.get_book_source(**keywords)
sheets = source.get_data()
filename, path = source.get_source_info()
re... | 2e6114c2948272ce2d342d954594a8d626a45635 | 3,648,670 |
def handler(
state_store: StateStore,
hardware_api: HardwareAPI,
movement_handler: MovementHandler,
) -> PipettingHandler:
"""Create a PipettingHandler with its dependencies mocked out."""
return PipettingHandler(
state_store=state_store,
hardware_api=hardware_api,
movement_h... | 099532e3c7d51812548643d10758ec23c8354a00 | 3,648,671 |
def get_domain(domain_name):
"""
Query the Rackspace DNS API to get a domain object for the domain name.
Keyword arguments:
domain_name -- the domain name that needs a challenge record
"""
base_domain_name = get_tld("http://{0}".format(domain_name))
domain = rax_dns.find(name=base_domain_na... | 5ea1bbe9c73250abf60c5ad9f1d796035ed87654 | 3,648,672 |
import sympy
def lobatto(n):
"""Get Gauss-Lobatto-Legendre points and weights.
Parameters
----------
n : int
Number of points
"""
if n == 2:
return ([0, 1],
[sympy.Rational(1, 2), sympy.Rational(1, 2)])
if n == 3:
return ([0, sympy.Rational(1, 2), 1... | 595610ec035dd9b059ab085375c017856359b837 | 3,648,673 |
def login():
"""Login."""
username = request.form.get('username')
password = request.form.get('password')
if not username:
flask.flash('Username is required.', 'warning')
elif password is None:
flask.flash('Password is required.', 'warning')
else:
user = models.User.login_user(username, password... | c54bc743ac305db8f0d74a7bd62f7bb70a952454 | 3,648,674 |
def sha2_384(data: bytes) -> hashes.MessageDigest:
"""
Convenience function to hash a message.
"""
return HashlibHash.hash(hashes.sha2_384(), data) | 7523ca7e2d11e3b686db45a28d09ccdad17ff243 | 3,648,676 |
import string
def cat(arr, match="CAT", upper_bound=None, lower_bound=None):
"""
Basic idea is if a monkey typed randomly, how long would it take for it
to write `CAT`. Practically, we are mapping generated numbers onto the
alphabet.
>"There are 26**3 = 17 576 possible 3-letter words, so the aver... | 1077bc5c4bc989e416cdaf27427f5a617491210d | 3,648,677 |
def encrypt_data(key: bytes, data: str) -> str:
"""
Encrypt the data
:param key: key to encrypt the data
:param data: data to be encrypted
:returns: bytes encrypted
"""
# instance class
cipher_suite = Fernet(key)
# convert our data into bytes mode
data_to_bytes = bytes(data, "ut... | 80e69657987956b3a0dc6d87dee79a4dcc5db3f7 | 3,648,678 |
from typing import List
from typing import Dict
def make_doi_table(dataset: ObservatoryDataset) -> List[Dict]:
"""Generate the DOI table from an ObservatoryDataset instance.
:param dataset: the Observatory Dataset.
:return: table rows.
"""
records = []
for paper in dataset.papers:
# ... | 6347142546579712574a63048e6d778dfd558249 | 3,648,679 |
def binarySearch(arr, val):
"""
array values must be sorted
"""
left = 0
right = len(arr) - 1
half = (left + right) // 2
while arr[half] != val:
if val < arr[half]:
right = half - 1
else:
left = half + 1
half = (left + right) // 2
if arr[ha... | 2457e01dee0f3e3dd988471ca708883d2a612066 | 3,648,681 |
from typing import Union
from re import M
from typing import cast
def foreign_key(
recipe: Union[Recipe[M], str], one_to_one: bool = False
) -> RecipeForeignKey[M]:
"""Return a `RecipeForeignKey`.
Return the callable, so that the associated `_model` will not be created
during the recipe definition.
... | f865bf1c7a91a124ca7518a2a2050371112e820e | 3,648,682 |
def posterize(image, num_bits):
"""Equivalent of PIL Posterize."""
shift = 8 - num_bits
return tf.bitwise.left_shift(tf.bitwise.right_shift(image, shift), shift) | 11dc20facfd5ac57e7547036304d192ce21fdb0a | 3,648,683 |
def polyFit(x, y):
"""
Function to fit a straight line to data and estimate slope and
intercept of the line and corresponding errors using first order
polynomial fitting.
Parameters
----------
x : ndarray
X-axis data
y : ndarray
Y-axis data
Return... | 0acc032492a63dbb271293bed8cf11c800621a35 | 3,648,685 |
def evaluate_error(X, y, w):
"""Returns the mean squared error.
X : numpy.ndarray
Numpy array of data.
y : numpy.ndarray
Numpy array of outputs. Dimensions are n * 1, where n is the number of
rows in `X`.
w : numpy.ndarray
Numpy array with dimensions (m + 1) * 1, where m... | 2e54a2bb64a590e3e35456b5039b4cfce7632c0f | 3,648,687 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up ha_reef_pi from a config entry."""
websession = async_get_clientsession(hass)
coordinator = ReefPiDataUpdateCoordinator(hass, websession, entry)
await coordinator.async_config_entry_first_refresh()
if not coor... | 655a1265a77cec38346931a6cf5feaf923c1573b | 3,648,688 |
def get_list(client):
"""
"""
request = client.__getattr__(MODULE).ListIpBlocks()
response, _ = request.result()
return response['results'] | 0836bc58d8108a804c9464a713184ac582bd4e90 | 3,648,689 |
import six
def file_asset(class_obj):
"""
Decorator to annotate the FileAsset class. Registers the decorated class
as the FileAsset known type.
"""
assert isinstance(class_obj, six.class_types), "class_obj is not a Class"
global _file_asset_resource_type
_file_asset_resource_type = class_o... | a21ae9d8ba84d2f6505194db6fd8bd84593f3928 | 3,648,690 |
def scheming_field_by_name(fields, name):
"""
Simple helper to grab a field from a schema field list
based on the field name passed. Returns None when not found.
"""
for f in fields:
if f.get('field_name') == name:
return f | ba4d04585b12ab941db8bc0787b076c32e76cadb | 3,648,692 |
def merge_sort(items):
"""Sorts a list of items.
Uses merge sort to sort the list items.
Args:
items: A list of items.
Returns:
The sorted list of items.
"""
n = len(items)
if n < 2:
return items
m = n // 2
left = merge_sort(items[:m])
right = mer... | d42c60dda40fc421adef2d47f302426d7c176ba1 | 3,648,694 |
from typing import Optional
def hunk_boundary(
hunk: HunkInfo, operation_type: Optional[str] = None
) -> Optional[HunkBoundary]:
"""
Calculates boundary for the given hunk, returning a tuple of the form:
(<line number of boundary start>, <line number of boundary end>)
If operation_type is provide... | c5ec0065e5ab85652a5d0d679a832fdd0dae1629 | 3,648,695 |
from pm4py.statistics.attributes.pandas import get as pd_attributes_filter
from pm4py.statistics.attributes.log import get as log_attributes_filter
def get_activities_list(log, parameters=None):
"""
Gets the activities list from a log object, sorted by activity name
Parameters
--------------
log
... | b0e335dd31cae3fb291317a559c721199217605f | 3,648,696 |
def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob,
source_vocab_size,
encoding_embedding_size):
"""
:return: tuple (RNN output, RNN state)
"""
embed = tf.contrib.layers.embed_sequence(rnn_inputs,
vocab_size=s... | 3179d478478e2c7ca5d415bb23643a836127f6fe | 3,648,697 |
def point_selection(start, end, faces):
""" Calculates the intersection points between a line segment and triangle mesh.
:param start: line segment start point
:type start: Vector3
:param end: line segment end point
:type end: Vector3
:param faces: faces: N x 9 array of triangular face vertices... | 287295de09a5375118ed050f025fa32b0690a9a9 | 3,648,698 |
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar, and the first date is not after
the second."""
month = month2
year = year2
day = day2 ... | 687a7ff0b29ec2a931d872c18057741d93571ac1 | 3,648,699 |
def derive_sender_1pu(epk, sender_sk, recip_pk, alg, apu, apv, keydatalen):
"""Generate two shared secrets (ze, zs)."""
ze = derive_shared_secret(epk, recip_pk)
zs = derive_shared_secret(sender_sk, recip_pk)
key = derive_1pu(ze, zs, alg, apu, apv, keydatalen)
return key | ed2015f683ecdba93288c9a40a9dce35c3d99c37 | 3,648,700 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.