content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def distance(a, b, R_weight=None, metrics='PEARSON', has_null=True):
"""Calculate distance between two np.arrays.
a, b: np.array
R_weight: np.array, default None, weighting vector
metrics: str, 'PEARSON' or 'MANHATTAN', or 'EUCLIDEAN'
has_null: wether input vector may contain NULL"""
... | b4202dcc65c5da096696e6ce98be037367ae1ef5 | 67,823 |
def generate_all_combinations(a, n):
"""
Generate all possible combinations of length n
from a list of a numbers
"""
if n > len(a):
return []
return list(combinations(a, n)) | 878bd5a051ee3a2b00ce05d4fc29bfe02cda07f4 | 67,824 |
def getSPP(mol):
"""
#################################################################
Calculation of submolecular polarity parameter(SPP)
#################################################################
"""
return round(getQmax(mol)-getQmin(mol), 6) | db7b4dc6f57f3de4267d0631f737cb347733f7a9 | 67,825 |
def num_words_on_board(board, words):
""" (list of list of str, list of str) -> int
Return how many words appear on board.
>>> num_words_on_board([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], ['ANT', 'BOX', 'SOB', 'TO'])
3
"""
count=0
for word in words:
if board_contains_word(board,... | fa2b22336d2c6020220fbce4267ef1a62cb44adc | 67,826 |
import logging
def _ensure_positive_percs_for_model(
model, reactions, verbose, raise_error, update_values, at_equilibrium_default
):
"""Ensure calculated PERCs for a model are positive.
Warnings
--------
This method is intended for internal use only.
"""
if reactions is None:
re... | 90ae1444e7a6b398bf098a54d048502e2be8bb79 | 67,827 |
def bulk_insert_dynamic(stream, index_name_attribute, message_attribute, bulk_size=1, credentials='es', ssl_trust_all_certificates=False, name=None):
"""Stores JSON documents in a specified index of an Elasticsearch database. The index name is part of the input stream.
Ingests tuples and stores them in Elastic... | 9ca1a0dd6a2a24acf432b4886f2938612b87ec4d | 67,829 |
def _resolve_absolute_url(absolute_url, allow_caching):
"""
Given a string that is an absolute URL, return a tuple consisting of: a
:py:class:`slicedimage.backends._base.Backend`, the basename of the object, and the baseurl of
the object.
"""
splitted = pathsplit(absolute_url)
backend = infe... | 84b8995b939f65a3e3f87eb6d2558543e8acb5c2 | 67,830 |
async def send_email(mail: BaseEmail = None):
"""Configure and send an email over SSL
Args:
mail (BaseEmail): The recipient(s), subject and contents of the message."""
# Set up an EmailMessage object
if not mail:
return None
message = EmailMessage()
message["From"] = mail.sender
... | c1d2dd605c1d4dcae1aeee69e87854553301eb97 | 67,831 |
import torch
def sample_image():
"""Sample torch image of correct shape."""
return torch.zeros((3, 300, 300)) | fc62ae5720fc1237822faad81c8924026f5b42a7 | 67,832 |
def softmax(x):
"""Compute softmax values for each set of scores in x."""
return np.exp(x) / np.sum(np.exp(x), axis=0) | 832c9d865fbdb1270f05f0721110b6ec9b8c1784 | 67,833 |
def generate_layer(layer_def, query_tokens, extent, empty_zoom):
"""
If empty_zoom is True, adds an extra sql column with a constant value,
otherwise if it is an integer, tests if the geometry of this layer covers the whole tile, and outputs true/false,
otherwise no extra column is added
"""
lay... | 6afc16d5d84775f329ceda1334c714e72b341e7a | 67,834 |
def invisible(fn):
"""A transform to make a quantum function non-recordable
or invisible within a QNode or quantum tape context.
Args:
fn (function): A quantum function that applies quantum operations.
Returns:
function: The input function transformed, so that it will not be
re... | 7d779163d533054664903124c1d017bf1428eb1d | 67,835 |
def __create_brightness_temparature_levels(df):
"""
Args:
df (pandas.DataFrame):
Returns:
dict: a dictionary of DataFrame objects;
"""
levels = {}
levels[1] = df.query("value > 330")
levels[2] = df.query("value <= 330 and value > 320")
levels[3] = df.query("value <= 320 ... | 6d85267219026c978720d0ba4dadc6ac58bb5836 | 67,836 |
def compute_distance_on_graph(G, s_id, t_id):
""" Computes the sum of the length in the shortest path between <tt>s</tt> and <tt>t</tt>.
If the shortest path are more than one the shorter in edge lengths is considered
<tt>return</tt> a double value of the length of the shortestpath between <tt>s</tt> and <t... | 22ab67a556d78bcb146a731e23af5e1cededc72c | 67,837 |
import logging
def parse_md(folder: str, inp: str, proj_name: str):
"""
Args:
folder (str): path of the folder
inp (str): the input file for CP2K
proj_name (str): the CP2K project name.
The prefix used for MD dumps
"""
logging.info(f"parse md in folde... | 06d353a563306a53abc8ed7cdefc3bc2426e6e24 | 67,838 |
def arch2abi(arch):
"""Map arch to abi"""
# pylint: disable=too-many-return-statements
if "rv32e" in arch:
if "d" in arch:
return "ilp32ed"
if "f" in arch:
return "ilp32ef"
return "ilp32e"
if "rv32i" in arch:
if "d" in arch:
return "ilp... | a315f04f5c45588953a15cc0fbfda8e3b9621621 | 67,839 |
def solve_L(centers_i,centers_r):
"""
From [1] as an intermediary step to obtain the reorientation of the
calibration plate.
L is a matrix which when multiplied with the rotation and
translation parameters r'1, r'2, r'4, r'5 and T'x returns the vector
of the x_r values at each calibration point. Solving it resu... | a1c57d29340a2f2dfc13257669b6ac35242d08a5 | 67,840 |
import Part
def edgeToSketch(edges, sketch):
"""
Project the selected edges onto Sketch plane and add
them to Sketch domain.
(return num_edge, return_edges, num_point, return_points)
Return the number of edges transferred in Sketch domain
and the corresponding projections and if any
the nu... | 14577f20289c872ede164e991f40f3516f37cdc4 | 67,841 |
def clean_age_column(age) -> str:
"""Cleans the age column of a dataframe
Args:
age (Any): An int, str or float representing age
Returns:
str: a string based on the age passed
"""
if isinstance(age, str):
n = age.replace(" ", "")
if 'or' in n:
return age... | 1c8dedd4f0d3abc19352aa9710f31b84517da74c | 67,842 |
import uuid
def create_id():
"""
Create ID with specified lenght based on HEX digits
"""
return uuid.uuid4().hex[:ID_LENGTH].upper() | c40ce9198828d3ff28d3ac36ef8cf029c36a1ab8 | 67,843 |
def get_haskell_command_window_view_file_project(view = None):
"""Returns window, view and file"""
if view:
return view.window(), view, view.file_name()
window = sublime.active_window()
view = None
if window:
view = window.active_view()
file_name = None
if view:
file... | afc3d8fddda99d878e2a4bad5103d444535c5032 | 67,844 |
def datasource_table_schema_get_by_name(request, datasource_name, table_name):
"""Get the schema for a data source table."""
datasource = datasource_get_by_name(request, datasource_name)
client = congressclient(request)
return client.show_datasource_table_schema(datasource['id'], table_name) | 54ee63820bddcfca568c7714c28a279e2c620006 | 67,845 |
def parsedir(directory, parsed, files, blocked, errfunc,
include_metainfo=True):
"""Recurses breadth-first starting from the passed 'directory'
looking for .torrrent files.
THIS IS BLOCKING. Run this in a thread if you don't want it to block
the program. Or better yet, use async_... | 135dae53cd0e6066f919c6fbb7097c1eadc4c6f4 | 67,846 |
def GetBisectFYITryJobEmailReport(job, message):
"""Gets the contents of the email to send once a bisect FYI job completes."""
results_data = job.results_data
subject_dict = {
'bot': job.bot,
'test_name': job.job_name,
}
report_dict = {
'message': message,
'bot': job.bot,
'job_ur... | e333f4ef4a6cabb4ec41453d7b2667044f445f49 | 67,847 |
def validate_integer(s):
"""digits and negative sign only. will not convert a decimal value!"""
if isinstance(s, intTypes):
return s
if not isinstance(s, basestring):
raise ConfigTypeError('integer value may contain only digits and a leading negative sign')
negate = s.startswith('-')
if ne... | eeba92fc248610ac08d67d04d9e886cb05f72d12 | 67,848 |
def _random_crop(image_list, crop_height, crop_width):
"""Crops the given list of images.
The function applies the same crop to each image in the list. This can be
effectively applied when there are multiple image inputs of the same
dimension such as:
image, depths, normals = _random_crop([image, depths, ... | 8326355405dad072f544b3a20c7dd35c49897096 | 67,849 |
def find_nearest_date(items, pivot):
"""This function will return the datetime in items which is the closest to the date pivot.
See https://stackoverflow.com/questions/32237862/find-the-closest-date-to-a-given-date
Parameters
----------
items : list
List containing datetimes
pivot : dat... | 7b719357c92210729857957e5b4ed8aee4a1f466 | 67,850 |
def next_coord(snake_coords, apple):
"""
计算下一个坐标
:param snake_coords: snake_coords
:param apple: apple
:return: 下一个坐标
"""
# 搜索head到apple的路径
if len(snake_coords) < HALF:
path = a_path_search.cal(snake_coords[0], apple, snake_coords[:-1]) # 移动时tail会腾出空间... | cb0e776949f9e4e2bdfaf5d5f16118b837476b58 | 67,851 |
def donsker_varadhan_eig(model, design, observation_labels, target_labels,
num_samples, num_steps, T, optim, return_history=False,
final_design=None, final_num_samples=None):
"""
Donsker-Varadhan estimate of the expected information gain (EIG).
The Donsker-... | 4df22857f1ce63aada170b5fbeb888bf174faec1 | 67,852 |
import base64
import json
def status(request, id):
"""
This view reports on the status of a running leximancer project. The id is actually the Leximancer URL base64 encoded.
"""
url = base64.urlsafe_b64decode(id.encode('ascii'))
try:
result = utils.get_project_status(url)
except utils... | 1724e5228e67914f8e34c66a1d1fdf190b534c29 | 67,853 |
from typing import Sequence
from typing import Mapping
from typing import List
import json
from typing import Dict
def get_graphql_property_inputs(
property_types: Sequence[PropertyDefinition],
properties_dict: Mapping[str, PropertyValue],
) -> List[PropertyInput]:
"""This function gets existing property ... | 39387d229c88b463cfe9703e510c3464d82c1903 | 67,854 |
def create_coordinate_dataset(
foci=1,
foci_percentage="100%",
fwhm=10,
sample_size=30,
n_studies=30,
n_noise_foci=0,
seed=None,
space="MNI",
):
"""Generate coordinate based dataset for meta analysis.
.. versionadded:: 0.0.4
Parameters
----------
foci : :obj:`int` o... | 080caab742bba4940cf1a524dd65136644a324ac | 67,855 |
def ng_CountVectorizer(X_train, ngram_range=(1, 3)):
"""
create CountVectorizer to validate in df the use of it.
Parameters
----------
X_train
ngram_range
Returns
-------
"""
# print('ngram_range=', ngram_range)
count_vectorizer = CountVectorizer(stop_words=None, ngram_rang... | 3b1fc15fe754d22881c0bb204ec6742552bda8ba | 67,856 |
def parse_interproscan_file(interproscan_file):
"""
Parses InterProScan TSV files into an assignment cache.
:param interproscan_file: A InterProScan file handle object.
:return: An assignment cache object.
"""
signatures_and_basic_match_info = create_match_dataframe(interproscan_file)
ident... | f9ad73eb161a7a3d1c3243686d0dcadd693b6ca7 | 67,857 |
import time
def package_graph_event(data):
"""
Package the summary graph event.
Args:
data (Bytes): Graph bytes string.
Retruns:
Event, event log object.
"""
graph_event = Event()
graph_event.wall_time = time.time()
modelp = ModelProto()
modelp.ParseFromString(dat... | bded3b99793546d29a1a40385e2ba13cea099841 | 67,858 |
def get_time_tied_leading_trailing(event, previous_score, last_goal_time):
"""
Calculate time of previous score state according to current event time
and time of last goal scored.
"""
if previous_score['home'] == previous_score['road']:
return 'tied', event['time'] - last_goal_time
elif ... | d53172e0beb9ab3155f02f3feca3680d25e5bcd0 | 67,859 |
def grappler_optimize(graph, fetches=None, config_proto=None):
"""Tries to optimize the provided graph using grappler.
Args:
graph: A `tf.Graph` instance containing the graph to optimize.
fetches: An optional list of `Tensor`s to fetch (i.e. not optimize away).
Grappler uses the 'train_op' collection... | 783def94de518ea19a2eb8f3382ccf747106c022 | 67,862 |
from typing import Optional
from typing import List
def prev_siblings_are(node: Optional[LN], tokens: List[Optional[NodeType]]) -> bool:
"""Return if the `node` and its previous siblings match types against the provided
list of tokens; the provided `node`has its type matched against the last element in
th... | 242c38542de8897b3392f994f03689ae1c1cd0b7 | 67,863 |
def request_uri(prefix=""):
""" Current request """
query_string = web.ctx.environ["QUERY_STRING"]
path_info = web.ctx.environ["PATH_INFO"]
query_string = query_string and ("?" + query_string)
return config.base_url + prefix + path_info + query_string | cc9b4e9e676ea575490d3f310c713fe7e8774eb8 | 67,864 |
import datasets
def evaluate(sess, test_inputs, test_labels, model, report):
"""Evaluates model against normal test examples and adversarial
training examples
:param sess: tensorflow session
:param test_inputs: placeholder for test inputs
:param test_labels: placeholder for test labels
:param model: cleve... | e428d870b573c0389bec505c518bc525fab65528 | 67,866 |
def getencoding():
"""
Returns the default encoding for input strings (usually 'utf-8').
"""
return NX_ENCODING | 70f3967c8726124d985a4dc8abaa839395dc21de | 67,867 |
from datetime import datetime
def isonow_str():
"""
Current timestamp in UTC with "Z".
"""
return datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z' | 6595f37391d81e915c8c78fe5e45e99676b60055 | 67,868 |
def transform_time_data(df):
"""
Return a dataframe with each timestamp in
the input dataframe extrapolated into units:
timestamp, hour, day, week of year, month, year, day of week
"""
timestamps = df.ts
time_data = []
for index, ts in timestamps.items():
dt = pd.to_datetime(ts... | bdbd9ed8fa8d6adfabfde03813a520245c3eef58 | 67,869 |
from typing import Collection
from typing import Tuple
from typing import Set
def find_namespace_orphans(
meta_manifests: Collection[MetaManifest]
) -> Tuple[Set[MetaManifest], bool]:
"""Return all orphaned resources in the `meta_manifest` set.
A resource is orphaned iff it lives in a namespace that ... | e46e41269d30aafd69dcdf2da9900102b9695b62 | 67,872 |
import numpy
def bd_PSNR(rate1, psnr1, rate2, psnr2):
"""
BJONTEGAARD Bjontegaard metric calculation
Bjontegaard's metric allows to compute the average gain in psnr between two
rate-distortion curves [1].
rate1,psnr1 - RD points for curve 1
rate2,psnr2 - RD points for curve 2
returns t... | fb981408fc2a35523e1e7c906adf8b67b9b51626 | 67,873 |
def linalg_mat_trace(matrix):
"""
Compute the trace of matrix
Parameters:
* matrix (matrix): The matrix
Return (number): The trace of the matrix
"""
return np.trace(matrix) | 0b16c27c95bbd96b3172e8f53e68a1c03ffd0cb6 | 67,874 |
from frappe.event_streaming.doctype.event_consumer.event_consumer import has_consumer_access
def get_update_logs_for_consumer(event_consumer, doctypes, last_update):
"""
Fetches all the UpdateLogs for the consumer
It will inject old un-consumed Update Logs if a doc was just found to be accessible to the Consumer
... | a8e8d59bcddd703fbfb0900a1c1b028a44f5bee3 | 67,875 |
def strategy_result_update(strategy_result, strategy_result_reason, phase_result,
phase_result_reason):
"""
Update Strategy Stage Result given a strategy phase result
"""
if STRATEGY_RESULT.WAIT == strategy_result:
# Nothing to update
return strategy_result, st... | fa5ea5dfe4ad74a121bd90b2177ebfbf199c81ee | 67,876 |
def J_int_yt(yt, membrane_geometry):
""" Jacobian using yt = 1. - rt coordination
Note that the coordination definition for y is not consist between [1] and [2].
"""
J = 1. - yt
if (membrane_geometry=='FMM' or membrane_geometry=='FMS'):
J = 1.
return J | 45e8ea2ef74c7bfd2dfa96543a8bfcb47531d6d4 | 67,877 |
from datetime import datetime
def get_current_utc_time():
"""Return string representation of current time in UTC."""
return datetime.datetime.utcnow() | 90b32042fe26986f63e8c30a6b29f1690c602c0b | 67,878 |
def df_to_aa_seqs(
IDs_df: DataFrame,
fasta_dict: dict,
n_flanking: int = 7
):
"""Takes a specifically structured DataFrame specifying variable site locations and defines
all amino acids sequences around those sites in a new column.
Args:
IDs_df: DataFrame of variable site l... | 891bb0e58184ab5571fb0e290725a61f0a603d42 | 67,879 |
def get_primer_direction(primer, delimiter='_', left='left', right='right'):
"""
Check if the primer is on the left or the right side of the amplicon.
"""
primer = delimiter.join([str(item) for item in primer])
try:
if left in primer.lower():
return 'LEFT'
elif right in p... | 3aed4e1d3397befa2ae713c5cae1a0c018abb5ae | 67,880 |
import numpy
def linear(domain_min, domain_max, range_min, range_max):
"""Return an instance of :class:`toyplot.projection.Piecewise` that performs a linear projection.
Parameters
-----------
domain_min, domain_max : number
Defines a closed interval of domain values that will be mapped to the... | ffdaeddf1d95ae4010277539209d67042e3bc1d0 | 67,881 |
def fully_connected_as_corr(ip, filters, bias):
"""turns a conv ouput to fully connected layer into a correlation by sliding
it across the horizontal direction. this only needs to happen in 1D as the
nuerons see the same size as the input
ip is DxHxW
filters is 2D - (DxHxW)x(num_neurons)
op is W... | 06c168b4f4a6c2056116cb12ab6dce4f4064eea7 | 67,882 |
def render(core):
"""Calls :func:`~megastep.cuda.render`, turns the output into an :ref:`attrdict <dotdicts>`,
then converts the :attr:`~megastep.cuda.Render.screen` attribute into the kind of (batch, channel, height, width)
tensor expected by PyTorch convolution modules.
This is almost always wha... | feaf82ccdc3bed5a7ef767032eb47b496fe6b394 | 67,883 |
def Rx(a):
"""Rotate y and z about x"""
R = [[1, 0, 0],
[0, +cos(a), -sin(a)],
[0, +sin(a), +cos(a)]]
return Matrix(R) | 706691ef88ac1bf4867ec8f1c37632b636fcdab3 | 67,884 |
import gc
def detect_mask(image):
"""Using Mask-RCNN to detect object and generate masks
Params
======
image (ndarray): image
"""
mrcnn_model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
# Load weights trained on MS-COCO
mrcnn_model.load_weigh... | 2287c6f7f51e1b3107a44a51b173cee33ecfbd9f | 67,885 |
import re
def get_sentences_list_matches(text, keysentence):
"""
Check which key-sentences from occurs within a string
and return the list of matches.
o Term count: The query counts as a “hint” every time that finds a term from our lexicon in the previously selected articles (by the target words ... | 0476a25e92d1e8278a0bd093975c73e957b7df03 | 67,887 |
def flatten(inputs):
"""
Flattens a tensor along all non-batch dimensions.
This is correctly a NOP if the input is already flat.
"""
if len(shape(inputs)) == 2:
return inputs
else:
size = inputs.get_shape().as_list()[1:]
return tf.reshape(inputs, [-1, size]) | 5ca09a1f33c53357d0432681c8d1864ae5dcdd99 | 67,888 |
def manhatten_distances(size, point):
""" Returns a numpy array of size size, with manhatten distances from the
given point for every location in the array
"""
x = np.linspace(0, size[0], size[0])
y = np.linspace(0, size[1], size[1])
distances = abs(x[:, None] - point[0]) + abs(y[None, :] - po... | d01106fb2ea26e806324b325ef156cd5c33b1f35 | 67,889 |
def get_ground_clearance(data):
"""
Extracts the minimum value of for_pos[2] and returns that value and the
timestep it happened at.
"""
structure = data.structure
min_clear = np.PINF
ts_min_clear = None
for ts, tstep in enumerate(structure.timestep_info):
try:
tstep.... | a6cb94100e4419e195f10ab7a7aa3891d6c2dce3 | 67,891 |
def is_global_meterdel(ofmsg):
"""Is a delete of all meters."""
return is_meterdel(ofmsg) and ofmsg.meter_id == ofp.OFPM_ALL | 12eef40bb2cd9cce13d90ee0867f4fb5e1a7503b | 67,892 |
def get_endpoints_by_server(server_id, data):
"""
Liste les endpoints connects au serveur [[id0,latence0],..]
:param server_id:
:param data:
:return:
"""
n_videos, n_endpoints, n_requests, n_servers, server_space, video_sizes, endpoints, requests = data
# Parcourir les endpoints et ajo... | 71280d187a2e9027d06d2686979005bb208fe0e9 | 67,893 |
def solar_alpha_(xDatetime, xLat, xLon): # pragma: no cover
""" solar azimuth angle relative to due north
# typically, allowed zero at night, ie when sza >9 deg below the horizon
:param xDatetime:
:param xLat:
:param xLon:
:return:
"""
psi = solar_psi_(xDatetime, xLat, xLon)
delta ... | f4ffc8b3f52abfc9fa79cb645dd1ae5cec3b35c3 | 67,895 |
def sample_from_simplex(rng, dim):
"""Uniformly samples a probability vector from a simplex of dimension dim."""
alpha = [1] * dim
return rng.dirichlet(alpha) | d034c4502634678874f89e17f2fde28eb8c28e0b | 67,896 |
import concurrent
def future_or_callback(future, callback, io_loop, return_value=_DEFAULT):
"""Compatible way to return a value in all Pythons.
PEP 479, raise StopIteration(value) from a coroutine won't work forever,
but "return value" doesn't work in Python 2. Instead, Motor methods that
return valu... | 41866105ef07937b7dd3d8532ee784729491b005 | 67,898 |
def get_proto_serializer():
"""
Return a proto serializer that serializes the proto, adds the associated
version, and then serializes the RedisState proto to a string
"""
def _serialize_proto(proto, version):
serialized_proto = proto.SerializeToString()
redis_state = RedisState(
... | c568290dc8f24535997462ff927cf2dcae3446b3 | 67,899 |
import torch
def dataframe2onehot(df, node_attributes):
"""
Convert the data in dataframe format to a torch one-hot encodded
format that the link prediction model can accept as input.
The reason why this function receives as input both the dataframe of interest (df)
and the NDSSL dataframe i... | 85a96c579830581b066be121188501c85a83627f | 67,901 |
def loaddb(cf, orderby='last DESC'):
"""Load all data in firewall database
Parameters
----------
cf : Config
orderby : str
Sorting order for data
Returns
-------
List[Dict[blacklist database schema]]
"""
db = FwDb(cf)
result = db.lookup('blacklist', orderby=orderby)
... | bd15c655f9dcb7582d558cc19e24a958ae5504e2 | 67,902 |
def __check_hdu(a) :
"""
Checks if input variable is an HDU
"""
if type(a) is fits.hdu.image.PrimaryHDU :
return True
else:
print('Input must be HDU type, with header and data!')
return False | 02f35d00651f8887fc2ec5d3eb8f75b7009b3989 | 67,903 |
def items():
"""This resource returns a list of items that were discovered by players
in the game. Details about a single item can be obtained using the
:func:`item_details` resource.
"""
return get_cached("items.json").get("items") | 9b54ae20af547626e669da4881dadbe6c2e3677b | 67,904 |
def gmm_pdf(x: np.ndarray) -> float:
"""
PDF.
:param x:
:return:
"""
centers = [(0, 0), (0, 10), (10, 0), (10, 10)]
pdf = 0
for i in range(len(centers)):
pdf += 0.25*multivariate_normal(np.array(centers[i]), np.eye(2)).pdf(x)
return pdf | 16f4c9c1df256668c556581815d062df2846249f | 67,905 |
def FileEdit(** kwargs):
"""
Library function to edit/make new files
:param deviceObj : Device object
:type deviceObj : object
:param stringEdit : File string content
:type stringEdit : string
:param filename : Filepath of the file to be edited
:type filename : string
:return: r... | 224fbc27a345cdaa4ee68641237febdc305932d2 | 67,906 |
def read_signal_timing_file(signal_timing_filename):
"""Read signal timing (% time green, amber, red) by link and 30 secs csv file and store in pandas dataframe (signals_df)"""
signals_df = pd.read_csv(supporting_files_path + signal_timing_filename)
# reformat trantime_30sec to string, convert timedelta to ... | 6236965fd14e346d9f7f13975e549f4cf3bc0e97 | 67,907 |
def is_event_stream(grid: MemoryGrid, **kwargs: Matcher) -> Matcher[tuple[str, dict]]:
"""
Match a Tahoe-LAFS directory entry representing a file which can be
retrieved from the given grid and which contains an ``EventStream`` with a
structure matched by the given keyword arguments.
"""
def is_... | f4611f4b5aa8624efda5d558dbcdf7786b9853e0 | 67,908 |
def scaled_dot_product_attention(q, k, v, mask):
"""Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but i... | 8c387e3d053466c1301fa1a0a38b0d0fb28a52ed | 67,909 |
from app.core.bot import bot
async def send(sentence: Sentence):
"""
情绪打分 \n
return: 返回分数, point
"""
bot.send_text(sentence.to_user, sentence.sentence_text)
return response_code.resp_200(sentence.to_user) | b214e5d66a41bddc89c36cc0181855b2da7cca68 | 67,911 |
def load_credentials_injector() -> CredentialsInjector:
"""Load the credentials injector fetching configuration from the environment."""
injector = CredentialsInjector()
injector = add_credentials_from_env(injector)
injector = add_credentials_from_env_file(injector)
return injector | 8cba31b5cfb8535feeb4f57f545a609eb67a54b7 | 67,913 |
def server_url() -> str:
"""
Get the url of the Enterprise Server.
:return: The current url
"""
return core.BNGetEnterpriseServerUrl() | f8267d1baef00126082ebf02c086a6bf8b3a8e68 | 67,914 |
import pytz
def load_from_yahoo(indexes=None,
stocks=None,
start=None,
end=None,
adjusted=True):
"""
Loads price data from Yahoo into a dataframe for each of the indicated
assets. By default, 'price' is taken from Yahoo's 'Ad... | 3f9ef862f795af88cf2aae7576b1e669a21111bc | 67,915 |
import math
def getDistance(p1, p2):
"""Return the distance between p1 and p2."""
return math.sqrt(sum([(p1[i] - p2[i])**2 for i in range(max(len(p1), len(p2)))])) | 28d8156ad1eb5557a3fb3fa8bc7a94a66d06db3e | 67,916 |
def subset(lst, k, empty=None, complement=False):
"""
An operative structure (like integer ot constant) that represent a subset of at most k elements.
:param lst: The data for the subsets.
:param k: The maximal bits for subsets.
:param empty: The empty element, 0, by default.
:param complement: ... | 3296dad70a7cad13262140855f88e07fe0f43dd4 | 67,917 |
import torch
def get_axis_matrix(a, b, c, norm=True):
""" Gets an orthonomal basis as a matrix of [e1, e2, e3].
Useful for constructing rotation matrices between planes
according to the first answer here:
https://math.stackexchange.com/questions/1876615/rotation-matrix-from-plane-a-to-b
... | 3490b7968e9e9c6eab0004846f41857e3dc73242 | 67,919 |
from typing import Dict
def load_pipeline(config: Dict, mode="train", **kwargs):
"""Load pipeline with required config.
Args:
config (Dict): Pipeline configuration.
Returns:
object: Pipeline object.
"""
validate_config(config)
pipeline_class = globals()[config["training"]["... | a5d9df76b83491c4aa467125a5bf6f5929c223fa | 67,920 |
from datetime import datetime
def read_iso0_grib_data(fname):
"""
Reads a 2D field of iso-0 degree data from a MF NWP in GRIB format
Parameters
----------
fname : str
name of the file to read
Returns
-------
iso0_data : dictionary
dictionary with the data and metadata... | 7dc826b718594924aa882cbee085af243e8e68cc | 67,921 |
def format_condition_value(conditions):
"""
@summary:
['111', '222'] -> ['111', '222']
['111', '222\n333'] -> ['111', '222', '333']
['', '222\n', ' 333 '] -> ['222', '333']
@param conditions:
@return:
"""
formatted = []
for val in conditions:
formatted += [it... | b79269ab375c1bec9724f29528c5a42d3bda3a72 | 67,922 |
from typing import Callable
from re import T
from typing import List
def parse_list(s: str, convert: Callable[[str], T] = identity, fallback: List[T] = None) -> List[T]:
"""
:returns list of values converted from comma separated substrings
:raises ValueError if value cannot be parsed and no fallback is pr... | 6684b0df4330e3a6f039f88a93870918d805b86a | 67,923 |
from sage.rings import sum_of_squares
from warnings import warn
def three_squares(n):
"""
Write the integer `n` as a sum of three integer squares if possible;
otherwise raise a ``ValueError``.
INPUT:
- ``n`` -- an integer
OUTPUT: a tuple `(a,b,c)` of non-negative integers such that
`n =... | 036d40660f237127956d252725ddc5d1357c37e7 | 67,924 |
def get_root_ids(phylogeny):
"""Get ids of root nodes in phylogeny
Args:
phylogeny (networkx.DiGraph): graph object that describes a phylogeny
Returns:
For all nodes in phylogeny, return ids of nodes with no predecessors.
"""
return [node for node in phylogeny.nodes
if ... | 624ab70805a9833c1fa46b9d3d8007afe43e2c10 | 67,925 |
def find_threshold_pr(y_test, y_preds, *, min_precision, min_recall):
"""
Find the threshold to use with `predict_proba()` for classification
based on the minimum acceptable precision and the minimum acceptable recall.
Parameters:
- y_test: The actual labels.
- y_preds: The predicted la... | 2ce8f1c8c76e1258dec2c8dddb30ea94265a1ab1 | 67,926 |
def ymdhms_format_from_day_sec(day, sec, sep="T", digits=None, suffix="",
buffer=None):
"""Date and time in ISO format 'yyyy-mm-ddThh:mm:ss....'. Works for both
scalars and arrays.
Input:
day integer or arbitrary array of integers defining day numbers
... | da99f88b688eb1a37bf30835d3f9ab6fc82a0357 | 67,928 |
def links_and_nodes():
"""
J4 S1
/ \ /
/ \ /
S3 / J3 S2
\ / | /
\ / | /
J6 BR
| // \
| // \
~BI J2 INF
... | b8a154738407fee77fbd2d111443a42753ff749c | 67,929 |
import numbers
def is_numeric(N):
"""Determine if `N` is numeric.
`N` may be a single value or a collection.
"""
def is_num(n):
return isinstance(n, numbers.Number) and (not isinstance(n, bool))
if '__iter__' in dir(N):
return False not in [is_num(n) for n in N]
else:
... | 4381d9ad7a3ee5f2f689b78f54b663e8349c58ff | 67,930 |
def find_unique_namespace(namespace, increment_fn=None):
"""
Returns a unique namespace based on the given namespace which does not exists in current scene
:param namespace: str, namespace to find unique name of
:param increment_fn: fn(basename, index), returns a unique name generated from the namespace... | 889e8ef59aaaa6e760ca90183dd2fb95b427c0e8 | 67,931 |
def GET(request):
"""Get this Rack's Machines."""
# Make sure required parameters are there
try:
request.check_required_parameters(
path={
'tileId': 'int'
}
)
except exceptions.ParameterError as e:
return Response(400, e.message)
# ... | 14289462b52335d88c0ccc195530f878174809f2 | 67,932 |
def get_most_stimulated_cell(mem_cells, pattern):
"""
Tim te bao kich thich thag pattern nhat.
:param mem_cells:
:param pattern:
:return:
"""
mem_cells = stimulate(mem_cells, pattern)
sorted_cells = sorted(mem_cells, key=lambda elem: elem['stimulation'])
# Sap xep tang dan` do kich ... | 38692b3f8538b7f1d6b88a1c41afa55adbec113d | 67,933 |
def is_timer_stopped():
"""
Check whether the current timer level is stopped.
Returns:
bool: True if stopped.
"""
return f.t.stopped | 62d3222241c81ae26678e597c2de4a09b7d7e2d3 | 67,934 |
def GET_feedback_search():
"""
Returns all feedback documents
"""
try:
feedbacks = feedback.find()
return dumpJSON(feedbacks)
except Exception as e:
return respond500(e) | f3591d17a2898b936955424c3635d4be3fd62150 | 67,935 |
import requests
def address_lookup(query: str) -> FeatureCollection:
""" Looks up address using DataBC's geocoder """
q = {
"addressString": query,
"autoComplete": "true",
"maxResults": 5,
"brief": "true"
}
search_url = "https://geocoder.api.gov.bc.ca/addresses.json?"... | acc72f47565da19c4d7d5b78473ad0b55bf74055 | 67,936 |
def _TrackFitter(kwargs):
"""Returns TrackFitter module name.
Arguments:
- `kwargs`: Used to supply options at construction time of the object.
"""
isCosmics = kwargs.get("isCosmics", False)
if isCosmics:
return ("RecoTracker.TrackProducer.CTFFinalFitWithMaterialP5_cff",
... | 2b61b02b5c9767362ad40eb2c968cd032d2f3f7e | 67,937 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.