content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
def load_test_data(columns: pd.Index, filename: str) -> Tuple[pd.Series, pd.DataFrame]:
"""
loads test data, proccesses it in a similar manner to the train data and return it as pandas df.
:param columns: column names of the traininst set the model was fitted on
:param filenam... | 6a1c34860e445089a2b73feb7a55a5a5bc496b86 | 3,633,800 |
def check_ancestors(page):
"""
First, check if the page's parent is one for which we want to index
the direct children of (constants.SEARCH_CHILDREN_OF)
If that's not the case, check all ancestors for any page we want all
descendants of (constants.SEARCH_DESCENDANTS_OF)
If there's a match in t... | 90428dbc7efe9175bbc0965df08842db1081809f | 3,633,801 |
def tobin(data, width):
"""
"""
data_str = bin(data & (2**width-1))[2:].zfill(width)
return [int(x) for x in tuple(data_str)] | 1679bc6826cbfd226e99f33dbfd049a284c26a75 | 3,633,802 |
def bisect_last_true(arr):
"""Binary search for last True occurrence."""
lo, hi = -1, len(arr)-1
while lo < hi:
mid = lo + hi + 1 >> 1
if arr[mid]: lo = mid
else: hi = mid - 1
return lo | 4ec436506e5823d54d6d31e45de76b30cd100746 | 3,633,803 |
def logLikelihood(theta, times, flux, fluxErr):
"""
Calculates the log likelihood based on the difference between the model and the data
Used by logProbability
Args:
theta (list) - parameters of the model
times (list) - time array of the light curve
flux (list) - array of flux da... | dc681cca6d8ca3b781475b58870b625c4d7fd51c | 3,633,804 |
def check_attrs(tag, required, optional):
"""
Helper routine to fetch required and optional attributes
and complain about any additional attributes.
:param tag (xml.dom.Element): DOM element node
:param required [str]: list of required attributes
:param optional [str]: list of optional attribute... | f08e65479cc7ee0a4d2290c9c0a011aac65fb2fa | 3,633,805 |
import os
def maybe_download(filename, expected_bytes):
"""Download a file if not present, and make sure it's the right size."""
if not os.path.exists(filename):
filename, _ = urlretrieve(url + filename, filename)
statinfo = os.stat(filename)
if statinfo.st_size == expected_bytes:
prin... | b3f435ca952446e376f0c6165bffcf6cde3923e6 | 3,633,806 |
def _interpolation(point_set: list)-> list:
"""
Written by Eric Muzzo, 101184817
Function returns a list which is stored in a variable. The function
takes a list as its parameter.
>>> _interpolation(point_set)
"""
if len(point_set[0]) == 2:
degree = 1
poly = np.po... | da37af093f48d0d2cdb41aaa9cfcc54e709f6a08 | 3,633,807 |
def create_app(label_studio_config=None):
""" Create application factory, as explained here:
http://flask.pocoo.org/docs/patterns/appfactories/.
:param label_studio_config: LabelStudioConfig object to use with input_args params
"""
app = flask.Flask(__package__, static_url_path='')
app.secr... | 4ec4b65843cfc8efd069fb5477ffb59a51da7eba | 3,633,808 |
import os
import json
def load_json_result(best_result_name, dataset_name):
"""Load json from a path (directory + filename)."""
result_path = os.path.join(RESULTS_DIR, dataset_name, best_result_name)
with open(result_path, 'r') as f:
return json.JSONDecoder().decode(
f.read()
... | 6b71fd1bd3cc55b6ad8d194bc68f0dbd0e4602f2 | 3,633,809 |
from collections import defaultdict
from typing import Union
from typing import List
from typing import Dict
def get_included_relationships(
results: Union[EntryResource, List[EntryResource]],
ENTRY_COLLECTIONS: Dict[str, EntryCollection],
include_param: List[str],
) -> Dict[str, List[EntryResource]]:
... | 38dc612011a68b5380f051b83e4314db6b7f4f97 | 3,633,810 |
import os
def guess_strategy_type(file_name_or_ext):
"""Guess strategy type to use for file by extension.
Args:
file_name_or_ext: Either a file name with an extension or just
an extension
Returns:
Strategy: Type corresponding to extension or None if there's no
cor... | d62826f272ec78b654ab46835efd8aad5afd0415 | 3,633,811 |
import math
def plot_width(G, ax, width, tips=True, plot=False):
""" Plot edge width of fault network
Parameters
----------
G : nx.graph
Graph
ax : plt axis
Axis
width : np.array
Width of network edges
tips : bolean
Plot tips
plot : False
Pl... | ade2f0780c5153a09be9cdf520549d593dc956bf | 3,633,812 |
import bisect
def get_mete_rad(S, N, beta=None, beta_dict={}):
"""Use beta to generate SAD predicted by the METE
Keyword arguments:
S -- the number of species
N -- the total number of individuals
beta -- allows input of beta by user if it has already been calculated
"""
assert S > 1, "S... | 4ff71a0460ea0d406658df8ec5465ba28641f728 | 3,633,813 |
def determine_firmware_versions(build_target):
"""Returns a namedtuple with main and ec firmware versions.
Args:
build_target (build_target_lib.BuildTarget): The build target.
Returns:
MainEcFirmwareVersions namedtuple with results.
"""
fw_versions = get_firmware_versions(build_target)
main_fw_ver... | d8e73722bde9edb57fd6962e285b6acf396e5dcf | 3,633,814 |
import sqlite3
def get_transcript_lengths(database, build):
""" Read the transcripts from the database. Then compute the lengths.
Store in a dictionary """
transcript_lengths = {}
conn = sqlite3.connect(database)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Get the exon... | d0fc2f229bd8a51770d06ac8021c5eb17e484ccf | 3,633,815 |
def segment_chars(plate_img, fixed_width):
"""
extract Value channel from the HSV format
of image and apply adaptive thresholding
to reveal the characters on the license plate
"""
V = cv2.split(cv2.cvtColor(plate_img, cv2.COLOR_BGR2HSV))[2]
thresh = cv2.adaptiveThreshold(V, 255,
cv2.ADAPTIVE_THRESH_GA... | a9bab29380c70b3d286f85e3e75a5c6ffc40fef3 | 3,633,816 |
from pathlib import Path
def get_filename_addition(orig_path: str, filename_addition: str) -> str:
"""Gets filename with addition. So if item is '/path/name.ext' and the filename_addition is '-add', the new result
would be '/path/name-add.ext'.
Args:
orig_path (str): The original path.
f... | 75611e4a265380febbb9b1830fd5e467ed5d4b97 | 3,633,817 |
def negated(input_words, include_nt=True):
"""
Determine if input contains negation words
"""
neg_words = []
neg_words.extend(NEGATE)
for word in neg_words:
if word in input_words:
return True
if include_nt:
for word in input_words:
if "n't" in word:
... | cc6c06af58fc6905f5b70dabfcfa3856a224c348 | 3,633,818 |
def get_box_value(box):
"""
Retrieves the value of the provided widget `box` and returns it.
"""
# Values (QAbstractSpinBox)
if isinstance(box, QW.QAbstractSpinBox):
return(box.value())
# Bools (QAbstractButton)
elif isinstance(box, QW.QAbstractButton):
return(box.isChecked... | 2123cb188e1198e6e456635a4df8edf11a9a9a28 | 3,633,819 |
from typing import Optional
from typing import Union
def pipeline(
task: str,
model: Optional = None,
tokenizer: Optional[Union[str, PreTrainedTokenizer]] = None,
use_cuda: Optional[bool] = True,
):
"""
:param task:
(:obj:`str`):
The task defining which pipeline will be return... | c4b17cfb09942a2893870636a952b468383a2526 | 3,633,820 |
def open_file_externally(path: str) -> None:
"""open_file_externally(path: str) -> None
(internal)
Open the provided file in the default external app.
"""
return None | 8bb6f5c19ad89fbef59e2ecbec89d5e2b5d05783 | 3,633,821 |
def _get_init_fn():
"""Return a function that 'warm-starts' the training.
Returns:
An init function.
"""
exclusions = []
if FLAGS.checkpoint_exclude_scopes:
exclusions = [scope.strip()
for scope in FLAGS.checkpoint_exclude_scopes.split(',')]
variables_to_resto... | 08a22de7161522939bc6a64da03bc1fd3572a81a | 3,633,822 |
def migration_indices(r_mgeo, p_mgeo):
""" identify migration indices
"""
idxs = None
r_mgrphs_iter = chain(*map(multibond_opening_resonances,
resonance_graphs(r_mgeo)))
p_mgrphs_iter = chain(*map(multibond_opening_resonances,
resonance_... | 0d130ee16446827c7b478e72363284346e905761 | 3,633,823 |
def counter():
"""Creates a counter instance"""
x = [0]
def c():
x[0] += 1
return x[0]
return c | 0f78a34b53bc5cc8b125a939cd88f58b047607a0 | 3,633,824 |
def replace_null(val):
"""
Replace given value with 'NULL' if it's an equivalent of NULL.
val {any}: value to check
returns {str}: 'NULL' or `val`
"""
if isinstance(val, float):
if np.isnan(val):
return 'NULL'
if val is None:
return 'NULL'
if isinstance(val... | 33f06075108eff6d12c6e83099c6b29ae457a74d | 3,633,825 |
import re
def Element(node, tag, mandatory=False):
"""Get the element text for the provided tag from the provided node"""
value = node.findtext(tag)
if value is None:
if mandatory:
raise SyntaxError("Element '{}.{}' is mandatory, but not present!".format(node.tag, tag))
return... | 2173f1ff50f8c685496d9b2708b19f1d6d808fb5 | 3,633,826 |
import base64
def fix_string_attr(tfjs_node):
"""
Older tfjs models store strings as lists of ints (representing byte values). This function finds and replaces
those strings, so protobuf can correctly decode the json.
"""
def fix(v):
if isinstance(v, list):
return base64.encode... | c137144fd9a42134451d2c49c93b20d562f1188b | 3,633,827 |
def get_env_space():
"""
Return obsvervation dimensions, action dimensions and whether or not action space is continuous.
"""
env = gym.make(ENV)
continuous_action_space = type(env.action_space) is gym.spaces.box.Box
if continuous_action_space:
action_dim = env.action_space.shape[0]
... | c8173ea96b8f16a2f12ac604f1e8c5f6b6f5ebd0 | 3,633,828 |
def is_windows_dark_theme():
"""Detect Windows theme"""
# From https://successfulsoftware.net/2021/03/31/how-to-add-a-dark-theme-to-your-qt-application/
settings = QtCore.QSettings(
"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
QtCore.QSettings.Nativ... | 9a6a70829827e6efc4d011f0c068e4536ea50297 | 3,633,829 |
def maximumProduct(nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = sorted(nums)
first_option=nums[0]*nums[1]*nums[-1]
second_option=nums[-3] * nums[-2] * nums[-1]
return first_option if first_option > second_option else second_option | 2ebbc11893499d18fcbf7630fc815b07abf329fd | 3,633,830 |
def calczeta(phi1, phi2, theta1, theta2):
"""
Calculate the angular separation between position (phi1, theta1) and
(phi2, theta2)
"""
zeta = 0.0
if phi1 == phi2 and theta1 == theta2:
zeta = 0.0
else:
argument = sin(theta1) * sin(theta2) * cos(phi1 - phi2) + cos(theta1) * c... | 76f13decbdea749bbd4aaadda7c95eb07682e54d | 3,633,831 |
import base64
import json
def handler(event):
"""Parses event payload, extract data from BigQuery table, write to GCS"""
json_data = base64.b64decode(event["data"]).decode("utf-8")
data = json.loads(json_data)
if "bq" not in data:
raise Exception("Invalid payload: no 'bq' field in payload", d... | 46039fdcc2b25a989eb36ea070ff35a6a6c726ba | 3,633,832 |
from typing import List
from typing import Tuple
def transform_coverage_to_coordinates(
coverage_list: List[int],
) -> List[Tuple[int, int]]:
"""
Takes a list of read depths where the list index is equal to the read position + 1 and returns
a list of (x, y) coordinates.
The coordinates will be sim... | 844eb986f4ccc322ec6e4720d8f969a7ce9562ec | 3,633,833 |
def complex_wrapper(func):
"""
Wraps complex valued functions into two-dimensional functions.
This enables the root-finding routine to handle it as a
vectorial function.
Args:
func (callable): Callable that returns a complex result.
Return:
two-dimensional, callable: function h... | ecd7530b8e0c43fa82c962b5753524d820213674 | 3,633,834 |
def test_rose_plot_data_using_cpt(data):
"""
Test supplying a 2D numpy array containing a list of lengths and
directions.
Use a cmap to color sectors.
"""
fig = Figure()
fig.rose(
data=data,
region=[0, 1, 0, 360],
sector=15,
diameter="5.5c",
cmap="bat... | 08db8c7b30856dc3d9f44db4b505c14d5f22e86b | 3,633,835 |
def mod_list_comparator(bot_entry, new_list, original_list):
"""Function to check the differences between new and old lists.
In the case of removals, the function also checks to see if their
removal is due to privatization or banning.
"""
formatted_lines = []
changes = list(set(new_list) - set(... | 9358025cd42902f938cd62b3930a9485ff2777cb | 3,633,836 |
import urllib
import json
def get_sources_articles(id):
"""
Function that gets the json response to our url request
"""
get_news_url = source_url.format(id,api_key)
with urllib.request.urlopen(get_news_url) as url:
get_news_data = url.read()
get_news_response = json.loads(get_news... | 4a321bc3a1a16c9dc989600419fe62878cb3b92d | 3,633,837 |
from typing import Optional
import enum
def cli_domain(name: Optional[str] = None):
"""
Register a value domain for the CLI displayed with its own name or ``name``
"""
def register(domain: TP) -> TP:
if issubclass(domain, enum.Enum):
_register_enum(domain, name)
else:
... | e1dc1e35e4e1921f107b3c5dfdfc9a22cbf4e413 | 3,633,838 |
def create_predict_function(
route, predict_service, decorator_list_name):
"""Creates a predict function and registers it to
the Flask app using the route decorator.
:param str route:
Path of the entry point.
:param expose.interfaces.PredictService predict_service:
The predict serv... | e72ad4b9877f2069ada79ae264c3c993072dfd30 | 3,633,839 |
def batch_pix_accuracy(output, target):
"""PixAcc"""
# inputs are NDarray, output 4D, target 3D
# the category -1 is ignored class, typically for background / boundary
predict = np.argmax(output.asnumpy(), 1).astype('int64') + 1
target = target.asnumpy().astype('int64') + 1
pixel_labeled = np.... | 030b46fc406f5293be0f1d55b0521878da26c93f | 3,633,840 |
def puma560() -> np.ndarray: # pragma: no cover
"""Get PUMA560 MDH model."""
return np.array(
[
[0, 0, 0, 0],
[-np.pi / 2, 0, 0, 0],
[0, 612.7, 0, 0],
[0, 571.6, 0, 163.9],
[-np.pi / 2, 0, 0, 115.7],
[np.pi / 2, 0, np.pi, 92.2],
... | ff0afbee7423ffa321e396fce7669a536949a8ba | 3,633,841 |
def get_scaling_factor(window: "Window" = None) -> float:
"""
Gets the scaling factor of the given Window.
This is the ratio between the window and framebuffer size.
If no window is supplied the currently active window will be used.
:param Window window: Handle to window we want to get scaling fact... | 1a75259d2d7214ad3437ed191cadb6e783121278 | 3,633,842 |
def fetch_addresses(xml_tree):
"""Pull out address information (addresses + instructions). Final
notices do not have addresses (as we no longer accept comments)."""
address_nodes = xml_tree.xpath('//ADD/P')
addresses = {}
for p in address_nodes:
p = cleanup_address_p(p)
if ':' in p:
... | 2e17731a81c6b51e9c9352139bc9a25adcf15080 | 3,633,843 |
import random
def css_tricks(data):
"""Handle data from css-tricks.com"""
articles = data["results"]
article = random.choice(articles)
title = article["highlight"]["title"][0]
description = article["highlight"]["content"][0]
if not description:
description = "No description found for t... | 188e2f01ff53839781632657018f2a623f4cf7b5 | 3,633,844 |
import pprint
def choose_(all_service_nodes, service_node,node, accepted_method_verbs=('get', 'describe', 'list', 'search')):
# def choose_(service_node, node, method_verbs=('describe', 'list', 'search')):
"""Choose between method verbs.
Priorities:
"""
# filter the node's methods with accepted method... | 3fab28343ee3059d8b989990368e5955ae9650db | 3,633,845 |
def rank(x, small_rank_is_high_num=True, rank_from_1=True):
"""
Rank items in an array. Using the 'first' method, which ranks ties using
the order of appearance. For rank functionality similar to R, see scipy's
rankdata function (which is imported from this module for convenience).'
Parameters
... | 365cddbb80bfe7efaebcc89d7256edf29f0fade7 | 3,633,846 |
def unauthorized():
"""For basic_auth. Return 403 instead of 401 to prevent browsers from displaying the default auth dialog."""
return make_response(jsonify({'error': 'Unauthorized access'}), 403) | 516105e6feb3dddcfe80a148e0cd1369eea95aa2 | 3,633,847 |
def cma_ajax_get_table_iso(request):
"""
Ajax view for fetching ISO images list.
"""
if request.method == 'GET':
iso = prep_data('admin_cm/iso_image/get_list/', request.session)
for item in iso:
item['size'] = filesizeformatmb(item['size'])
return messages_ajax.succ... | 7d5a4353dcb07aa0263ad90818a5136eb4212859 | 3,633,848 |
import os
def get_config_filepath():
"""Return the filepath of the configuration file."""
default_config_root = os.path.join(os.path.expanduser('~'), '.config')
config_root = os.getenv('XDG_CONFIG_HOME', default=default_config_root)
return os.path.join(config_root, 'zoia/config.yaml') | 53d78749adf56219ca08b3b4556901241608a57d | 3,633,849 |
def prefs(func: callable):
"""This decorator will pass the result of the given func to PREFS.convert_to_prefs,
to print a dictionary using PREFS format.
Example:
# Without prefs decorator
def dictionary():
return {'keybindings': {'Ctrl+C': 'Copy', 'Ctrl+V': 'Paste'}}
print(dicti... | f458c896cdcf96b21bcaaf0acfdd796cec04ab39 | 3,633,850 |
def friction_fnc(normal_force,friction_coefficient):
"""Usage: Find force of friction using normal force and friction coefficent"""
return normal_force * friction_coefficient | 7c25e651d7ef8990eab049a5b356f5470496af8e | 3,633,851 |
def parse_line(line):
"""
Parse a line of assembly code to create machine code byte templates.
If a line is not identifiably a JUMP_IF_OVERFLOW_FLAG assembly line,
return an empty list instead.
Args:
line (str): Assembly line to be parsed.
Returns:
list(dict): List of machine c... | 54eb89b6912cb0a4d69b3fd10009a6e64073bc1c | 3,633,852 |
def unpack_asn1_general_string(value): # type (Union[bytes, ASN1Value]) -> bytes
""" Unpacks an ASN.1 GeneralString value. """
return extract_asn1_tlv(value, TagClass.universal, TypeTagNumber.general_string) | 9d9fda9713a57e4e7c0d7a5162dbf19f37621bf0 | 3,633,853 |
def opti_loc_poly_traj(data_traj, t, minh, maxh, nb_h):
"""
Find the optimal parameter h to estimate the derivatives with local polynomial regression
...
"""
HH = np.linspace(minh,maxh,nb_h)
err_h = np.zeros(len(HH))
kf = KFold(n_splits=10, shuffle=False)
for j in range(len(HH)):
... | bed960693b17928683284d69bd69bff19391c2f2 | 3,633,854 |
def _trimmed_mean(arr, n=2, axis=None, maskval=0):
"""
Return the trimmed mean of an input array.
Parameters
----------
arr: ndarray
Data to trim
n: integer
Number of points to trim at each end
axis: int
The axis along which to compute the trimmed mean.
... | 4c4315d6e10bb51af01074fd404f745f54233dae | 3,633,855 |
def validate_kind_name(value):
"""Validate the value of the kind_name."""
if value is not None and not isinstance(value, str):
raise ValidationError('kind_name must be a string')
return value | cb01b96bd9d5c75765c1d004f3a6794e50c275b9 | 3,633,856 |
def setup_directories(env, saving_dir, replay_filename, expert_replay_file_path, agent_replay_file_path, pretrain_model_save_path, create_dirs=True):
""" Setup directories where information will be saved
env: Pass in current environment to have access to getting environment variables for recording purposes
... | e68874de0f61d023306f8f0fcb2a76dc2f83cb7e | 3,633,857 |
def keyInfoCtxCopyUserPref(dst, src):
"""
Copies user preferences from src context to dst context.
dst : the destination context object.
src : the source context object.
Returns : 0 on success and a negative value if an error occurs.
"""
return xmlsecmod.keyInfoCtxCopyUserPref(dst, s... | 709fd4f3a42d7dede8ddc801adc717668b92fa19 | 3,633,858 |
def kernel_classifier_distance_and_std_from_activations(real_activations,
generated_activations,
max_block_size=500,
dtype=None):
"""Kernel "classif... | e3197b9e5952bcb98faba0705115e887aa34e067 | 3,633,859 |
def yolo_eval(yolo_outputs,
anchors,
num_classes,
image_shape,
max_boxes=20,
score_threshold=.6, # max_boxes=20, score_threshold=.6,iou_threshold=.5
iou_threshold=.5):
"""Evaluate YOLO model on given input and return filtered boxes."""
num_layers = len(yolo_outputs)
anchor_mask = [[6,7... | ddb8afc6c1ead0cf7dfcfcdab3cc1e6438bdcaa7 | 3,633,860 |
from typing import List
def tile_images(images: List[np.ndarray]) -> np.ndarray:
"""Tile multiple images into single image
Args:
images: list of images where each image has dimension
(height x width x channels)
Returns:
tiled image (new_height x width x channels)
"""
... | dfa1bf0f6b778575083c99e6bf88c12614d8b8f2 | 3,633,861 |
def network(images1, images2, weight_decay):
"""
Siamese neural network for training person re-identification. Based on:
https://www.cv-foundation.org/openaccess/content_cvpr_2015/papers/Ahmed_An_Improved_Deep_2015_CVPR_paper.pdf
:param images1, images2: image pairs (positive and negative examples)
... | 6a84f19cf529ec7e5828b97b1edc9ea2f1ecbe7f | 3,633,862 |
def prepQuestAppliedNotification(shipper, questr, questdetails):
"""Prepare the details for notification emails for new quests"""
template_name="Quest_Accepted_Notification_Questr"
subject="Questr - Your shipment has been processed"
quest_support_email="support@questr.co"
email_details = {
... | 2457baf3e320b1ac8e93e622b213379aa04e31b7 | 3,633,863 |
from typing import Iterable
from typing import Tuple
def commit_ref_db_val_from_raw_val(db_kvs: Iterable[Tuple[bytes, bytes]]) -> DigestAndBytes:
"""serialize and compress a list of db_key/db_value pairs for commit storage
Parameters
----------
db_kvs : Iterable[Tuple[bytes, bytes]]
Iterable ... | 16ce44bfe82c9d884d20aafaf360160755128a02 | 3,633,864 |
def measure_text(text, r, ax):
"""Measure size of text string on canvas."""
t = plt.text(0.5, 0.5, text, **font_opts)
res = measure_text_obj(t, r, ax)
t.remove()
return res | c7ce29547f88552ef9489615da4e148546516ada | 3,633,865 |
def add_sto_plants(net: pypsa.Network, topology_type: str = "countries",
extendable: bool = False, cyclic_sof: bool = True) -> pypsa.Network:
"""
Add run-of-river generators to a Network instance
Parameters
----------
net: pypsa.Network
A Network instance.
topology_ty... | d871cf0a8fd1caffa8c74eaf91704f9a85cfc070 | 3,633,866 |
def flow_to_image(flow):
"""
Convert flow into middlebury color code image
:param flow: optical flow map
:return: optical flow image in middlebury color
"""
print('flow to image shape', flow.shape)
u = flow[:, :, 0]
v = flow[:, :, 1]
maxu = -999.
maxv = -999.
minu = 999.
... | fabd87b248994393df4297001b02f32bca9508d3 | 3,633,867 |
def contract_edges(graph, edge_weight='weight'):
"""
Given a graph, contract edges into a list of contracted edges. Nodes with degree 2 are collapsed into an edge
stretching from a dead-end node (degree 1) or intersection (degree >= 3) to another like node.
Args:
graph (networkx graph):
... | 1b8976831c3ca9d19354d52869106f6402bc21b5 | 3,633,868 |
def lagval3d(x, y, z, c):
"""
Evaluate a 3-D Laguerre series at points (x, y, z).
This function returns the values:
.. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * L_i(x) * L_j(y) * L_k(z)
The parameters `x`, `y`, and `z` are converted to arrays only if
they are tuples or a lists, otherwise th... | 34852c6c7945e166c7742552dc035b497ee450bb | 3,633,869 |
async def get_file_path(project_id: str, file_id: str) -> str:
"""
获取文件id
:param project_id:
:param file_id:
:return:
"""
file_path = PROJECT_FILE_DICT[project_id].pop(file_id)
return file_path | 368c40174bf06ede8f331ac6016704b15bf42599 | 3,633,870 |
def makeTopRegister(board, jigFrameSize, jigThickness, pcbThickness,
outerBorder=fromMm(3), innerBorder=fromMm(1),
tolerance=fromMm(0.05)):
"""
Create a SolidPython representation of the top register
"""
print("Top")
return makeRegister(board, jigFrameSize, ji... | 0ec41afa722cfd1d96f84f3a82f175bd9b5115bb | 3,633,871 |
def pvxpv(a, b):
""" Outer product of two pv-vectors.
:param a: first pv-vector.
:type a: array-like of shape (2,3)
:param b: second pv-vector.
:type b: array-like of shape (2,3)
:returns: a x b as a numpy.matrix of shape 2x3.
.. seealso:: |MANUAL| page 191
"""
axb = _np.asmatrix... | d238777454de939045f8e31d1a763afc9e973bbb | 3,633,872 |
def _encodeImage(image, encoding='JPEG', jpegQuality=95, jpegSubsampling=0,
format=(TILE_FORMAT_IMAGE, ), tiffCompression='raw',
**kwargs):
"""
Convert a PIL or numpy image into raw output bytes and a mime type.
:param image: a PIL image.
:param encoding: a valid PIL e... | db1b08c936bca8e4b8a79a7cbeddd469f48c87fb | 3,633,873 |
from typing import Optional
from typing import Sequence
from typing import Mapping
def get_local_gateway(filters: Optional[Sequence[pulumi.InputType['GetLocalGatewayFilterArgs']]] = None,
id: Optional[str] = None,
state: Optional[str] = None,
tags: Opt... | 723ffdd550fccad9f21ac86530cffaaa0bc1c589 | 3,633,874 |
def last_char(text: str, begin: int, end: int, chars: str) -> int:
"""Returns the index of the last non-whitespace character in string
`text` within the bounds [begin, end].
"""
while end > begin and text[end - 1] in chars:
end -= 1
return end | 5d59cd50fb99593d5261513327b9799fc175cd6c | 3,633,875 |
import argparse
import sys
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test a scene graph generation network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU id to use',
default=0, type=int)
parser.add_argument('-... | e1969c7fa389d4aa48d95ff95645a27ee31c141c | 3,633,876 |
import asyncio
def test_cache_memoize_async(cache):
"""Test that cache.memoize() can decorate async functions."""
loop = asyncio.get_event_loop()
marker = 1
@cache.memoize()
@asyncio.coroutine
def func(a):
return (a, marker)
assert asyncio.iscoroutinefunction(func)
assert le... | 716981f584136a4fb947172876028e8ce031a196 | 3,633,877 |
def _gen_write_element(e: UxsdElement, parent: str) -> str:
"""Function to generate partial C++ code for writing out a struct generated
from an UxsdElement.
Currently, all values with non-zero default values are emitted.
Otherwise, we would have to check against the nonzero value, and the
check would create a cas... | b8fd26c9a937bbd55bc8dd217d5afb1830ae1e42 | 3,633,878 |
import math
def compare_cols(fg_col, fg_cons, fg_size, fg_weights,
bg_col, bg_cons, bg_size, bg_weights,
aa_freqs, pseudo_size):
"""Compare amino acid frequencies between aligned columns via G-test."""
# Calculate the "expected" aa frequencies
bg_counts = count_col(bg_col... | adc473257286d1703b0b52d31ad2db3e3d95652c | 3,633,879 |
import os
def quick_nph(mol, confId=0, step=2000, time_step=None, press=1.0, f_press=None, shake=False, idx=None, tmp_clear=False,
solver='lammps', solver_path=None, work_dir=None, omp=1, mpi=0, gpu=0, **kwargs):
"""
MD.quick_nph
MD simulation with NPH ensemble
Args:
mol: RDKit M... | 24c8c60e2909c9931a26d7960bbad72dddefe0fd | 3,633,880 |
def parameter_converter(
possible_types: list,
default_return: t.Any,
cache_handler: t.Optional[t.Callable],
):
"""
parameter_converter is used for converting annotated parameters
of a function into the annotated types.
Conversion is attempted in the order that they are annotate... | 4472debf197d4c7726da7036faeabdb3d77a836b | 3,633,881 |
import time
def next_tide_state(tide_info, current_time):
"""Compute next tide state"""
# Get next tide time
next_tide = tide_info.give_next_tide_in_epoch(current_time)
if next_tide.get("error") == None:
tidetime = time.strftime("%H:%M", time.localtime(next_tide.get("tide_time")))
tide... | cc4f78cf41aa76d3788b69daaf64f4711d68714f | 3,633,882 |
def dct_2d_reverse(block):
"""
:reverse 2d Discrete Cosine Transformation
:param tensor:
:return:
"""
block = end_T(block)
block = idct(block, norm='ortho')
block = end_T(block)
block = idct(block, norm='ortho')
return block | 851261541dd7c7e4e15ba0bef0653ebdbe2a37a3 | 3,633,883 |
def convert_idx(text, tokens):
"""
Calculates the coordinates of each start
end spans of each token.
:param text: The text to extract spans from.
:param tokens: The tokens of that text.
:return: A list of spans.
"""
current = 0
spans = []
for token in tokens:
current = ... | 6022dca6591ae4a9bea3902af09ff59fee7d5cd5 | 3,633,884 |
import zipfile
def parse_zip(bufferstr):
"""
parse binary object as zip file
"""
z = zipfile.ZipFile(BytesIO(bufferstr))
filenames = z.namelist()
if not filenames:
print('No names found.')
with open('tmp.badzipfile.zip', 'wb') as f:
f.write(bufferstr)
exit(... | c448a505d21a65bec10799a5d2f6b52802788be8 | 3,633,885 |
def downsample(u_t, Fs, Fs_new, plotit=False):
"""
The proper way to downsample a signal.
First low-pass filter the signal
Interpolate / Decimate the signal down to the new sampling frequency
"""
tau = 2/Fs_new
nt = len(u_t)
tt = _np.arange(0, nt, 1)/Fs
# tt = tt.reshape(n... | 3bfdce2bb3b90278c04865185a52626ebf8b3f80 | 3,633,886 |
def convert_date_hours(times, start):
"""
This function converts model output time in hours to datetime objects.
:arg times: array of hours since the start date of a simulation.
From time_counter in model output.
:type times: int
:arg start: string containing the start date of the ... | 5e6f4703a63f898f9653ed14c246398ae7c7108c | 3,633,887 |
def idf_unit_test(app=UT, dut=IDFDUT, chip="ESP32", module="unit-test", execution_time=1,
level="unit", erase_nvs=True, **kwargs):
"""
decorator for testing idf unit tests (with default values for some keyword args).
:param app: test application class
:param dut: dut class
:param ... | 6afb6be19cd2760be829f01283f3d9a4073e87ef | 3,633,888 |
import os
def get_materials():
"""return _materials dictionary, creating it if needed"""
mat = {}
fname = 'materials.dat'
if os.path.exists(fname):
fh = open(fname, 'r')
lines = fh.readlines()
fh.close()
for line in lines:
line = line.strip()
if... | b89b230954d5690314069810b4595a49557e6620 | 3,633,889 |
import subprocess
import os
def decoratebiom(biom_file, outdir, metadata, core=""):
"""inserts rows and column data
"""
out_biom = '.'.join(biom_file.split('.')[0:-1]) + '.meta.biom'
cmd_sample = f"biom add-metadata -i {biom_file} -o {out_biom} -m {metadata} --output-as-json"
res_add = subprocess.... | 1c327110ba7b27d710dced5e3d59cfabf3f440fc | 3,633,890 |
def index(request):
"""The home page for MMS Pair App"""
# If the client-side forgets to run the command manage.py checkdb,
# this check ensures that the data will be updated on the home page.
coins = Coin.objects.all().count()
# If database is empty, call the load_coin function
if coins == 0:... | d17e86e6020b7ded4d667aa1a5e33416ad9e960b | 3,633,891 |
from typing import Iterable
from typing import Tuple
def cbdiag(size: int, blocks: Iterable[Tuple[int, ndarray]]) -> ndarray:
"""
Build a block matrix with (sub-)diagonal blocks and the given size.
Each block is specified with its offset from the diagonal and its data
(sub matrix). All blocks are exp... | 7d952221621996abe7b0f6dbed16774b67291302 | 3,633,892 |
from pathlib import Path
def read_hca_metadata(metadata_file: Path) -> nx.DiGraph:
"""
:param metadata_file:
:return: A unique set of donor metadata
"""
donor_data = pd.read_table(metadata_file)
row_data = []
for i, row in donor_data.iterrows():
dotted_row_dict = dict(zip(row.inde... | 1c9d2ef837335d26a3a3fdaccfdb33ea3b2aa909 | 3,633,893 |
def search_results(rows):
"""
Display search results
"""
print()
print(to_table(rows))
print()
# Ask user input
input_ = menu.get_input(
message='Select a result # or type any key to go back to the main menu: ')
if input_:
try:
result = [row for row... | ffca73c5e59fd2db463acf1559d7ed44065f0324 | 3,633,894 |
def eval_js(expression_, **args):
"""Execute JavaScript expression in the user's browser and get the value of the expression
:param str expression_: JavaScript expression. The value of the expression need to be JSON-serializable.
:param args: Local variables passed to js code. Variables need to be JSON-ser... | dab88f4d3cc574a9ffd60fc9992dfe4c038f0579 | 3,633,895 |
def quat2rot(q):
"""
Convert quaternion to 3x3 rotation matrix.
Source:
Blanco, Jose-Luis. "A tutorial on se (3) transformation parameterizations
and on-manifold optimization." University of Malaga, Tech. Rep 3 (2010): 6.
[Page 18, Equation (2.20)]
"""
assert len(q) == 4
qw, qx, qy, qz = q
qx2 = q... | 97f94538b30347f049349df7b4ad58c2d688936e | 3,633,896 |
def insert_stroke(seq, stroke, offset=0):
"""Insert into seq positions from the stroke dict"""
frame = offset
for i, p in enumerate(stroke):
frame = p["frame"] + offset
if i == 0:
# Do not override a keyframe at the start of the insert position.
if launch_keyframe(seq... | 76b6b683c03ec8cd58450a01ec65a8bee365d675 | 3,633,897 |
def get_dest_file(src_file):
"""
Takes a src file location
Returns the destination file location.
In the case of files with exif data, the destination file location is the
year/month/filename
In the case of files with exif data, but no Image DateTime, the destination
file location is... | 8f3aeaca31efa57f8e04db10f914d0770f544d0c | 3,633,898 |
def Lazy(func=None, *, lazy=True):
""""Decorator that provides a function with a boolean parameter "lazy".
When set to true, the function will not be executed yet, sort of like a
coroutine (see examples). This can be nice for testing purposes. Also
opens the door to some interesting things (maybe sort o... | 44df263b412830ee3aa3a610f45953318ad8d2b1 | 3,633,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.