content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def rzpad(value, total_length):
"""
Right zero pad value `x` at least to length `l`.
"""
return value + b"\x00" * max(0, total_length - len(value)) | 76a0884e9f8a65e0ff3efac56223dfa2fbed31b4 | 3,615,772 |
import unittest
def getTestSuite():
"""
set up composite test suite
"""
test_suite = unittest.TestSuite([])
test_suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestAzureP2P))
#test_suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestDocStrings))
return test_suit... | a76c925cf6bd99981f7979af85864b99d2a95dcd | 3,615,773 |
def visual_map(visual_type='color',
visual_range=None,
visual_text_color=None,
visual_range_text=None,
visual_range_color=None,
visual_range_size=None,
visual_orient='vertical',
visual_pos="left",
vis... | 8e812b50fab992efecaabc8fd5430eb409a4e679 | 3,615,775 |
def calc_precision_recall(img_results):
"""Calculates precision and recall from the set of images
Args:
img_results (dict): dictionary formatted like:
{
'img_id1': {'true_pos': int, 'false_pos': int, 'false_neg': int},
'img_id2': ...
...
... | b6946bcc83c2c16d91b4413c0d551d421ae2b252 | 3,615,776 |
def compose(*funcs):
"""Returns a function that is the composition of multiple functions."""
def wrapper(x):
for func in reversed(funcs):
x = func(x)
return x
return wrapper | d93d59f2f1979fa35638357fcac5130710e0fda3 | 3,615,777 |
def svm_model(C=10**1.5, gamma='scale', kernel='rbf'):
"""SVM"""
return svm.SVC(kernel=kernel, gamma=gamma, C=C, probability=True) | 19886c1025471dcfceeb829861b44b687cafecc3 | 3,615,778 |
def fmgr_set_ha_mode(fmgr, paramgram):
"""
:param fmgr: The fmgr object instance from fortimanager.py
:type fmgr: class object
:param paramgram: The formatted dictionary of options to process
:type paramgram: dict
:return: The response from the FortiManager
:rtype: dict
"""
# INIT A ... | 4b7980d1f7fa9f1e2632eac09335a7a2bda33d26 | 3,615,779 |
def cinder_client(os_creds):
"""
Creates and returns a cinder client object
:return: the cinder client
"""
return Client(version=os_creds.volume_api_version,
session=keystone_utils.keystone_session(os_creds),
region_name=os_creds.region_name) | 3b46c0222d9fd8fca6cf2cd4d50df75e5021d849 | 3,615,780 |
from functools import reduce
def compose(*functions):
"""
Compose all the function arguments together
:param functions: Functions to compose
:return: Single composed function
"""
# pylint: disable=undefined-variable
return reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x) | d69ab8953d8e846fffd50aa9c0925935e38e9e38 | 3,615,781 |
def mul_fft(f_fft, g_fft):
"""Multiplication of two polynomials (coefficient representation)."""
deg = len(f_fft)
return [f_fft[i] * g_fft[i] for i in range(deg)] | 67db62dc812827b6aa7c7406a068ae9e47f97a65 | 3,615,783 |
def atr_cache_nb(high_ts, low_ts, close_ts, windows, ewms, adjust):
"""Caching function for `vectorbt.indicators.basic.ATR`."""
# Calculate TR here instead of re-calculating it for each param in atr_apply_nb
tr = true_range_nb(high_ts, low_ts, close_ts)
cache_dict = dict()
for i in range(len(windows... | 9937dff358a3f7dc38608e333e3a5c4686ddaf1e | 3,615,785 |
import torch
def custom_decode_labels(mask, num_images=1, num_classes=20):
"""Decode batch of segmentation masks.
Args:
mask: result of inference after taking argmax.
num_images: number of images to decode from the batch.
num_classes: number of classes to predict (including background).
... | d4b7d7a95872b3d541b8f011004ae198f0cb508d | 3,615,786 |
import re
def clean_text(text):
""" Cleans abstract text from scopus documents.
Args:
text (str): Unformatted abstract text.
Returns:
(str) Abstract text with formatting issues removed.
"""
if text is None:
return None
try:
cleaned_text = re.sub("© ([0-9])\w*... | 7ffbf3a6ebe0c0caac203cea109e939b5c861724 | 3,615,788 |
def web_context(req, resource=None, id=False, version=False, parent=False,
absurls=False):
"""Create a rendering context from a request.
The `perm` and `href` properties of the context will be initialized
from the corresponding properties of the request object.
>>> from trac.test impor... | 28ac532e37f14fcc84a4daf4372aa496763453bf | 3,615,789 |
def a_vs_b(ship_a, ship_b, trials, attack_range):
"""This uses a random agent to choose actions during attacks from ship_a to ship_b.
Args:
ship_a ((Ship, str)): Attacker and hull zone tuple.
ship_b ((Ship, str)): Defender and hull zone tuple.
trials (int): Number of trials in average calcula... | 7545a9b8626b5ab22ae49c22328f3a58fd64c072 | 3,615,790 |
def activity_index(windowed_array):
"""
Compute activity index of windowed tri-axis accelerometer signal.
Activity index defined here as:
sqrt(mean(vx, vy, vz))
where vx, vy, vz are the variances in x, y, z
Activity index accounting for device specific systematic variance is def... | a5af2242f78760a6f343761522cb4e4ec3b1c274 | 3,615,791 |
def getPathToRoot(label):
""" Returns all the nodes present in all the paths from node 'label' to root. """
path = [label]
if len(labelDict[label]['parents'])==0:
return path
for item in labelDict[label]['parents']:
path += getPathToRoot(item)
return list(set(path)) | 7daf1374233504392791707ed5ae7bbde3d20fc5 | 3,615,792 |
def macAddress(value):
"""Return true if mac-address is valid, otherwise - false."""
return False | c7fbedf2975861ce7b8666f72ab497b640e9e611 | 3,615,793 |
def merge_channels(x):
"""
Takes a NxMx4 array and returns a 2Nx2M array by stacking the 4 2D images in a 2x2 grid.
:param x: Input array
:return: Output array
"""
return np.vstack((np.hstack((x[:, :, 0], x[:, :, 1])), np.hstack((x[:, :, 2], x[:, :, 3])))) | 2cf9f661e1c9f6505e2f38215fd7a35e7e5e9cb2 | 3,615,794 |
def collect_inference_outputs(inference_output_uri):
"""
collect information related to output of inference.
"""
sagemaker_output_file = "unlabeled.manifest.out"
prediction_output_uri = inference_output_uri + sagemaker_output_file
prediction_output_s3 = S3Ref.from_uri(prediction_output_uri)
... | 9de5aadea8df6757869112d161603ec095e6b9b4 | 3,615,795 |
def get_classname(hwnd):
""" @return A empty string if failed. """
try:
return win32gui.GetClassName(hwnd)
except Exception:
pass
return '' | 0a75a5b64b02a6ec99ab0364dbad85f8821b3bb1 | 3,615,797 |
def xrecons_single_sample(X, read_attn_params, write_attn_params, args):
"""
Create a single image containing the output canvas at each of the T time
steps.
Parameters:
-----------
X : X is a batch of image canvases. (T, batch_size, H, W, C)
read_attn_params: Tuple containing parameters needed to draw rea... | 9db5415be21d456572c0f197562ebc573bc3e0d7 | 3,615,798 |
from datetime import datetime
def undersc_str2dt(undersc):
"""Converts the format with underscores to a datetime instance
Args:
undersc(str): time in underscores-format
Returns:
`datetime`: datetime instance
"""
(mydate, mytime) = undersc.split("_")
ymd = mydate.split("-")
... | 36988c6af6a20590d781f7ec1ea1ee2e8713941e | 3,615,800 |
def console_to_str(s: bytes) -> str:
"""From pypa/pip project, pip.backwardwardcompat. License MIT."""
try:
return s.decode(console_encoding, "ignore")
except UnicodeDecodeError:
return s.decode("utf_8", "ignore") | 86940f491c4d2bc9f3ac345e613f464f531b881a | 3,615,801 |
def make_animation_all_channels(satellite: Satellite, example_index: int):
"""
Make animation of all channels
An animation is made over time. Subplots show the different satellite channels
Args:
satellite: satellite data
example_index: which example to use
Returns: plotly figure
... | 28dc3f9bf86e09e752c0c1a73d749c680b36bc35 | 3,615,802 |
def mgmt_lock(timeout=MGMT_LOCK_TIMEOUT, key_args=(), key_kwargs=(), wait_for_release=False, bound_task=False,
base_name=None):
"""
Decorator for runtime task locks.
This means that task will run, but will wait in a loop until it acquires a lock or will fail if timeout is reached.
"""
... | 39d6b11d7a7e53b12cbfd8eedfa8882eb5ccc554 | 3,615,804 |
def get_value(rgb, animated=False):
"""
Obtains pixel value if it is enabled. Color is not supported yet here.
:param rgb:
:param animated: It is a WTF from SP1. If I do animation it requires me to invert the values...
:return:
"""
if rgb[0] > 0 or rgb[1] > 0 or rgb[2] > 0:
return "... | da154d07ca007c183a62ea05a9b6bb5d467b6b0c | 3,615,806 |
def get_ldap_conn(host, username, password, reuse=None):
"""
Returns an LDAP connection
"""
if reuse:
ldap_conn = reuse
else:
ldap_conn = initialize("ldap://"+host)
try:
ldap_conn.bind_s(username, password)
except Exception as err_msg:
return False, 'Error: {}... | 9d51c34f65e2d8013a9d86a22aa935b2b26d1980 | 3,615,807 |
def make_profile_middleware(
app, global_conf,
log_filename='profile.log.tmp',
limit=40):
"""
Wrap the application in a component that will profile each
request. The profiling data is then appended to the output
of each page.
Note that this serializes all requests (i.e., removing
c... | cad275e1a9448af1453ec5eeff421e12620c9387 | 3,615,808 |
def dup_children(my_task, file_info, children, copy_bfid, fcc):
"""
Create duplicates of package children in FC DB for copy of package file copy_bfid. It is metadata operation, no data copied.
Get children of this package identified by file_info
Children information is used to create children copies in... | 1568f56d1b5188287e4e185fbec5fd659df60518 | 3,615,809 |
def encode_matrix_fbs(matrix, row_idx=None, col_idx=None):
"""
Given a 2D DataFrame, ndarray or sparse equivalent, create and return a Matrix flatbuffer.
:param matrix: 2D DataFrame, ndarray or sparse equivalent
:param row_idx: index for row dimension, Index or ndarray
:param col_idx: index for col... | 193abb2690a80c2875056f5d8ffcd2467f4a81c8 | 3,615,810 |
import torch
def mAP(pred, target, cutoff=.5):
"""
Computes the Average Precision of the semantic segmentation
Arguments:
pred: predicted segmentation output by network
target: binary segmentation targets
cutoff: prediction cutoff for foreground vs background
"""
with torc... | 4b2978a1dfec690aa43b6829c6c19ea88180cdca | 3,615,812 |
def create_User(name, email):
"""Create a new User.
Args:
name ([string]): The name of the User
email ([string]): An email
Raises:
exceptions.DatabaseError: if an errors occurs during SQL execution
Returns:
[User]: A User model
"""
LOGGER.info("Create a User %... | 707cdfff60fdc4ef84dc5a55bd9a3ea6f8bc78b6 | 3,615,814 |
import yaml
def load_yaml_config(filepath):
"""Load Krake base configuration settings from YAML file
Args:
filepath (os.PathLike, optional): Path to YAML configuration file
Raises:
FileNotFoundError: If no configuration file can be found
Returns:
dict: Krake YAML file config... | a5970ab968a9da7c89733077834a88b05ca2d6a0 | 3,615,815 |
def insert_pms(payloads, app_name):
"""Summary
Args:
payloads (TYPE): Description
Returns:
TYPE: Description
"""
responses_list = []
for payload in payloads:
print("inserting", payload)
response = knackpy.record(
payload,
obj_k... | 9247d8d7b8bcfce97794d40a6dcbd1564fba0853 | 3,615,816 |
def max_cum_build_rule(mod, g, p):
"""
**Constraint Name**: GenNewLin_Max_Cum_Build_Constraint
**Enforced Over**: GEN_NEW_LIN_VNTS_W_MAX_CONSTRAINT
Can't build more than certain amount of capacity by period p.
"""
return mod.GenNewLin_Capacity_MW[g, p] \
<= mod.gen_new_lin_max_cumulativ... | 9122a05867ccccbe36378c36d34e98462c62f85d | 3,615,817 |
import json
def preprocess2(lowercase, break_hashtags, replacements, line):
""" returns lowered line """
try:
tweet = json.loads(line)
text = tweet['text']
except:
tweet = dict()
text = line.decode('utf8')
# Break hash sign: #hashtag -> # hashtag
if break_hashtags:... | 7e833af980e2d881d3dee61845fd507eed2b0d6e | 3,615,818 |
def get_vrf_description(device, vrf):
"""Gets description of configured VRF.
Args:
device (Device): This is the device object of an NX-API enabled device
using the Device class within device.py
vrf: case-sensitive VRF (because 'show run section $VRF' is being used)
Returns:
... | aedd4bcf3792a94b4b0df5fdad7bf12c8dffb87a | 3,615,819 |
from torch import as_tensor
def normalize(tensor, mean=NORMALIZE_MEAN, std=NORMALIZE_STD, inplace=False):
"""
Normalizes image tensor using VGG mean and std.
Assumes image has [0,1] values.
Accepts CxHxW or BxCxHxW images.
"""
if not inplace:
tensor = tensor.clone()
dtype = tenso... | f98d52212169437ef020d783f26a45ea54831545 | 3,615,820 |
import warnings
def _scale_factory(scale, axis, *args, **kwargs):
"""If `scale` is a `~matplotlib.scale.ScaleBase` instance, nothing is
done. If it is a registered scale name, that scale is looked up and
instantiated."""
if isinstance(scale, mscale.ScaleBase):
if args or kwargs:
wa... | 85111485ebf53f1b9902820882b19f52442de067 | 3,615,821 |
def clean_job_task(job_id, db_name=config.PG_JOB_TASK_DB_NAME):
"""This will directly clean job and related task from db"""
deletion_command = f"""DELETE FROM "Task" WHERE "jobId"='{job_id}';DELETE FROM "Job" WHERE "id"='{job_id}';"""
client = postgres.PGClass(config.PG_HOST, db_name, config.PG_USER, config... | ba42ebb024ff812e751fbde12f9f3e213bab91f9 | 3,615,822 |
from pathlib import Path
import logging
def call_qualimap(bamfile: Path, outdir: Path) -> Path:
"""
Makes a system call to Qualimap with the provided .bam file. Finds and returns the output file (genome_results.txt)
:param bamfile: .bam file generated via BBmap.sh
:param outdir: output directory for Q... | f05776ee6b4d20e8622ea4697744d5cb68253b51 | 3,615,823 |
def _pos_phrases(tokens, preprocess):
"""Extract phrases from a text using POS Tagging-derived rule-based approach.
Args:
tokens (list of str): A list of semantically-ordered tokens.
preprocess (callable): A function that pre-processes the extracted
phrases.
Returns:
li... | f3bf9f0acecda39281e9ba90f5bebc5248c22603 | 3,615,824 |
import json
def create_controller():
"""
1. Check the token
2. Call the worker method
3. Show results
"""
minimum_buffer_min = 3
if views.ds_token_ok(minimum_buffer_min):
# 2. Call the worker method
args = {
'account_id': session['ds_account_id'],
'b... | 2426c999b9d82db1c0a8403f1e874eb0e2307eb3 | 3,615,825 |
def total_seconds(td):
"""Since ``timedelta.total_seconds()`` is new in 2.7"""
return float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 | 8a25267b3c61a41dee1cbe643174fd20ebb7d835 | 3,615,827 |
def review_table(queryset: QuerySet, fields_str: str) -> dict:
"""
This tag displays a QuerySet of reviews as a table
:param queryset: The set of Reviews to display
:type queryset: QuerySet
:param fields_str: The fields to get for each review
:type fields_str: str
:r... | 76632f481b459350299bf00dd6e15af1dd133bdd | 3,615,828 |
from re import T
def get_sparsity_penalty(nnet, inputs, sparsity, mode="mean",
deterministic=False):
"""
returns the sparsity penalty on network activations combined as a sum
"""
assert mode in ("mean", "l1")
rho = sparsity
penalty = 0
eps = 0.0001 # for numeric... | 4804b41446ae32d90b2c787692da014da983a964 | 3,615,829 |
def generate_config(context):
""" Entry point for the deployment resources. """
properties = context.properties
name = properties.get('name', context.env['name'])
project_id = properties.get('project', context.env['project'])
zone = properties.get('zone')
# Network formatting
if 'network' ... | 3976f7e52f652ef0e0467cc5afec00d821fcd956 | 3,615,830 |
from dateutil import tz
from datetime import datetime
def tznow(time_zone="Europe/London"):
"""
# to get the list of time zones:
#from dateutil.zoneinfo import get_zonefile_instance
#print(list(get_zonefile_instance().zones)) # over 500 timezones
"""
my_tz = tz.gettz(time_zone) # or =tz.get... | 4fe3e65fecc9adce09ba74910b82aff1ac6f5b11 | 3,615,831 |
def create_table():
"""Создает пустую таблицу для тестов."""
id_ = base.create_id(ports.USD, ports.USD)
return usd.USD(id_) | 7aad4c5422adb4a75192c6498b4f3df2ee233412 | 3,615,832 |
def load_yaml(yaml_file_path, logger):
"""
Read a yaml file from the filesystem and return it as a dict
Returns 'None' if the file is not found
:param yaml_file_path: string - Location of the yaml file to be read
:param logger: Logger - Logger for logging events
"""
if file_exists(yaml_file... | e9ece324a8fdfab903241957e68ff2f57206ad3a | 3,615,833 |
from typing import List
def available_years() -> List[int]:
"""List available years with datasets."""
return [2012, 2013, 2014, 2015, 2016, 2017, 2018] | 898fd02e0cde1ac71251cd70069c52c481a66acf | 3,615,834 |
def rotational_groups(rxn, key1, key2, dummy=False):
""" Obtain the rotational groups for a given rotational axis
:param rxn: a hydrogen migration Reaction object
:param zma: a z-matrix; if passed in, the linear atoms will be determined
from this; otherwise they will be determined heuristically fro... | a61286aeb183c62875c1f1e7f6aed12f3eee5ba5 | 3,615,835 |
from typing import Any
from typing import Dict
from typing import Optional
import requests
def main(*wtf: Any, **kwwtf: Any) -> Any:
"""
入口函数。该函数用于在允许直接运行的同时,兼容 GCP Cloud Function/AWS Lambda 等云函数平台。
:return: 由检测到的平台决定
"""
config: Dict[str, Optional[ConfigValue]] = initialize_config(CONFIG_SCHEMA)... | 5db680d4c4d0083d5b83b1de9f9b1824826a544f | 3,615,836 |
def plot_ecdf_all_states(df_mape):
"""Function for ECDF plots for all states
Args:
df_mape (pd.DataFrame): The dataframe with MAPE values for every model, region
Returns:
mpl.Figure, [mpl.Axes] : The figure and axes objects
"""
fig, axs = plt.subplots(figsize=(21, 6*15), nrows=15, ... | 2c0ee1dee752f5c0233f1a376bbc13b7ce7f7aa9 | 3,615,837 |
def delete_products(wishlist_id, product_id):
"""
Delete an Product
"""
app.logger.info(
"Request to delete product with id: %s from wishlist with id: %s", product_id, wishlist_id)
product = Product.find(product_id)
if product:
product.delete()
return make_response("", status... | 01c12911c4844aced4fcf951854852c4e9b17c7f | 3,615,838 |
import aiohttp
async def http_call(url, method, data=None, headers=None):
"""
Performs an http request
Args:
url (str): The URL to send the request to
method (str): The HTTP method to use
data (dict): The data to send with the request
headers (dict): The headers to send wi... | 10d72f32312b7fe9071a8776f784a1ce7c4954d6 | 3,615,839 |
import uuid
from datetime import datetime
def new_flight(app, init_db, new_airplane):
"""Fixture to create a new flight"""
new_airplane.save()
flight = {
"id": str(uuid.uuid4()),
"airplane_id": new_airplane.id,
"flight": 'FL111',
"check_in": datetime.datetime(2019, 9, 10, 0... | 990886f93c0571f97680cd7f7eebcf01be8d3950 | 3,615,840 |
import functools
def tabulate(start, slots, time_context=None):
"""Takes a list of slots and converts it into a week schedule table.
Args:
start: The aware datetime representing the start of the schedule. May
be any timezone.
slots: The (filled, ordered, annotated) list of timesl... | a00045fc5c684353feef7f7b71efcf82bd79085f | 3,615,841 |
import inspect
import warnings
def cached(user_function=None, max_size=None, ttl=None, algorithm=CachingAlgorithmFlag.LRU, thread_safe=True):
"""
@cached decorator wrapper
:param user_function: The decorated function, to be cached
:param max_size: The max number of items can be held in the cache
:... | 43dd083a9eb3bdbeee3ee277bf01b764e67073ba | 3,615,842 |
import json
def add_comment(blog_id, commenter, comment_content):
"""
add a comment to a blog post
:param blog_id:
:param commenter:
:param comment_content:
:return:
"""
target_post_key = ndb.Key('Post', blog_id)
target_post = target_post_key.get()
json_comments = target_post.... | 3a5589accc27add32099115bdeb2b9a6399bbf14 | 3,615,843 |
import asyncio
def status_handler(func):
"""Register the status response handler."""
def register_status(instance_func, address):
# This registers all messages for a device but only triggers on
# status messages if they return within the TIMEOUT period
address = Address(address)
... | 0e7c6ccd0d9deece8ed24b3e1ea6883d0a91428b | 3,615,844 |
from typing import Tuple
from typing import List
def check_all_categories(categories) -> Tuple[List, List, List]:
"""
Check all categories in ``categories``.
Parameters
----------
categories: List
A list of categories
Returns
-------
Tuple[List, List, List]
A tuple co... | 2727a89e17b90da551ae12020d8d327e49a5a28d | 3,615,845 |
from typing import Counter
import re
def typographeur(text,
fix_parenthesis=True,
fix_colon=True, fix_exclamation=True,
fix_interrogation=True, fix_semicolon=True,
fix_ellipsis=True, fix_point_space=True,
fix_comma_space=True, fix_do... | 1dc760f87c5fcc2bd404d60ccbaa5c6e3f596189 | 3,615,846 |
def get_triggered(categories):
"""Returns any of the categories exceeding blocking threshold."""
triggered = []
for x in BLOCKED_CATEGORIES:
for category in categories:
if category.name.startswith(x) and category.confidence > BLOCKED_CATEGORIES[x]:
triggered.append((categ... | baeded2cc9fc7b1d4cf8ee65c12cb6450c82f400 | 3,615,847 |
import torch
from typing import Optional
def find_best_peak(
values: torch.Tensor,
) -> tuple[Optional[PositiveInt], Optional[float]]:
"""Takes a Tensor of values (with 1 dimension), and finds the index of the best peak
If peak finding fails, (None, None) is returned.
Parameters
----------
va... | a4c72e07a9fa2d88dc6f9b0144b84855db8769a3 | 3,615,848 |
def delete_records(request):
"""Deletes all records of model."""
model_id = request.matchdict['model_id']
try:
records = request.db.delete_records(model_id)
for record in records:
request.notify('RecordDeleted', model_id, record['id'])
except ModelNotFound:
request.er... | 7362572eef30a4d4d0bad5f9647dac40be707053 | 3,615,849 |
def coordinates_contain_point(coordinates, point):
"""
This function uses `Crossing number method` (http:#geomalgorithms.com/a03-_inclusion.html) to check whether
a polygon contains a point or not.
For each segment with the coordinates `pt1` and `pt2`, we check to see if y coordinate of `point` is
b... | 97176955324be459595503d204e0e13ce9983562 | 3,615,850 |
def obstruction(info_dict):
""" Obstruction due to M2 """
# Multiply by 1.05 to take the arms into account
info_dict["obstruction"] = (
info_dict["M2_factor"] * info_dict["D_M2"]
) ** 2.0 / info_dict["D_M1"] ** 2.0
return info_dict | b67cc8b87d68dbd386d75fdb869f999072085607 | 3,615,851 |
def readArduinoData():
"""
DOCSTRING: this is the function for reading data from the arduino
return : function will return a 3xn matrix containg RGB data and averaged 1D array
"""
# here finds the port which arduino connected to
data = []
PORT = 0
while True:
try:
... | 5f2bfe1318f8a2548f9690bd58f5b13af28a38d6 | 3,615,852 |
def int_sin_m(x: float, m: int) -> float: # pragma: no cover
"""Computes the integral of sin^m(t) dt from 0 to x recursively"""
cosx = cos(x)
sinx = sin(x)
start = m % 2
res = x if start == 0 else 1 - cosx
for p in range(start + 1, m, 2):
res = p / (p + 1) * res - cosx * sinx**p / (p + ... | 2696b4a4412fad78efa1e06fe90858b68268bc10 | 3,615,853 |
import struct
def load(filename):
"""Load image file in .b16 format
as used by PCO CamWare
and return image data as numpy array.
"""
# read image file
imgfile = open(filename, 'rb') # read binary
buf = imgfile.read()
imgfile.close()
# read header
# 32 bit values (long)
h... | 7bc554e001970ffb68872b09bf3bad0aaf6a3ab9 | 3,615,855 |
def stanza_factory(xmlnode, stream = None):
"""Creates Iq, Message or Presence object for XML stanza `xmlnode`"""
if xmlnode.name=="iq":
return Iq(xmlnode, stream = stream)
if xmlnode.name=="message":
return Message(xmlnode, stream = stream)
if xmlnode.name=="presence":
return Pr... | f46d7f6f1cc69f4896846192857b18d6e3cc2b0f | 3,615,856 |
def _request_sts_credentials(billing_account_id, options):
"""
Request STS Credentials to get access to the billing account.
With the assumed role, this script will be able to traverse over the
member accounts in the AWS Organization.
Args:
billing_account_id (str): The Billing/Root AWS Acc... | 0d4ce0c87535e1db0769897b19de6877ece66a20 | 3,615,857 |
import typing
import time
def get_cache_response_headers(
response: Response, *, max_age: int
) -> typing.Dict[str, str]:
"""Return caching-related headers to add to a response."""
assert max_age >= 0, "Can't have a negative cache max-age"
headers = {}
if "Expires" not in response.headers:
... | 85aea5eeda87c34512ef596179ce9022a1f67225 | 3,615,859 |
def parse_response(response):
"""
:param response: output of boto3 rds client describe_db_instances
:return: an array, each element is an 3-element array with DBInstanceIdentifier, Engine, and Endpoint Address
Example:
[
['devdb-ldn-test1', 'mysql', 'devdb-ldn-test.cjjimtutptto.eu-we... | edaa4abbb695adb06c43dc93d70178bc10a82445 | 3,615,860 |
def is_linear(x, y):
"""
Returns True if molecule is linear
(largest eigenvalue almost equivalent to second largest)
"""
x = x - np.mean(x,axis=0)
y = y - np.mean(y,axis=0)
N = x.shape[0]
L, Q = sorted_eigh(build_F(x, y))
if L[0]/L[1] < 1.01 and L[0]/L[1] > 0.0:
return True
... | d997e70960813f88f443397540eef418c7d84879 | 3,615,861 |
def instantiate_me(spectrograph, par, **kwargs):
"""
Instantiate the FluxSpec subclass appropriate for the provided spectrograph.
The class must be subclassed from FluxSpec. See :class:`FluxSpec` for
the description of the valid keyword arguments.
Args:
spectrograph : Spectrograph or str
... | 5518a2cc36dd48cc3f6a6c2d33292ba3eb0ced9a | 3,615,862 |
from pathlib import Path
from typing import Tuple
def generate_theme(
corethemepath: Path,
theme_options: ThemeOptions,
outdirpath: Path,
additional: Tuple[Theme, Path] = ()
) -> Tuple[Theme, Path]:
"""Tema üretir ve dosyaya yazar
Arguments:
corethemepath {Path} -- Üretim yapılacak çe... | e40beeb02c478edb90b381fb12e54c667832f756 | 3,615,863 |
from typing import Optional
from typing import cast
def get_expression(
string: str, inputs: CWLObjectType, self: Optional[CWLOutputType]
) -> Optional[str]:
"""
Find and return a normalized CWL expression, if any.
CWL expressions in the $() form are converted to the ${} form.
"""
if not isin... | b7d71c0e6e362797dccd2b76d272f8dd4f350b7d | 3,615,864 |
def neighbours(row_number: int, column_number: int) -> set[tuple[int, int]]:
"""
Returns all the neighboring cells within the grid
"""
output: set[tuple[int, int]] = set()
for i in (-1, 0, 1):
for j in (-1, 0, 1):
if i == 0 and j == 0:
continue
new_row... | b169af2d37658fffcd14d35c2f43357a356fd705 | 3,615,865 |
def appprotect_setup(
request, kube_apis, ingress_controller_endpoint, test_namespace
) -> AppProtectSetup:
"""
Deploy simple application and all the AppProtect(dataguard-alarm) resources under test in one namespace.
:param request: pytest fixture
:param kube_apis: client apis
:param ingress_co... | b6e1dc49e38e8d24efc02631e848115a43f2b963 | 3,615,866 |
def _mrci_energy(output_str):
""" Reads the MRCISD+Q energy from the output file string.
Returns the energy in Hartrees.
:param output_str: string of the program's output file
:type output_str: str
:rtype: float
"""
ene = ar.energy.read(
output_str,
app.LINE... | 1aceadfb697ac35819626a695b56ea1071f011fd | 3,615,867 |
def format_csv(factor_name, entry):
"""Format a data entry as a csv line."""
return "%s, %s, %s" % (entry[factor_name], entry['quarter'], entry['count']) | 8d3f4f794f58f6aa0c6d259fcda124340df8d4da | 3,615,868 |
from typing import Optional
def create_security_group(security_group_name: str, vpc_id: str, other_group: Optional[SecurityGroup] = None):
"""Creates security group with proper ports open. Optionally allows all traffic from other_group"""
print("Creating security group " + security_group_name)
ec2 = u.get_ec2_r... | d5cc8362c42021578574f92e29d533fd76e7d5f2 | 3,615,869 |
def p_stat_val_indirect_indexed(p):
"""stat_val : '(' arithmetic ')' ',' REGISTER"""
if p[5][0] != 'Y':
raise ParseError(f"Only register Y can be used for indexed indirect addressing, found {p[5][0]} at "
f"{p.lineno(5)}, column {_get_column(p, index=5)}")
p[0] = Addressing(... | 6de1a3cc4ad91953669e4a1486520b2680c9487d | 3,615,870 |
def _remove_quotes(values):
"""Remove any quotes from quoted values."""
removed = []
for value in values:
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
removed.append(value)
return removed | a75bd25198a56a28748af059647e62c26df74232 | 3,615,871 |
def write_yaml(data, file_path):
"""Write plain data to a file as yaml
Parameters
----------
data
Data to write (should be lists, dicts and simple values)
file_path : str
The path of the configuration file to write
"""
with open(file_path, 'w+') as file_handle:
yaml ... | 915a11a707f60adb2696e7e8824663cbbb5f3b81 | 3,615,872 |
def bootstrapped_ecdf(variable, weights, seeds, ax,
bootstraps=200, normalisation=None, x_count=10000,
log_scale=(False, False), color="tab:blue", label=None,
**kwargs):
"""Create a bootstrapped weighted ECDF plot.
Parameters
----------
... | 40f638ef59558f61b207d66e262a27a7a267d705 | 3,615,874 |
def consolidate(voice, length):
"""
Join notes of the same pitch together, and increase their duration. No attempt is made to handle ties between bars,
They are just treated as separate notes.
:param voice:
:param length:
:return:
"""
out = list()
try:
for bars in range(0, ... | 6e6a60be0a6438b6f7c5fb23a1be720d5486e693 | 3,615,875 |
def get_filename(training_datasets, testing_datasets, beta, sr_model):
"""Get filename for saving results."""
if sr_model == 'convolutional_embedding':
model_str = '' # For past consistency.
else:
model_str = '_%s' % sr_model
file_name = ('end_to_end%s_stim_%s_resp_%s_beta_%d_taskid_%d'
... | 933b1179131a627bdf4bfbbc13b730fa90fba2c4 | 3,615,876 |
import json
def get_dimensions(cube_id):
"""
For this test data we will use a predefined dimension object matching cube-420 in the acceptance environment,
but this could be read from the TAP service.
"""
dims = json.loads(
'{"axes": [{"name": "RA", "numPixels": "4096", "pixelSize": "5.555... | aab639236510785649fd02ff80c795d7941007fd | 3,615,878 |
def validateRouterDetails(result):
"""
Runs device validations on each Router object that is returned by
getRouterDetails, if a device requires normalization return it for
processing by normalizeRouters
"""
print "Validating router details"
devicesToCorrect = []
for device, results in r... | ad23382a926d5eef06bdc8d04741a90053c97efe | 3,615,879 |
from pathlib import Path
import yaml
def load_yaml_config(file_path: str | Path) -> dict:
"""
Parameters
----------
file_path : str or Path
Yaml config file name. The file is assumed to be in
the repo's config directory.
Returns
-------
config : dict
Configuration... | 88a137807d6d1caabd3b8f7f7a03a3be3f04bdfe | 3,615,880 |
def advice(aa):
"""If a user asks for health advice or tips, then bot wil reply with an randomly generated advice"""
for ab in aa.split():
if ab.lower() in advice_questions:
return rndm.choice(advice_reply) | 2d5aabb4fbfb42a176ab6782a3f6688de47ba1ac | 3,615,881 |
def dmp_strip(f, u):
"""
Remove leading zeros from ``f`` in ``K[X]``.
Examples
========
>>> from sympy.polys.densebasic import dmp_strip
>>> dmp_strip([[], [0, 1, 2], [1]], 1)
[[0, 1, 2], [1]]
"""
if not u:
return dup_strip(f)
if dmp_zero_p(f, u):
return f
... | 2b77c5546121d59b06ef604c77df66e8725bfd15 | 3,615,883 |
import torch
def mvdr_beamformer(
noise_psd: ComplexTensor,
steering_vector: ComplexTensor,
eps=1e-15
) -> ComplexTensor:
"""
Standard MVDR beamformer
Args:
noise_psd: time-averaged noise psd of shape [B, F, C, C]
steering_vector: [B, F, C, 1]
eps: eps
... | fb17a43343f059ad2bbdabd62e8a4f9caafdf903 | 3,615,884 |
def split_in_words(text, num_letters):
"""
Split a long text (without space) into words of num_letters letters.
For instance if text is niijighkqj and num_letters is 4, will return
["niij", "iiji", "ijig", "jigh", "ighk", "ghkg", "hkgj"]
:param text: Text to split into words
:param num_letters: ... | 334be65a1592b13056dede738fb5cabb67e79236 | 3,615,885 |
def _get_delivery_voucher_discount_for_cart(voucher, cart):
"""Calculate discount value for a voucher of delivery type."""
if not cart.is_delivery_required():
msg = pgettext(
'Voucher not applicable',
'Your task does not require delivery.')
raise NotApplicable(msg)
de... | 9e08a3b47f0d7749081459f02d3c1038f28a02d4 | 3,615,886 |
import ast
def rname(node):
""" Obtains names from different types of AST nodes. """
if isinstance(node, str):
return node
if isinstance(node, ast.Num):
return str(node.n)
if isinstance(node, ast.Name): # form x
return node.id
if isinstance(node, ast.Constant):
re... | bc600545a2b072e258a06c54fb671ed388a8cf63 | 3,615,887 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.