content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
from typing import Dict
from typing import Tuple
from typing import Callable
from typing import Optional
from typing import Iterable
def nupack_4_strand_pair_constraint(
threshold: Union[float, Dict[Tuple[StrandGroup, StrandGroup], float]],
temperature: float = dv.default_temp... | 123f804285caacee5fe3a05cbe899534a79b7ce3 | 55,900 |
def find_datacenter(response):
"""Grabs the X-Served-By header and pulls the last three characters
as the datacenter
Returns:
string: the datacenter identification code
"""
xsb = response.headers['X-Served-By']
return xsb[len(xsb) - 3: len(xsb)] | 2c2556e5e9ed2044ed810c90fc9f4b65bbd7650e | 55,901 |
def get_rotatable_bond(mol):
"""Get rotatable bond features.
Args:
mol (rdMol): input rdkit mole with N atoms
Returns:
r_bonds (np.ndarray): (N, N) shape numpy array indicating whether the bonds between two atoms are rotatable.
"""
n = mol.GetNumAtoms()
r_bonds = ... | b7833f87f55e5a8acfe02347a9d5eaf785e3521c | 55,902 |
def encrypt_aes(data,passwd):
"""
wynik:
out, iv, ogon
iv - wektor początkowy
ogon - ile bajtów z wyniku należy zignorować przy odszyfrowaniu
"""
# hasło musi mieć 32 bajty aby użyć AES256
#p = hashlib.sha256(passwd).digest()
# IV musi mieć 16 bajtów na wejściu
rnd = Random.... | 0cbf1df4ad1bff26e1440cc152784f4347575094 | 55,903 |
def judge(bot, trigger):
"""Judge someone or something."""
judges = ['not guilty! https://p.actionsack.com/misc/not-guilty.png',
'guilty! https://p.actionsack.com/misc/guilty.png']
text = plain(trigger.group(2) or '')
if not text:
return bot.reply('I need someone or something to judg... | 16801226b8325fa5773f8edd67a22b3379aaf5b7 | 55,904 |
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
def project_opening_to_fit_plane(poly, boundary_ids, points, MESH_SIZE):
"""
This function projects the opening geometry to a best fit plane defined by the points on opennings. Differenet from the previous function, not only the points on openings ... | b81de1a77ef114087b33f748871db7a8df3fd346 | 55,905 |
def clean_duplication(token, DUPLICATE):
"""
Checks token for duplication. (ex. araw-araw = araw)
token: word to be stemmed duplication
returns STRING
"""
if check_validation(token):
return token
if '-' in token and token.index('-') != 0 and \
token.index('-') != len(token) - 1:
split = token.split... | bd2f955deb38771c2d593a1ebadd515ca6c6d4aa | 55,906 |
import os
import urllib
def authorize_url():
"""Generate authorization uri"""
db_entry = get_user()
latest_strava = sorted(db_entry["strava"], key=lambda k: k['datetime'])[-1]
latest_strava_client_id = latest_strava["client_id"]
app_url = os.getenv('APP_URL', 'http://localhost')
logger.debug... | 33263aa71141f3487ece9be523035ba5f351ee45 | 55,907 |
def extract_signals(y, w):
"""
Extract the mean and variance of an image over the sampling windows.
Parameters
----------
y: 2d array, Image
w: 3d list
list of window indices as output by create_windows()
Returns
-------
mean : 2d array
mean values of signal in each... | 5ad284c42ffff54cec0b745de9a3f4475d4b214d | 55,908 |
from typing import Optional
import json
def initialize_execution(session: Session, experiment: Experiment,
journal: Journal) -> Optional[Response]:
"""
Initialize the execution payload and send it over.
"""
experiment_id = get_experiment_id(experiment.get('extensions'))
if... | f7d094878734d451b9cb779b93770c731a1b3682 | 55,909 |
def color_selection(sample, sample_error, verbose=True):
"""
Run full SDSS quasar candidates selection as specified in
Richards et al. (2002, AJ 123, 2945-2975).
All the color and photometric criteria are implemented.
The returned arrays contain `True` if the given set of
photometry has passed t... | 33707bbf401a2376aa0986c9ecbd0995f4ef89de | 55,910 |
def geometric_inductance_per_unit_length_finite_thickness(trace, gap, thickness):
"""Return the geometric inductance per unit length of a finite-thickness CPW.
See JG Equation 3.31
The result depends only on ratios of the lengths, so they can be specified in any units as long as they are all the
same;... | b5f015271bbde066392d248040a6a04c6c675f5a | 55,911 |
def wcGeneralSettingLookup(gSettings, sid):
"""
Lookup an ID in WooCommerce general settings.
"""
assert gSettings is not None
assert isinstance(sid, str)
for settings in gSettings:
if "id" in settings and settings["id"] == sid:
return settings
return None | ab3ca8a7f8a15db8fa93eaabd3b0f377d31e3b0c | 55,912 |
import subprocess
import torch
import time
def multi_gpu_launcher(commands):
"""
Launch commands on the local machine, using all GPUs in parallel.
"""
print('WARNING: using experimental multi_gpu_launcher.')
DEFAULT_ATTRIBUTES = (
'index',
'memory.free',
)
def get_gpu... | d8113ee76b99c6b00249c1a6531db0257b6255b9 | 55,913 |
def semicolon_str_as_list(s):
"""
see utils.tests.MiscTests.test_semicolon_str_as_list().
"""
if not s:
return []
return [x.strip() for x in s.split(';')
if len(x.strip()) > 0] | 01751bbe2702705c6a39701a9289ae12265b5146 | 55,914 |
def binom_coeff(n):
"""
Calculate the binomial coefficient (n, 2), i.e. the number of distinct pairs possible
in a set of size n
:param n: size of set
:return: number of pairs
"""
return int(n * (n-1) / 2) | b7f249524cda01ab8de14c7148745dd153d08b90 | 55,915 |
def read_dat_file(file):
"""Read a dat file containing meteorological mast metadata
You don't really need to care about this, because your files are unlikely to be in the same form as our
example dat files. You'll need to build your own file readers and test them (or use open-source libraries to do
the... | 73a9c597f53151986235abf532ef7c54dd1a4e36 | 55,916 |
import os
def readFitsCube(file, verbose, log = print):
"""The old version of this function could only accept 3 or 4 axis input
(and implicitly assumed that in the 4 axis case that axis 3 was degenerate).
I'm trying to somewhat generalize this, so that it will accept NAXIS=1..3
cases and automatically... | ba64414451f1e5277463588d0e1b7658d7925f6e | 55,917 |
import click
def connect_target(targets, target_id):
"""
Connect to the target defined by target_id. This function does
not actually contact the server so there is no try block
"""
try:
target = targets[target_id]
except Exception as ex:
raise click.ClickException("%s: %s" % ... | 341095cde2c15b975746a2ea62bb63c0fef61330 | 55,918 |
import six
def keras_test(func):
"""Function wrapper to clean up after TensorFlow tests.
# Arguments
func: test function to clean up after.
# Returns
A function wrapping the input function.
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
output = func(*args, **kwargs... | 43bc30a385a932defa722a99c6bd273157bdfe4d | 55,919 |
def graph_factory(graph_type, n, m, epsilon):
""" Creates graph based on given attributes.
:param graph_type: Type of graphs in population: "random" or "euclidean".
:param n: Expected value for generated graph number of vertices.
:param m: Expected value for number of edges of graph.
:param epsilon... | 2025822b46239646327b1bc44848f4c047d53b8c | 55,920 |
def homo_lumo_mix(C, nocc, beta):
"""
Mix a portion of LUMO to HOMO.
Used when generating spin-unrestricted guess.
"""
if beta < 0. or beta > 1.:
raise Exception("Mixing beta must be in [0, 1]")
Cb = C.copy()
homo = C[:, nocc - 1]
lumo = C[:, nocc]
Cb[:, nocc - 1] = (1. - bet... | 081c9149ad2d5fe39a16796943fb4d2c53c7b3d7 | 55,921 |
from pathlib import Path
def chrom_from_csv(filename):
"""
A specific parser for .txt files exported from Shimadzu LabSolutions
software.
Extracts data from the chromatogram file into a dictionary using string
manipulation and regex parsing (not all information in the file is
scraped).
P... | 44318b6aa5bc62745c435866c5e5c8ba7205a9da | 55,922 |
def market_last_split_train(market=None):
"""
使用最后一次切割好的训练集symbols数据
:param market: 待获取测试集市场,eg:EMarketTargetType.E_MARKET_TARGET_US
:return: 最后一次切割好的训练集symbols数据
"""
if market is None:
# None则服从ABuEnv.g_market_target市场设置
market = ABuEnv.g_market_target
market_name = market.v... | 4648f9e844dc498a0fc383da0f4bdc0e2202fc25 | 55,923 |
import time
def run(wrapped):
"""
Special decorator encapsulating query method.
"""
@wraps(wrapped)
def _run(self, query, bindings=None, *args, **kwargs):
self._reconnect_if_missing_connection()
start = time.time()
try:
result = wrapped(self, query, bindings, ... | 0564d145637778660319e4c6df7f9c884d568b03 | 55,924 |
def pipulate(tab, rows, cols, columns=None):
"""All that pipulate really is"""
row1, row2 = rows
col1, col2 = cols
col1, col2 = aa(col1), aa(col2)
cl = tab.range(row1, col1, row2, col2)
list_of_tuples = cl_to_tuples(cl)
if not columns:
columns = tab.range(row1, col1, row1, col2)
... | bdf98fa984b5a589051a1978ce1295e3374f7357 | 55,925 |
def make_rect( cxy , wh, **kwa ):
"""
:param cxy: center of rectangle
:param wh: width, height
"""
ll = ( cxy[0] - wh[0]/2., cxy[1] - wh[1]/2. )
return Rectangle( ll, wh[0], wh[1], **kwa ) | 657096f62c32b017c60a4a70d4b77d4537191cbd | 55,926 |
def guild_owner():
"""A guild owner check
Returns whether or not the author is a guild or bot owner
Returns
-------
bool
If the user owns the guild or the bot this will return True
Otherwise it will return False, raising a check failure
"""
async def inner(ctx: Context):
... | 3d4b8674f24fdfe436e81f7652764ef1bab36271 | 55,927 |
def on_delete(url='/'):
"""
Route registerer for DELETE http method
:param url: str
:return: function
"""
return _utils.register_route(_utils.caller(), url, methods=['DELETE']) | b8dff2a10ec82e41f53e2dc9ceb907310152c594 | 55,928 |
def _npadding_bytes(pkt_byte_len, spb):
"""
Generate sufficient padding such that each packet ultimately ends
up being a multiple of 512 bytes when sent across the USB. We
send 4-byte samples across the USB (16-bit I and 16-bit Q), thus
we want to pad so that after modulation the resulting packet
... | c769381de81e9d0044152ada9617e8225f0009d7 | 55,929 |
def exe_mask_wrapper(func, x0, mask,
parameterfile, parameterwriter, outputfile, outputreader,
kwarg, x):
"""
Same as `exe_wrapper` incl./excl. parameters with mask.
Makes the transformation:
`xx = np.copy(x0)`
`xx[mask] = x`
and calls `exe_w... | 3668e6781606c50a96387dff312859cf63877caf | 55,930 |
def _global_module_cache_path(bin_dir):
"""Returns the path to the location where the Swift compiler should cache modules.
Note that the use of this cache is non-hermetic; the cached modules are not declared inputs or
outputs and they are not wiped between builds. The cache is purely a build performance
... | 67fa6be70c2758475c2f1041822280b051af98ae | 55,931 |
from numpy import asarray
from PIL import Image
def resize_image(image, final_image_shape):
"""Utility to resize an image.
Input:
image: original image (2D numpy array of real numbers)
final_image_shape: final size of the resized image (2-ple of positive integers)
Output:
resized... | 97fdf504152151ca249243cdb56c9387b3eefad3 | 55,932 |
import types
def filter_result(S, algo, asset_filter=None, result=None):
""" Filter assets for algo by their past-performance. """
result = result or algo.run(S)
asset_filter = asset_filter or AssetFilter()
# monkey-patch algo's step
step_fun = algo.step
def step(self, x, last_b, history):
... | 0991f89efb58cc49b817594c4c3033459a5b9de4 | 55,933 |
import os
import logging
import sys
def get_logger(
name,
log_level: str = "DEBUG",
local: bool = False,
local_log_dir: str = None,
log_format=DEFAULT_LOG_FMT,
):
"""
Args:
name:
log_level:
local:
local_log_dir:
log_format:
Returns:
"""
... | c7efd262297b632b46a482f1835eb05a8ef0d9b5 | 55,934 |
def construct_source_candidate_set(addr, plen, laddr):
"""
Given all addresses assigned to a specific interface ('laddr' parameter),
this function returns the "candidate set" associated with 'addr/plen'.
Basically, the function filters all interface addresses to keep only those
that have the sa... | fab6c8ec990c5cebaa19b95d2f4a11ccf87c009c | 55,935 |
def H_to_nu(H, ecc):
"""
Retrieves hyperbolic anomaly from true one.
Parameters
----------
H: float
Hyperbolic anomaly
ecc: float
Eccentricity of the orbit
Returns
-------
nu: float
True anomaly
"""
nu = 2 * np.arctan(np.sqrt((ecc + 1) / (ecc - 1)) ... | d1e5730aa2ccc36454ea6524e2a286d41c9db2cb | 55,936 |
def getJumpTargets(disas):
"""Get the targets to jump and call instructions.
Takes a interator of Capstone disassembled instructions.
Returns a list of jump target addresses
Example: [0x0, 0x1, 0x3] <- getJumpTargets(disas)
"""
targets = []
for op in disas:
if op.group(CS_GRP_JUMP):... | da5998f4ce5e8437984712c6b5261307c21fbff1 | 55,937 |
def read_coefficients(filename="A_coefficients.dat"):
"""
read_coefficients() as defined above
Parameter
=========
filename (optional): another path to the A_coefficients.dat file.
"""
# unpack the text file
l, u, As = np.loadtxt(filename, unpack=True, delimiter=",",
... | 38c5610fc4f89ffc0684ee053d869c77ff66fa5f | 55,938 |
import random
def random_sampling(dataset:dict, num_of_images=1000) -> list:
"""
Does a random oversampling of the `dataset` to balance all of the classes.
Parameters
----------
`dataset` : `dict`\n
Dict representation of the dataset.
`num_of_images` : `int`, `optional`\n
Numb... | eaf839734528140952bd07f6447e145376367a7c | 55,939 |
def is_in_display_surface(cell):
"""Return True if given cell is in display surface."""
x, y = cell
return all([x >= 0, x < CELL_WIDTH, y >= 0, y < CELL_HEIGHT]) | 26c09537e50a67da852a2b7d5950620a6db2cb64 | 55,940 |
import email
def quoteaddr(addrstring):
"""
引用RFC 821定义的电子邮件地址的子集
"""
displayname, addr = email.utils.parseaddr(addrstring)
if (displayname, addr) == ('', ''):
# parseaddr 无法解析时,原封不动地使用
if addrstring.strip().startswith('<'):
return addrstring
return "<%s>" % add... | b68ffa8e9a432c442fe17bb5581dfae55c955e3d | 55,941 |
from typing import Optional
def has_matching_phone_number(
source: location.NormalizedLocation,
candidate: dict,
) -> Optional[bool]:
"""Compares phone numbers
- True if has at least one matching phone number
- False is only mismatching phone numbers
- None if no valid phone numbers to compar... | 564a1b7695aedbccc9e3ba61101f39c017ade380 | 55,942 |
import os
import sys
def check_input(args):
"""Checks whether to read from stdin/file and validates user input/options.
"""
# Defaults
fl = [] # file list
if len(args) >= 1:
for fn in args:
if not os.path.isfile(fn):
emsg = 'ERROR!! File not found or not read... | 61056d8f5cb0c3e6bc279993c1c3a8e9e2913ef3 | 55,943 |
import os
import torch
def load_and_cache_examples(args, task, tokenizer, processor, data_type='eval_cosine'):
"""
Load data features from cache or dataset file
:param processor:
:param data_type: eval_original、eval_cosine
:return:
"""
cached_features_file = os.path.join(
args.... | 947c8f23092daa6ff197d61d7c1a50360be17eeb | 55,944 |
import json
def loadJson(jsonfile):
"""
Reads a .json file into a python dictionary.
Requires json package.
"""
with open(jsonfile, "r") as data:
dictname = json.loads(data.read())
return dictname | de059637ea0dc1b0ef729a5d2bbfa7c3e72bb5b1 | 55,945 |
import warnings
def _landsat_stats(
band,
address_prefix,
metadata,
overview_level=None,
max_size=1024,
percentiles=(2, 98),
dst_crs=CRS({"init": "EPSG:4326"}),
histogram_bins=10,
histogram_range=None,
):
"""
Retrieve landsat dataset statistics.
Attributes
--------... | 9da1425b6fda466a0607264290f80915a541b6a5 | 55,946 |
def isEqual(lhs, rhs):
"""types should be a either a list, tuple, etc"""
for x,y in zip(lhs, rhs):
if x == y:
continue
else:
return False
return True | b089afcec393657737dee163b897b376550cedee | 55,947 |
def get_item_id(url):
"""
Gets item id from url
:param url: facebook url string
:return: item id or empty string in case of failure
"""
ret = ""
try:
link = create_original_link(url)
ret = link.split("/")[-1]
if ret.strip() == "":
ret = link.split("/")[-2]... | 795e77fba85d6a2eae1d07c2b23f075d3d8cddff | 55,948 |
def get_texcoord_index_from_shader_node(glTF, name, shader_node):
"""Return the texture coordinate index, if assigned and used."""
from_node = get_shader_image_from_shader_node(name, shader_node)
if from_node is None:
return 0
#
if len(from_node.inputs['Vector'].links) == 0:
retur... | 04749faea42c375578fc628b5ec64e4c584c1943 | 55,949 |
import argparse
def get_parser():
"""Defines the argument parser
Returns:
argparse.ArgumentParser.
"""
DEFAULT_VALUES = configuration.get_configuration_values_for("usufy")
# Capturing errors just in case the option is not found in the configuration
try:
excludeList = [DEFAULT_... | 083b5313b7b280afa05322bb7d2cfe97873e594c | 55,950 |
def _FunRewriteIntoAABForm(fun: ir.Fun, unit: ir.Unit) -> int:
"""Bring instructions into A A B form (dst == src1). See README.md"""
return ir.FunGenericRewrite(fun, _InsRewriteIntoAABForm) | b9839e3f8a2c683c1c3e17cdffbe208e20ebdbf9 | 55,951 |
import pathlib
def asurl(path: pathlib.Path) -> URL:
"""Convert filesystem path to URL."""
# Get an absolute path but avoid Path.resolve.
# https://bugs.python.org/issue38671
path = realpath(path)
return URL(path.as_uri()) | e02c1cf2bce21f0818ce178b27d6a2e2252bc0e5 | 55,952 |
import subprocess
def stat_ticket(ticket_number):
"""
Test for existence of a ticket
The basis for validate_existence
"""
subproc = subprocess.Popen(['testsnot', '-s', str(ticket_number)], stdout=subprocess.PIPE)
response, err = subproc.communicate()
error_msg = "Cannot open ticket {0}".f... | e55b42423c342329ed3d3f19ea785a38bba5ffe8 | 55,953 |
def convert(source_file, target_file, trim_unused_by_output="", verbose=False, compress_f16=False):
"""
Converts a TensorFlow model into a Barracuda model.
:param source_file: The TensorFlow Model
:param target_file: The name of the file the converted model will be saved to
:param trim_unused_by_out... | 7c24de147faa5d1693ca97ab38d5b1f3378deaef | 55,954 |
def recall_micro(y_true, y_pred, **args):
"""Recall score based on the `sklearn.metrics.recall_score`_ function.
Average argument set to 'micro'.
More details here : `Precision, recall and F-measures`_
.. _sklearn.metrics.recall_score: https://scikit-learn.org/stable/modules/generated/sklearn.metrics... | 84e2e208fc6a6ec8dfa20ef259e5cb835e5e8894 | 55,955 |
import requests
def find_articles(park_code):
""" Find articles from park code """
global api_key
url = "https://developer.nps.gov/api/v1/articles?parkCode=" + park_code + "&api_key=" + API_KEY
response = requests.get(url)
json_object = response.json()
articles_total = json_object['total']
... | 7041765b578d133e158ac73a88f57ffd470cba72 | 55,956 |
import os
import json
import torch
def predict(image_path, model, top_k, category_names, device, use_gpu):
"""Predicts the flower and probability based on the image given and the loaded model"""
# Check if the category name argparse input is valid
if os.path.isfile(category_names):
with open(cate... | a681ac5daafef480f58a3087a4f01dd8e72e85a7 | 55,957 |
def getLayerAnimCurves(node, layerName):
"""get animation curves asociated to an animationlayer
Args:
node (str): name of an animated node
layerName (str): name of a animation layer
Returns:
list: animation curves names
"""
animCurves = set()
for attr in cmds.listAttr(nod... | efc679d6346ac4973c9844657737133879d261b0 | 55,958 |
def square_crop(image, x_pos, y_pos, size=35):
"""Returns a square crop of size centered on (x_pos, y_pos)
Inputs:
image: np.ndarray, image data in an array
x_pos: int, x-coordinate of the hotspot
y_pos: int, y-coordinate of the hotspot
size: int, side length for the returned cro... | 2e327d5b1a9cc358b0806c86e84241d083a390b1 | 55,959 |
import time
def md5_func(text: str) -> str:
"""md5哈希."""
start = time.time()
result = md5(text.encode("utf-8")).hexdigest()
end = time.time()
log.info("time it", seconds=end - start)
return result | 8d90b35a5a5d5321f8a113f41c6f10f17206337c | 55,960 |
def bulk_import(cell_ids = None, debug = False):
"""
mostly just calls import_single_file
"""
if cell_ids is not None:
neware_files = get_good_neware_files().filter(
valid_metadata__cell_id__in = cell_ids)
else:
neware_files = get_good_neware_files()
errors = list(ma... | 89949d1c42eee100e4d40bc033efd403a00b6edc | 55,961 |
def restrict_chains(data, k):
"""Restrict data to people with at least k rows.
Parameters
----------
data : pandas.DataFrame
The `data` from US to be subsetted.
k : int
The minimum number of measurements needed for a person to be kept.
Returns
-------
data : pandas.DataF... | 106fc9c43d12085392a84a188dcc8d40a89ae817 | 55,962 |
def list_of_elem(elem, length):
"""return a list of given length of given elements"""
return [elem for i in range(length)] | d72bdab16a541714b2a0a781a3077d40e309e9f7 | 55,963 |
def celsius2kelvin(celsius):
"""
Convert temperature in degrees Celsius to degrees Kelvin.
:param celsius: Degrees Celsius
:return: Degrees Kelvin
:rtype: float
"""
return celsius + 273.15 | 7fe8ae285cf1619591762ebed9634b5436a52939 | 55,964 |
from xml.dom import minidom
import os
def getOutFilesGuids(outFiles, workdir, experiment, TURL=False):
""" get the outFilesGuids from the PFC """
ec = 0
pilotErrorDiag = ""
outFilesGuids = []
# Get the experiment object and the GUID source filename
thisExperiment = getExperiment(experiment)
... | bee243978801bd408b516e5d0bf8b862fa8b07b5 | 55,965 |
def resize_image(x, size):
"""
Resize image using skimage.transform.resize even when range is outside [-1,1].
:param x: np.ndarray
:param size: new size (H,W)
:return: np.ndarray
"""
if size != x.shape[:2]:
minx, maxx = minmax(x)
if maxx > 1 or minx < -1:
x = map... | dcd161008433504f531a902fd27bd36e55420a25 | 55,966 |
def delete_relationship(request, slug, handle_id, rel_id):
"""
Removes the relationship if the node has a relationship matching the
supplied id.
"""
success = False
if request.method == 'POST':
nh, node = helpers.get_nh_node(handle_id)
try:
relationship = nc.get_relat... | 554230da208d8dd97f81fb6da843c318433388f8 | 55,967 |
def extract_pqrst(ecg_detrend, r_idx, fs=100, diagPlot=False):
""" Extract peaks from ECG data
Based on results from extract_r, extract PQRST peaks
Returns
-------
peak_idx, peak_val: N x 5 numpy array, index and value of peaks of PQRST
"""
p_idx, q_idx, s_idx, t_idx = [], [... | 46337a5933966273290e0e268327c760d410ffc0 | 55,968 |
from typing import List
from typing import Tuple
def _qspr_from_padel(smiles: List[str], timeout: int = None) -> Tuple[List[List[float]], List[str]]:
"""
Args:
smiles (list[str]): list of SMILES strings
timeout (int, optional): timeout for PaDEL-Descriptor process call; if None, uses
m... | 6a74d186059c651879e5a9eb601b76ef3b22e595 | 55,969 |
def create_rect_polygon(obj, state):
"""Creates an SVG polygon element from a Faint Rect."""
element = ET.Element('polygon')
point_str = str(obj.get_points())[1:-1]
element.set('faint:type', 'rect')
element.set('points', point_str)
# Bundle as shape_style?
style = (svg_fill_style(obj, stat... | 4c8b30f5cf45a3c74cbb9e610acc9e3970150878 | 55,970 |
def set_median_flux_to_one(flux):
"""Set median flux to one."""
if not np.all(np.isfinite(flux)):
raise ValueError('flux must contain all finite values')
medflux = np.median(flux)
if np.isclose(medflux, 0):
return flux + 1
flux = flux.copy()
flux /= medflux
return flux | 255a90c6b724eac2fab89d6a551ca6b567dcca2f | 55,971 |
def all_ones(vector):
"""
Return True/False if all vector's entries are/are not
1s.
"""
return all([e==1 for e in vector]) | 5bd1509c72945de83f3e84e956efae39bd32fee0 | 55,972 |
def max_pool_1d(incoming, kernel_size, strides=None, padding='same',
name="MaxPool1D"):
""" Max Pooling 1D.
Input:
3-D Tensor [batch, steps, in_channels].
Output:
3-D Tensor [batch, pooled steps, in_channels].
Arguments:
incoming: `Tensor`. Incoming 3-D Layer.
... | 2dc550aa3bae009bb32944bc0d3e464664f2c4ab | 55,973 |
import requests
def get_observer_v():
"""Selects all data from the ObserverV view.
:return: a dictionary of key/ObserverID : value/NickName
Eg. request: https://api.nve.no/hydrology/regobs/v3.0.6/Odata.svc/ObserverV/?$filter=ObserverId%20lt%203000&$format=json
"""
url_1 = 'http://api.nve.no/hyd... | 6614a0d68b3ec7a367f8e52f98729e90a05af540 | 55,974 |
def reverse(number) -> int:
"""
Takes a integer number as input and returns the reverse of it.
"""
rev = 0
while number > 0:
d = number % 10
rev = rev*10+d
number //= 10
return rev | aea32007aeb94cb281a98f0f3daba635d79316e7 | 55,975 |
def controlador(msg):
"""
Vai ser responsavel por filtrar as mensagens que chegam
"""
msg.pop(-1) # remove a ultima palavra da string que é uma msg de controle
t = msg.pop(0) # remove a primeira palavra da string que é o codigo do tipo de msg
if t == '0': #Nós que estão coletando temperat... | 4fc53840a03dcd3f200c6957fdd784834bef8e9b | 55,976 |
import os
import statistics
def get_local_medias_files(
path: str = LOCAL_MEDIA_PATH,
save_to_disk: bool = True,
files_list_path: str = FILES_LIST_PATH,
files_list_filename: str = FILES_LIST_FILENAME,
config_path: str = CONFIG_PATH,
) -> list:
""" Generates a list of local media files """
... | 7f5693f527d0d2ecf8c93751c44235f2399a5e78 | 55,977 |
def checkLibraries(buildReport=False):
"""
Looks for required libraries, and their matching QA versions.
@ In, buildReport, bool, optional, if True then report all libraries instead of just problems
@ Out, missing, list(tuple(str, str)), list of missing libraries and needed versions
@ Out, notQA, list... | 7b82808f8cecf1d9cb3f10cdb3b9ccc7f2d7980d | 55,978 |
def formatNumber(n):
"""格式化数字到字符串"""
rn = round(n, 2) # 保留两位小数
return format(rn, ',') | 7d7da1f0cec70c0a6814daf9cc4bf3bf88559c14 | 55,979 |
def get_limit(past):
"""
Get the date `past` time ago as the matplotlib representation
"""
return num_now() - float(past) * 365 | 0eb2d77609a55f696a18c238dd8e0099e61af427 | 55,980 |
def kappa_idx(n):
"""
Provide scalar products indexes for kappa values.
Parameter:
n -- integer
Return:
list_kappa_idx -- list of lists
"""
list_kappa_idx = []
if n == 5:
list_kappa_idx0 = [['*00**', 0, False, False],
['*01**', 1, False, True],
['*10**', 2, True, False],
['*11**... | 1e19fb2eca480711346d262e91990b79d3d71928 | 55,981 |
def checkin_file(session,driveid,itemid):
"""
checkin a file to Sharepoint.
"""
# create the Graph endpoint to be used
endpoint = f'drives/{driveid}/items/{itemid}/checkin'
return session.put(api_endpoint(endpoint)) | d3411ecc63966ac31799625626bd3bde8a9ffe35 | 55,982 |
from typing import Sequence
import json
def custom_network_main():
"""
Profile comparison tool, accepts a species and a list of probes and plots the profiles for the selected
"""
form = CustomNetworkForm(request.form)
form.populate_method()
if request.method == 'POST':
terms = request... | d2450b124862157bacc9cb0ff406eb78081d037f | 55,983 |
def find_meaningfull_alias(name,
istringmax=30):
"""
we try to limit the alias to ~40 characters
"""
name = name.replace(',', '') # a bit of preprocessing
if len(name.split(' '))==1: # this means it is not real text, that's a real alias
return name
else:
... | 0f72409a93783ecca6ce78eebcc3db00c85e23f6 | 55,984 |
import argparse
import os
def get_evaluation_argument(method=False):
"""
Reading a path to a json file for evaluation purposes
"""
# defining command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--eval_file", help="Path to the evaluation file")
parser.add_a... | 1b52d3630d219b2f32c43e5dbb13af411fc686d2 | 55,985 |
import yaml
def _load_clean_genres():
"""Auxiliary function to load the file with the clean genre list and
parse it to a python dictionary. Original format is YAML.
"""
with open(GENRE_LIST_PATH, 'r') as fgenre:
genres = yaml.load(fgenre)
return genres | 6a11729c0af00a0bfaa5932f18c05587af6dcaaa | 55,986 |
def gfmul(x, y):
"""Returns the 128-bit carry-less product of 64-bit x and y."""
ret = 0
for i in range(64):
if (x & (1 << i)) != 0:
ret ^= y << i
return ret | 3639195b423e516ad374cd9dff263e9137634e68 | 55,987 |
def add_quote(inp, *, date, user, message):
"""Add new quote."""
if db.Quote.find_one(user=user, channel=inp.channel, text=message):
return lex.quote.already_exists
db.Quote.create(
user=user,
channel=inp.channel,
time=(date or arrow.utcnow()).format('YYYY-MM-DD'),
t... | 904bdf9b3ed9f3a606645c937b1b4fc279c43e69 | 55,988 |
from datetime import datetime
def test_ini(t):
""" Monkey-patch to make doctest think it's always time t:
"""
u = Date.now
d = datetime.datetime.strptime(t, '%Y-%m-%d.%H:%M:%S.%f')
Date.now = lambda x: d
return u | be9b2851343679ca0a05e3a7f0a94f0203f790c3 | 55,989 |
def get_name(node: Node) -> bool:
"""
Evaluate the value of a NAME node.
Parameters
----------
node
The node to be evaluated.
Returns
-------
bool
The node's evaluated value.
"""
name = node.token.value.lower()
if name == "exit":
raise KeyboardInterr... | 2b4785c2c27e3fd57ba87deed93146309b2a40ac | 55,990 |
def search_first(pattern, sequence):
"""从sequence中寻找子串pattern
如果找到,返回第一个下标;否则返回-1。
"""
n = len(pattern)
for i in range(len(sequence)):
if sequence[i:i + n] == pattern:
return i
return -1 | 3139c877e7113f6d860e921aba31635570a2e972 | 55,991 |
import logging
def generate_embedding(token: Token) -> Tensor:
"""Use a pre-trained model to get/calculate a vector for the input `token.name`"""
logging.info(f"\nGenerating embedding for current TOKEN: '{token.name}'")
tensor = EMBEDDING_MODEL.query(token.name) # return: ndarray i.e. Token
return te... | 1c4de2f0e92c63872e73166950a2a66143269fab | 55,992 |
def raw_to_ts(raw, min_date=None, max_date=None, date_format=None):
"""
Turns a raw pd.DataFrame into a time-series DataFrame, by creating a DatetimeIndex and a 'timestamp' column
:param raw: a pd.DataFrame with a date column
:param min_date: Minimum date for the time series
:param max_date: Maximum... | 575f3fbccebc801382f3c43bf4d982af30912647 | 55,993 |
from typing import Callable
def compute_bordawise_distance(election_1: OrdinalElection, election_2: OrdinalElection,
inner_distance: Callable) -> float:
""" Compute Bordawise distance between ordinal elections """
vector_1 = election_1.votes_to_bordawise_vector()
vector_2 = ... | 27d7f0893ee7e719c94e7869043df2b4b5e2859b | 55,994 |
def data_prepocessing(csv_filepath):
"""
Implement load_data
Arguements:
csv_filepath -- the path directory of the csv_filepath in the workspace
Returnes:
X_train, X_test, y_train, y_test
"""
df = pd.read_csv(csv_filepath)
df['extracted features'] = df.apply(lambda row : fin... | 661fc4d0eb7e7149940d76e548542436d6562485 | 55,995 |
def time_frequency_features_estimation(signal, frame, step):
"""
Compute time-frequency features from signal using sliding window method.
:param signal: numpy array signal.
:param frame: sliding window size
:param step: sliding window step size
:return: h_wavelet: list
"""
h_wavelet = []... | dcf3aacd18a4119b7c3df85b175002d5019c62bf | 55,996 |
def permute_labels(in_data, permutation):
"""
Permute the values of the labels in an int image.
:param in_data: array corresponding to an image segmentation.
:param permutation:
:return:
"""
if not is_valid_permutation(permutation):
raise IOError('Input permutation not valid.')
r... | a67212119cdef3e4e47b6be13978cc92f539c07b | 55,997 |
def dhash(img):
"""Compute a perceptual has of an image.
Algo explained here :
https://blog.bearstech.com/2014/07/numpy-par-lexemple-une-implementation-de-dhash.html
:param img: an image
:type img: numpy.ndarray
:return: a perceptual hash of img coded on 64 bits
:rtype: int
"""
T... | 7604a91c32dc42c01d503441280990a6dbd85484 | 55,998 |
def kalman_xy(x,
P,
measurement,
R,
motion=np.matrix('0. 0. 0. 0.').T,
Q=np.matrix(np.eye(4))):
"""
Args:
x: initial state 4-tuple of location and velocity: (x0, x1, x0_dot, x1_dot)
P: initial uncertainty convariance matrix
... | 9583162de055aded2389ed52048d5a69a787a8c0 | 55,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.