content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def to_rgb_image(render_data, color_by_elevation=False):
"""
convert raw sar image and / or point cloud into 8-bit RGB for display
"""
im_rgb = None
radar_image_display = RadarImageStreamDisplay()
# Default image region
xmin = 0
xmax = 60
ymin = -30
ymax = 30
im_res = 0.1
... | 014d348368e6d3c4e8f9ab804dc1896deda23da7 | 3,620,100 |
def torad( theta ):
""" convert to radian
"""
return theta * np.pi / 180.0 | 03323e96477b084f569617d8481f3c49b2e6c34d | 3,620,101 |
import dateutil
from datetime import datetime
def dt_now(delta=None, tz=dateutil.tz.tzutc()):
"""Get the current datetime in for a specific tz.
Args:
delta (:obj:`datetime.timedelta`, optional): default ``None`` -
subtract timedelta from now
tz (:obj:`datetime.timezone`, optional)... | bc7b7f2085d7db90bfcfaff1afa474958d5a14f5 | 3,620,102 |
def lock_change_receiver():
"""
A decorator for connecting receivers to signals that a lock has change.
@receiver(post_save, sender=MyModel)
def signal_receiver(sender, **kwargs):
...
"""
def _decorator(func):
LockCache.lock_change_receivers.append(func)
re... | b8f36a317b3bc9418deca240f831f876f3f670ac | 3,620,103 |
def find_cached_kernel(R, x0, N=32, M=64, max_dx0=1/16):
""" Returns the key for a cached gridder with th given parameters
:param R: Half support in pixels
:param x0: Image plane coordinates up to which coordinates are optimised
:param N: Number of points to evaluate in image space
:param M: Numbe... | 25ebac87308d9ea85abfc68a86c6387475a653a4 | 3,620,104 |
def create_kmer_loc_fn(size):
""" Hash location of kmer for specific size.
NOTE: This is pretty much similar to encode. May refactor later.
"""
offset = kmer_location("A" * size)
def wrapped(seq):
return kmer_location(seq) - offset
return wrapped | 4a8784490079874934cec622867799b690f3da93 | 3,620,105 |
async def suggest_best_practice_by_QA_model(response: Response, data: suggest_best_practice_by_QA_model_body):
"""Example Questions:\n"What is the Item to be sell?",\n"Who is the buyer?",\n"Who is the seller?","What is the due date?"\n\n# Example Context: \n"Dan (the seller) Will be deemed to have completed its del... | ee7757ef3536234b8a59b63af8eee39d1ca5d40f | 3,620,106 |
from typing import Union
def kind_div(x, y) -> Union[int, float]:
"""Tries integer division of x/y before resorting to float. If integer
division gives no remainder, returns this result otherwise it returns the
float result. From https://stackoverflow.com/a/36637240."""
# Integer division is tried fi... | 97343b68051291acc5a614d086d09f59f9b9abfd | 3,620,107 |
def check_tps(row, method, correct_tps):
"""
Check if the trapping clips questions are answered correctly
:param row:
:param method: acr, dcr, or ccr
:return:
"""
# correct_tps = 0
try:
tp_itemcode = row['answer.tp_item_code']
print(tp_itemcode)
suffix =... | e350b39513bb681bdb56bc8a080973910cce8571 | 3,620,108 |
import torch
def to_device(model):
"""
push model to gpu(s) if available
"""
# Send the model to GPU
if torch.cuda.device_count() > 1:
print("Using", torch.cuda.device_count(), "GPUs!")
model = nn.DataParallel(model)
model = model.to(config.DEVICE)
return model | bed878a972a1cdff8c4a3b675f943fad74f3392c | 3,620,109 |
def collect_predicates(subject, row, structure_row, files, stc, prefixes):
"""
Function to collect predicates for a given subject
Parameters
----------
subject : string
Turtle object
row : Series
row from structure_to_keep
pandas series from generator
ie, row[1]... | ead43f7048570d28b150cb1f9ed25939a2aa7195 | 3,620,110 |
import urllib
import os
def path_to_file_uri(path):
"""Convert local filesystem path to legal File URIs as described in:
http://en.wikipedia.org/wiki/File_URI_scheme
"""
x = urllib.pathname2url(os.path.abspath(path))
if os.name == 'nt':
x = x.replace('|', ':') # http://bugs.python.org/issu... | 3dd1b264f92f46a1a077bc0b549c4ec31de7fade | 3,620,111 |
import enum
import os
def build_amqp_url(
user: str = None,
password: str = None,
host: str = None,
port: int = None,
virtual_host: str = None,
connection_attempts: int = None,
heartbeat_interval: int = None,
ssl_options: dict = None,
) -> str:
"""
Create a AMQP connection URL ... | 846fec83122a117eef693a6b629df838d3515d3d | 3,620,112 |
def parse_fun(serialized_example):
""" Data parsing function.
"""
features = tf.io.parse_single_example(serialized_example,
features={'image': tf.io.FixedLenFeature([], tf.string),
'label': tf.io.FixedLenFeature([], tf.i... | f8e7c17309995fa6920bc67100ddd39f388422ae | 3,620,113 |
import os
def load_train_val_public_set(split=SPLIT, is_one_hot=False,
is_plot_data=False, is_drop_col=False, pca_transform=0):
"""
Load and transform public dataset by config mode
Return:
X, Y or X, Y divide into train/val set
"""
X = load_csv(os.pa... | 53b1e322a5e1c603fa0331a037f83b1d02eb87ca | 3,620,114 |
from itertools import chain
import os
def parse_feedstock_file(feedstock_fpath):
"""
Takes a file with space-separated feedstocks on each line and comments
after hashmarks, and returns a list of feedstocks
:param str feedstock_fpath:
:return: `list` -- list of feedstocks
"""
if not (isins... | 0c6bd403c07c97256db9fd310ceaf2476b2b78f3 | 3,620,115 |
import os
def get_processes(options):
"""Interprets provided options and returns a list of processes"""
nf_core_mapping = {}
multiprocesses = {}
inputs = []
outputs = []
errouts = []
pargs = []
workloads = options.cmd.split(';')
print(workloads)
if options.input != "":
... | 9fba9b31c385c7bf0e0caf10da33e97c39d2056e | 3,620,116 |
def softmax(Z):
"""
Z: output out of the dense layer. shape: (vocab_size, m)
"""
softmax_out = np.divide(np.exp(Z), np.sum(np.exp(Z), axis=0, keepdims=True) + 0.001)
assert (softmax_out.shape == Z.shape)
return softmax_out | e947c22c18d65e4db9d8d7e6b3dae37b4cc97cac | 3,620,117 |
from typing import cast
def lin_2020_to_xyz(rgb: MutableVector) -> MutableVector:
"""
Convert an array of linear-light rec-2020 values to CIE XYZ using D65.
(no chromatic adaptation)
http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
"""
return cast(MutableVector, util.dot(RGB... | 95f01fe5314908ba491bb5384c0b4ad4c54c8288 | 3,620,118 |
def match_matrix_transform(source, target):
"""
match the transform
:param source: <str> source object to snap to target.
:param target: <str>, <tuple> target object, or matrix array.
:return: <bool> True for success. <bool> False for failure.
"""
if isinstance(target, (tuple, list)) and len... | db9086ec40bda6fb8dd37f18e072e10c56d3043a | 3,620,119 |
import typing
def gather_ss_evaluations(
evaluations: typing.Iterable[tuple],
) -> tk.evaluations.EvalsType:
"""evaluate_ss_singleの結果のリストから評価結果を作成して返す。
Args:
evaluations: evaluate_ss_singleの結果のリスト
Returns:
各種metrics
- "iou": クラスごとのIoU
- "miou": クラスごとのIoUのマクロ平均
... | 8eb165e2a19344425f476a3b93b5ebf037b1a478 | 3,620,120 |
from pathlib import Path
from typing import Dict
from typing import Optional
def get_unrecognized_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
"""dirs that don't contain recognizable archive data and aren't listed in the main index"""
unrecognized_folders: Dict[str, Optional[Link... | defe14201267ee8cb942f39b4abb4f43ae9114c0 | 3,620,121 |
def lookup_device(name):
"""Look up the device's address from the given name"""
global DEBUG, m_devices
devaddr = 0
if m_devices is None or name == '':
return devaddr
if DEBUG: print("DEBUG: Looking up device ID from database")
for dev in m_devices:
try:
devname = dev... | 55958ff5210205f5f5bdc8d8c81ceb2d77dbf34f | 3,620,122 |
def _remove_empty_timesteps(sp_tensor):
"""Creates a 3D SparseTensor skipping empty time steps.
Args:
sp_tensor: A SparseTensor with at least 2 dimensions (subsequent ones will
be ignored and simply flattened into the 2nd dimension).
Returns:
A 3D SparseTensor with index 0 for dimension 3 and a se... | dd65bdc9c6509649dcfab9a47b08ca6696a88b4b | 3,620,123 |
def get_first_node_of_tree(root_node):
"""root_node's rhythm is #4"""
return root_node.sons[0].sons[0].sons[0].sons[0].sons[0] | 3dc2d8cb4a2ea006c35cc3fcfdf5efde5c21bb78 | 3,620,124 |
import os
def secondary_feature(name, dependencies):
"""
Some explanation of how to use this decorator goes here.
"""
def _wrapper1(func):
def _wrapper2(*args, **kwargs):
# Verify all required parameters for the primary feature function.
params = [
... | 45047eb8f49ef2e7c69f73b45d9016a75cf204e5 | 3,620,125 |
def rat_fun(x, poles):
"""
Computes the value of a rational function with poles in poles and roots in
-poles; see Definition 8.29 from the doctoral thesis "Model Order Reduction
for Fractional Diffusion Problems" for a precise definition.
Parameters
----------
x : float
The argument... | 48e14764595f1242e65908d8008ada2ac64a4a90 | 3,620,126 |
def orffinder(sequence, output, min_prot_len=30, description="putative protein"):
"""
Find all open reading frames in a nucleotide sequence.
ORFs are translated to amino acid sequences and written to a protein
fasta. The unique identifier for each translated ORF contains information
about it's star... | a7840142a6e830c3ecbfb5c23456ae5e2324c101 | 3,620,127 |
def createCode(videoNameList, fileUrlList, videoIdList, codeFile):
"""
参数:文件名称列表,文件链接列表,文件id列表,代码文件
功能:将已有数据批量写入代码并形成列表
返回值:代码列表
"""
codeList = []
for i in range(len(videoNameList)):
codeF = open(codeFile, "r", encoding = "utf-8")
code = codeF.read()
codeF.close()
... | 6c6bc86e971975a1c9524a201c74c2fcfec7c1fc | 3,620,128 |
def snapshot_in_progress(client, repository=None, snapshot=None):
"""
Determine whether the provided snapshot in `repository` is ``IN_PROGRESS``.
If no value is provided for `snapshot`, then check all of them.
Return `snapshot` if it is found to be in progress, or `False`
:arg client: An :class:`el... | 7c51d41b056ef9adc291d6101305f67054188b71 | 3,620,129 |
from re import DEBUG
def is_ssl_cert_master(votes=None):
"""Return True if this unit is ssl cert master."""
votes = votes or get_ssl_cert_master_votes()
set_votes = set(votes)
# Discard unknown votes
if 'unknown' in set_votes:
set_votes.remove('unknown')
# This is the elected ssl-cer... | 9d35ada7263edfd802c7081ffa1e8cf663a0ad0d | 3,620,130 |
def get_crop_cycle_length(crop):
"""Get crop cycle length for named crop"""
path = _find_crop_file(crop)
return _get_crop_cycle_length(path) | fe86bdb93e936e1fe3b5caf1adb4352d94b7fee4 | 3,620,131 |
def node_to_get_shape_value_of_indices(shape_node: Node, indices: list) -> Node:
"""
The function returns a node that produces values of the specified indices of the input node 'shape_node'
:param shape_node: the node of 1D output shape to get elements from
:param indices: the list of element indices t... | b4d600643456b0e75fe776527df1a1d74f96e3bd | 3,620,132 |
def get_TIS_highest_interface_update_mask(
TIS_origins, highest_interface, update_factor):
"""Make a mask with the update_factor at all positions of the
highest interface and 0 everywhere else.
"""
return get_TIS_highest_interface_true_mask(
TIS_origins, highest_interface) * update_facto... | c4f95316f69ad27ba4341c618ad0bfee2c47a1e1 | 3,620,133 |
import click
from datetime import datetime
def import_mission_reports(vehicles_file, missions_file, no_confirm):
""" Imports the existing mission reports. """
if not no_confirm:
click.confirm(
'This will delete all existing missions and vehicles, continue?',
abort=True
... | e4434a762e23538e13409a072fb3a02b041537f2 | 3,620,134 |
def _optargs_to_kwargs(args):
"""Convert --bar-baz=quux --xyzzy --no-squiz to kwargs-compatible pairs.
E.g., [('bar_baz', 'quux'), ('xyzzy', True), ('squiz', False)]
"""
kwargs = []
for arg in args:
if not arg.startswith('--'):
raise RuntimeError("Unknown option %r" % arg)
... | f0523442f3de88d123c0d968a770f817084149df | 3,620,135 |
import torchvision
def vgg19_bn():
"""VGG19_BN Model pre-trained on ImageNet"""
model = torchvision.models.vgg19_bn(pretrained=True)
obj = ImageClassificationModule(model, "VGG19_BN", model_example="default")
return obj | 6ef62887dd6c649d6ef5e07dd7a2180869ee454b | 3,620,136 |
def spatial_aggregation(target_dataset, lon_min, lon_max, lat_min, lat_max):
""" Spatially subset a dataset within the given longitude and latitude boundaryd_lon-grid_space, grid_lon+grid_space
:param target_dataset: Dataset object that needs spatial subsetting
:type target_dataset: Open Climate Workbench D... | f2f9cb8bbf95f3e2ffba886a5437b195423cca8b | 3,620,137 |
def mark_overlaps_high_res(low_list,high_list):
"""mark overlapping loops between low resolution loops
and high resolution loops,
return lists of loops in which low resolution overlaping loops marked by 1"""
marker=np.zeros(len(low_list))
for index, row in low_list.iterrows():
c1=row[0... | c68a508081da332046dec43a2390d6ca7bdb4caf | 3,620,138 |
from re import T
def crosschannelnormalization(alpha = 1e-4, k=2, beta=0.75, n=5,**kwargs):
"""
This is the function used for cross channel normalization in the original Alexnet
combing the conventkeras and pylearn functions.
erralves
"""
def f(X):
ch, r, c, b = X.shape
half =... | 241ac6e37ae2fd222af94d20ba38f6a1c4b82a5b | 3,620,139 |
def fetSpIdx(spikes_data):
"""Spike sequential index (0,1,2, ...)
"""
spikes = _get_data(spikes_data, [0])
n_datapts = spikes.shape[1]
return {'data':np.arange(n_datapts)[:, np.newaxis],'names':["SpIdx"]} | c986dbb31bc7d422c885945b38b4096293ef5e0a | 3,620,140 |
def onfiledeletion(archiveselection_name, p5_connection=None, command=None):
"""
Syntax: ArchiveSelection <name> onfiledeletion <command>
Description: Registers the <command> to be executed immediately after the
files are deleted through a job created by the submit method. See
onjobactivation for fu... | edce77ba1ac465a381e9c579d35ad682c85c7097 | 3,620,141 |
from typing import Counter
def scopes_size(scopes: Scopes) -> Counter:
"""
scopes_size(scopes: Scopes) -> Counter:
Calculate the different scope lengths.
Parameters
----------
scopes
Dictionary of cells (keys) and their scopes
Returns
-------
Counter of scopes... | 228899dd9b87f6e79204c39c5ea21b9f99d987bb | 3,620,142 |
import torch
from typing import List
def compile(model: torch.nn.Module,
example_args: List[torch.Tensor],
output_type: OutputType = OutputType.TORCH,
use_tracing=False):
"""Convert a PyTorch model to MLIR.
Args:
model: The PyTorch model to convert.
example... | fe333d7d3d72418e66f774a1cae36c40790758cb | 3,620,143 |
import csv
def _get_reader(file):
"""Get CSV reader and skip header rows."""
reader = csv.reader(file)
# Skip first 3 rows because they're all headers.
for _ in range(3):
next(reader)
return reader | 588328d9ccb5af32abad0c0d8fe8c4489d306c12 | 3,620,144 |
import array
def hx(x):
""" compute measurement for slant range that
would correspond to state x.
"""
global X1,Y1,X2,Y2,X3,Y3,A1,A2,A3,n1,n2,n3
h1 = -(A1+5*n1*log10(pow((x[0]-X1),2)+pow((x[1]-Y1),2)))
h2 = -(A2+5*n2*log10(pow((x[0]-X2),2)+pow((x[1]-Y2),2)))
h3 = -(A3+5*n3*log10(pow((x[0]-... | 82f1e454cd4faa05820e1d3d2d531dbb8da110cf | 3,620,145 |
from typing import Counter
def add_intersection_delay(G, intersection_delay=7, time_col = 'time', highway_col='highway', filter=['projected_footway','motorway']):
"""
Find node intersections. For all intersection nodes, if directed edge is going into the intersection then add delay to the edge.
If the hig... | 536ac0d22fcccf9426140e7b4de6367a029c41a6 | 3,620,146 |
def left_justify_string(keyword, value):
"""Returns a string with dotted separation.
"""
return '%s' % keyword .ljust(40, ".") + ": " + '%s\n' % value | dc9c59224ee2c62e2c55093792f352f80df5c4b2 | 3,620,147 |
import dotenv
import os
async def get_obs_loc(place='', *, exclude=''):
"""
Accepts place and JSON arguments for One Call data to ignore.
Returns tuple with PyOWM OneCall and geopy Location.
Default place is Toronto, ON.
Observation taken using OWM One Call API.
https://openweathermap.org/ap... | cefb127b1ef8696865f31442419de7d366d765d3 | 3,620,148 |
def svn_inheritance_from_word(*args):
"""svn_inheritance_from_word(char word) -> svn_mergeinfo_inheritance_t"""
return apply(_core.svn_inheritance_from_word, args) | 36b0b40f005ecb86e3c4ffdc2a41cb97fb3fd263 | 3,620,149 |
def APO(ds, count, fastperiod=-2**31, slowperiod=-2**31, matype=0):
"""Absolute Price Oscillator"""
return call_talib_with_ds(ds, count, talib.APO, fastperiod, slowperiod, matype) | 1bdb96d40d26c5b9283465db4f65016ba84d0aea | 3,620,150 |
import pathlib
def write_text(path: str, data: str, encoding=None, append=False):
"""write text `data` to path `path` with encoding
e.g
j.sals.fs.write_text(path="/home/rafy/testing_text.txt",data="hello world") -> 11
Args:
path (str): path to write to
data (str): ascii content
... | 1d64c9494ee87c3ce0f0ad33466e260c1d7e43bd | 3,620,151 |
import json
def request_json(url: str, data=None, headers=None, method=None) -> dict:
"""
requests a url and convert return into json
:raises EzeNetworkingError: on networking error or json decoding error"""
log_debug(f"calling url '{url}'")
if not headers:
headers = {}
contents = req... | 9fd629f4e09a0be82f15fa028e99efbead8eb553 | 3,620,152 |
import os
def main(filenames=[], debug=False):
"""
start the editor, with a new empty document
or load all *filenames* as tabs
returns the tab object
"""
odmlui.DEBUG = debug
Editor.register_stock_icons()
editor = Editor.EditorWindow()
# Convert relative path to absolute path, if... | 909fb96a0630286f5b6bf52b20f0d0549ec48da4 | 3,620,153 |
import scipy
def z_cmp(calculated_z_score_proportion, criticalz_percentage_proportion):
"""
calculated_z_score_proportion: the z score calculated from mu and xbar in proportion
criticalz_percentage_proportion: Given Critical Value proportion for acceptance criteria
if calculated_z_score_proportion > c... | aad97f76f704a3a126edadd200cdcb894e0dc71d | 3,620,154 |
def get_first_index_greater_than_benchmark(arr, benchmark, reverse=False):
"""
获取在数组 arr 中第一个大于基准值的索引。reverse 控制反向查找或正向查找
Args:
arr(list):
benchmark():
reverse(bool):
Returns:
"""
if reverse:
start = len(arr) - 1
stop = -1
step = -1
else:
start = 0
stop = len(arr)
ste... | 8bc6fd64e07428af68da4dd39e1f44db856e55d8 | 3,620,155 |
import numpy
def load_from_dump(inLoc):
"""
Loads data from dumped state (generated by dumped_params), and creates a
new DBN.
"""
dump = cPickle.load(open(inLoc, 'rb'))
# Get the number of layers.
max_layer = 0
for layer, _ in dump:
if layer > max_layer:
max_layer =... | 240b48cd18f29216eaa0d02e36c159473fd8f27a | 3,620,156 |
from typing import Tuple
import itertools
def make_roc_curve_plot(
train_inputs: Tuple[np.ndarray],
test_inputs: Tuple[np.ndarray],
job_config: ht.config,
save_dir: ht.pathlike,
):
"""Plots ROC curve."""
logger.info("Plotting train/test ROC curve.")
tc = job_config.train.clone()
ac = j... | 4ff642735af694f6638defea95fb3a591a00a380 | 3,620,157 |
from typing import Optional
def _assemble_tn_as_iterator_content_by_verse(
usfm_resource: Optional[USFMResource],
tn_resource: Optional[TNResource],
tq_resource: Optional[TQResource],
tw_resource: Optional[TWResource],
ta_resource: Optional[TAResource],
usfm_resource2: Optional[USFMResource],
... | 69756da3f0c5e47b82975df658222bc2b66b4b95 | 3,620,158 |
def _labels_cost(Xnum, Xcat, centroids, num_dissim, cat_dissim, gamma, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-prototypes algorithm.
"""
n_points = Xnum.shape[0]
Xnum = check_array(Xnum)
cost = 0.
labels = np.empty(n_... | cc1f046bb8df5e9a8fc7327921e95ac387af6750 | 3,620,159 |
def cookie_app(environ, start_response):
"""A WSGI application which sets a cookie, and returns as a response any
cookie which exists.
"""
response = Response(environ.get('HTTP_COOKIE', 'No Cookie'),
mimetype='text/plain')
response.set_cookie('test', 'test')
return respon... | 27ef26b4bb65f74a6f2862f0cc0e044f679f9a20 | 3,620,160 |
import argparse
def local_args():
""" Create an argparse namespace to create a local dask cluster.
"""
args = argparse.Namespace()
args.num_procs = 1
args.num_threads_per_proc = 1
args.cluster_location = "LOCAL"
args.client_restart = False
return args | 2c9d9d260a1994bfa794d356babe101af9722521 | 3,620,161 |
def weighted_bipartite_matching(A, perm_type='row'):
"""
Returns an array of row permutations that attempts to maximize the product
of the ABS values of the diagonal elements in a nonsingular square CSC
sparse matrix. Such a permutation is always possible provided that the
matrix is nonsingular.
... | 77a423f0c25cce01ca26d5e750f2bfecc2b11c14 | 3,620,162 |
def filename_timestamp():
"""Returns a timestamp appropriate for inclusion as part of a filename.
The timestamp includes microseconds, and so subsequent calls to this
function are guaranteed to return different filenames.
"""
# FILENAME_TIMESTAMP_FORMAT is hidden inside this function because it
... | 573afce5de2916cf351ecf7353926dc730f74f2c | 3,620,163 |
import logging
def set_file_logger(filename, name='funcx', level=logging.DEBUG, format_string=None):
"""Add a stream log handler.
Args:
- filename (string): Name of the file to write logs to
- name (string): Logger name
- level (logging.LEVEL): Set the logging level.
- format_... | 5ad8325d5bfe41631fa56ca919591235a50a29ea | 3,620,164 |
def generate_files(app_config):
"""Generate a Dockerfile and helper files for an application.
Args:
app_config (AppConfig): Validated configuration
Returns:
dict: Map of filename to desired file contents
"""
if app_config.has_requirements_txt:
optional_requirements_txt = ge... | efb384ae404089d5c16313f5640b2ee0ae65b107 | 3,620,165 |
def fixture_packages_with_trailing_spaces():
"""
A packages dictionary with trailing spaces on some items
"""
packages = {
"basic": ["package-one ", "package-two"],
"complex": ["package-three", "package-four", "package-five"],
}
return packages | cdf80f2f45ad339aeb8da40c175ad26b10e1e1c6 | 3,620,166 |
def solve_pdd(cell: PVCell, v: f64, pot_ini: Potentials):
"""Solve PDD system at a specified voltage, with IFT for gradient
Args:
cell (PVCell): An initialized cell
v (f64): Voltage to solve at, in dimensionless form
pot_ini (Potentials): Initial guess of solution
Returns:
... | e8ccd978fcc38a96a354c9722fadfa605a414eea | 3,620,167 |
def Backbone(backbone_type='ResNet50', use_pretrain=True, post_name='_extractor'):
"""Backbone Model"""
weights = None
if use_pretrain:
weights = 'imagenet'
def backbone(x):
if backbone_type.lower() == 'MLSD'.lower():
extractor = MobileNetV2(
input_shape=... | d5ecace400bfd304ef15e3b1c13773b14a6c786f | 3,620,168 |
import subprocess
def run_dmenu(words=[]):
"""
Runs dmenu
"""
if not words:
command = ["echo", "Search wikipedia"]
else:
command = ["echo", '\n'.join(words)]
ps = subprocess.Popen(command, stdout=subprocess.PIPE)
result = subprocess.check_output([
_get_exec(), "-p",... | 696d46e79b7e6c489a6f3ccbfe43c873b219cd05 | 3,620,169 |
def convert_numeric(dataframe: pd.DataFrame) -> pd.DataFrame:
"""Convert objects or numerics to downcasted nullable boolean, nullable integer, or nullable float data type if possible.
Parameters
----------
dataframe (pandas.DataFrame) : contains unconverted and non-downcasted columns
Returns
-... | 7547af0e50b2f54c6a436d640889d06f05a31794 | 3,620,170 |
def conn_portal(webgis_config):
"""Creates a connection to an ArcGIS Portal."""
w_gis = None
try:
if cfg_webgis['profile']:
w_gis = GIS(profile=webgis_config['profile'])
else:
w_gis = GIS(webgis_config['portal_url'], webgis_config['username'], webgis_config['password'... | ed17716b185b2f51a323637f3a8f237d089f03f3 | 3,620,171 |
def about():
"""
The about me page.
"""
about_page = Page.query.filter(name='about')
return render_template('blog/about.html', about=about_page, page='about') | cf1780a190c4461165d73aa6e901a5073dc96573 | 3,620,172 |
def dice(a, b):
"""
"Entity-based" measure in CoNLL; #4 in CEAF paper
"""
if a and b:
return (2 * len(a & b)) / (len(a) + len(b))
return 0. | ef650786ad86e0e60a3b80c99445bc95b2b5187d | 3,620,173 |
def traverseFilter(node,filterCallback):
"""Traverse every node and return a list of the nodes that matched the given expression
For example:
expr='a+3+map("test",f())'
ast=SeExprPy.AST(expr)
allCalls=SeExprPy.traverseFilter(ast.root(),lambda node,children: node.type==SeExprPy.ASTType.C... | 751810f0eb54b4aa08cf020f34649780bd208d81 | 3,620,174 |
def int2bin(n,digits=8):
""" integer to binary string"""
return "".join([str((n >> y) & 1) for y in range(digits-1, -1, -1)]) | 13e8ad69a1f8523c647376473605f581369488d9 | 3,620,175 |
def infer_locations(data: InferenceHint) -> pd.DataFrame:
"""Infer the locations for the given input."""
return infer_concat(get_location_model(), data, columns=LOCATION_COLUMNS) | f49c40d54d99d9bf45f35dea9f496584d2199dcb | 3,620,176 |
def replace_digits(p, digits):
"""If p contains more than one of the same digit, replace them will all
other possible digits."""
if 0 in digits:
other_digits = [str(d) for d in list(range(1, 10))
if str(d) != str(p)[digits[0]]]
else:
other_digits = [str(d)... | e29c2e95d043f07aefb538c71f57bbe7d857b086 | 3,620,177 |
def flattendataitem(dataitem):
"""
This could easily be more elegant, but
"""
# If it's a dataitem for the multiplex stream we don't flatten it
if not isnormaldataitem(dataitem):
return dataitem
# Nice normalized dataitems get to be flattened of course
flattened = dict()
innerda... | 5a9ad20865d5d8041bd9a1276ac9063a56a65e1d | 3,620,178 |
def active_piece(piece):
"""
Validate piece as active.
"""
return piece & 1 and piece & 0xE | bb9740b3eabfade4fa6f2a810243965e03c64d2e | 3,620,179 |
def get_db_connection(config_filename):
"""
Create a database connection to the mysql database associated with slurm.
:param config_filename: path to slurmdbd.conf
:return: database connection
"""
config = Config(config_filename)
port = None
if config.port:
port = int(config.port... | d9ee99d1b9e3394dc4589f7a6a80892aac03528f | 3,620,180 |
import torch
def _create_gradient_clipper(cfg):
"""
Creates gradient clipping closure to clip by value or by norm,
according to the provided config.
"""
cfg = cfg.clone()
def clip_grad_norm(p: _GradientClipperInput):
torch.nn.utils.clip_grad_norm_(p, cfg.CLIP_VALUE, cfg.NORM_TYPE)
... | 35fc3aa49c2b86094b38c0fe0b3b20a2a2572ccf | 3,620,181 |
def readwav(filename):
""" read in audio data from a wav file. Return d, sr """
# Read in wav file
sr, wavd = wav.read(filename)
# normalize short ints to floats of -1 / 1
data = np.asfarray(wavd) / 32768.0
return data, sr | 4c9ecbececeadb413ffcb25bfaaf4e93bc453f74 | 3,620,182 |
def jacobian(x0, system, weight=False):
"""Compute the Jacobians of a steady state nonlinear state-space model
Jacobians of a nonlinear state-space model
x(t+1) = A x(t) + B u(t) + E zeta(x(t),u(t))
y(t) = C x(t) + D u(t) + F eta(x(t),u(t))
i.e. the partial derivatives of the modeled ou... | 2b9d2c942e38678fe1b68954c922d5d9b22515c5 | 3,620,183 |
import sys
import os
def parse_args(argv=None):
"""Return the parsed args to use in main()."""
if argv is None:
argv = sys.argv
prog = argv[0]
if prog == __file__:
prog = '{} -m ptvsd'.format(os.path.basename(sys.executable))
else:
prog = argv[0]
argv = argv... | 36173a48b75915d63945f6aa1d0f9cd3ff4df4a9 | 3,620,184 |
import urllib
import os
def bay_bridge_example(render=None,
use_inflows=False,
use_traffic_lights=False):
"""
Perform a simulation of vehicles on the Oakland-San Francisco Bay Bridge.
Parameters
----------
render: bool, optional
specifies whet... | f1be3d5bd759201323c15410b28ebb31228563b0 | 3,620,185 |
import os
from pathlib import Path
def load_training_dataset(data_path,datafile,normalize_by='by_subject',scaling=True,padding=True,input_shape=(79, 95, 69)):
"""
Loads the training dataset from datset.pickle file and returns the train, test and val dataset
data_path: str full path of the data
datafil... | bb60f6afeb87ee6b986a99bc3c482c75ceca8c32 | 3,620,186 |
def keepClosestMarkupRelationships(markup):
"""Initially modifiers may be applied to multiple targets. This function
computes the text difference between the modifier and each modified
target and keeps only the minimum distance relationship
Finally, we make sure that there are no self modifying modifie... | 97b3a76f441c5b45eaf90313afe265a625a72618 | 3,620,187 |
def dsfdP(P):
""" Derivative of Specific entropy [kJ m^3 / kg K kJ]
of saturated liquid w.r.t. pressure"""
T = satT(P)
return region1.dsdP(P, T) + region1.dsdT(P, T) * dTsdP(P) | 8bb7bbe6a8dd184a825a4fcb38c444af7e2bdfec | 3,620,188 |
def calcDeDt(stars,tau):
"""
Calculates the change in binary orbital eccentricity over time at each radial bin due to
the torque/mass from the surrounding CB disk.
Parameters
----------
stars: pynbody stars object (sim units)
tau: torque/mass on binary due to CB disk during a given snapshot... | 51dabb0ec241adebdcd3329440f05a251def1ac3 | 3,620,189 |
def zamid_to_name(zamid):
""""Finds and returns the name of the nuclide"""
dic = d.nuc_name_dic
if len(zamid) == 5:
nz = int(zamid[0:1])
na = int(zamid[1:4])
state = int(zamid[4])
if len(zamid) == 6:
nz = int(zamid[0:2])
na = int(zamid[2:5])
state = int(zamid[5])
if len(zamid) == 7:
nz = int(zamid[0... | f0813e7da557b06ed9a14ffcaf82aafcc0e4e781 | 3,620,190 |
def rk4_solve_parallel(y, t, w):
"""
Runge-Kutta solver for systems of 1st order ODEs
(should call function rk4_step_parallel)
Args:
f: name of right-hand side function that gives rate of change of y
y: numpy array of dependent variable output (fist entry should be initial conditions)
... | 7025313f490a086c6a79f0a47e852700cfeb0cdc | 3,620,191 |
def get_hist(data, bins=None, range=None, dx=None, wts=None):
""" return hist, bins, var after binning data
This is just a wrapper for numpy.histogram, with optional weights for each
element and proper computing of variances.
Note: there are no overflow / underflow bins.
Available binning methods... | 548e7925a3c62f4e83e4dab7ab78c995f7e7bbe7 | 3,620,192 |
import os
def get_all_source_files(arr=None, prefix="."):
"""Return source files."""
if arr is None:
arr = []
if not os.path.isdir(prefix):
# assume a file
arr.append(prefix)
return arr
for fx in os.listdir(prefix):
# pylint: disable=too-many-boolean-expressio... | 7dd0cf00e90b1e403ce34b8b158b3e37201b0822 | 3,620,193 |
def count_all_questions_yes(group_input: str) -> int:
"""count questions all group members answered with yes"""
list_of_sets = [set(line.strip()) for line in group_input.split("\n")]
return len(set.intersection(*list_of_sets)) | ba9ce06b4bdbd09ff871114a74de53ccdf60dab3 | 3,620,194 |
import os
def parseIncludeReferenceStatementsByDir(dir_path):
"""
Resolves `include` and `$ref` statements for all the JSON files inside a given directory.
Args:
dir_path (str): directory to parse.
Returns:
dict|list
"""
data = []
for root, dirs, files in os.walk(dir_pat... | 4b1f0681a37cb0469357c904a0ebeba998d89fe7 | 3,620,195 |
def check_service_status(service):
""" queries systemd through dbus to see if the service is running """
service_running = False
bus = SystemBus()
systemd = bus.get_object("org.freedesktop.systemd1", "/org/freedesktop/systemd1")
manager = Interface(systemd, dbus_interface="org.freedesktop.systemd1.M... | a58c734e923b6c2280d83a0ae322ce684b9a2ee9 | 3,620,196 |
def get_job_results(job_id):
"""
A ndb helper method that manipulates the _scraper object.
"""
return ndb.root._spiders.lists[job_id].results | bd5d62fea03ed9ccc10d389cc54605222d8126c3 | 3,620,197 |
from typing import Iterable
from typing import Optional
from typing import Dict
from pathlib import Path
from typing import List
def filter_valid_classification_data_sources_items(items: Iterable[ScalarDataSource],
file_to_path_mapping: Optional[Dict[str, Path]],
... | fa7f3512fabce26edcc41f3ed338122b0ad1d3c6 | 3,620,198 |
def z_coord(cube):
"""Heuristic way to return the dimensionless vertical coordinate."""
try:
z = cube.coord(axis='Z')
except CoordinateNotFoundError:
z = cube.coords(axis='Z')
for coord in cube.coords(axis='Z'):
if coord.ndim == 1:
z = coord
return z | 28b0f2b067ab8e1789f7932c85fc105c4d8424f5 | 3,620,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.