content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import logging
from datetime import datetime
def save_feed(site, full_url, feed_url, feed_type, feeds, feed_urls):
"""
Add a feed to the list of feeds found on a website.
:param site: The site being crawled
:param full_url: The full URL of the page on which the feed was found
:param feed_url: The feed URL
... | 2a3946979a99f99d28ce1d0e7187619e046f7a66 | 3,607,100 |
def govf(array, classes):
"""
GVF function to assist in finding optimal number of jenks classes
Funtion to implement a Goodness of Variance Fit to minimize
squared deviations of the class means.
Paramters
---------
array: np.array
SWE array that you would like to classify
"""
... | 9b94cb9b255b827bab1bb5a49409608c6cbd0199 | 3,607,101 |
def add_cord_metadata(input_data, metadata_path):
"""
Add paper publish time and title metadata to the given cord claim pairs.
:param input_data: pandas dataframe with cord claim pairs
:param metadata: path to cord metadata.csv
:return: Merged dataframe
"""
# Read metadata
metadata = pd... | dd86edd884a04181bfdef25519d4d853c5ba1927 | 3,607,102 |
from datetime import datetime
def et_to_datetime(et, scale='TDB'):
"""
convert a SPICE ephemerides epoch (TBD seconds) to a python datetime
object. The default time scale returned will be TDB but can be set
to any of the accepted SPICE time scales.
Args:
et (float): SPICE ephemerides sceo... | 8f7570859354570785743af67f5da7f2c0997b1a | 3,607,103 |
import os
def badge_path(sysname):
"""Returns a path pointing to the badge for a given sysname."""
return os.path.join('static', 'badges', sysname + '.png') | 68d6f3f16b49cb5457464818264eaf9becd132fa | 3,607,104 |
def get_player_selection(scorepad):
"""Prompt player for category choice for scoring to update scorepad
"""
while True:
user_choice = input('Please enter your choice by entering the menu item key: ')
if user_choice.upper() in valid_keys and user_choice.upper() in scorepad.available_choices... | 04cbc03a2f218a41141debcffbf29ec0e3533621 | 3,607,105 |
def mandel_number(x: float, y: float, n: int = 100) -> int:
"""Return the mandel-number of point (x, y).
This is the smallest index of the mandel sequence at which u_n^2 + v_n^2 > 4.
Assumptions:
* the sequence diverges when u_n^2 + v_n^2 > 4
:param x: x-coordinate of the point for which the Man... | 9f4e7c0d8713146c55a9e0253a00f4127ad4269d | 3,607,106 |
import glob
import os
import re
def has_severe_errors(results="run_outputs"):
"""Check for severe errors in the eplusout.end file."""
end_filename = glob("{}/*.end".format(results))[0]
with open(os.path.join(end_filename), "r") as end_file:
end_txt = end_file.read()
num_severe = int(re.findall... | 26bf445a3b49d6a2ba6dad131ddc5f367c749822 | 3,607,107 |
def getWarrenData(dF, outSnowVar, outDensityVar='None'):
"""
Assign Warren1999 snow dept/density climatology to dataframe
Added
Args:
dF (data frame): Pandas dataframe
outSnowVar (string): name of Warren snow depth variable
outDensityVar (string): name of Warren snow density v... | ac7531faeb75ceb88646bf11f0048b7fd5ea96c5 | 3,607,108 |
def detections_boxes(detections):
"""
Converts center x, center y, width and height values to coordinates of top left and bottom right points.
:param detections: outputs of YOLO v3 detector of shape (?, 10647, (num_classes + 5))
:return: converted detections of same shape as input
"""
# center_... | 161c64b2d30e68db3c8227eca6e20bf5046a4a3a | 3,607,109 |
def indefinite_article(word, gender=MALE):
""" Returns the indefinite article (un/una/unos/unas) for a given word.
"""
if MASCULINE in gender:
return PLURAL in gender and "unos" or "un"
return PLURAL in gender and "unas" or "una" | 80c8c566f4de58f647ec7ba864e1de4c8eb842e5 | 3,607,110 |
def conv_repoids_to_list(repo_ids):
"""
Convert repo ids seperated by "\n" to list.
"""
if not repo_ids:
return []
repoid_list = []
for repo_id in repo_ids.split("\n"):
if repo_id == '':
continue
repoid_list.append(repo_id)
return repoid_list | 6a76a8ae4f565ac27839478f068f9e9a13276263 | 3,607,111 |
def truncate_seq_pair(tokens_a, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequ... | c2d1772b0c727071dc8cb13a5313860278ece294 | 3,607,112 |
import itertools
def _select_iterables(elements):
"""expand tables into individual columns in the
given list of column expressions.
"""
return itertools.chain.from_iterable(
[c._select_iterable for c in elements]
) | 12ecce590ab7d599e62b1105f7a405263cb7022c | 3,607,113 |
def create_grammar(string):
"""Creates a grammar from a string"""
return walk(grammar.parse(string, start="grammar_start")[0]) | 82663f420e8145ae00aa965468f86156545860bd | 3,607,114 |
def _run_on_proxy(role=None, host=None):
"""
Decorator that creates the actual decorator to route tasks through proxy.
This is necessary in order to be able to pass parameters to the actual decorator.
Usage:
@hosts(env.proxy_server)
@_run_on_proxy([host='somehost'|role='somerole'])
... | 962a6c9039e1db86f883d9e4f127c22424e0349d | 3,607,115 |
from typing import Union
from typing import Tuple
from typing import Optional
def parse_constrained_string_or_bytes(
field: Union[ConstrainedStr, ConstrainedBytes]
) -> Tuple[Optional[int], Optional[int], bool]:
"""Parses and validates the given field"""
lower_case = field.to_lower
min_length = field.... | df3e344fac8f68e0a06d7f0e3f55a6f6f81edb1e | 3,607,116 |
import pkg_resources
import os
def get_filter_throughput_file(instrument, filter_name, pupil_name, nircam_module=None, fgs_detector=None):
"""Locate the filter throughput file in the config directory that
corresponds to the given instrument/module/filter
Parameters
----------
instrument : str
... | 564347b0cc76f3261d2c2be63ec69764ef97ef36 | 3,607,117 |
def roundAllFloats(lista, l):
"""Round to 3 decimals"""
nlista = []
for ii in lista:
tt = ii[:l + 1]
for jj in ii[l + 1:]:
if jj > 100.0:
jj = round(jj, -1)
nn = round(jj, 3)
tt.append(nn)
nlista.append(tt)
return nlista | 47707449128215bc2288fc1b033f05a74eef51f4 | 3,607,118 |
def read_clustal_alignment(filename):
""" Read in the alignment stored in the CLUSTAL file, filename. Return
two lists: the names and sequences. """
names = []
alignment = []
f = open(filename)
for line in f:
if line[-1].upper() not in iupac_alphabet:
line = line[:-1]
if... | 456845a7091430adc5aa3f0e09b5a16d78b5f38a | 3,607,119 |
def rename(term):
"""
Re-format feature terms after they've been formated by the vectorizer.
Parameters:
----------
term : str
Mutilated term in string format.
Returns
-------
str
The normalised term.
"""
term = term.upper()
if 'IPR' in term:
return ... | ec7f963ea37a0057f9a5b92ed3f4d9fc37167d17 | 3,607,120 |
def engine_status(engine_name: str):
"""Returns the status of a given engine
"""
if engine_name in template_db.engines:
if template_db.engines[engine_name].is_up():
return 'OK', 200
else:
return 'KO', 402
else:
return 'KO', 404 | b7159db0de9b7ccd84aed09fcd63bd77682deb2c | 3,607,121 |
import os
def reduce2grid(ds, model_group=None, grid="geo"):
"""Return the reduced Dataset, evaluated at grid points.
model_group is one of CHAOS_COMBOS or CI_COMBOS
"""
if grid == "geo":
gridvar = "gridpoint_geo"
elif grid == "qdmlt":
gridvar = "gridpoint_qdmlt"
else:
... | f93764724dae7d2daae30a36e4ef387175b6bede | 3,607,122 |
def _get_pos_from_key(key, char):
""" Returns a list of the indices where char appears in the string.
Pass in a list of only the pulses no residuals (ie capital letters)
+1 is because the pulses are index from 1.
"""
return [i+1 for i, c in enumerate(key) if c == char] | 6870266a92db59bf3f5dd9f69211e13297321e7c | 3,607,123 |
from typing import Optional
from typing import List
def layout_rects(base_rect: Rect, cols: Optional[int]=None, rows: Optional[int]=None, item_width: Optional[int]=None, item_height: Optional[int]=None, padding: Optional[int]=None, padding_top: int=0, padding_bottom: int=0, padding_left: int=0, padding_right: int=0, ... | 18d0ba61fc19c362548bb89be657118f2627319e | 3,607,124 |
from datetime import datetime
def _datetime2timestamp(datetime_str: str) -> int:
"""Convert UTC datetime string to timestamp."""
converted_time = datetime.strptime(datetime_str, "%Y-%m-%dT%H:%M:%SZ")
timestamp = converted_time.replace(tzinfo=timezone.utc).timestamp()
return int(timestamp) | 0475544baab406d7583633bf20f71ca5dad6d3f9 | 3,607,125 |
import os
import sys
def get_sample_names(infiles, ext, reads):
"""
Get sample names without file extensions
"""
s = set()
lext = len(ext)
l0 = len(reads[0])
l1 = len(reads[1])
for x in infiles:
x = os.path.basename(x)[:-lext]
if x.endswith(reads[0]):
x = x[... | e2f67a30338bb28ea7961ca92ba8b4436a5997a0 | 3,607,126 |
def to_litho_class_num(lithology, kv):
"""Get a numeric code for a lithology, or NaN if not in the dictionary mapping lithologies to numeric code
Args:
lithology (str): Name of the lithology
kv (dict[str,float]): lithologies keywords to numeric code
"""
if lithol... | 601b1fc65c113fa4d3f6d97cc3a0eb101b3d997f | 3,607,127 |
def sandwiched_Renyi_rel_ent(rho, sigma, alpha):
"""
Computes the sandwiched Renyi relative entropy for either 0<=alpha<=1,
or for alpha>=1 provided that supp(rho) is contained in supp(sigma).
"""
sigma_a = np.matrix(fractional_matrix_power(sigma, (1.0 - alpha) / (2 * alpha)))
Q = np.real(Tr(f... | a28f8d96886a7ba95c0ec78007cbdb0f09bd4a1d | 3,607,128 |
import array
import struct
def melt(
df,
id_vars, value_vars,
var_name, value_name):
"""Convert :class:`DataFrame` from wide to long format."""
# Create array<struct<variable: str, value: ...>>
_vars_and_vals = array(*(
struct(lit(c).alias(var_name), col(c).alias(value_nam... | 3c17e2673a33bf09586a1828080c9cd6b4910afb | 3,607,129 |
def bpstr(ts, accum):
"""Make a string representation of this breakpoint and accumulation"""
return "%02i.%02i %6.2f" % (ts.hour, ts.minute / 60.0 * 100.0, accum) | bd2ae124b5ef094ea7927124b86f100749bf0405 | 3,607,130 |
def __unique_prefix(values):
"""
Obtain shortest unique prefix for all values in list by means of sorting
:param values: list of string values
:return: list
"""
# Instantiate output list
output = {}
# Sort array
values = sorted(values)
# Save first character in first string as a... | 2a8e5867ef986b04a6e1e6acf89c2a16ff6deacd | 3,607,131 |
def dist_soergel(datamtx, strict=True):
""" Calculate soergel distance between rows of a matrix
see for example Evaluation of Distance Metrics..., Fechner 2004
dist(a,b) = sum on i( abs(a_i - b_i) ) / sum on i( max(a_i, b_i) )
returns: a symmetric distance matrix, numrows X numrows
* comparisons a... | 21ce9ee3fedca34ff67f01a7bbfbfa319136e71b | 3,607,132 |
def sigma_lambda_to_Sigma(sigma, l, eps2=0):
"""
Parameters
----------
Sigma: shape (m, k)
Returns
-------
sigma: shape (m, k)
l: shape (m, k)
l-parameter ready for gradient computation
"""
m = len(l)
return sigma ** 2 / (m * (l ** 2 + eps2)) | 808b970802938cd3f30187bea993cfe1ae1933c5 | 3,607,133 |
import torch
def preprocessing(image, expected_size=224, pad_value=0):
"""
Pre-processing steps to use pre-trained model on images
"""
imgnet_mean = np.array([0.485, 0.456, 0.406])[None, None, :]
imgnet_std = np.array([0.229, 0.224, 0.225])[None, None, :]
image, pad_up, pad_left, h_new, w_n... | 57d5dd14cbaa7bf08de3f34b75e48419e3fb8d1c | 3,607,134 |
import os
def download_local(name: str, data_dir: str):
"""
Get path to a previously-downloaded local version of the corpus (which may be an older version).
:param name: name of Corpus
:return: string path to local Corpus
"""
custom_data_dir = data_dir
data_dir = os.path.expanduser("~... | ce07f445961fb9f4878782db51c2bf2d15ce4897 | 3,607,135 |
async def get_zone(name=None,resource_group_name=None,opts=None):
"""
Use this data source to access information about an existing DNS Zone.
"""
__args__ = dict()
__args__['name'] = name
__args__['resourceGroupName'] = resource_group_name
__ret__ = await pulumi.runtime.invoke('azure:dns/get... | a7d4e1c9ff1775f2e1ab8c51eaa9a954135ae218 | 3,607,136 |
import numpy
def one_body_basis_change(one_body_tensor, rotation_matrix):
"""Change the basis of an 1-body interaction tensor such as the 1-RDM.
M' = R^T.M.R where R is the rotation matrix, M is the 1-body tensor
and M' is the transformed 1-body tensor.
Args:
one_body_tensor: A square numpy ... | 6082a7ca5620dd7e00a545e86867d85b254b4304 | 3,607,137 |
import math
def CalculateDistanceT92(info):
"""
P,Q: transitions, transversions frequencies
q: G+C content
d = -2q(1 - q)loge(1 - P/[2q(1 - q)] - Q) -[1 -2q(1 -q)]loge(1 - 2Q)/2,(4.18)
V(d) = [c12P + c32Q - (c1P + c3Q)2]/n,(4.19)
where c1 = 1/(1 - P/[2q(1 - q)] - Q), c2 = 1/(1 - 2Q), c3 = 2q(... | 90242b905283785524d6b96682abc854346b2d11 | 3,607,138 |
import os
from re import S
def get_dataset_headers_by_id(context, dataset_ids, datasets_since=None):
"""Return { dataset_id : { header } } for `dataset_ids`."""
context = os.path.basename(context)
return S.get_dataset_headers_by_id(context, dataset_ids, datasets_since) | 1714a508c2b0c4f922639620dc871f12d2eaa64e | 3,607,139 |
import requests
from datetime import datetime, timedelta
def update_data_covid_states(cursor):
"""
Summary: Adds in the table "covid_states" daily data of Covid to home Brazilian state.
* Ir first sets the API base URL and make a request
* Third creates a loop that adds the data returned from JSON re... | 6266390dd79275e1428ee9d432952d58efe8c743 | 3,607,140 |
from typing import List
from typing import Union
def convert(raw_data: List[str]) -> List[Union[int, float]]:
"""Helper method to convert numerical strings in their appropriate type"""
return [numerical_conversion(value.strip()) for value in raw_data] | 3be0d3a938aaeced172fcb043e42758324a3d968 | 3,607,141 |
def nnPredict(w1, w2, data):
"""% nnPredict predicts the label of data given the parameter w1, w2 of Neural
% Network.
% Input:
% w1: matrix of weights of connections from input layer to hidden layers.
% w1(i, j) represents the weight of connection from unit i in input
% layer to unit ... | f88bc6a0b4edd1316ce0b4cc211e3655a270afe2 | 3,607,142 |
def physical_to_comoving(dist_physical, redshift):
"""
Converts a physical distance to a comoving distance.
This assume a Flat Lambda CDM Cosmology.
dist_comoving = dist_physical / scale_factor
Parameters
----------
dist_physical: array-like
redshift:
Returns
-------
dis... | 1afb9367b6f37c21eabe620bb86c775d33bac001 | 3,607,143 |
import os
def configure_out_name(in_gct_path, out_name_from_args):
"""If out_name_from_args is None, append DEFAULT_TEAR_SUFFIX to the input
gct name.
Args:
in_gct_path (file path)
out_name_from_args (string)
Returns:
out_gct_name (file path)
"""
input_basename = os.... | 784aa231f2bae9c71081ff74d6a5ac13f0337ee7 | 3,607,144 |
def dup_to_dict(f, K=None, zero=False):
"""
Convert ``K[x]`` polynomial to a ``dict``.
Examples
========
>>> from sympy.polys.densebasic import dup_to_dict
>>> dup_to_dict([1, 0, 5, 0, 7])
{(0,): 7, (2,): 5, (4,): 1}
>>> dup_to_dict([])
{}
"""
if not f and zero:
r... | c67684ea9133ffc3d42267a117534819410113ab | 3,607,145 |
import torch
def sparse_softmax_cross_entropy_with_logits_pytorch(logits, labels):
"""
# onehot
labels = labels.squeeze().long()
num_classes = logits.shape[1]
labels_onehot = torch.zeros(labels.shape[0], num_classes, device=labels.device).scatter_(1, labels.view(-1, 1), 1)
"""
num_classes... | ac77252aa6deec987238f7f3e22368882f4464b4 | 3,607,146 |
def create_outcubes(metric_dict, atts, units, time_coord):
"""Create an iris cube for each metric."""
cube_list = []
for hemisphere, data in metric_dict.items():
standard_name = 'pe_amplitude_%s' %(hemisphere)
long_name = 'pe amplitude %s' %(hemisphere)
var_name = 'pe_amp_%s' %(h... | d84f565d727cb24af467b0408e31d1890e5f58d4 | 3,607,147 |
def linear_warmup_lr(current_step, warmup_steps, base_lr, init_lr):
"""Linear learning rate"""
lr_inc = (float(base_lr) - float(init_lr)) / float(warmup_steps)
lr = float(init_lr) + lr_inc * current_step
return lr | 0ea43c8cf815d25d8caf4d3e5ee8f0f027c5cd41 | 3,607,148 |
import pickle
def unpickle(filename):
"""
Parse CIFAR10 data.
Return a dict containing {data, filenames, labels, batch_label}
"""
with open(filename, 'rb') as fo:
data = pickle.load(fo, encoding='bytes')
return data | 48cb766df6ffc0e448d1c4937a5097bae83c8b78 | 3,607,149 |
def __compute_sf(fit_type,
frequency,
log_luminosity,
dlog_luminosity,
dof,
break_frequency,
injection_index,
remnant_ratio,
b_field=None,
redshift=None):
"""
"""
... | ca256a7bbf6130f97fcb885290e788175a0ca940 | 3,607,150 |
import os
def magic_read(filenames, *, use_dask=None, stack=True):
"""Dispatch the appropriate reader given some files.
The files are assumed to all have the same type.
Parameters
-------
filenames : list
List of filenames to be opened
use_dask : bool
Whether to use dask to c... | 4ff70293d6653b2c4e40a5804408f90a7a5cf486 | 3,607,151 |
import os
import re
def get_info(var):
"""Get version from the package."""
with open(os.path.join('token_cloak','__init__.py')) as f:
content = f.read()
return re.search(var + r'\s*=\s*["\'](.+?)["\']', content).group(1) | 9e498b8d823d82b6cf6228619ca09c2e28a6c86a | 3,607,152 |
from datetime import datetime
def utc_this_hour() -> datetime.datetime:
"""Get offset-aware beginning of the current hour in the utc time zone."""
now = datetime.datetime.now(datetime.timezone.utc)
return datetime.datetime(year=now.year,
month=now.month,
... | 5380f7f6b25ded7f52f2e6254c3002f748cae406 | 3,607,153 |
def getHeadangle(axisP,axisD):
"""Head angle calculation function.
This function takes in two axis and returns three angles.
and It uses the inverse Euler rotation matrix in YXZ order.
the output shows the angle in degrees.
Parameters
----------
axisP : list
Shows the unit ... | a7ea561c2223c37ed37cec8f2268eb6ea36db0f3 | 3,607,154 |
def getCitiesData():
"""
This function gets the data from the file and formats it in this format:
{ format }: 'City/Country'
"""
print('(Info): Select the name of the file you will work with.')
print('(Notice): Example the file name `test.txt`.')
fileName = input('> ')
if fileName == 'exit':
exit()
try... | 8385e5dd25aab13b279680062e4862e0dbcc81df | 3,607,155 |
def func_str2hex(*args):
"""字符串 -> Hex"""
return func_byte2hex(func_str2byte(*args)) | e314954344c8ed531c5a57b8f53dfce47c24b011 | 3,607,156 |
def oadrCreatedPartyRegistration(response_code, response_description, response_requestId, registrationID, venID, vtnID,
profiles, poll_freq, specific_info, extensions):
"""
Generates the oadrCreatedPartiRegistration with the vtnInfo
:param response_code:
:param response_... | 44b774d1bfafc3cab312bc4fbdabc1ad14107c01 | 3,607,157 |
def _get_docs_to_update(update_set, leaf_count, leaf_docs, remove_idx, da):
"""
Return a set of document indices to be udpated for this tree.
Return
- Set of training indices.
Note
-Parallelizable method.
"""
# update only the remove example
if update_set == 0:
res... | 03480413a4a93e68c24942329f3ac3af0ea6d4f2 | 3,607,158 |
def get_prediction_vs_actual_data(y_true, y_pred, outlier_threshold=None):
"""Combines y_true and y_pred into a single dataframe and adds a column for outliers. Used in `graph_prediction_vs_actual()`.
Arguments:
y_true (pd.Series, ww.DataColumn, or np.ndarray): The real target values of the data
... | c1e47f82f4bfaea2c7bb44d62e97a4f37ffbe9d4 | 3,607,159 |
def h5base():
"""Fixture for forming basic HDF5Base object"""
return HDF5Base(FILE_VERSION_MAJOR, FILE_VERSION_MINOR) | e7a9567d5fa3aee6f401668bfea6b3fbf97c9c5e | 3,607,160 |
def mark(name: str, episode: int) -> ControllerResult:
"""
:param name: name of the bangumi you want to mark
:param episode: bangumi episode you want to mark
"""
result = {}
try:
followed_obj = Followed.get(bangumi_name=name)
except Followed.DoesNotExist:
runner = ScriptRunn... | 1b61271f813efaaf7bd0fff0e902cfddc0f1815e | 3,607,161 |
import json
def get_object_manifest(api_root, collection_id):
"""
Defines TAXII API - Collections:
Get Object Manifests section (5.3) `here <https://docs.oasis-open.org/cti/taxii/v2.1/cs01/taxii-v2.1-cs01.html#_Toc31107537>`__
Args:
api_root (str): the base URL of the API Root
collect... | 4bd65246a2c75f15254f592390ed10ed82d9e599 | 3,607,162 |
import typing
import base64
def decode_inline_pronunciation(
word: str,
) -> typing.Optional[typing.Tuple[InlinePronunciationType, str]]:
"""Return encoded inline phonemes from word encoded as __phonemes_<base32-phonemes>__"""
match = ENCODED_PHONEMES_PATTERN.match(word)
if match:
phonemes = b... | 855b487c1e9e3ed8a1341aee2f2a26c5b7e4f518 | 3,607,163 |
def get_axes_list(self):
"""Get the value of variables stored in Solution.
Parameters
----------
self : SolutionMat
an SolutionMat object
Returns
-------
axis_dict: list
a list of axis names containing axis sizes
"""
return self.axis_name, self.axis_size | 812de306267af3daf6713bfdff8ecef05c1a5a0e | 3,607,164 |
def syntactic_roles_to_semantic_match(syntactical_sentence,
voice_is_active=True):
"""
Selects which elements of the syntactical sentence must match the
verb, agent and patient, respectively.
Args:
syntactical_sentence: a list of tuples (symbol, attributes)
... | 84ade39bf48bcc0b065680ac2094da76bde0a5d5 | 3,607,165 |
import requests
import sys
def access_data_from_guardian():
"""
**While there has been a api package for the Guardian, our package will focus on the news on the Guardian releated to the covid. None of the code is copied/paraphrased from the existed package. If there is any similarity, it would be just a coinc... | 47d8374d34e2d06c91f13cca55cf2da4f85c7f2b | 3,607,166 |
from typing import Optional
from typing import Callable
from typing import Any
from typing import Mapping
def get_postprocess_fn(
task_name: str,
task_path: str,
subtask_name: Optional[str] = None,
bigbench_task_type: BigBenchTaskType = BigBenchTaskType.GENERATIVE,
json_util: json_utils.JsonUtils ... | 038b191a587217e6a625d4eafbc49ded2a2ede7e | 3,607,167 |
import subprocess
def is_valid_tar_gz(file_path: str):
"""Check tar file integrity."""
try:
retcode = subprocess.call(['gunzip', '-t', file_path])
return retcode == 0
except BaseException:
return False | abb1495e213d297e8d687b4166de85192b3a3b40 | 3,607,168 |
import os
import pickle
import pKaTool.pKaIO
import pickle
import Protool
import string
import types
import Design_pKa_help
import os
import Protool
def analyse_one_pdbfile(pdbfile,bigdict=None):
"""Load the MC.tabdata file and the sugelm file to determine the
effective dielectric constant for single mutation... | 25b3b858582265108dc61a3d6fa9a1515a025630 | 3,607,169 |
def test_iter_batch(
dataset,
dataloader,
batch_size=1,
shuffle=False,
drop_last=False
):
"""Test DataLoader class"""
if drop_last:
test = IterBatchTest(
dataloader,
batch_size=batch_size,
len_=len(dataset) // batch_size,
... | f85b8ae8d95ef81343862c377d76450aebb16ada | 3,607,170 |
import os
import json
def teardown_class_decorator(func):
"""
Users should wrap their tearDownClass methods with this decorator.
This will stamp the log with an indication that the tearDownClass method
is running and will uninstall all log handlers used by this test.
"""
def wrapper(*args, **k... | 3f61f2eab8f18425470c5f1302265e788eb8c5ba | 3,607,171 |
def no_data_full_shape_func(attrs, inputs, out_ndims):
"""
Shape func for zeros and ones.
"""
if len(inputs) == 0:
return [_convert_shape(convert(attrs.shape))]
return [_full_shape_func(inputs[0])] | d78aa710fb6e8cf0c43de0cf73b85d5d01bb0bdb | 3,607,172 |
def get_tool_study_max_java_heap_size():
"""
Some of the tools allow you to specify the java heap size. We want to ensure all of the tools
use the same heap size (if they allow it to be specified), so the run_analysis scripts
should use this method to retrieve the size
"""
return "4096m" | 8d180d76052bacdbc7350cc2efacc0a55acdb29e | 3,607,173 |
def schedule_for(current_track, task, client_index):
"""
Calculates a client's schedule for a given task.
:param current_track: The current track.
:param task: The task that should be executed.
:param client_index: The current client index. Must be in the range [0, `task.clients').
:return: A ... | f2d096c92f639ae13bdf9cfac02deed74c98cc18 | 3,607,174 |
def roi_align_nchw(data, rois, pooled_size, spatial_scale, sample_ratio=-1):
"""ROI align operator in NCHW layout.
Parameters
----------
data : tvm.Tensor
4-D with shape [batch, channel, height, width]
rois : tvm.Tensor
2-D with shape [num_roi, 5]. The last dimension should be in f... | 6e83f10722d6d7779dd6792407ef4399f256fb66 | 3,607,175 |
def CCNOT(control1: QubitDesignator, control2: QubitDesignator, target: QubitDesignator) -> Gate:
"""Produces a doubly-controlled NOT gate::
CCNOT = [[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
... | 8f6c56fae1b4f4044818f174ce008bdf993d7b75 | 3,607,176 |
import torch
def evaluateCNN(df, artifacts, device=torch.device("cpu")):
"""
Perform model evaluation on unseen data
:param df: dataset
:param artifacts: run artifacts to evaluate
:param device: torch device
:return y_true, y_pred, performance
"""
# Get artifacts (load model, encoder a... | abdbb86764cab0c9aef14e37c38a5f8d07eb0198 | 3,607,177 |
def _distance(n, m, mesh):
"""
Calculate the distance (in number of cells) between cells n and m in mesh.
"""
ni, nj, nk = _index2ijk(n, mesh)
mi, mj, mk = _index2ijk(m, mesh)
return sqrt((ni - mi) ** 2 + (nj - mj) ** 2 + (nk - mk) ** 2) | 5f71b37e0eb5723e9fc203f82b83b33f3b62692c | 3,607,178 |
import sys
def user_input():
"""user input function for selecting dataset, label from dataset, number of runs (defaults to 1 run)"""
print("Dataset Options\n 1-flowers\n 2-titanic\n 3-breast_cancer\n 4-adult_income\n 5-cars\n 6-chess\n 7-mushrooms\n 8-custom\n else-EXIT")
print()
data_selection = inpu... | 26b1401013c74fd864b41e904f340b727fbbb080 | 3,607,179 |
def generate_random_phase_field(diffracted_pattern):
"""
Initiate random phase.
Parameters
----------
diffracted_pattern : array
diffraction pattern from experiments
Returns
-------
sample_obj : array
sample information with phase
"""
pha_tmp = np.random.uniform... | 0dd869e74aa2d11e1e9c58bba5dfb06a2b753fad | 3,607,180 |
import re
import os
import codecs
def run(new_version):
"""
Updates the package version in the various locations
:param new_version:
A unicode string of the new library version as a PEP 440 version
:return:
A bool - if the version number was successfully bumped
"""
# We use ... | fed6dcb5c575d4b5eb0c9337220adabbb8f53d7b | 3,607,181 |
def is_holiday(date):
"""
判断是否为节假日,放假的日子
"""
return date in cs.holidays | 8686b8e0c2a475354b4bde809c00dfa0a8b4c956 | 3,607,182 |
def cbf(dic,data,last=10,reg=False,slice=slice(None)):
"""
Constant Baseline correction
Parameters ref and slice should be python slice objects if explicit
correction is desired (recall python arrays start at 0 not 1). The
noseq and nodmx parameters are not implemented.
Parameters:
... | 24c9683c2bdf3f038be6e690ccb967376c3226ac | 3,607,183 |
def creation(create_db_instance):
"""Return a CreationStage instance."""
stage = CreationStage(None)
stage.instance = create_db_instance
return stage | 862574e84dd9ce1ad2cc54f1f199905580138e50 | 3,607,184 |
def undo_preemphasis(preemphasized_signal, coeff=0.95):
"""Undo the preemphasis of an input signal. The preemphasised
signal p is computed from the signal s by the relation
p(n) = s(n) - coeff*s(n-1)
with p(0) = s(0). The inverse operation constructs the signal from the
preemphasize... | 11cb93c67672c9b2003d2e7b9eed931dffeffcf5 | 3,607,185 |
def apply_dropout2(computation_graph, variables, drop_prob,
rng=None, seed=None, dropout_mask=None):
"""Support using the same dropout mask at all time steps"""
divisor = (1 - drop_prob)
replacements = []
for var in variables:
if dropout_mask:
var_dropout_mask = d... | 9b7d52f808cd532c96c499fd13724ab6efe036b2 | 3,607,186 |
def shapeprior_head_generator(params):
"""Generator function for shape prior head architecture."""
head_params = params.shapemask_head
return heads.ShapemaskPriorHead(
head_params.num_classes,
head_params.num_downsample_channels,
head_params.mask_crop_size,
head_params.use_category_for_mas... | a62490539e74ee5e4e89a5308501046736c33939 | 3,607,187 |
def utils_sample_from_networks_on_batch(speaker_model, listener_model, target_input, candidates, target_candidate_idx, sampled_target_idx, candidate_idx_set):
"""
All inputs: Just one instance. No bs dimensize.
"""
speaker_message, speaker_probs = speaker_model.sample_from_speaker_policy(target_input)
chosen_targe... | 1f105ab531b4adfa44408ca8b3bbc1d3b6bde7fd | 3,607,188 |
import os
def is_git_repo(path):
"""returns whether a path is a git repo"""
if blacklisted(path):
return False
return os.path.isdir(os.path.join(path, '.git')) | 608ddb052b47374863f1be764026a035f7bee1ae | 3,607,189 |
import requests
def is_holiday(day):
"""
判断是否节假日, api 来自百度 apistore: http://apistore.baidu.com/apiworks/servicedetail/1116.html
:param day: 日期, 格式为 '20160404'
:return: bool
"""
params = {'d': day, 'apiserviceid': 1116}
api = 'http://tool.bitefu.net/jiari/'
rep = requests.get(api, para... | fffc20ef2b8d882e3bf03162a9113a61a45e3f8a | 3,607,190 |
def hostile_ship_near(x, y, player, m, cargo):
""" check if hostile ship is in one move away from game_map[x][y] and has less or equal halite """
# m = game map
n = get_c(y - 1)
e = get_c(x + 1)
s = get_c(y + 1)
w = get_c(x - 1)
if (
(m[x][n]["ship"] != player and m[x][n]["ship"]... | dc16208e838d32cde9b335f5bbccc367f35e7c39 | 3,607,191 |
def _calc_pairwise(args):
"""
Helper function to calculate a pairwise alignment.
Args:
args: Tuple of two sequence objects.
Returns:
List [1st sequence id, 2nd sequence id, percentage identity].
"""
seq_i, seq_j = args
ident = 0
matrix = MatrixInfo.blosum62
for a i... | d85d6f25789bfa93faf852a27e25a29d5883546e | 3,607,192 |
import csv
def openCSVfile(filepath, delimiter = ","):
"""
Returns the lists for csv file
"""
with open(filepath,"r") as csvfile:
rows = csv.reader(csvfile,delimiter = delimiter)
return list(rows) | 5d8beda891862281976ec48ea117d3c768a553a6 | 3,607,193 |
def main(global_config, **settings):
"""This function returns a Pyramid WSGI application.
"""
# Initialize Authentication/Authorization
authn_policy = AuthTktAuthenticationPolicy(settings['secret'])
authz_policy = ACLAuthorizationPolicy()
# Configure Pyramid
config = Configurator(settings=se... | 2412595e962b7c1e3c0f428e3a95132fb5147301 | 3,607,194 |
def find_direction(start, end):
"""
Find direction from start to end
"""
if start[0] == end[0]:
if start[1] < end[1]:
return 5
else:
return 1
elif start[1] == end[1]:
if start[0] < end[0]:
return 3
else:
return 7
eli... | ff282de669832159d236cd5fe805b1832b990bb6 | 3,607,195 |
def load_lookup(data):
"""
Load output area lookup.
"""
output = {}
for idx, row in data.iterrows():
output[row['msoa']] = {
'lad': row['lad'],
'region': row['region'],
'population': row['population'],
'area_km2': row['area_km2'],
... | 77e3b88b1d4a270860b4ce328fd1e3d53f3af45a | 3,607,196 |
def adain(net1, net2, epsilon=1e-9, name='in'):
"""use shape NCHW"""
with tf.variable_scope(name):
mu, sigma_sq = tf.nn.moments(net1, [2, 3], keep_dims=True)
normalized = (net1 - mu) / tf.sqrt(sigma_sq + epsilon)
shift, scale = tf.nn.moments(net2, [2, 3], keep_dims=True)
normali... | 8dabc5be35751994b2de428bb00cb8d16c334eb0 | 3,607,197 |
def day_date(src):
"""
Returns the date string for the given day.
:param src:
:return:
"""
return src.xpath('./h4[1]')[0] | f71343c8f63941e0ab4045e2d94febf4aaebfa5b | 3,607,198 |
from typing import Dict
from typing import Hashable
from typing import Set
from typing import List
from typing import Tuple
def set_closure(
sets: Dict[Hashable, Set[Hashable]]
) -> Dict[Hashable, Set[Hashable]]:
"""Computes the closure for each element of a antisymmetric relation.
The relatio... | fdd498ae0d4cd0bb0a0067cd8a6c61bd6c5d8ef7 | 3,607,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.