content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dummy_house():
"""
Sample dataset that will be used to alter and make prediction on
"""
return {
"Id": 34,
"MSSubClass": 20, # Identifies the type of dwelling involved in the sale.
"LotFrontage": 70.0, # Linear feet of street connected to property
"LotArea": 10552, ... | d1360a8709712746f07f92df85a8d704bccd797c | 3,620,083 |
def create_instances(region='us-east-1', count=1):
"""Create some dummy instances and return the instance ids"""
client = boto3.client('ec2', region_name=region)
ids = []
create_results = client.run_instances(ImageId='ami-123abc', MinCount=count, MaxCount=count)
for created_instance in create_resu... | 57a70545e3e6e3d2108c380794cc072f1723d3fe | 3,620,084 |
def get_subsystem_other_info(dut, map_key):
"""Get the value from subsystem table other_info column."""
subsystem_uuid = dut(ovs_vsctl + "list subsystem | grep -i uuid|cut -d :"
" -f 2", shell="bash")
uuid = subsystem_uuid.replace('\r\n', '')
c = ovs_vsctl + "get subsystem " + u... | 30069642b985d92e2a83e83ae04d918db412ca70 | 3,620,085 |
def vg(P):
""" Specific volume [m^3 / kg]
of saturated vapor"""
return region4.vg(P) | 5febea48babd41eec73c85023c59f7723a8f5d05 | 3,620,086 |
def is_gray(img):
"""Checks if the image is grayscale, i.e., has exactly two channels.
Args:
img: an image
Returns:
True/False
"""
return img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1) | c9fc884416b12e3fcfb451c6b4c3f16dc1cfb422 | 3,620,087 |
def __process_nasa_data(name, file):
"""Helper function to process NASA data"""
if name == 'nasa_carbon_dioxide_levels':
ret = __process_nasa_co2_data(file)
elif name == 'nasa_sea_level':
ret = __process_nasa_sea_level_data(file)
elif name == 'nasa_temperature_anomaly':
ret = __p... | debb141c59b6d4da541b7e2f8bd9b225f8ef7f2f | 3,620,088 |
from typing import Union
def parse_year(x: pd.Series) -> Union[pd.Series, ValueTypeError]:
"""
Parse strings as years.
Per XML Schema, permits negative years and years greater than 9999.
However, time zones are not supported
(https://www.w3.org/TR/xmlschema-2/#timeZonePermited).
Arguments:
... | 22544efa086077cc85bd088a82948ab25131c638 | 3,620,089 |
def heatmaps_to_coordinates(heatmaps):
"""
Heatmaps is a numpy array
Its size - (batch_size, n_keypoints, img_size, img_size)
"""
batch_size = heatmaps.shape[0]
sums = heatmaps.sum(axis=-1).sum(axis=-1)
sums = np.expand_dims(sums, [2, 3])
normalized = heatmaps / sums
x_prob = normali... | bae5eddcda8a19310a2cc29cbd57b2e6bc416972 | 3,620,090 |
from pathlib import Path
def setup(query) -> list:
"""Setup is successful if an empty list is returned.
Use this function if you need the user to provide you data
"""
results = []
query_str = query.string
# abbreviations file
if not abbr_store_fname.is_file():
results.append(
... | 62e4e33761dd1a288922d8d0d12cd8c4550636c3 | 3,620,091 |
def construct_description(prefix: str, suffix: str, items: list):
"""Construction of complete description with prefix and suffixx.
Args:
prefix (str): prefix
suffix (str): suffix
items (list): itesm
Returns:
str: complete description string
"""
item_str = ','.join(... | 61eec7c2f40bf3b4857cdd682e52aabac1f2ec76 | 3,620,092 |
def read_cookies_file(filename):
"""read cookie txt file
:param filename: (str) cookies file path
:return: (dict) cookies
"""
with open(filename, 'r') as fp:
cookies = fp.read()
return cookies | 79ce16fabdec49a7b7b60b4d8bd5346798f03edf | 3,620,093 |
def xlinregress(da_y, da_x, dim=None, ess_on=False, alpha=0.05):
"""xarray-version linregress (accept xr.DataArray as input)"""
if dim is None:
dim = [d for d in da_y.dims if d in da_x.dims][0]
slope, intercept, r, dof, tvalue, slope_stderr, intercept_stderr, predict_stderr, pvalue, t_alpha = xr.app... | 5dfd7002c60db0e4dfca64eceffff55451a21f0b | 3,620,094 |
def outer_prod(mat1: tf.Tensor, mat2: tf.Tensor):
"""
Parameters
----------
mat1: torch.Tensor[nBatch, mat1_dim1, mat1_dim2, mat1_dim3, ...]
mat2: torch.Tensor[nBatch, mat2_dim1, mat2_dim2, mat2_dim3, ...]
Returns
-------
res : torch.Tensor[nBatch, mat1_dim1, ..., mat2_dim1, ...]
""... | 29b3df7c4a770219bfb04c5035af4ee621409f94 | 3,620,095 |
import re
import gzip
def open_or_fd(file, mode='rb'):
""" fd = open_or_fd(file)
Open file, gzipped file, pipe, or forward the file-descriptor.
Eventually seeks in the 'file' argument contains ':offset' suffix.
"""
offset = None
try:
# strip 'ark:' prefix from r{x,w}filename (optional),
if re.se... | 73d09ac1092231484b060f989090c98f06eeb09c | 3,620,096 |
from typing import List
def discover(directory: str = '.') -> List[Module]:
"""
Discover all modules in the given directory recursively and import them.
:param directory: the directory in which modules are to be discovered.
:return: a ``list`` of all discovered modules.
"""
paths = _find_paths... | 82ef625aca47f3155ac614156de9188e635f8419 | 3,620,097 |
def replace_functions_in_pdata(pdata, attributes, function_keys):
"""
:param pdata: container of which some attributes are sympy expressions (will be altered)
:param attributes: relevant attribute-dict, in which the functions have to be replaced
:param function_keys: dict like {x1(t): ... | ae2108e2287c7f2a1a77fc18ca2d3e819c60ad1d | 3,620,098 |
def sec(arg):
"""Secant"""
return 1 / np.cos(arg) | 8a8a01990ed2a3d39adc3c1fbf98b2a612ad809f | 3,620,099 |
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 |
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 |
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 _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 |
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 |
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 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 |
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 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 |
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 |
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 |
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 |
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 |
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 |
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 |
import pkg_resources
def pool_drivers():
""" Return a list of EntryPoints names """
return [ep.name
for ep in pkg_resources.iter_entry_points(STORAGE_ENTRY_POINT)] | 1818d645ef7ddd67641ed88929ec67a444d3b601 | 3,620,200 |
from typing import Union
import torch
def to_bagua_process_group(
process_group: Union[TorchProcessGroup, BaguaProcessGroup, None] = None
):
"""Convert a PyTorch process group to a Bagua process group.
Args:
process_group (Union[TorchProcessGroup, BaguaProcessGroup, None], optional): PyTorch
... | 7e97a8eb1cab8192076cb084e68eb6609c38d0d0 | 3,620,201 |
def operate_favorite(bvid: str = None, aid: int = None, add_media_ids: list = None,
del_media_ids: list = None, verify: utils.Verify = None):
"""
操作音频收藏夹
:param aid:
:param bvid:
:param add_media_ids:
:param del_media_ids:
:param verify:
:return:
"""
if not (... | 7232b490d206fbda8abd79f008eaaa58c49d5693 | 3,620,202 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.