content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_trainable_vars(name):
"""
returns the trainable variables
:param name: (str) the scope
:return: ([TensorFlow Variable])
"""
return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=name) | 22,000 |
def batch_add_annotations(cursor, annotations, annot_type, batch_size):
""" Add gene/transcript/exon annotations to the appropriate annotation table
"""
batch_size = 1
if annot_type not in ["gene", "transcript", "exon"]:
raise ValueError("When running batch annot update, must specify " + \
... | 22,001 |
def getLambdaFasta():
"""
Returns the filename of the FASTA of the lambda phage reference.
"""
return _getAbsPath('lambdaNEB.fa') | 22,002 |
def find_gaps(num_iter):
"""Generate integers not present in an iterable of integers.
Caution: this is an infinite generator.
"""
next_num = -1
for n in num_iter:
next_num += 1
while next_num < n:
yield next_num
next_num += 1
while True:
next_num += 1
yield next_num | 22,003 |
def register_field(name):
"""Register a custom accessor on Activity objects.
Based on :func:`pandas.api.extensions.register_dataframe_accessor`.
Args:
name (str): Name under which the accessor should be registered. A warning
is issued if this name conflicts with a preexisting attribute.
Returns:
... | 22,004 |
def test_deprecation_warnings_set_power(cst_power_2freq):
"""
Test the deprecation warnings in set_power.
"""
power_beam = cst_power_2freq
power_beam2 = power_beam.copy()
with uvtest.check_warnings(DeprecationWarning, match="`set_power` is deprecated"):
power_beam2.set_power()
asse... | 22,005 |
def Rotation_ECL_EQD(time):
"""Calculates a rotation matrix from ecliptic J2000 (ECL) to equatorial of-date (EQD).
This is one of the family of functions that returns a rotation matrix
for converting from one orientation to another.
Source: ECL = ecliptic system, using equator at J2000 epoch.
Targe... | 22,006 |
def _make_players_away(team_size):
"""Construct away team of `team_size` players."""
away_players = []
for i in range(team_size):
away_players.append(
Player(Team.AWAY, _make_walker("away%d" % i, i, _RGBA_RED)))
return away_players | 22,007 |
def store_barbican_secret_for_coriolis(
barbican, secret_info, name='Coriolis Secret'):
""" Stores secret connection info in Barbican for Coriolis.
:param barbican: barbican_client.Client instance
:param secret_info: secret info to store
:return: the HREF (URL) of the newly-created Barbican sec... | 22,008 |
def test_Has_Disk_At__Effective_Disk(score, max_score):
"""Function has_disk_at: effective disk."""
max_score.value += 1
try:
set_up()
assert Board.has_disk_at(test_board_4, (1, 1))
score.value += 1
except:
pass | 22,009 |
def wfr2_grad_single(image, sigma, kx, ky, kw, kstep, grad=None):
"""Optimized, single precision version of wfr2_grad.
Single precision might be faster on some hardware.
In addition to returning the
used k-vector and lock-in signal, return the gradient of the lock-in
signal as well, for each pixel ... | 22,010 |
def padding():
"""Return 16-200 random bytes"""
return URANDOM(random.randrange(16, PAD_MAX)) | 22,011 |
def listener(phrase_limit: int, timeout: int = None, sound: bool = True) -> str:
"""Function to activate listener, this function will be called by most upcoming functions to listen to user input.
Args:
phrase_limit: Time in seconds for the listener to actively listen to a sound.
timeout: Time i... | 22,012 |
def find():
"""Prints user message and returns the number of HP-49 connected.
"""
hps = com.find()
if len( hps ) == 0:
print "No HP49-compatible devices connected."
sys.stdout.flush()
else:
print "Number of HP49-compatible devices: %d" % len( hps )
sys.stdout.flush()
retu... | 22,013 |
def get_children_templates(pvc_enabled=False):
"""
Define a list of all resources that should be created.
"""
children_templates = {
"service": "service.yaml",
"ingress": "ingress.yaml",
"statefulset": "statefulset.yaml",
"configmap": "configmap.yaml",
"secret": "... | 22,014 |
def split_blocks(block_iter, expected_hdr=None):
"""Extract a sequence of MPEG audio frames from a stream of data blocks.
Args:
block_iter: An iterable object that yields a sequence of data
blocks.
expected_hdr: If given, only yield frames matching this MP3Header
template
Y... | 22,015 |
def sort_as_int(environment, value, reverse=False, attribute=None):
"""Sort collection after converting the attribute value to an int"""
def convert_to_int(x):
val = str(x)
# Test if this is a string representation of a float.
# This is what the copy rig does and it's annoying
if... | 22,016 |
def get_pretty_table_for_item(item, output_fields):
"""
"""
x = PrettyTable(["Attribute", "Value"])
attrs = _filter_attributes(item.get_attributes(), output_fields)
for attr in attrs:
row = []
row.append(attr)
row.append(getattr(item, attr))
x.add_row(row)
return... | 22,017 |
def create_t1_based_unwarp(name='unwarp'):
"""
Unwarp an fMRI time series based on non-linear registration to T1.
NOTE: AS IT STANDS THIS METHOD DID NOT PRODUCE ACCEPTABLE RESULTS
IF BRAIN COVERAGE IS NOT COMPLETE ON THE EPI IMAGE.
ALSO: NEED TO ADD AUTOMATIC READING OF EPI RESOLUTION TO... | 22,018 |
def get_qnode(caching, diff_method="finite-diff", interface="autograd"):
"""Creates a simple QNode"""
dev = qml.device("default.qubit.autograd", wires=3)
@qnode(dev, caching=caching, diff_method=diff_method, interface=interface)
def qfunc(x, y):
qml.RX(x, wires=0)
qml.RX(y, wires=1)
... | 22,019 |
def segment_relative_timestamps(segment_start, segment_end, timestamps):
""" Converts timestamps for a global recording to timestamps in a segment given the segment boundaries
Args:
segment_start (float): segment start time in seconds
segment_end (float): segment end time in seconds
tim... | 22,020 |
def compare_dataframes_mtmc(gts, ts):
"""Compute ID-based evaluation metrics for MTMCT
Return:
df (pandas.DataFrame): Results of the evaluations in a df with only the 'idf1', 'idp', and 'idr' columns.
"""
gtds = []
tsds = []
gtcams = gts['CameraId'].drop_duplicates().tolist()
tscams ... | 22,021 |
def visit_simpleimage_node(self, node):
"""
Visits a image node.
Copies the image.
"""
if node['abspath'] is not None:
outdir = self.builder.outdir
relpath = os.path.join(outdir, node['relpath'])
dname = os.path.split(node['uri'])[0]
if dname:
relpath = os... | 22,022 |
def launch_corba(
exec_file=None,
run_location=None,
jobname=None,
nproc=None,
verbose=False,
additional_switches="",
start_timeout=60,
):
"""Start MAPDL in AAS mode
Notes
-----
The CORBA interface is likely to fail on computers with multiple
network adapters. The ANSYS... | 22,023 |
def run_import(data_file: str, mapping_file: str, batch_size: int = 1000,
validate: bool = True, dry_run: bool = False):
"""
Inserts the data from data_file into the database using the mapping_file.
"""
logging.info("Connecting to database")
connection, cursor = connect_db()
log... | 22,024 |
def test_objlist(client, query):
"""Initialize a DataSelection from a list of objects.
"""
objs = client.search(query)
invIds, dsIds, dfIds = get_obj_ids(objs)
selection = DataSelection(objs)
assert selection.invIds == invIds
assert selection.dsIds == dsIds
assert selection.dfIds == dfId... | 22,025 |
def test_get_daily_statements(session, client, jwt, app):
"""Assert that the default statement setting is daily."""
# Create a payment account and statement details, then get all statements for the account
token = jwt.create_jwt(get_claims(), token_header)
headers = {'Authorization': f'Bearer {token}',... | 22,026 |
def fetch_xml(url):
"""
Fetch a URL and parse it as XML using ElementTree
"""
resp=urllib2.urlopen(url)
tree=ET.parse(resp)
return tree | 22,027 |
def update_hirsch_index(depth_node_dict, minimum_hirsch_value, maximum_hirsch_value):
"""
Calculates the Hirsch index for a radial tree.
Note that we have a slightly different definition of the Hirsch index to the one found in:
Gómez, V., Kaltenbrunner, A., & López, V. (2008, April).
Statistical an... | 22,028 |
def migrate():
"""
Apply database migrations.
"""
app_name = orm_settings["config"]["app"]
os.environ["USER_ROOT"] = user_root
utils.set_pythonpath(user_root)
with Path(lib_root):
print()
subprocess.run(f"python manage.py migrate {app_name}")
print() | 22,029 |
def read_trajectory(filename, matrix=True):
"""
Read a trajectory from a text file.
Input:
filename -- file to be read
matrix -- convert poses to 4x4 matrices
Output:
dictionary of stamped 3D poses
"""
file = open(filename)
data = file.read()
lines = data.replace("... | 22,030 |
async def async_start(hass: HomeAssistantType, config_entry=None) -> bool:
"""Start Ampio discovery."""
topics = {}
@callback
async def version_info_received(msg):
"""Process the version info message."""
_LOGGER.debug("Version %s", msg.payload)
try:
data = json.loads... | 22,031 |
def get_E_E_fan_H_d_t(P_fan_rtd_H, V_hs_vent_d_t, V_hs_supply_d_t, V_hs_dsgn_H, q_hs_H_d_t):
"""(37)
Args:
P_fan_rtd_H: 定格暖房能力運転時の送風機の消費電力(W)
V_hs_vent_d_t: 日付dの時刻tにおける熱源機の風量のうちの全般換気分(m3/h)
V_hs_supply_d_t: param V_hs_dsgn_H:暖房時の設計風量(m3/h)
q_hs_H_d_t: 日付dの時刻tにおける1時間当たりの熱源機の平均暖房能力(-)
... | 22,032 |
def load_func(func_string):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if func_string is None:
return None
elif isinstance(func_string, str):
return import_from_string(func_string)
return func_string | 22,033 |
def normalize(features):
"""
Scale data in provided series into [0,1] range.
:param features:
:return:
"""
return (features - features.min()) / (features.max() - features.min()) | 22,034 |
def get_gitlab_template_version(response):
"""Return version number of gitlab template."""
return glom(response, 'ref', default=False).replace('refs/tags/', '') | 22,035 |
def test_get_encoder_for_error_loss_params(D_hat):
"""Tests for invalid value of `loss_params`."""
with pytest.raises(AssertionError,
match="loss_params should be a valid dict or None."):
get_z_encoder_for(X=X,
D_hat=D_hat,
n_at... | 22,036 |
def getConfigXmlString(version, name, protocol, user, host, port, path):
"""! Arguments -> XML String. """
tag_root = ET.Element(TAG_ROOT)
tag_root.set(ATTR_VERSION, version)
tag_remote = ET.Element(TAG_REMOTE)
tag_remote.set(ATTR_NAME, name)
tag_root.append(tag_remote)
appendElement(tag_r... | 22,037 |
def phase_angle(A: Entity,
B: Entity,
C: Entity) -> Optional[float]:
"""The orbital phase angle, between A-B-C, of the angle at B.
i.e. the angle between the ref-hab vector and the ref-targ vector."""
# Code from Newton Excel Bach blog, 2014, "the angle between two vectors"
... | 22,038 |
def point2geojsongeometry(x, y, z=None):
"""
helper function to generate GeoJSON geometry of point
:param x: x coordinate
:param y: y coordinate
:param z: y coordinate (default=None)
:returns: `dict` of GeoJSON geometry
"""
if z is None or int(z) == 0:
LOGGER.debug('Point has n... | 22,039 |
def main(args):
"""
Run processes in parallel if --all=True, otherwise run one process.
"""
if args.all:
# Get all json files
filespath = args.data_dir + 'Original/'
filenames = [os.path.splitext(f)[0] for f in os.listdir(filespath) if f.endswith('.json')]
# ... | 22,040 |
def upper(string): # pragma: no cover
"""Lower."""
new_string = []
for c in string:
o = ord(c)
new_string.append(chr(o - 32) if LC_A <= o <= LC_Z else c)
return ''.join(new_string) | 22,041 |
def test_main_setPref_invalid_field(capsys, reset_globals):
"""Test setPref() with a invalid field"""
class Field:
"""Simple class for testing."""
def __init__(self, name):
"""constructor"""
self.name = name
prefs = MagicMock()
prefs.DESCRIPTOR.fields_by_name.... | 22,042 |
def getid(obj):
"""Return id if argument is a Resource.
Abstracts the common pattern of allowing both an object or an object's ID
(UUID) as a parameter when dealing with relationships.
"""
try:
if obj.uuid:
return obj.uuid
except AttributeError: # nosec(cjschaef): 'obj' doe... | 22,043 |
def dateToUsecs(datestring):
"""Convert Date String to Unix Epoc Microseconds"""
dt = datetime.strptime(datestring, "%Y-%m-%d %H:%M:%S")
return int(time.mktime(dt.timetuple())) * 1000000 | 22,044 |
def _compute_applied_axial(R_od, t_wall, m_stack, section_mass):
"""Compute axial stress for spar from z-axis loading
INPUTS:
----------
params : dictionary of input parameters
section_mass : float (scalar/vector), mass of each spar section as axial loading increases with spar depth
OUT... | 22,045 |
def glob(loader, node):
"""Construct glob expressions."""
value = loader.construct_scalar(node)[len('~+/'):]
return os.path.join(
os.path.dirname(loader.name),
value
) | 22,046 |
def categorical(p, rng=None, size=()):
"""Draws i with probability p[i]"""
if len(p) == 1 and isinstance(p[0], np.ndarray):
p = p[0]
p = np.asarray(p)
if size == ():
size = (1,)
elif isinstance(size, (int, np.number)):
size = (size,)
else:
size = tuple(size)
... | 22,047 |
def parse_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(description='DSNT human pose model info')
parser.add_argument(
'--model', type=str, metavar='PATH', required=True,
help='model state file')
parser.add_argument(
'--gpu', type=int, metavar='N',... | 22,048 |
def get_model(theme, corpus_all, dictionary_all, num_topics=15, passes=25, iterations=400,
eval_every=None, update_every=0, alpha='auto', eta='auto'):
"""
Get the LDA model
"""
# Check if a model with the same config already exists.
# If it does, load the model instead of gener... | 22,049 |
def download_query_log(file_path, from_, to, hashids=None, **opts):
"""
Downloads and saves query search engine/s logs into file.
"""
with open(file_path, 'wb') as file:
log_iter = query_log_iter(from_, to, hashids, **opts)
file.writelines(log_iter) | 22,050 |
def mono_culture(fungi_1, fungi_2, file_dir, reference):
"""
Main
"""
trial_name = fungi_1.name+'_'+fungi_2.name+'_'+reference
fig = plt.figure()
WIDTH = 100
HEIGHT = 100
TIME = 30
# cells = generate_board(WIDTH,HEIGHT)
cells = generate_temp_gradient(WIDTH,HEIGHT)
# cell... | 22,051 |
def covariance_distance(covariances: List[Covariance],
x: np.ndarray) -> np.ndarray:
"""Euclidean distance of all pairs gp_models.
:param covariances:
:param x:
:return:
"""
# For each pair of kernel matrices, compute Euclidean distance
n_kernels = len(covariances)
... | 22,052 |
def create_inputs(im, im_info, model_arch='YOLO'):
"""generate input for different model type
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
model_arch (str): model type
Returns:
inputs (dict): input of model
"""
inputs = {}
inputs['image'... | 22,053 |
def runDSSAT(dbname, options):
"""Driver function for performing a DSSAT nowcast simulation"""
log = logging.getLogger(__name__)
startyear, startmonth, startday = map(
int, options['nowcast']['startdate'].split('-'))
endyear, endmonth, endday = map(
int, options['nowcast']['enddate'].spl... | 22,054 |
def draw_masks(
points,
pil_image,
left_chin_nose_connection,
right_chin_nose_connection,
bottom_chin_nose_connection,
mask
):
"""
It receives 4 key points of the mask in the following format:
points: [top, right, bottom, left]
"""
top, right, bottom, left = points
# Vert... | 22,055 |
def print_args(args):
"""Print out the input arguments."""
print ('Sending test email by file: %s' % args.html) | 22,056 |
def kill_topology(heron_cli_path, cli_config_path, cluster, role, env, topology_name):
"""
Kill a topology using heron-cli
"""
cmd = "%s kill --config-path=%s %s %s" % \
(heron_cli_path, cli_config_path, cluster_token(cluster, role, env), topology_name)
logging.info("Killing topology: %s", cmd)
if ... | 22,057 |
def multiplex(n, q, **kwargs):
""" Convert one queue into several equivalent Queues
>>> q1, q2, q3 = multiplex(3, in_q)
"""
out_queues = [Queue(**kwargs) for i in range(n)]
def f():
while True:
x = q.get()
for out_q in out_queues:
out_q.put(x)
t =... | 22,058 |
def select_project(FILENAME):
"""
lee el fichero xml FILENAME, muestra los proyectos para que el usuario
escoja uno de ellos
input
FILENAME: fichero xml de estructura adecuada situada donde se encuentran
los scripts del programa
return:
el proyecto seleccionado po... | 22,059 |
def compute_average(arr):
"""Compute average value for given matrix
Args:
arr (numpy array): a numpy array
Return:
float: average value
"""
val_avg = np.average(arr)
return val_avg | 22,060 |
def _read_config(rundate, pipeline, *args, **kwargs):
"""Read the configuration of a Where analysis from file
Todo: Add this as a classmethod on Configuration
Args:
rundate: Rundate of analysis.
pipeline: Pipeline used for analysis.
session: Session in analysis.
Returns:
... | 22,061 |
def ta_series(func: Callable, *args, **kwargs) -> QFSeries:
"""
Function created to allow using TA-Lib functions with QFSeries.
Parameters
----------
func
talib function: for example talib.MA
args
time series arguments to the function. They are all passed as QFSeries.
fo... | 22,062 |
def find_trendline(
df_data: pd.DataFrame, y_key: str, high_low: str = "high"
) -> pd.DataFrame:
"""Attempts to find a trend line based on y_key column from a given stock ticker data frame.
Parameters
----------
df_data : DataFrame
The stock ticker data frame with at least date_id, y_key co... | 22,063 |
def find_core(read, core, core_position_sum, core_position_count, start = -1):
"""
Find the core sequence, trying "average" position first for efficiency.
"""
if start < 0 and core_position_count > 0:
core_position = round(core_position_sum/core_position_count)
if len(read) > core_po... | 22,064 |
def clambda(n):
"""
clambda(n)
Returns Carmichael's lambda function for positive integer n.
Relies on factoring n
"""
smallvalues=[1,1,2,2,4,2,6,2,6,4,10,2,12,6,4,4,16,6,18,4,6,10,22,2,20,12,18,\
6,28,4,30,8,10,16,12,6,36,18,12,4,40,6,42,10,12,22,46,4,42,20,16,12,52,18,\
20,6,18,28,58,4,... | 22,065 |
def dashboard():
"""
Render the dashboard template on the /dashboard route
"""
return render_template('page/home/dashboard.html', title="Dashboard") | 22,066 |
def get_port_status(cluster, lswitch_id, port_id):
"""Retrieve the operational status of the port"""
try:
r = do_single_request("GET",
"/ws.v1/lswitch/%s/lport/%s/status" %
(lswitch_id, port_id), cluster=cluster)
r = json.loads(r)
e... | 22,067 |
def ensure_stdout_handles_unicode():
""" Ensure stdout can handle unicode by wrapping it if necessary
Required e.g. if output of this script is piped or redirected in a linux
shell, since then sys.stdout.encoding is ascii and cannot handle
print(unicode). In that case we need to find some compatible en... | 22,068 |
def make_nearest_neighbors_graph(data, k, n=1000):
"""Build exact k-nearest neighbors graph from numpy data.
Args:
data: Data to compute nearest neighbors of, each column is one point
k: number of nearest neighbors to compute
n (optional): number of neighbors to compute simultaneously
Returns:
A... | 22,069 |
def read_examples(input_files, batch_size, shuffle, num_epochs=None):
"""Creates readers and queues for reading example protos."""
files = []
for e in input_files:
for path in e.split(','):
files.extend(file_io.get_matching_files(path))
thread_count = multiprocessing.cpu_count()
# The minimum numbe... | 22,070 |
def gen_context(n=10):
"""
method returns a random matrix which can be used to produce private prices over a bunch of items
"""
return np.random.randint(-3,4,size=(n,n)) | 22,071 |
def test_default_lower_rules():
"""Check that the default lower section rules are set correctly."""
lower_rules = yh.DEFAULT_LOWER_RULES
expected_types = {
"Three of a Kind": rl.NofKindScoringRule,
"Four of a Kind": rl.NofKindScoringRule,
"Full House (Two of a Kind and Three of a Kin... | 22,072 |
def test_get_from_different_buckets(empty_hash_table):
"""Test get works from different buckets."""
empty_hash_table.set('abc', 'a')
empty_hash_table.set('xyz', 'b')
assert empty_hash_table.get('abc') == 'a'
assert empty_hash_table.get('xyz') == 'b' | 22,073 |
def _parallel_binning_fit(split_feat, _self, X, y,
weights, support_sample_weight,
bins, loss):
"""Private function to find the best column splittings within a job."""
n_sample, n_feat = X.shape
feval = CRITERIA[_self.criterion]
split_t = None
spl... | 22,074 |
def _get_latest_template_version_w_git_ssh(template):
"""
Tries to obtain the latest template version using an SSH key
"""
cmd = 'git ls-remote {} | grep HEAD | cut -f1'.format(template)
ret = temple.utils.shell(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr = ret.stderr.decode('utf... | 22,075 |
def checkkeywords(keywordsarr, mdtype):
""" Check the keywords
Datasets: for Check 9
Services: for Check 9
Logic: there must be at least one keyword to get a score = 2. If keywords contain comma's (","), then a maimum of score = 1 is possible.
"""
score = 0
# keywordsarr is an array of objec... | 22,076 |
def update_subset(record, fields, *source_records, **kwds):
"""Given a destination record, a sequence of fields, and source
for each field, copy over the first value found in the source records.
The argument for fields must be an iterable where each item is either a
string or a pair of strings. If it is... | 22,077 |
def compute_presence_ratios(
sorting,
duration_in_frames,
sampling_frequency=None,
unit_ids=None,
**kwargs
):
"""
Computes and returns the presence ratios for the sorted dataset.
Parameters
----------
sorting: SortingExtractor
The sorting result to be... | 22,078 |
async def test_ws_long_lived_access_token(hass, hass_ws_client, hass_access_token):
"""Test generate long-lived access token."""
assert await async_setup_component(hass, "auth", {"http": {}})
ws_client = await hass_ws_client(hass, hass_access_token)
# verify create long-lived access token
await ws... | 22,079 |
def img_box_match(bboxes_gt, bboxes_pre, iou_threshold):
"""
Goal:
Returns info for mAP calculation (Precision recall curve)
Precision = TP / (TP + FP)
Recall = TP / (TP + FN)
Returns:
list of [TP/FP, conf]
num_gt_bboxes : int
Notes:
For each prediction ... | 22,080 |
def random_char():
"""Return a random character."""
return Char(choice(_possible_chars)) | 22,081 |
def test_valid_team():
"""Test the Team static class method is_valid()."""
team = Team("1", "", "Brussel Sprouts")
assert not Team.is_valid(team)
team = create_test_team("1", "brussel-sprouts", "Brussel Sprouts")
assert Team.is_valid(team) | 22,082 |
def _add_subparsers(subparsers):
"""Adds argument subparsers"""
subparsers.required = True # Workaround: http://bugs.python.org/issue9253#msg186387
_add_debian_subparser(subparsers)
_add_macos_subparser(subparsers)
_add_linux_simple_subparser(subparsers) | 22,083 |
def bond(self, atom:Atom, nBonds:int=1, main=False) -> Atom:
"""Like :meth:`__call__`, but returns the atom passed in instead, so you
can form the main loop quickly."""
self(atom, nBonds, main); return atom | 22,084 |
def train_list():
"""
Return a sorted list of all train patients
"""
patients = listdir_no_hidden(INPUT_PATH)
patients.sort()
l = []
for patient in patients:
if labels[patient] != None:
l.append(patient)
return l | 22,085 |
def split_data(X, Y):
"""
This function split the features and the target into training and test set
Params:
X- (df containing predictors)
y- (series conatining Target)
Returns:
X_train, y_train, X_test, y_test
"""
X_train, X_test, Y_train, Y_test = train_test_split(
... | 22,086 |
def load_libsrc():
"""
loads directories in 'nest_py/lib_src' into the sys path.
TODO: needs to automatically pick up new directories,
currently hardcode
"""
import sys
ops_dir = os.path.dirname(os.path.realpath(__file__))
fst_package = ops_dir + '/../lib_src/fst_pipeline'
sys.path.a... | 22,087 |
def get_bucket(client=None, **kwargs):
"""
Get bucket object.
:param client: client object to use.
:type client: Google Cloud Storage client
:returns: Bucket object
:rtype: ``object``
"""
bucket = client.lookup_bucket(kwargs['Bucket'])
return bucket | 22,088 |
def n2(data_source, outfile='n2.html', show_browser=True, embeddable=False,
title=None, use_declare_partial_info=False):
"""
Generate an HTML file containing a tree viewer.
Optionally opens a web browser to view the file.
Parameters
----------
data_source : <Problem> or str
The ... | 22,089 |
def drefrrefsC(dref:DRef, context:Context, S=None)->Iterable[RRef]:
""" Iterate over realizations of a derivation `dref` that match the specified
[context](#pylightnix.types.Context). Sorting order is unspecified. """
for rref in drefrrefs(dref,S):
context2=rrefctx(rref,S)
if context_eq(context,context2):... | 22,090 |
def test_bullet_glyphs(font_fixture):
"""Test that rendering of unicode glyphs works."""
font_fixture.create_window()
font_fixture.load_font(
size=60
)
font_fixture.create_label(
text=u'\u2022'*5,
)
font_fixture.ask_question(
'You should see 5... | 22,091 |
def remove_macros(xml_tree: etree._ElementTree) -> etree._ElementTree:
"""Removes the macros section from the tool tree.
Args:
xml_tree (etree._ElementTree): The tool element tree.
Returns:
etree.ElementTree: The tool element tree without the macros section.
"""
to_remove = []
... | 22,092 |
def change_wireframe_mode():
"""
Change the display mode for the unit cell box.
Equivalent to pressing the `i` key.
"""
gcv().change_wireframe_mode() | 22,093 |
def flight_time_movies_2_binary_search(movie_lengths, flight_length):
"""
Solution: Sort the list of movies, then iterate it, conducting a binary
search on each item for different item, when added together, equals the
flight length.
Complexity:
Time: O(n * lg{n})
Space: O(1)
"""
if len(movie_lengths) < 2:
... | 22,094 |
def section9():
"""
## Update Label Features
""" | 22,095 |
def find_vertical_bounds(hp, T):
"""
Finds the upper and lower bounds of the characters' zone on the plate based on threshold value T
:param hp: horizontal projection (axis=1) of the plate image pixel intensities
:param T: Threshold value for bound detection
:return: upper and lower bounds
"""
N = len(h... | 22,096 |
def _rrd_update(self, timestamp, **kwargs):
"""
Updates a RRD file with the given samples. This implements the
rrdupdate_ command.
:param timestamp: Is either an integer or string containing the
number of seconds since the epoch or a
:py:c... | 22,097 |
def populate_agrument_parser(ap) -> None:
"""
Populates an argparse.ArgumentParser or an subcommand argument parser
"""
pass | 22,098 |
def square_crop_and_resize(image, size):
"""Crops an image to be square by removing pixels evenly from both sides of
the longest side of the image. Then the image is resized to the desired
size"""
# Calculate how much longer the longest side is than the shortest.
extra = max(image.width, image.heig... | 22,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.