content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _read_one_cml(cml_g,
cml_id_list=None,
t_start=None,
t_stop=None,
column_names_to_read=None,
read_all_data=False):
"""
Parameters
----------
cml_g
cml_id_list
t_start
t_stop
column_names_to_rea... | 952b40329fc75b0a37f210a734a6aa4a0f3b79f8 | 3,639,900 |
import os
def get_commands():
"""
returns a dictionary with all the az cli commands, keyed by the path to the command
inside each dictionary entry is another dictionary of verbs for that command
with the command object (from cli core module) being stored in that
"""
# using Microsoft VSC... | 6e0e77db9f508851d3aabca5571a10cc8736a42f | 3,639,901 |
def calculate_keypoints(img, method, single_channel, graphics=False):
"""
Gray or single channel input
https://pysource.com/2018/03/21/feature-detection-sift-surf-obr-opencv-3-4-with-python-3-tutorial-25/
"""
if single_channel=='gray':
img_single_channel = single_channel_gray(img)
... | 18fa71aa824f7ce4ab5468832dbc020e4fc6519d | 3,639,902 |
def plot_pos_neg(
train_data: pd.DataFrame,
train_target: pd.DataFrame,
col1: str = 'v5',
col2: str = 'v6'
) -> None:
"""
Make hexbin plot for training transaction data
:param train_data: pd.DataFrame, features dataframe
:param train_target: pd.DataFrame, target dataframe... | 2a5c27a638d43eb64192b28345edcbafd592825a | 3,639,903 |
def raffle_form(request, prize_id):
"""Supply the raffle form."""
_ = request
prize = get_object_or_404(RafflePrize, pk=prize_id)
challenge = challenge_mgr.get_challenge()
try:
template = NoticeTemplate.objects.get(notice_type='raffle-winner-receipt')
except NoticeTemplate.DoesNotExist:... | c84f6a1824ad0d6991306cb543fdaee439b2d183 | 3,639,904 |
def is_rldh_label(label):
"""Tests a binary string against the definition of R-LDH label
As defined by RFC5890_
Reserved LDH labels, known as "tagged domain names" in some
other contexts, have the property that they contain "--" in the
third and fourth characters but which otherwise co... | c44fef221381abaf0fa88115962ab9946c266090 | 3,639,905 |
def offence_memory_patterns(obs, player_x, player_y):
""" group of memory patterns for environments in which player's team has the ball """
def environment_fits(obs, player_x, player_y):
""" environment fits constraints """
# player have the ball
if obs["ball_owned_player"] == obs["activ... | 18643be138781ae7025e6f021437fd1ac2038566 | 3,639,906 |
import psutil
import os
def get_mem() -> int:
"""Return memory used by CombSpecSearcher - note this is actually the
memory usage of the process that the instance of CombSpecSearcher was
invoked."""
return int(psutil.Process(os.getpid()).memory_info().rss) | e2f3a5e4f954ad9a294df1747835cad7684486b0 | 3,639,907 |
import os
import yaml
def load_parameters(directory_name):
"""
Loads the .yml file parameters to a dictionary.
"""
root = os.getcwd()
directory = os.path.join(root, directory_name)
parameter_file_name = directory
parameter_file = open(parameter_file_name, 'r')
parameters = yaml.load(pa... | 793efa00af16851b78fd0f4277b24d03db76fe2c | 3,639,908 |
def aggregated_lineplot_new(df_agg,countries,fill_between=('min','max'),save=False,fig=None,ax=None,clrs='default'):
"""
Creates an aggregates lineplot for multiple countries
Arguments:
*df_agg* (DataFrame) : contains the aggregated results, either relative (df_rel) or absolute (df_abs)
*co... | 0f6214298bb23e0c87d23458092b2b15302e2689 | 3,639,909 |
from typing import OrderedDict
def _stat_categories():
"""
Returns a `collections.OrderedDict` of all statistical categories
available for play-by-play data.
"""
cats = OrderedDict()
for row in nfldb.category.categories:
cat_type = Enums.category_scope[row[2]]
cats[row[3]] = Ca... | fd4df74e8b3c2f94d41f407c88a3be997913adb4 | 3,639,910 |
from typing import List
import random
import math
def rsafactor(d: int, e: int, N: int) -> List[int]:
"""
This function returns the factors of N, where p*q=N
Return: [p, q]
We call N the RSA modulus, e the encryption exponent, and d the decryption exponent.
The pair (N, e) is the public key. As... | 21e655bc3f5b098da0d437a305baf89c70cebd56 | 3,639,911 |
def integrate_prob_current(psi, n0, n1, h):
"""
Numerically integrate the probability current, which is
Im{psi d/dx psi^*} over the given spatial interval.
"""
psi_diff = get_imag_grad(psi, h)
curr = get_prob_current(psi, psi_diff)
res = np.zeros(psi.shape[0])
with progressbar.Prog... | bda6efda2f61d21139011f579398c5363ae53872 | 3,639,912 |
import base64
def getFile(path):
"""
指定一个文件的路径,放回该文件的信息。
:param path: 文件路径
:return: PHP-> base64 code
"""
code = """
@ini_set("display_errors","0");
@set_time_limit(0);
@set_magic_quotes_runtime(0);
$path = '%s';
$hanlder = fopen($path, 'rb');
$res = fread($hanlder, filesize... | e44e3f90e5febee54d2f5de48e35f0b83acf9842 | 3,639,913 |
def rgc(tmpdir):
""" Provide an RGC instance; avoid disk read/write and stay in memory. """
return RGC(entries={CFG_GENOMES_KEY: dict(CONF_DATA),
CFG_FOLDER_KEY: tmpdir.strpath,
CFG_SERVER_KEY: "http://staging.refgenomes.databio.org/"}) | 1b79c9f4d5e07e13a23fe5ff88acf4e022481b42 | 3,639,914 |
import sys
import os
def execlog(command): # logs commands and control errors
"""
controling the command executions using os.system, and logging the commands
if an error raise when trying to execute a command, stops the script and writting the
rest of commands to the log file after a 'Skipping from here' note.
""... | cea497df52838cbeb22fe9d29f72234f4e0076d5 | 3,639,915 |
import time
def simulate_quantities_of_interest_superoperator(tlist, c_ops, noise_parameters_CZ, fluxlutman,
fluxbias_q1, amp,
sim_step,
verbose: bool=True):
"""
Calculates the propagator and the quanti... | d81737e78a9e58ee160f80c58f70f73250f47844 | 3,639,916 |
def __polyline():
"""Read polyline in from package data.
:return:
"""
polyline_filename = resource_filename(
'cad', join(join('data', 'dxf'), 'polyline.dxf'))
with open(polyline_filename, 'r') as polyline_file:
return polyline_file.read() | 667a8a31decd074b1a8599bcde24caaedfd88d02 | 3,639,917 |
import random
import math
def create_identity_split(all_chain_sequences, cutoff, split_size,
min_fam_in_split):
"""
Create a split while retaining diversity specified by min_fam_in_split.
Returns split and removes any pdbs in this split from the remaining dataset
"""
data... | 2be670c382d93437d22a931314eade6ed8332436 | 3,639,918 |
def get_SNR(raw, fmin=1, fmax=55, seconds=3, freq=[8, 13]):
"""Compute power spectrum and calculate 1/f-corrected SNR in one band.
Parameters
----------
raw : instance of Raw
Raw instance containing traces for which to compute SNR
fmin : float
minimum frequency that is used for fitt... | 8536e0856c3e82f31a99d6d783befd9455054e7d | 3,639,919 |
def get_all_child_wmes(self):
""" Returns a list of (attr, val) tuples representing all wmes rooted at this identifier
val will either be an Identifier or a string, depending on its type """
wmes = []
for index in range(self.GetNumberChildren()):
wme = self.GetChild(index)
if wme.IsI... | fb66aef96ca5fd5a61a34a86052ab9014d5db8a4 | 3,639,920 |
from pathlib import Path
import tqdm
def scan_image_directory(path):
"""Scan directory of FITS files to create basic stats.
Creates CSV file ready to be read by pandas and print-out of the stats if
less than 100 entries.
Parameters
----------
path : str, pathlib.Path
Returns
-------... | aaffe891d9c5879973d18d28eff4a18954f0a348 | 3,639,921 |
def load_mat(filename):
"""
Reads a OpenCV Mat from the given filename
"""
return read_mat(open(filename, 'rb')) | 73faf2d2890a859681abdd6043bb4975516465fb | 3,639,922 |
def connected_components(image, threshold, min_area, max_area, max_features, invert=False):
"""
Detect features using connected-component labeling.
Arguments:
image (float array): The image data. \n
threshold (float): The threshold value. \n
...
Returns:
features (pa... | 541e2e8213681a064b605053033fc9aea095ad69 | 3,639,923 |
import os
def reduce_scan(row, params, **kwargs):
"""
Reduce scan-mode grism data
.. warning::
This function is not yet implemented. It will raise an exception.
Parameters
----------
row : abscal.common.exposure_data_table.AbscalDataTable
Single-row table of the expos... | 9a9e19f8a5a48d62181208562a4ecff526b41638 | 3,639,924 |
import os
import sys
import importlib
def module(spec):
""" Returns the module at :spec:
@see Issue #2
:param spec: to load.
:type spec: str
"""
cwd = os.getcwd()
if cwd not in sys.path:
sys.path.append(cwd)
return importlib.import_module(spec) | 33928f92dddeee5fa8822e2a592d9a957867b5d9 | 3,639,925 |
from typing import Tuple
def transform_digits_to_string(labels: Tuple[str], coefficients,
offset: Fraction) -> str:
"""Form a string from digits.
Arguments
---------
labels: the tuple of lablels (ex.: ('x', 'y', 'z') or ('a', 'b', 'c')))
coefficients: the pa... | e9486bd7cd1749a4a33e1ca8d29637468dd0d54b | 3,639,926 |
def match_peaks_with_mz_info_in_spectra(spec_a, spec_b, ms2_ppm=None, ms2_da=None):
"""
Match two spectra, find common peaks. If both ms2_ppm and ms2_da is defined, ms2_da will be used.
:return: list. Each element in the list is a list contain three elements:
m/z from spec 1; i... | 253b51abdc9469a411d5ed969d2091929ba20cd6 | 3,639,927 |
from typing import Callable
from typing import List
from typing import Type
from typing import Optional
def make_recsim_env(
recsim_user_model_creator: Callable[[EnvContext], AbstractUserModel],
recsim_document_sampler_creator: Callable[[EnvContext], AbstractDocumentSampler],
reward_aggregator: Callable[[... | 8056be88f9eb24b4ad29aea9c1a518efb07b26a4 | 3,639,928 |
def unflatten(dictionary, delim='.'):
"""Breadth first turn flattened dictionary into a nested one.
Arguments
---------
dictionary : dict
The dictionary to traverse and linearize.
delim : str, default='.'
The delimiter used to indicate nested keys.
"""
out = defaultdict(di... | f052363b8d71afa8bec609497db8646c26107b54 | 3,639,929 |
def read_array(dtype, data):
"""Reads a formatted string and outputs an array.
The format is as for standard python arrays, which is
[array[0], array[1], ... , array[n]]. Note the use of comma separators, and
the use of square brackets.
Args:
data: The string to be read in.
dtype: The data... | cc272b0e71ddec3200075fe5089cdaf2d6eeea29 | 3,639,930 |
def in_ipynb():
"""
Taken from Adam Ginsburg's SO answer here:
http://stackoverflow.com/a/24937408/4118756
"""
try:
cfg = get_ipython().config
if cfg['IPKernelApp']['parent_appname'] == 'ipython-notebook':
return True
else:
return False
except Name... | 04c9aece820248b3b1e69eaf2b6721e555557162 | 3,639,931 |
import logging
def load_bioschemas_jsonld_from_html(url, config):
"""
Load Bioschemas JSON-LD from a webpage.
:param url:
:param config:
:return: array of extracted jsonld
"""
try:
extractor = bioschemas.extractors.ExtractorFromHtml(config)
filt = bioschemas.filters.Biosc... | 6b3838260c39023b44423d5bcbc81f91a0113a95 | 3,639,932 |
import collections
def pformat(dictionary, function):
"""Recursively print dictionaries and lists with %.3f precision."""
if isinstance(dictionary, dict):
return type(dictionary)((key, pformat(value, function)) for key, value in dictionary.items())
# Warning: bytes and str are two kinds of collect... | d509e8871c6749be61d7b987e5fa67cd3e824232 | 3,639,933 |
def _tonal_unmodulo(x):
"""
>>> _tonal_unmodulo((0,10,0))
(0, -2, 0)
>>> _tonal_unmodulo((6,0,0))
(6, 12, 0)
>>> _tonal_unmodulo((2, 0))
(2, 0)
"""
d = x[0]
c = x[1]
base_c = MS[d].c
# Example: Cb --- base=0 c=11 c-base=11 11 - 12 = -1
if c - base_c > 6:
... | 50ae6b1eea4a281b32d07f0661837748b066af8d | 3,639,934 |
def get_ncopy(path, aboutlink = False):
"""Returns an ncopy attribute value (it is a requested count of
replicas). It calls gfs_getxattr_cached."""
(n, cc) = getxattr(path, GFARM_EA_NCOPY, aboutlink)
if (n != None):
return (int(n), cc)
else:
return (None, cc) | 82c212d1d6aa68b49cde7ec170a47fdb09d1dd46 | 3,639,935 |
def has_three_or_more_vowels(string):
"""Check if string has three or more vowels."""
return sum(string.count(vowel) for vowel in 'aeiou') >= 3 | 8b0b683ebe51b18bdc5d6f200b41794a4cb3a510 | 3,639,936 |
def lbfgs_inverse_hessian_factors(S, Z, alpha):
"""
Calculates factors for inverse hessian factored representation.
It implements algorithm of figure 7 in:
Pathfinder: Parallel quasi-newton variational inference, Lu Zhang et al., arXiv:2108.03782
"""
J = S.shape[1]
StZ = S.T @ Z
R = jnp... | 1cc279a3fd97d8d1987be532bb3bc3c06a76bea7 | 3,639,937 |
from typing import List
from typing import Dict
from typing import Any
def get_geojson_observations(properties: List[str] = None, **kwargs) -> Dict[str, Any]:
""" Get all observation results combined into a GeoJSON ``FeatureCollection``.
By default this includes some basic observation properties as GeoJSON ``... | b87f3bcff5ea022ef6509c3b29491dd0f3c665be | 3,639,938 |
import signal
def createFilter(fc, Q, fs):
"""
Returns digital BPF with given specs
:param fc: BPF center frequency (Hz)
:param Q: BPF Q (Hz/Hz)
:param fs: sampling rate (Samp/sec)
:returns: digital implementation of BPF
"""
wc = 2*pi*fc
num = [wc/Q, 0]
den = [1, wc/Q, wc**2]
... | 9152d9f89781e1151db481cd88a736c2035b9fbd | 3,639,939 |
def create_uno_struct(cTypeName: str):
"""Create a UNO struct and return it.
Similar to the function of the same name in OOo Basic.
Returns:
object: uno struct
"""
oCoreReflection = get_core_reflection()
# Get the IDL class for the type name
oXIdlClass = oCoreReflection.forNam... | acdb7dfaedc75d25e0592b7edf4928779835e5f4 | 3,639,940 |
import pkg_resources
def get_dir():
"""Return the location of resources for report"""
return pkg_resources.resource_filename('naarad.resources',None) | e9f450e3f46f65fed9fc831aaa37661477ad3d14 | 3,639,941 |
import torch
def SoftCrossEntropyLoss(input, target):
"""
Calculate the CrossEntropyLoss with soft targets
:param input: prediction logicts
:param target: target probabilities
"""
total_loss = torch.tensor(0.0)
for i in range(input.size(1)):
cls_idx = torch.full((input.size(0),), ... | e760fb7a8c85cc32e18bf5c1b5882c0a0682d211 | 3,639,942 |
def composite_layer(inputs, mask, hparams):
"""Composite layer."""
x = inputs
# Applies ravanbakhsh on top of each other.
if hparams.composite_layer_type == "ravanbakhsh":
for layer in xrange(hparams.layers_per_layer):
with tf.variable_scope(".%d" % layer):
x = common_layers.ravanbakhsh_set_l... | f5cc3981b103330eef9d2cf47ede7278eef00bdc | 3,639,943 |
def edit_expense(expense_id, budget_id, date_incurred, description, amount, payee_id):
"""
Changes the details of the given expense.
"""
query = sqlalchemy.text("""
UPDATE budget_expenses
SET
budget_id = (:budget_id),
date_incurred = (:date_incurred),
description = (:description),
... | 83a1e591e71efa9a5f8382c934f9090a737a9d5c | 3,639,944 |
def get_mnist_iterator(batch_size, input_shape, num_parts=1, part_index=0):
"""Returns training and validation iterators for MNIST dataset
"""
get_mnist_ubyte()
flat = False if len(input_shape) == 3 else True
train_dataiter = mx.io.MNISTIter(
image="data/train-images-idx3-ubyte",
l... | 4a042595b30aa2801221607d5605dc41eac7acf4 | 3,639,945 |
def dataset():
"""Get data frame for test purposes."""
return pd.DataFrame(
data=[['alice', 26], ['bob', 34], ['claire', 19]],
index=[0, 2, 1],
columns=['Name', 'Age']
) | 53d023b57f5abdd1226f2dfe22ce1853e405c71f | 3,639,946 |
def get_consumer_key():
"""This is entirely questionable. See settings.py"""
consumer_key = None
try:
loc = "%s/consumer_key.txt" % settings.TWITTER_CONSUMER_URL
url = urllib2.urlopen(loc)
consumer_key = url.read().rstrip()
except (urllib... | 77ac3ce96660c32ce9dc43afa0116b7a6e1e1bc2 | 3,639,947 |
from typing import Tuple
def disconnect() -> Tuple[str, int]:
"""Deletes the DroneServerThread with a given id.
Iterates over all the drones in the shared list and deletes the one with a
matching drone_id. If none are found returns an error.
Request:
drone_id (str): UUID of the drone.
R... | c69192ccdc73c27089952d3a27c3ff79dfb932a5 | 3,639,948 |
import torch
def get_graph_feature(x, k=20, idx=None, x_coord=None):
"""
Args:
x: (B, d, N)
"""
batch_size = x.size(0)
num_points = x.size(2)
x = x.view(batch_size, -1, num_points)
if idx is None:
if x_coord is None: # dynamic knn graph
idx = knn(x, k=k)
... | e895a1663fb716846af0976a3203045509591a6e | 3,639,949 |
def get_markers(
image_array: np.ndarray,
evened_selem_size: int = 4,
markers_contrast_times: float = 15,
markers_sd: float = 0.25,
) -> np.ndarray:
"""Finds the highest and lowest grey scale values for image flooding."""
selem = smo.disk(evened_selem_size)
evened = sfi.rank.mean_bilateral(
... | 865d2f5170b85a54902aabdfaee61199359e7d90 | 3,639,950 |
def pd_bigdata_read_csv(file, **pd_read_csv_params):
"""
读取速度提升不明显
但是内存占用显著下降
"""
reader = pd.read_csv(file, **pd_read_csv_params, iterator=True)
loop = True
try:
chunk_size = pd_read_csv_params['chunksize']
except:
chunk_size = 1000000
chunks = []
while loop:
... | 0350e543bc10da5165b97b18c83d6f848cbbc503 | 3,639,951 |
import numpy
def PCA(Y_name, input_dim):
"""
Principal component analysis: maximum likelihood solution by SVD
Adapted from GPy.util.linalg
Arguments
---------
:param Y: NxD np.array of data
:param input_dim: int, dimension of projection
Returns
-------
:rval X: - Nxinput_dim np.array of dimensionality redu... | 0d49a1c8470cba2d6d56a4ce191449b3106e8a93 | 3,639,952 |
import os
import sh
def data_cache_path(page, page_id_field='slug'):
"""
Get (and make) local data cache path for data
:param page:
:return:
"""
path = os.path.join(CACHE_ROOT, '.cache', 'data', *os.path.split(getattr(page, page_id_field)))
if not os.path.exists(path):
sh.mkdir('-p... | 6e96637afab0daaa3e77cd664fa099fd1404dcdf | 3,639,953 |
import collections
def _get_sequence(value, n, channel_index, name):
"""Formats a value input for gen_nn_ops."""
# Performance is fast-pathed for common cases:
# `None`, `list`, `tuple` and `int`.
if value is None:
return [1] * (n + 2)
# Always convert `value` to a `list`.
if isinstance(value, list):... | e2ac408cf299f186bb74fa4b1decc885b1229f9d | 3,639,954 |
def make_linear(input_dim, output_dim, bias=True, std=0.02):
"""
Parameters
----------
input_dim: int
output_dim: int
bias: bool
std: float
Returns
-------
torch.nn.modules.linear.Linear
"""
linear = nn.Linear(input_dim, output_dim, bias)
init.normal_(linear.weight, ... | 57361cadbf3121501da65c3f2f37e61404bc26e3 | 3,639,955 |
def matnorm_logp_conditional_col(x, row_cov, col_cov, cond, cond_cov):
"""
Log likelihood for centered conditional matrix-variate normal density.
Consider the following partitioned matrix-normal density:
.. math::
\\begin{bmatrix}
\\operatorname{vec}\\left[\\mathbf{X}_{i j}\\right] \\\... | 0970ba5a2f67a6156a6077dbd05e2d1cca331476 | 3,639,956 |
import os
def get_map_folderpath(detectionID):
"""
Make sure map directory exists and return folder location for maps to be
saved to.
"""
homedir = os.path.dirname(os.path.abspath(__file__))
if not os.path.exists('map'):
os.makedirs('map')
detection_folder = 'map/'+s... | 3fd3f0bae5d8152b9b46f4f99dc79e14b5318e76 | 3,639,957 |
def get_next_by_date(name, regexp):
"""Get the next page by page publishing date"""
p = Page.get(Page.name == name)
query = (Page.select(Page.name, Page.title)
.where(Page.pubtime > p.pubtime)
.order_by(Page.pubtime.asc())
.dicts())
for p in ifilter(lambda x: regexp.m... | 16e956508c1ccbdf444e84ad769848124449ab84 | 3,639,958 |
import sys
def relative_performance(r_df, combinations, optimal_combinations, ref_method='indp', ref_jt='nan', ref_at='nan',
ref_vt='nan', cost_type='Total', deaggregate=False):
"""
This functions computes the relative performance, relative cost, and univeral
relative measure :cit... | 95a9ed19cf989a426dccf351deb8fd631eaefd98 | 3,639,959 |
def generate_raw_mantissa_extraction(optree):
""" generate an operation graph to extraction the significand field
of floating-point node <optree> (may be scalar or vector).
The implicit bit is not injected in this raw version """
if optree.precision.is_vector_format():
base_precision = o... | f1f0b38f0c68e997ade20ead827f71427104d138 | 3,639,960 |
import time
def read_temp_f(p):
"""
read_temp_f
Returns the temperature from the probe in degrees farenheit
p = 1-Wire device file
"""
lines = read_temp_raw(p)
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw(p)
equals_pos = lines[1].find... | 52114550688f06c8f58dfe37f7c0faa4d93715a2 | 3,639,961 |
def count_parameters(model, trainable_only=True, is_dict=False):
"""
Count number of parameters in a model or state dictionary
:param model:
:param trainable_only:
:param is_dict:
:return:
"""
if is_dict:
return sum(np.prod(list(model[k].size())) for k in model)
if trainable_... | 8e95c3302eca217c694bb4c5262c0196254505fb | 3,639,962 |
def setup_conf(conf=cfg.CONF):
"""Setup the cfg for the status check utility.
Use separate setup_conf for the utility because there are many options
from the main config that do not apply during checks.
"""
common_config.register_common_config_options()
neutron_conf_base.register_core_common_co... | c5ebcc4516e317fc558d8bddeb74343b7006c999 | 3,639,963 |
import pathlib
def release_kind():
"""
Determine which release to make based on the files in the
changelog.
"""
# use min here as 'major' < 'minor' < 'patch'
return min(
'major' if 'breaking' in file.name else
'minor' if 'change' in file.name else
'patch'
for fi... | 115f75c1e0f1e8b02916db518e3983462d9bc19c | 3,639,964 |
import re
def edit_text_file(filepath: str, regex_search_string: str, replace_string: str):
"""
This function is used to replace text inside a file.
:param filepath: the path where the file is located.
:param regex_search_string: string used in the regular expression to find what has to be replaced.
... | e0f5945a96f755a9c289262c3d19552c0e1b40fd | 3,639,965 |
def find_sums(sheet):
"""
Tallies the total assets and total liabilities for each person.
RETURNS:
Tuple of assets and liabilities.
"""
pos = 0
neg = 0
for row in sheet:
if row[-1] > 0:
pos += row[-1]
else:
neg += row[-1]
return pos, neg | 351e13d6915288268a56d8292c470fe354fa9842 | 3,639,966 |
def read_links(title):
"""
Reads the links from a file in directory link_data.
Assumes the file exists, as well as the directory link_data
Args:
title: (Str) The title of the current wiki file to read
Returns a list of all the links in the wiki article with the name title
"""
with... | 50f128bcf4cd36bc783bc848ab2e6b6280973ea3 | 3,639,967 |
def test_compile_model_from_params():
"""Tests that if build_fn returns an un-compiled model,
the __init__ parameters will be used to compile it
and that if build_fn returns a compiled model
it is not re-compiled.
"""
# Load data
data = load_boston()
X, y = data.data[:100], data.target[:... | a4cbc7b4dbc4d9836766c37d8eb1cfdd3d5c324e | 3,639,968 |
import numpy
def writeFEvalsMaxSymbols(fevals, maxsymbols, isscientific=False):
"""Return the smallest string representation of a number.
This method is only concerned with the maximum number of significant
digits.
Two alternatives:
1) modified scientific notation (without the trailing + and ze... | a5434c5f6e845473f2187b969e4fa42538a95633 | 3,639,969 |
def closedcone(r=1, h=5, bp=[0,0,0], sampH=360, sampV=50, fcirc=20):
"""
Returns parametrization of a closed cone with radius 'r' and height 'h at
basepoint (bpx,bpy,bpz), where 'sampH' and 'sampV' specify the amount of
samples used horizontally, i.e. for circles, and vertically, i.e.
for height,... | 8cbf46f0a626d8cc858bab004a21dd9eb189a3eb | 3,639,970 |
def E_lndetW_Wishart(nu,V):
"""
mean of log determinant of precision matrix over Wishart <lndet(W)>
input
nu [float] : dof parameter of Wichart distribution
V [ndarray, shape (D x D)] : base matrix of Wishart distribution
"""
if nu < len(V) + 1:
raise ValueError, "dof parameter n... | 1fa84eb843c91b66b3937b7542be31c00faf002d | 3,639,971 |
def crop_range_image(range_images, new_width, shift=None, scope=None):
"""Crops range image by shrinking the width.
Requires: new_width is smaller than the existing width.
Args:
range_images: [B, H, W, ...]
new_width: an integer.
shift: a list of integer of same size as batch that shifts the crop wi... | 364dc2e1e77052327e3517fb35c0223463179a69 | 3,639,972 |
import string
import random
def randomString(length):
"""Generates a random string of LENGTH length."""
chars = string.letters + string.digits
s = ""
for i in random.sample(chars, length):
s += i
return s | fff13713271b3064b4e42c42c420aad190475d85 | 3,639,973 |
def DrawMACCloseButton(colour, backColour=None):
"""
Draws the wxMAC tab close button using wx.GraphicsContext.
:param `colour`: the colour to use to draw the circle.
"""
bmp = wx.EmptyBitmapRGBA(16, 16)
dc = wx.MemoryDC()
dc.SelectObject(bmp)
gc = wx.GraphicsContext.Create(dc)
... | 96982b68aa926341d7ab74d7ed705c19c232392e | 3,639,974 |
def dispatch(args, validator):
"""
'dispath' set in the 'validator' object the level of validation
chosen by the user. By default, the validator
makes topology level validation.
"""
print("Printing all the arguments: {}\n".format(args))
if args.vnfd:
print("VNFD validati... | b2625b5cb46295d0790b37fa691b8a4d60341e47 | 3,639,975 |
def create_app():
"""Create and configure and instance of the Flask application"""
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
DB.init_app(app)
@app.route('/')
def home():
return ren... | 1e122846bfdfc68a1143eb2d53b87eda9ae9cff6 | 3,639,976 |
import re
import os
def write_chart_json(j2_file_name, item):
"""Write a chart JSON file.
Args:
j2_file_name: the name of the Jinja template file
item: a (benchmark_id, chart_dict) pair
Returns:
returns the (filepath, json_data) pair
"""
file_name = fcompose(
lambda x: ... | a3b19e487ea2c0d4578a88ff12fc32d6de0f0d65 | 3,639,977 |
def get_motif_class(motif: str) -> str:
"""Return the class of the given motif."""
for mcls in gen_motif_classes(len(motif), len(motif) + 1):
for m in motif_set(mcls):
if m == motif:
return mcls
else:
raise ValueError(
"Unable to find the class of the ... | fea293fcf25b77bbf78c400facf450067c94be2b | 3,639,978 |
def resnet_v1(inputs,
blocks,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
include_root_block=True,
spatial_squeeze=True,
store_non_strided_activations=False,
reuse=... | b2008da41f5ada502941c058134ded4d95c3d5c0 | 3,639,979 |
def findConstell(cc):
"""
input is one character (from rinex satellite line)
output is integer added to the satellite number
0 for GPS, 100 for Glonass, 200 for Galileo, 300 for everything else?
author: kristine larson, GFZ, April 2017
"""
if (cc == 'G' or cc == ' '):
out = 0
eli... | d7a85fc5f7324acdb5277fd6db458523cd4ad4b8 | 3,639,980 |
def Controller(idx):
"""(read-only) Full name of the i-th controller attached to this element. Ex: str = Controller(2). See NumControls to determine valid index range"""
return get_string(lib.CktElement_Get_Controller(idx)) | 5adb2f806133319546ea627c705579a3a7e662dd | 3,639,981 |
def smooth_2d_map(bin_map, n_bins=5, sigma=2, apply_median_filt=True, **kwargs):
"""
:param bin_map: map to be smooth.
array in which each cell corresponds to the value at that xy position
:param n_bins: number of smoothing bins
:param sigma: std for the gaussian smoothing
:return: sm_map: s... | a1d8c9b2b8107663746d2c1af9e129d7226e9d0b | 3,639,982 |
import socket
def _select_socket(lower_port, upper_port):
"""Create and return a socket whose port is available and adheres to the given port range, if applicable."""
sock = socket(AF_INET, SOCK_STREAM)
found_port = False
retries = 0
while not found_port:
try:
sock.bind(('0.0.0... | 19427fd0146b5537c6fab898b5e3e0868c8c4a21 | 3,639,983 |
import tqdm
def _stabilization(sr, nmax, err_fn, err_xi):
"""
A function that computes the stabilisation matrices needed for the
stabilisation chart. The computation is focused on comparison of
eigenfrequencies and damping ratios in the present step
(N-th model order) with the previous step ((N-1... | 945f1cb74506753f81112497fb87bf805031f957 | 3,639,984 |
def _factory(cls_name, parent_cls, search_nested_subclasses=False):
"""Return subclass from parent
Args:
cls_name (basestring)
parent_cls (cls)
search_nested_subclasses (bool)
Return:
cls
"""
member_cls = None
subcls_name = _filter_out_underscore(cls_name.lower())
members = (_all_subclasses(p... | 2eb5fb4c3333aaddec418ebac8ecdd824ff4e8ba | 3,639,985 |
def tabuleiro_actualiza_pontuacao(t,v):
"""list x int -> list
Esta funcao recebe um elemento tabuleiro do tipo lista e um elemento v do tipo inteiro e modifica o tabuleiro, acrescentando ao valor da pontuacao v pontos"""
if isinstance(v,int) and v%4==0 and v>=0:
t[4]=tabuleiro_pontuacao(t)+v
... | a247f2c14ffd42fc4d77ae9871ccc08bd967296d | 3,639,986 |
import os
def pybullet_options_from_shape(shape, path='', force_concave=False):
"""Pybullet shape"""
options = {}
collision = isinstance(shape, Collision)
if collision:
options['collisionFramePosition'] = shape.pose[:3]
options['collisionFrameOrientation'] = rot_quat(shape.pose[3:])
... | e89d0fbf23abb99c64914da5ffd132e9bd3f0372 | 3,639,987 |
def showcase_code(pyfile,class_name = False, method_name = False, end_string = False):
"""shows content of py file"""
with open(pyfile) as f:
code = f.read()
if class_name:
#1. find beginning (class + <name>)
index = code.find(f'class {class_name}')
code = code[index:]
... | fe62a99adf5f97164ac69e68554f31d20e126dfa | 3,639,988 |
def get_hyperparams(data, ind):
"""
Gets the hyperparameters for hyperparameter settings index ind
data : dict
The Python data dictionary generated from running main.py
ind : int
Gets the returns of the agent trained with this hyperparameter
settings index
Returns
-----... | 3734f4cf00564a1aa7c852091d366e6e42b6d55b | 3,639,989 |
from typing import Dict
from typing import Any
from typing import Tuple
def _check_df_params_require_iter(
func_params: Dict[str, ParamAttrs],
src_df: pd.DataFrame,
func_kwargs: Dict[str, Any],
**kwargs,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""Return params that require iteration and those ... | e66a42a173f24a33f2457bf6b8cfe4124984f646 | 3,639,990 |
import torch
def train_linear_classifier(loss_func, W, X, y, learning_rate=1e-3,
reg=1e-5, num_iters=100, batch_size=200,
verbose=False):
"""
Train this linear classifier using stochastic gradient descent.
Inputs:
- loss_func: loss function to use when ... | 4587781a47859acf4f4360b0e09e0ef3cdd74289 | 3,639,991 |
import os
def plot_confusion_matrix(cm, classes, std, filename=None,
normalize=False, cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
# std = std * 100
if normalize:
c... | 88e6321deafd1cd10bc142dea263ae636466e675 | 3,639,992 |
import sys
def ruleset_from_auto(source):
""" Automatically load a ruleset from any format
Automatically uncompresses files in either gzip or bzip2 format based
on the file extension if source is a filepath.
source: A file path or file handle
return: A ruleset or an exception
... | a1085a534a5918447745e7a630e1c0a1fa380f0c | 3,639,993 |
import random
import re
import os
import subprocess
def GetEvol(x, **kwargs):
"""
Run a VPLanet simulation for this initial condition vector, x
"""
# Get the current vector
dMass, dSatXUVFrac, dSatXUVTime, dStopTime, dXUVBeta = x
dSatXUVFrac = 10 ** dSatXUVFrac # Unlog
dStopTime *= 1.e9 #... | 6935000c6fae31faf1beebe9f7e5719f5680677f | 3,639,994 |
def _inverse_permutation(p):
"""inverse permutation p"""
n = p.size
s = np.zeros(n, dtype=np.int32)
i = np.arange(n, dtype=np.int32)
np.put(s, p, i) # s[p] = i
return s | 0e8a4cf7156c9dac6a3bb89eb3edb8960478d7b6 | 3,639,995 |
def blend0(d=0.0, u=1.0, s=1.0):
"""
blending function trapezoid
d = delta x = xabs - xdr
u = uncertainty radius of xabs estimate error
s = tuning scale factor
returns blend
"""
d = float(abs(d))
u = float(abs(u))
s = float(abs(s))
v = d - u #offset by radius
... | d501db66c34f28421c1517dcd3052fa7b2ee8643 | 3,639,996 |
def median(a, dim=None):
"""
Calculate median along a given dimension.
Parameters
----------
a: af.Array
The input array.
dim: optional: int. default: None.
The dimension for which to obtain the median from input data.
Returns
-------
output: af.Array
Array... | 0a117fe2f072747e752e77613dc658812630dacc | 3,639,997 |
from typing import Union
async def is_photo(obj: Union[Message, CallbackQuery]) -> bool:
"""
Checks if message content is photo
:return: True if so
"""
obj = await _to_message(obj)
return obj.content_type == 'photo' | 13207a44dba000ad0486997f364f011cfffa9d26 | 3,639,998 |
def check_win(mat):
"""
Returns either:
False: Game not over.
True: Game won, 2048 is found in mat
"""
if 2048 in mat: # If won, teriminal state is needed for RL agent
return True # Terminal state
else:
return False | 0824bc059cfa32b275c7b63f98d22e8a5b667e06 | 3,639,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.