content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import subprocess
def supported_camera_list():
""" Grabs the list of gphoto2 cameras and parses into a list
"""
check_gphoto2() # No reason to keep going if GPhoto2 isn't installed
# TODO: Error checking/Handling
# Capture and cleanup camera list output
cameras = subprocess.run("gphoto2 --l... | bcb9c69a56d8bcc9e613db818b8e38ca5f9e5ac8 | 3,642,400 |
from typing import Iterable
from typing import Callable
def get_features_and_labels(instances: Iterable[NewsHeadlineInstance],
feature_generator: Callable[[NewsHeadlineInstance],
dict[str]]) -> tuple[list[dict[str]], list[int]]:
"... | 56d2f1a0a18eb1d1f8ecf9547184ae873d0b60e3 | 3,642,401 |
def countBarcodeStats(bcseqs,chopseqs='none',bcs = ["0","1"],use_specific_beginner=None):
"""this function uses edlib to count the number of matches to given bcseqs.
chopseqs can be left, right, both, or none. This tells the program to
chop off one barcode from either the left, right, both, or non... | af19f5a77f241362d50245885ab15dabd5197dcd | 3,642,402 |
def is_underflow(bin_nd, hist):
"""Retuns whether global bin number bin_nd is an underflow bin. Works
for any number of dimensions
"""
flat1d_bin = get_flat1d_bin(bin_nd, hist, False)
return flat1d_bin == 0 | 377c5a339f404ef4e55832f163952575f7b8d6a4 | 3,642,403 |
def deprecated_func_docstring(foo=None):
"""DEPRECATED. Deprecated function."""
return foo | f9c996c4f3735ed2767f0bbb139b1494e2a0fa39 | 3,642,404 |
def get_all_nodes(starting_node : 'NodeDHT') -> 'list[NodeDHT]':
"""Return all nodes in the DHT"""
nodes = [starting_node]
node = starting_node
while node != starting_node:
node = node.succ
nodes.append(node)
return nodes | 91b2968b000abac3d6f9f51bad5889ccf0fe8388 | 3,642,405 |
import sys
def get_uvj(field, v4id):
"""Get the U-V and V-J for a given galaxy
Parameters:
field (str): field of the galaxy
v4id (int): v4id from 3DHST
Returns:
uvj_tuple (tuple): tuple of the form (U-V, V-J) for the input object from mosdef
"""
# Read the file
uvj_df = ascii.re... | 39e1f6fd87ee4c7fc0f29fcfd18b7d780de4d532 | 3,642,406 |
import re
def by_regex(regex_tuples, default=True):
"""Only call function if
regex_tuples is a list of (regex, filter?) where if the regex matches the
requested URI, then the flow is applied or not based on if filter? is True
or False.
For example:
from aspen.flows.filter import by_rege... | a3d47690120a8091596047d73792b0d1f637132b | 3,642,407 |
def deserialize(name):
"""Get the activation from name.
:param name: name of the method.
among the implemented Keras activation function.
:return:
"""
name = name.lower()
if name == SOFTMAX:
return backward_softmax
if name == ELU:
return backward_elu
if name == SEL... | 133f01edaa678d60f85bf720590c0df3d1c552f3 | 3,642,408 |
def delete_item_image(itemid, imageid):
"""
Delete an image from item.
Args:
itemid (int) - item's id
imageid (int) - image's id
Status Codes:
204 No Content – when image deleted successfully
"""
path = '/items/{}/images/{}'.format(itemid, imageid)
return delete(pa... | 28d3c7bea85cd7132de6010def1c2ec41a9cfc82 | 3,642,409 |
def bytes_(s, encoding='utf-8', errors='strict'): # pragma: no cover
"""Utility to ensure binary-like usability.
If ``s`` is an instance of ``text_type``, return
``s.encode(encoding, errors)``, otherwise return ``s``"""
if isinstance(s, text_type):
return s.encode(encoding, errors)
return... | 269d315c1204be941766558fc3cbbc07c8e63657 | 3,642,410 |
import os
import uuid
def create_job_id(success_file_path):
"""Create job id prefix with a consistent naming convention based on the
success file path to give context of what caused this job to be submitted.
the rules for success file name -> job id are:
1. slashes to dashes
2. all non-alphanumeri... | 36417832ef7a7745af46798dbc0b83dcce5ba5f1 | 3,642,411 |
from operator import inv
import numpy
def normal_transform(matrix):
"""Compute the 3x3 matrix which transforms normals given an affine vector transform."""
return inv(numpy.transpose(matrix[:3,:3])) | b7f7256b9057b9a77b074080e698ff859ccbefb2 | 3,642,412 |
async def async_unload_entry(hass, config_entry):
"""Unload OMV config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(
config_entry, PLATFORMS
)
if unload_ok:
controller = hass.data[DOMAIN][config_entry.entry_id]
await controller.async_reset()
hass... | 60955e2aac51d211a296de0736f784c2332f855b | 3,642,413 |
import typing
import csv
def create_prediction_data(validation_file: typing.IO) -> dict:
"""Create a dictionary object suitable for prediction."""
validation_data = csv.DictReader(validation_file)
races = {}
# Read each horse from each race
for row in validation_data:
race_id = row["Entry... | 6ec67b277460feb5d80bf7a35e7bc40f3014e6ce | 3,642,414 |
def username(request):
""" Returns ESA FTP username """
return request.config.getoption("--username") | 2393884c2c9f65055cd7a14c1b732fccf70a6e28 | 3,642,415 |
def complete_data(df):
"""Add some temporal columns to the dataset
- day of the week
- hour of the day
- minute
Parameters
----------
df : pandas.DataFrame
Input data ; must contain a `ts` column
Returns
-------
pandas.DataFrame
Data with additional columns `da... | be342df461c04fc4b7f5b757f8287973c8826bd8 | 3,642,416 |
import re
def is_valid_mac_address_normalized(mac):
"""Validates that the given MAC address has
what we call a normalized format.
We've accepted the HEX only format (lowercase, no separators) to be generic.
"""
return re.compile('^([a-f0-9]){12}$').match(mac) is not None | 7c4ea0a3353a3753907de21bbf114b2a228bb3c0 | 3,642,417 |
def get_Y(data):
"""
Function: convert pandas data table to sklearn Y variable
Arguments
---------
data: panadas data table
Result
------
Y[:,:]: float
sklearn Y variable
"""
return np.array((data["H"],data["sigma"])).T | d5e9d5b116fe8e82165d019c23394b6f1dfc4d9c | 3,642,418 |
def get_bbox(mask, show=False):
"""
Get the bbox for a binary mask
Args:
mask: a binary mask
Returns:
bbox: (col_min, col_max, row_min, row_max)
"""
area_obj = np.where(mask != 0)
bbox = np.min(area_obj[0]), np.max(area_obj[0]), np.min(area_obj[1]), np.max(area_obj[1])
i... | 2e074d305d50334809eb0fe3e15def6fd4d21644 | 3,642,419 |
from pineboolib.core import settings
def check_mobile_mode() -> bool:
"""
Return if you are working in mobile mode, searching local settings or check QtCore.QSysInfo().productType().
@return True or False.
"""
return (
True
if QtCore.QSysInfo().productType() in ("android", "ios")... | 99327efbc3d329218d027e4451aae1979a9ebccc | 3,642,420 |
def check_for_overflow_candidate(node):
"""
Checks if the node contains an expression which can potentially produce an overflow
meaning an expression which is not wrapped by any cast, which involves the operator
+, ++, *, **. Note, the expression can have several sub-expression. It is the case
of the expression (a... | 77232f5d94a6cba6fef79bd51886145e2dfec4bf | 3,642,421 |
import struct
def parse_monitor_message(msg):
"""decode zmq_monitor event messages.
Parameters
----------
msg : list(bytes)
zmq multipart message that has arrived on a monitor PAIR socket.
First frame is::
16 bit event id
32 bit event value
no pad... | df71541d34bc04b1ac25c6435b1b298394e27362 | 3,642,422 |
import toml
import json
def load_config(fpath):
"""
Load configuration from fpath and return as AttrDict.
:param fpath: configuration file path, either TOML or JSON file
:return: configuration object
"""
if fpath.endswith(".toml"):
data = toml.load(fpath)
elif fpath.endswith(".jso... | 27c68c944a431b4d8b12c6b64609f33043363b03 | 3,642,423 |
def softmax_layer(inputs, n_hidden, random_base, drop_rate, l2_reg, n_class, scope_name='1'):
"""
Method adapted from Trusca et al. (2020). Encodes the sentence representation into a three dimensional vector
(sentiment classification) using a softmax function.
:param inputs:
:param n_hidden:
:p... | 1f77d99d12c927c0d77e136098fe8f9c2bc458b8 | 3,642,424 |
def node2freqt(docgraph, node_id, child_str='', include_pos=False,
escape_func=FREQT_ESCAPE_FUNC):
"""convert a docgraph node into a FREQT string."""
node_attrs = docgraph.node[node_id]
if istoken(docgraph, node_id):
token_str = escape_func(node_attrs[docgraph.ns+':token'])
if... | 8c6690e5fec41f98501060f5bf24ed823a2c31b6 | 3,642,425 |
import argparse
def build_arg_parser():
"""Build the ArgumentParser."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-f", "--fritzbox", default="fritz.box")
parser.add_argument("-u", "--username", default="dslf-config")
pars... | acf1baafdedfa8db7328e095eac5324f4ddae1ee | 3,642,426 |
import os
def get_marathon_url():
"""Get Marathon URL from the environment.
This is optional, default: http://leader.mesos:8080.
"""
marathon_url = os.environ.get("MARATHON_URL", None)
if marathon_url is None:
logger.warning("Unable to parse MARATHON_URL environment variable, using defaul... | 69ff96ad112897067a7301053031a78c30112d4a | 3,642,427 |
import os
import zipfile
def _load_dataset(name, split, return_X_y, extract_path=None):
"""Load time series classification datasets (helper function)."""
# Allow user to have non standard extract path
if extract_path is not None:
local_module = os.path.dirname(extract_path)
local_dirname =... | 32d5b83951b81d35f4bb26056521e2a2ff076144 | 3,642,428 |
def search(news_name):
"""method to fetch search results"""
news_name_list = news_name.split(" ")
search_name_format = "+".join(news_name_list)
searched_results = search_news(search_name_format)
sourcess=get_source_news()
title = f'search results for {news_name}'
return render_template('sea... | 7521221b66a872b00310693a3ccc6c81013098a2 | 3,642,429 |
def encrypt_document(document):
"""
Useful method to encrypt a document using a random cipher
"""
cipher = generate_random_cipher()
return decrypt_document(document, cipher) | 9a7e4bd79a83df261c4f946f62ff9bf40bfbf068 | 3,642,430 |
def bootstrap_alert(visitor, items):
"""
Format:
[[alert(class=error)]]:
message
"""
txt = []
for x in items:
cls = x['kwargs'].get('class', '')
if cls:
cls = 'alert-%s' % cls
txt.append('<div class="alert %s">' % cls)
if 'clos... | c2803176b2e1ed9b3d4aecd622eedcac673d4c42 | 3,642,431 |
def masked_mean(x, *, mask, axis,
paxis_name, keepdims):
"""Calculates the mean of a tensor, excluding masked-out entries.
Args:
x: Tensor to take the mean of.
mask: Boolean array of same shape as 'x'. True elements are included in the
mean, false elements are excluded.
axis: Axis... | 3242e86f571af61909efa63bd60158aa0f8eba88 | 3,642,432 |
def aspectRatioFix(preserve,anchor,x,y,width,height,imWidth,imHeight):
"""This function helps position an image within a box.
It first normalizes for two cases:
- if the width is None, it assumes imWidth
- ditto for height
- if width or height is negative, it adjusts x or y and makes them positive
... | 73a686f122ad31ee6693641e1ef386f13b67b4d8 | 3,642,433 |
def __do_core(SM, ToDB):
"""RETURNS: Acceptance trace database:
map: state_index --> MergedTraces
___________________________________________________________________________
This function walks down almost each possible path trough a given state
machine. During the process of walking ... | 621c9c26f9a7054b2e1ef20984105b05738878e9 | 3,642,434 |
import random
def circle_area(radius: int) -> float:
""" estimate the area of a circle using the monte carlo method.
Note that the decimal precision is log(n). So if you want a precision of
three decimal points, n should be $$ 10 ^ 3 $$.
:param r (int): the radius of the circle
:return (int): the ... | 2c85759ffbf798749263fca368cdfd159d67028b | 3,642,435 |
def Quantized_MLP(pre_model, args):
"""
quantize the MLP model
:param pre_model:
:param args:
:return:
"""
#full-precision first and last layer
weights = [p for n, p in pre_model.named_parameters() if 'fp_layer' in n and 'weight' in n]
biases = [pre_model.fp_layer2.bias]
#layer... | cd5b36c1b10567fee5a8b1f10679e6868f42f98f | 3,642,436 |
def _super_tofrom_choi(q_oper):
"""
We exploit that the basis transformation between Choi and supermatrix
representations squares to the identity, so that if we munge Qobj.type,
we can use the same function.
Since this function doesn't respect :attr:`Qobj.type`, we mark it as
private; only thos... | da91aff35d891000773100b998b80dc5d998414f | 3,642,437 |
def get_attention_weights(data):
"""Get the attention weights of the given function."""
# USE INTERACTIONS
token_interaction = data['tokeninteraction']
df_token_interaction = pd.DataFrame(token_interaction)
# check clicked tokens to draw squares around them
clicked_tokens = np.array(data['final... | e3189bd67f3da6ee8c1173348eec249d9c8cfa9a | 3,642,438 |
def save_ecg_example(gen_data: np.array, image_name, image_title='12-lead ECG'):
"""
Save 12-lead ecg signal in fancy .png
:param gen_data:
:param image_name:
:param image_title:
:return:
"""
fig = plt.figure(figsize=(12, 14))
for _lead_n in range(gen_data.shape[1]):
curr_lea... | 456fa204b20eee53645a900614877a6fb6a53e9c | 3,642,439 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an entry."""
component: EntityComponent = hass.data[DOMAIN]
return await component.async_unload_entry(entry) | b4ae648493b63a27f5127139876cf0bca2a2dcbb | 3,642,440 |
import os
import time
import tqdm
def get_all_score_dicts(ref_punc_folder_name, res_punc_folder_name):
"""
Return a list of score dictionaries for a set of two folders. This function assumes the naming
of the files in the folders are correct according to the diagram and hence if sorted
match files. Bo... | 27943b7694f420123dcd8bfebb79b99fc5dab617 | 3,642,441 |
def run_random_climate(gdir, nyears=1000, y0=None, halfsize=15,
bias=None, seed=None, temperature_bias=None,
climate_filename='climate_monthly',
climate_input_filesuffix='', output_filesuffix='',
init_area_m2=None, unique_sample... | 2887c1e62d3357e028c7be0539225bfb879323d9 | 3,642,442 |
from typing import Optional
def sync_get_ami_arch_from_instance_type(instance_type: str, region_name: Optional[str]=None) -> str:
"""For a given EC2 instance type, returns the AMI architecture associated with the instance type
Args:
instance_type (str): An EC2 instance type; e.g., "t2.micro"
region_n... | 2289deea91c9a9dafa0492fac9230292b546e9b7 | 3,642,443 |
import math
def atan2(y, x):
"""Returns angle of a 2D coordinate in the XY plane"""
return math.atan2(y, x) | ede5a647c175bebf2800c22d92e396deff6077e2 | 3,642,444 |
def index_objects(
*, ids, indexer_class, index=None, transforms=None, manager_name=None
):
"""
Index specified `ids` in ES using `indexer_class`. This is done in a single
bulk action.
Pass `index` to index on the specific index instead of the default index
alias from the `indexed_class`.
... | c93ea99946bb1516a58bb39aa5d43b1644f4f4da | 3,642,445 |
def get_attrs_titles_with_transl() -> dict:
"""Returns attribut titles and translation"""
attr_titles = []
attrs = Attribute.objects.filter(show_in_list=True).order_by('weight')
for attr in attrs:
attr_titles.append(attr.name)
result = {}
for title in attr_titles:
result[title] ... | 167955e669ddb3f6d5bbbd48cc01d26155a9e4ba | 3,642,446 |
def kde_KL_divergence_2d(x, y, h_x, h_y, nb_bins=100, fft=True):
"""Uses Kernel Density Estimator with Gaussian kernel on two
dimensional samples x and y and returns estimated Kullback-
Leibler divergence.
@param x, y: samples, given as a (n, 2) shaped numpy array,
@param h: width of the Gaussian k... | ce7ef19846dfd729fe5703aceaec69392f455ca6 | 3,642,447 |
def gml_init(code):
"""
Initializes a Group Membership List (GML) for schemes of the given type.
Parameters:
code: The code of the scheme.
Returns:
A native object representing the GML. Throws an Exception on error.
"""
gml = lib.gml_init(code)
if gml == ffi.NULL:
... | 5558f2db6a1c2269796cd52f675d5579ce357949 | 3,642,448 |
def before_run(func, force=False):
"""
Adds a function *func* to the list of callbacks that are invoked right before luigi starts
running scheduled tasks. Unless *force* is *True*, a function that is already registered is not
added again and *False* is returned. Otherwise, *True* is returned.
"""
... | 378604f6c574345682d8bd3d155ef8e4344aac27 | 3,642,449 |
def calc_z_scores(baseline, seizure):
""" This function is meant to generate the figures shown in the Brainstorm
demo used to select the 120-200 Hz frequency band. It should also
be similar to panel 2 in figure 1 in David et al 2011.
This function will compute a z-score for each value of the seizure p... | db3f6fbc42450658700ca2d120bf6faa31fccdfd | 3,642,450 |
def get_column(data, column_index):
"""
Gets a column of data from the given data.
:param data: The data from the CSV file.
:param column_index: The column to copy.
:return: The column of data (as a list).
"""
return [row[column_index] for row in data] | 3fd5c8c76ccfed145aba0e685aa57ad01b3695a5 | 3,642,451 |
def analytic_solution(num_dims,
t_val,
x_val=None,
domain_bounds=(0.0, 1.0),
x_0=(0.5, 0.5),
d=1.0,
k_decay=0.0,
k_influx=0.0,
trunc_order=100,
... | 0a920ec22fbe1ae3ff510ddd4389c1cf4ae0912d | 3,642,452 |
def safe_gas_limit(*estimates: int) -> int:
"""Calculates a safe gas limit for a number of gas estimates
including a security margin
"""
assert None not in estimates, "if estimateGas returned None it should not reach here"
calculated_limit = max(estimates)
return int(calculated_limit * constants... | 439eca363dc1fe1f53972c69191513913feef39b | 3,642,453 |
import typing
def integer_years(dates: typing.Any) -> typing.List[int]:
"""Maps a list of 'normalized_date' strings to a sorted list of integer years.
Args:
dates: A list of strings containing dates in the 'normalized_date' format.
Returns:
A list of years extracted from "dates".
""... | cdf14f0a2fee197177f12ead43346dfd4eabb5ef | 3,642,454 |
def add_wmts_gibs_basemap(ax, date='2016-02-05'):
"""http://gibs.earthdata.nasa.gov/"""
URL = 'http://gibs.earthdata.nasa.gov/wmts/epsg4326/best/wmts.cgi'
wmts = WebMapTileService(URL)
# Layers for MODIS true color and snow RGB
# NOTE: what other tiles available?: TONS!
#https://wiki.earthdata.... | 434ff85e1a721937ba83d0438bb7384d1a1f0600 | 3,642,455 |
import torch
def encode_position(
batch_size: int,
axis: list,
max_frequency: float,
num_frequency_bands: int,
sine_only: bool = False,
) -> torch.Tensor:
"""
Encode the Fourier Features and return them
Args:
batch_size: Batch size
axis: List containing the size of eac... | 06a81219b85006226069b288cce8602fc62e7119 | 3,642,456 |
def expr_erode(src, size = 5):
"""
Same result as core.morpho.Erode(), faster and workable in 32 bit.
"""
expr = _morpho_matrix(size, mm = 'min')
return core.akarin.Expr(src, expr) | 06f76f889cadcec538639ca1a920168c6a9ec467 | 3,642,457 |
def response_modification(response):
"""
Modify API response format.
"""
if (
status.is_client_error(response.status_code)
or status.is_server_error(response.status_code)
) and (status.HTTP_400_BAD_REQUEST != response.status_code):
return response
# Modify the response d... | f8a3120f3a1671d71f32158b742212b896074bdc | 3,642,458 |
import logging
import six
import base64
import urllib
def http_request(
url,
json_string,
username = None,
password = None,
timeout = None,
additional_headers = None,
content_type = None,
cookies = None,
gzipped = None,
ssl_context = None,
debug = None
):
"""
Fetch ... | 76e41483157fb01541aae5a29a12526f69a89326 | 3,642,459 |
import trace
def process_source_lineage(grid_sdf, data_sdf, value_field=None):
"""
performs the operation to generate the
"""
try:
subtypes = arcpy.da.ListSubtypes(data_sdf)
st_dict = {}
for stcode, stdict in list(subtypes.items()):
st_dict[stcode] = subtypes[stcod... | 298e615474debbb01addc583ae19fc1c5191084b | 3,642,460 |
def class_to_mask(classes: np.ndarray, class_colors: np.ndarray) -> np.ndarray:
"""クラスIDの配列をRGBのマスク画像に変換する。
Args:
classes: クラスIDの配列。 shape=(H, W)
class_colors: 色の配列。shape=(num_classes, 3)
Returns:
ndarray shape=(H, W, 3)
"""
return np.asarray(class_colors)[classes] | c574594b18d312e9ce432b68c8c2ff4d73771e6f | 3,642,461 |
from typing import List
import logging
def get_vocab(iob2_files:List[str]) -> List[str]:
"""Retrieve the vocabulary of the iob2 annotated files
Arguments:
iob2_files {List[str]} -- List of paths to the iob2 annotated files
Returns:
List[str] -- Returns the unique list of vocabula... | 0dc2a1f969ed6f92b36b1b31875c855d5efda2d9 | 3,642,462 |
import numpy
def taylor_green_vortex(x, y, t, nu):
"""Return the solution of the Taylor-Green vortex at given time.
Parameters
----------
x : numpy.ndarray
Gridline locations in the x direction as a 1D array of floats.
y : numpy.ndarray
Gridline locations in the y direction as a 1... | f47f4cdf11b81fe8b8c38ae50d708ec4361f7098 | 3,642,463 |
def static_initial_state(batch_size, h_size):
""" Function to make an initial state for a single GRU.
"""
state = jnp.zeros([h_size], dtype=jnp.complex64)
if batch_size is not None:
state = add_batch(state, batch_size)
return state | a803da5b0af0ce17fc7d1f303f6141416da6d120 | 3,642,464 |
def get_desklamp(request, index):
"""
A pytest fixture to initialize and return the DeskLamp object with
the given index.
"""
desklamp = DeskLamp(index)
try:
desklamp.open()
except RuntimeError:
pytest.skip("Could not open desklamp connection")
def fin():
desklamp... | 8f00296f5625c8a80bb094d1e470936a0733b83e | 3,642,465 |
import torch
def conj(x):
"""
Calculate the complex conjugate of x
x is two-channels complex torch tensor
"""
assert x.shape[-1] == 2
return torch.stack((x[..., 0], -x[..., 1]), dim=-1) | b22cfd3f12759f9b237099ca0527f0cbe9b99348 | 3,642,466 |
def label_clusters(img, min_cluster_size=50, min_thresh=1e-6, max_thresh=1, fully_connected=False):
"""
Label Clusters
"""
dim = img.dimension
clust = threshold_image(img, min_thresh, max_thresh)
temp = int(fully_connected)
args = [dim, clust, clust, min_cluster_size, temp]
processed_arg... | efe63ea0e71d3a5bf3b2f0a03f3c0f1c295c063b | 3,642,467 |
def update_schema(schema_old, schema_new):
"""
Given an old BigQuery schema, update it with a new one.
Where a field name is the same, the new will replace the old. Any
new fields not present in the old schema will be added.
Arguments:
schema_old: the old schema to update
schema_ne... | e97827ac0d8ee943b88fc54506af3f6fc8285d71 | 3,642,468 |
def get_estimators(positions_all, positions_relevant):
"""
Extracts density estimators from a judged sample of paragraph positions.
Parameters
----------
positions_all : dict of (Path, float)
A sample of paragraph positions from various datasets in the NTCIR-11
Math-2, and NTCIR-12 ... | b5f95247ff683e6e7e86d425ec64c988daacab60 | 3,642,469 |
def openbabel_force_field(label, mol, num_confs=None, xyz=None, force_field='GAFF', return_xyz_strings=True,
method='diverse'):
"""
Optimize conformers using a force field (GAFF, MMFF94s, MMFF94, UFF, Ghemical)
Args:
label (str): The species' label.
mol (Molecule, ... | 9964d94d2601e5cd7871886e396778457bb6e2cd | 3,642,470 |
def parse_flarelabels(label_file):
"""
Parses a flare-label file and generates a dictionary mapping residue identifiers (e.g. A:ARG:123) to a
user-specified label, trees that can be parsed by flareplots, and a color indicator for vertices.
Parameters
----------
label_file : file
A flare... | 23df49af14af720311b320f65894e995983365bf | 3,642,471 |
def remove_background(data, dim="t2", deg=0, regions=None):
"""Remove polynomial background from data
Args:
data (DNPData): Data object
dim (str): Dimension to perform background fit
deg (int): Polynomial degree
regions (None, list): Background regions, by default entire region ... | 54141b6f28b7a21ebdf1b0b920af3bfea4303b07 | 3,642,472 |
def get_hmm_datatype(query_file):
"""Takes an HMM file (HMMer3 software package) and determines what data
type it has (i.e., generated from an amino acid or nucleic acid alignment).
Returns either "prot" or "nucl".
"""
datatype = None
with open(query_file) as infh:
for i in infh:
... | 27653784b8a9fbae92226f8ea7d7b6e2b647765e | 3,642,473 |
def detect_min_threshold_outliers(series, threshold):
"""Detects the values that are lower than the threshold passed
series : series, mandatory
The series where to detect the outliers
threshold : integer, float, mandatory
The threshold of the minimum value that will be consid... | 6032693341073d101c0aad598a105f6cbc0ec578 | 3,642,474 |
from datetime import datetime
def new_datetime(d):
"""
Generate a safe datetime from a datetime.date or datetime.datetime object.
"""
kw = [d.year, d.month, d.day]
if isinstance(d, real_datetime):
kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])
return datetime(*kw) | 58479d70918dd287bfd29b1a15b6cd4dc1bfd695 | 3,642,475 |
def _to_str(x):
"""Converts a bool tensor to a string with True/False values."""
x = tf.convert_to_tensor(x)
if x.dtype == tf.bool:
return tf.where(x, 'True', 'False')
return x | 7919139e0f2cb19cd0856110e962acb616193ada | 3,642,476 |
def inpaintn(x,m=100, x0=None, alpha=2):
""" This function interpolates the input (2-dimensional) image 'x' with missing values (can be NaN of Inf). It is based on a recursive process
where at each step the discrete cosine transform (dct) is performed of the residue, multiplied by some weights, and then th... | 2fddabc6e512f9fc1ae7e8298f8d44582eaf7c46 | 3,642,477 |
def obtain_bboxs(path) -> list:
"""
obatin bbox annotations from the file
"""
file = open(path, "r")
lines = file.read().split("\n")
lines = [x for x in lines if x and not x.startswith("%")]
lines = [x.rstrip().lstrip() for x in lines] # get rid of fringe whitespaces
bboxs = []
for... | 75ceaac4bd8500320007d2ffb4cf4c490bd29473 | 3,642,478 |
def Timeline_Integral_with_cross_before(Tm,):
"""
计算时域金叉/死叉信号的累积卷积和(死叉(1-->0)不清零,金叉(0-->1)清零)
这个我一直不会写成 lambda 或者 apply 的形式,只能用 for循环,谁有兴趣可以指导一下
"""
T = [Tm[0]]
for i in range(1,len(Tm)):
T.append(T[i - 1] + 1) if (Tm[i] != 1) else T.append(0)
return np.array(T) | fdbd68e84e2a79a96c2078f92a7b69ab0138874e | 3,642,479 |
from typing import Generator
def list_image_paths() -> Generator[str, None, None]:
"""List each image path in the input directory."""
return list_input_directory(INPUT_DIRECTORIES["image_dir"]) | bce70f2af3c42905a27a30bf97de0a993161130f | 3,642,480 |
def a_star(graph: Graph, start: Node, goal: Node, heuristic):
"""
Standard A* search algorithm.
:param graph: Graph A graph with all nodes and connections
:param start: Node Start node, where the search starts
:param goal: Node End node, the goal for the search
:return: shortest_path: list|False Either a ... | ca25a15733d041cfca2560164ea8b047e55991b8 | 3,642,481 |
def buildAndTrainModel(model, learningRate, batchSize, epochs, trainingData, validationData, testingData, trainingLabels, validationLabels, testingLabels, MODEL_NAME, isPrintModel=True):
"""Take the model and model parameters, build and train the model"""
# Build and compile model
# To use other optimi... | af00f383311588525e66cff317908a99fa39859f | 3,642,482 |
def gaussian_temporal_filter(tsincr: np.ndarray, cutoff: float, span: np.ndarray,
thr: int) -> np.ndarray:
"""
Function to apply a Gaussian temporal low-pass filter to a 1D time-series
vector for one pixel with irregular temporal sampling.
:param tsincr: 1D time-series vecto... | 54060dbfc84ce1738698fda893afb556b48396e4 | 3,642,483 |
import requests
import json
def get_mactable(auth):
"""
Function to get list of mac-addresses from Aruba OS switch
:param auth: AOSSAuth class object returned by pyarubaoss.auth
:return list of mac-addresses
:rtype list
"""
url_mactable = "http://" + auth.ipaddr + "/rest/" + auth.version ... | 8f81a03640d7a4ed0d6d70bcaf268b647dee987e | 3,642,484 |
def presentations():
"""Shows a list of selected presentations"""
return render_template(
'table.html',
title='Presentations',
data=PRESENTATIONS,
target='_blank',
) | 643c1b7a6595f4c8c84abc47019a0346b414df56 | 3,642,485 |
def get_consensus_mask(patient, region, aft, ref=HIVreference(subtype="any")):
"""
Returns a 1D vector of size aft.shape[-1] where True are the position that correspond to consensus sequences.
Position that are not mapped to reference or seen too often gapped are always False.
"""
ref_filter = traje... | da7699350609ffc29d20b9922fa03c0d1944b57d | 3,642,486 |
import argparse
def parse_arguments():
""" Parse arguments """
parser = argparse.ArgumentParser()
parser.add_argument(
"-i",
type=str,
dest="input_pics",
help="A file consists of pics path with each pic on a single line.",
)
parser.add_argument("-o", type=str, dest=... | 8956c690bfffbe2e93c40c98db0eb785ff440530 | 3,642,487 |
def return_next_entry_list_uri(links):
"""続くブログ記事一覧のエンドポイントを返す"""
for link in links:
if link.attrib["rel"] == "next":
return link.attrib["href"] | 0c4c4139270ef8dedbb106f2db852097f4cd3028 | 3,642,488 |
def none(**_):
""" Input: anything
Return: 0.0 (float)
Descr.: Dummy method to handle no temperature correction"""
return 0.0 | e06b22f91d5a73450ddb4ca53fbb2569d567dcf1 | 3,642,489 |
def paths_and_labels_to_rgb_dataset(image_paths, labels, num_classes, label_mode):
"""Constructs a dataset of images and labels."""
path_ds = dataset_ops.Dataset.from_tensor_slices(image_paths)
img_ds = path_ds.map(lambda path: load_rgb_img_from_path(path))
label_ds = dataset_utils.labels_to_dataset(lab... | 7c72b3d628937fe999d89f5524d4d079ef20d9da | 3,642,490 |
def get_custom_headers(manifest_resource):
"""Generates the X-TAXII-Date-Added headers based on a manifest resource"""
headers = {}
times = sorted(map(lambda x: x["date_added"], manifest_resource.get("objects", [])))
if len(times) > 0:
headers["X-TAXII-Date-Added-First"] = times[0]
head... | 6c3acf2ea330b347387bfec574b4f8edfffa69ab | 3,642,491 |
def checkCulling( errs, cullStrings ) :
"""
Removes all messages containing sub-strings listed in cullStrings. cullStrings can be either a string or a
list of strings. If as list of strings, each string must be a sub-string in a message for the message to
be culled.
"""
def checkCullingMatch( m... | 5414e52df999a8aef7ed34328a689efa1582aabb | 3,642,492 |
def gram_matrix(x, ba, hi, wi, ch):
"""gram for input"""
if ba is None:
ba = -1
feature = K.reshape(x, [ba, int(hi * wi), ch])
gram = K.batch_dot(feature, feature, axes=1)
return gram / (hi * wi * ch) | 6e6145d9941c2e63120c7d030ac5b6b1ccd5d97e | 3,642,493 |
import csv
def read_pinout_csv(csv_file, keyname="number"):
"""
read a csv file and return a dict with the given keyname as the keys
"""
reader = csv.DictReader(open(csv_file))
lst = []
for row in reader:
lst.append(row)
d = {}
for item in lst:
d[item[keyname]] = item
... | 07a30b1191d311fee315c87773e3b3c1111d7624 | 3,642,494 |
async def start(hub, ctx, name, resource_group, **kwargs):
"""
.. versionadded:: 1.0.0
Power on (start) a virtual machine.
:param name: The name of the virtual machine to start.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-... | 74a09ef57ea735ea6a5af2ee5d10d3407e770980 | 3,642,495 |
def Render(request, template_file, params):
"""Render network test pages."""
return util.Render(request, template_file, params) | a30e34297de9ec44982dc8bc19231c471cc080c4 | 3,642,496 |
import logging
from pathlib import Path
def setup_global_logger(log_filepath=None):
"""Setup logger for logging
Args:
log_filepath: log file path. If not specified, only log to console
Returns:
logger that can log message at different level
"""
logger = logging.getLogger(__name__... | 74a8911243947387352b5c20e81ef0a304b48aa5 | 3,642,497 |
def calculate_class_recall(conf_mat: np.array) -> np.array:
"""
Calculates the recall for each class from a confusion matrix.
"""
return np.diagonal(conf_mat) / np.sum(conf_mat, axis=1) | 715f20b3e957dee25630bb413aff48140cf6aad3 | 3,642,498 |
def findall(element, path):
""" A helper function around a :attr:`lxml.etree._Element.findall` that passes the
element's namespace mapping.
"""
return element.findall(path, namespaces=element.nsmap) | 20da8cb66ac591751501e5c944f6f95235582e80 | 3,642,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.