content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def natr(
client,
symbol,
timeframe="6m",
highcol="high",
lowcol="low",
closecol="close",
period=14,
):
"""This will return a dataframe of normalized average true range for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
symbol (str... | 88bef923fdf638c2d064c29df48e47c2356db12e | 39,689 |
async def validation_handler(request, exc):
"""Handle Pydantic validation errors raised by FastAPI."""
error = exc.errors()[0]
return JSONResponse(
{"output": error["msg"], "level": "error", "keywords": error["loc"]},
status_code=422,
) | 431ded5caf61adeca61bbb9d4dfbefe3e8c98ac2 | 39,690 |
def tex_cii(tcii, tau_cii, tbg):
"""
"""
return tstar/np.log(1. + tstar*(1. - np.exp(-tau_cii))/(tcii + J(tbg))) | 71874e69a740e4b0e3b9ca76b7f560969cab49c4 | 39,692 |
def initDriver(browser):
"""
Funcion para crear una instancia de un navegador web
para realizar las pruebas automaticas usando Selenium
:param browser: navegador a usar firefox o chrome (firefox no sirve la captura de logs)
:type browser: String
:return: driver Selenium
"""
if browser =... | e24ebac9b76833ffa67acf22991e425e7dce846b | 39,695 |
def search(request):
"""Handling search request
"""
if 'q' in request.GET:
q = request.GET['q']
# results = SearchItem.objects.all()
results = search_request(q)
return render(request, 'search/result.html', {'results': results, 'query': q}) | 4caf6933aeeeca350cb5bc9e181293752b7c47ed | 39,696 |
from typing import Any
def valid_topic(value: Any) -> str:
"""Validate that this is a valid topic name/filter."""
value = cv.string(value)
try:
raw_value = value.encode("utf-8")
except UnicodeError as err:
raise vol.Invalid("MQTT topic name/filter must be valid UTF-8 string.") from err... | 2258474263b6754fe4866e97944051a7dbdb1720 | 39,698 |
import typing
from typing import Dict
from typing import Optional
import urllib
import re
def parse_agent_uri(uri: str) -> typing.Tuple[str, Dict[str, Optional[str]]]:
"""
Parse an agent uri and return the settings
:attr uri: The uri to parse
:return: (scheme, config)
"""
parts = urllib.parse... | 15e6615ac7f2b652b9d9a411c8221bbe2c3a0fe4 | 39,699 |
def light_vgg():
"""
this model is inspired by vgg net, but lighter
CV_Accuracy ~75% in 10 epoch, 12s per epoch
"""
model = Sequential([
# Block 1: in:100x100x3, out:50x50x16
layers.Conv2D(16, (3, 3), activation='relu', padding='same', name='b1_conv1'),
layers.Conv2D(16, (3,... | ee14d0dadc57320b8a787499106bf812a844f238 | 39,702 |
def plot_2d_contour(x, y, data,
ax = None, ax_labels = None,
**plot_opts):
"""
Generic command to plot a 2-dimensional field
"""
if ax is None:
ax = plt.axes()
if ax_labels is None:
ax_labels = {"title" : "", "xlabel" : "", "ylabel" : ""}
cs = ax.c... | 1998b92260c6748e7b46da8b5dd4a14ccdd14330 | 39,703 |
from typing import Union
from pathlib import Path
from typing import Tuple
from typing import List
from typing import Dict
from typing import Callable
from typing import Optional
import copy
def initialize(
config: Union[dict, str, Path]
) -> Tuple[
List[PatientAgent],
Dict[
Union[str, int],
... | ae38a271461b730e90ee68788bec616c03a4a3bb | 39,704 |
def get_job_details(name):
"""Return job details (properties + instances)."""
if is_job(name):
props = get_job_properties(name)
props.update({'instances': get_instance_properties(name)})
return props
else:
return None | 9705f4b66e1cf1b5eae96c64030bb5055eb7b315 | 39,705 |
def set_initxval(constr_func, constr_values):
""" Calculates the initial value of xval.
Args:
constr_func (:obj:`list`): constraint functions applied.
constr_values (:obj:`list`): Values of constraint functions applied.
Returns:
initial_xval (:obj:`float`): First value of xval
... | 434608817ed261538e605b8a8d4e4b53c0749906 | 39,706 |
def rms_rfft(spectrum, n=None):
"""
Use Parseval's theorem to find the RMS value of an even-length signal
from its rfft, without wasting time doing an inverse real FFT.
spectrum is produced as spectrum = numpy.fft.rfft(signal)
For a signal x with an even number of samples, these should produce the
... | 7dd4de5c534f82c45d1f987b84011822eb8302d5 | 39,707 |
import pickle
def unpickle(file):
"""
Each of the files from the CIFAR-10 dataset is a Python "pickled" object produced with cPickle
This routine opens such file and returns a dictionary
"""
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict | 8cc2f18089900f4584da9cf2e612cd208bd58e1a | 39,708 |
def task_docs():
"""Docs"""
return {'actions': [(build_sphinx, [SphinxOutputType.HTML,
docs_dir,
build_docs_dir])],
'task_dep': ['deps']} | 7256a31e3facebb449edfaeebc1abf13374e67c1 | 39,709 |
from typing import Iterable
def yearly(
records: Iterable[Transaction], *, year: int, months: int = 12
) -> Iterable[Transaction]:
"""Return an iterator for records dated within a given year.
Optionally only include records up to (and including) a given month.
For example, if months=5, only include r... | 823863eadd5ab3c1bbb815da8e9f501a4df15a8f | 39,711 |
from typing import List
def get_timeseries_deaths(api: ArcGisFeatureServer) -> List:
"""
Get a timeseries of deaths.
"""
# First build a lookup table for records with no collection date.
data = api.query(CASES_SERVICE,
where='DtDeath <> NULL',
outFields='D... | a6703bed2fe744142bfff28edfa3db94170cbecf | 39,712 |
def deep_dictionary_check(dict1: dict, dict2: dict) -> bool:
"""Used to check if all keys and values between two dicts are equal, and recurses if it encounters a nested dict."""
if dict1.keys() != dict2.keys():
return False
for key in dict1:
if isinstance(dict1[key], dict) and not deep_dicti... | b5011c2c79c79ecc74953e5f44db5c4a62464c07 | 39,713 |
def stat(filename):
"""Returns file statistics for a given path.
Args:
filename: string, path to a file
Returns:
FileStatistics struct that contains information about the path
Raises:
errors.OpError: If the operation fails.
"""
return stat_v2(filename) | eb1d1021d028ebc921932e66f96d7e4397e69599 | 39,715 |
def odd_ext(x, n, axis=-1):
"""Extends `x` along with `axis` by odd-extension.
This function was previously a part of "scipy.signal.signaltools" but is no
longer exposed.
Args:
x : input array
n : the number of points to be added to the both end
axis: the axis to be extended
"""
if n < 1:
... | edf0270dce4bb7ccf2033498498d48c714ad3224 | 39,716 |
def unshared_copy(inList):
"""perform a proper deepcopy of a multi-dimensional list (function from http://stackoverflow.com/a/1601774)"""
if isinstance(inList, list):
return list( map(unshared_copy, inList) )
return inList | 44cfd186e02a70a51cd29a3cdf01c698c1380d02 | 39,717 |
def SEARCH(find_text, within_text, start_num=1):
"""
Returns the position at which a string is first found within text, ignoring case.
Find is case-sensitive. The returned position is 1 if within_text starts with find_text.
Start_num specifies the character at which to start the search, defaulting to 1 (the fi... | 1afc843583695a801aca28b5013a6afa21221094 | 39,718 |
def GetDefaultAndCustomPreset(presets):
""" Get the default and custom preset values from the saved property group"""
defaultPreset = ''
customPreset = ''
if presets:
for p in presets:
if p.name == 'Default':
defaultPreset = p.value
if p.name == 'Custom':
... | ad5ee60ec995a1662f7c674a11ebf11bf16ab3be | 39,719 |
def getvaluelist(doclist, fieldname):
"""
Returns a list of values of a particualr fieldname from all Document object in a doclist
"""
l = []
for d in doclist:
l.append(d.fields[fieldname])
return l | b85d171b537636477b00021ce717788b5e4735da | 39,720 |
def admissiblenums(n=1e9):
"""generates a set of all admissible numbers not exceeding 1e9"""
admissibleset=set()
for i in range(len(pr)):
nth_admissible_prime=set(loop(n,i))
admissibleset|=nth_admissible_prime #union of admissibles up to nth prime
return admissibleset | d8b21659dc52db858b15c23e566aeee172412b75 | 39,721 |
from typing import Dict
def to_sources(settings: ApplicationConfiguration) -> Dict[str, str]:
"""Transform the current settings into representation of sources.
:param settings: The current settings
:returns: The settings sourced represented as a dictionary of path, source
"""
sources = {}
for... | ee8090bfb984c612fad1c9a83fce066105b00d9f | 39,722 |
def nhanesi(display=False):
""" A nicely packages version of NHANES I data with surivival times as labels.
"""
X = pd.read_csv(cache(github_data_url + "NHANESI_subset_X.csv"))
y = pd.read_csv(cache(github_data_url + "NHANESI_subset_y.csv"))["y"]
X_display = X.copy()
X_display["Sex"] = ["Male" if... | e25c905f2415639060bed2dfe10f3f6faf5ff980 | 39,723 |
def zenkey_oidc_service(required_params, optional_token_request_params, id_token_validator_params):
"""
Execute entire flow necessary to:
- discover provider configuration (based on mccmnc)
- exchange auth code for an access token
- use that access token to request user info
Returns user's zenk... | 343a5c97048d4d7f9f53f6066170e50eb79405ec | 39,724 |
def concat_vec(x1, f2):
"""Concatenates numpy vectors
"""
x2 = np.load(f2)
x = np.concatenate((x1, x2), axis=1)
return x | 58b2686ae81ad75e9f479d25d90568022ded999f | 39,725 |
import warnings
from re import T
def nullColumns_detection(
spark,
idf,
list_of_cols="missing",
drop_cols=[],
treatment=False,
treatment_method="row_removal",
treatment_configs={},
stats_missing={},
stats_unique={},
stats_mode={},
print_impact=False,
):
"""
This fun... | c802d953bf26d0b646cb5b0c364ece0cddd55582 | 39,726 |
async def async_test_host(hass: HomeAssistant, type: ArgoDeviceType, host: str):
"""Return true if host seems to be a supported device."""
try:
session = async_create_clientsession(hass)
client = ArgoApiClient(type, host, session)
result = await client.async_sync_data(ArgoData(type))
... | 5ed99f4380cd3798689c6f500f6f75053fa9cb97 | 39,727 |
def binned_to_2x2_image(coverage_start: str, table_id: int, img_binned):
"""
Convert binned detector data to image (1024, 1024)
"""
try:
bin_ckd = BinningTables()
bin_ckd.search(coverage_start)
except Exception as exc:
raise RuntimeError from exc
return bin_ckd.unbin(tab... | ff6e4926d15c3f0586a5d1fb0d28db7300200b64 | 39,728 |
def get_foreign_key_desciptors(obj):
"""
finds all :class:`~django.db.models.fields.ForeignRelatedObjectsDescriptor` in obj.
:param obj: A model instance or class.
"""
return _get_members_of_type(obj, ForeignRelatedObjectsDescriptor) | 8f2d626e66c46849b1e920a85ed698d70d596047 | 39,730 |
import requests
def create_client(
url: str = CONFLUENCE_URL, token: str = CONFLUENCE_TOKEN
) -> Confluence:
"""Create the Confluence client.
Parameters
----------
url : str
The confluence URL.
token : str
The token with read/write permissions.
"""
s = requests.Sessio... | aac4de81299d86e1aa5d33c56c8ac34b1421d0fc | 39,731 |
def get_unspents(address, blockchain_client=ReddcoinComClient()):
""" Get the spendable transaction outputs, also known as UTXOs or
unspent transaction outputs.
"""
if not isinstance(blockchain_client, ReddcoinComClient):
raise Exception('A ReddcoinComClient object is required')
url = R... | e9e7be78a511aeae7dacd89988438d4d08a49365 | 39,732 |
import numpy
def to_cpu_async(array, stream=None):
"""Copies the given GPU array asynchronously to host CPU.
Args:
array: Array to be sent to GPU.
stream (~pycuda.driver.Stream): CUDA stream.
Returns:
~numpy.ndarray: Array on CPU.
If given ``array`` is already on CPU, th... | 2149ddf3de42a7ea41e59810dea3151f5eb97d9b | 39,733 |
def make_time(t_str: str) -> Time:
""" Returns Time instance from given t_str.
REQUIRES: t_str is in format 'hh:mm:ss,mms'
"""
hr = int(t_str[:2])
mins = int(t_str[3:5])
sec = int(t_str[6:8])
ms = int(t_str[9:])
return Time(hr, mins, sec, ms) | 37d697dd0d12644518831834c35ed3a419399132 | 39,734 |
import json
import requests
def get_auth_token(filepath):
"""A function to retrieve a CAM authentication token
Uses a CAM Deployment Service Account JSON file to request a CAM authentication token.
Args:
filepath (str): the location of CAM Deployment Service Account JSON file
Returns... | b21bb2a9db449e7c57e070a07fc636246658355b | 39,735 |
def wide_limit_2l(q: np.ndarray) -> np.ndarray:
"""Compute the limit between resonant and wide-separation caustics.
Args:
q: list of lens mass ratios.
Returns:
limit as a function of q.
"""
cw = (1.0 + q**(1.0 / 3.0))**3 / (1.0 + q)
dw = np.power(cw, 0.5)
return dw | f399f08ab5d7f4cf76bf60b012e97b5caa3f8e42 | 39,736 |
def get_properties_data():
""" Returning a parser which will be used to read
application.properties file data """
parser = ConfigParser()
parser.read('./application.properties')
return parser | 5112c9a140a7871b8afee26ee44c49340f3d32b9 | 39,737 |
def getclasstree(classes, unique=False):
"""Arrange the given list of classes into a hierarchy of nested lists.
Where a nested list appears, it contains classes derived from the class
whose entry immediately precedes the list. Each entry is a 2-tuple
containing a class and a tuple of its base classes.... | b5ee13017b86cf54e455a07f82ee6c45a15efeb2 | 39,738 |
def float_input(msg):
"""
This methods should be used to request a float value from the user. This
method will not return until the user inputs a valid float value.
:param str msg: Message to be displayed to the user.
:return: Returns the float value inserted by the user.
:rtype: float
"""
... | 32632529e4a154c3127461d5cd740e16887c10f2 | 39,739 |
import numpy
def preprocess_depth(depth_data):
""" preprocess depth data
This function "reverses" the original recorded data, and
convert data into grayscale pixel value.
The higher the value of a pixel, the closer to the camera.
Parameters
----------
depth_data : numpy.ndarray
The data coming f... | 25aa5f13594752f262a27b9ea99ee72c38ab3db7 | 39,740 |
def create_movie():
"""Route handler for the endpoint for creating a new movie.
Returns:
response: A json object representing info about the created movie
"""
try:
movie = Movie(
title=request.json.get("title"),
release_date=request.json.get("release_date"),
... | 399e2863cdecb7af3c566e75d3b338bccd6161e2 | 39,741 |
from typing import Dict
def get_client_name_message_map() -> Dict[str, Client]:
"""Gets a dictionary mapping Client names to Client messages.
Returns:
A dictionary mapping Client names to Client messages.
"""
return get_message_maps()[1] | 239e852f6d824e1601889c0cf2deb6dc1561a8ab | 39,742 |
from typing import Hashable
from typing import Dict
def groupby_topk(
df: pd.DataFrame,
groupby_column_name: Hashable,
sort_column_name: Hashable,
k: int,
sort_values_kwargs: Dict = None,
) -> pd.DataFrame:
"""
Return top `k` rows from a groupby of a set of columns.
Returns a DataFram... | 274704a8ad8f3d5bf2050b4c0c23e04e3f0858d7 | 39,743 |
def changed_keys(a: dict, b: dict) -> list:
"""Compares two dictionaries and returns list of keys where values are different"""
# Note! This function disregards keys that don't appear in both dictionaries
return [k for k in (a.keys() & b.keys()) if a[k] != b[k]] | 77ae93614a2c736091886024338c1b4ecb1f6ec1 | 39,744 |
def get_interfaces_by_status(dut, status, cli_type=''):
"""
:param dut:
:type dut:
:param status:
:type status:
:return:
:rtype:
"""
cli_type = st.get_ui_type(dut, cli_type=cli_type)
output = get_status(dut, None, cli_type=cli_type)
retval = []
match = {"oper": status} if... | d0399816effe6ce70261863df0f75aeb884b4023 | 39,745 |
def _negation(value):
"""Parse an optional negation after a verb (in a Gherkin feature spec)."""
if value == "":
return False
elif value in [" not", "not"]:
return True
else:
raise ValueError("Cannot parse '{}' as an optional negation".format(value)) | c13f06b8a11ecbe948a4c2d710e165e1731f08fd | 39,746 |
import re
import requests
import json
def get_all_stealth_cards():
"""Returns a list of all the Stealth Cards"""
class StealthCard:
def __init__(self, card_info):
self.name = card_info["Name"]
self.img_url = card_info["ImageUrl"]
self.cost = card_info["Cost"]
... | 93abd19276a600f9b344ca5d72a87d7a7f0a9e1a | 39,747 |
def add_adsorbate_fractional(surf, adsorbate, x, y, z, mol_index):
"""Add an adsorbate to surf at the fractional coordinates x and y."""
cell_parameters = surf.get_cell()
ax, ay, az = cell_parameters[0]
bx, by, bz = cell_parameters[1]
ase.lattice.surface.add_adsorbate(
surf, adsorbate, z,
... | 51e19078a85e4cfd27cddb28c1933c4c309cbc45 | 39,748 |
def create_edgelist_from(pairs):
"""
Function to create edgelists for "speaking-in-turn" pairs
Returns results in a way that will be useful in Gephi
"""
# Create edgelist using defaultDict
edges = defaultdict(int)
for people in pairs:
for personA in people:
for personB i... | 3299ce443413d2a0c702574178ada8240ff5ca29 | 39,749 |
def hourly_spatial_agg(date, hour_range=(0,23), cols=["temperature", "pressure", "humidity", "magnetic_tot"]):
"""
For a certain date, get hourly aggregations and count for the desired columns. For available hours.
Parameters
----------
hour_range: int or tuple of int, default (0,23)
Range ... | 15614c08c1f5e80ec65a917b0293de24ad0e352d | 39,751 |
from typing import Any
from pathlib import Path
def config_to_ext(conf: Any) -> str:
"""Find the extension(flag) of the configuration"""
if isinstance(conf, dict):
return "dict"
conf = Path(conf)
out = conf.suffix.lstrip(".").lower()
if not out and conf.name.lower().endswith("rc"):
... | 53a4c452c050266736d1fddc1bd18634702e2f5a | 39,752 |
import numpy
def unique_raster_values(dataset):
"""Get list of unique integer values within given dataset.
Args:
dataset: a gdal dataset of some integer type
Returns:
unique_list (list): a list of dataset's unique non-nodata values
"""
band = dataset.GetRasterBand(1)
nodata =... | c7f0f717abc5880f7c3de607d264b7ad919b79ac | 39,753 |
def random_rat(
nvars: int = 10,
ndegree: int = 20,
nterms: int = 50,
ncoeffbits: int = 32,
seed: int = 42,
) -> RationalFunction:
"""Return a random rational function."""
while True:
r1 = random_poly(nvars, ndegree, nterms, ncoeffbits, seed)
r2 = random_poly(nvars, ndegree, ... | 0df15ff791cfa4e7d908c53bc7617b5f1534528d | 39,754 |
def _user_can_merge(gh, org, repo, username, addons_dir, target_branch):
"""
Check if a user is allowed to merge.
addons_dir must be a git clone of the branch to merge to target_branch.
"""
gh_repo = gh.repository(org, repo)
if github.github_user_can_push(gh_repo, username):
return True... | f1836ead9c304b1fe8cac3c16e4bab9bbab12b1f | 39,755 |
import calendar
from datetime import datetime
def start_end_date_for_period(period, default_start_date=False, default_end_date=False):
"""Return the start and end date for a goal period based on today
:param str default_start_date: string date in DEFAULT_SERVER_DATE_FORMAT format
:param str default_end_d... | ee9639852c5378fe7c47032de413f8d3a4052916 | 39,757 |
def get_status_messages(connection, uid, timeline='home:', page=1, count=30):
"""默认从主页从时间线获取给定页数的最新状态消息,另外还可以获取个人时间线"""
# 获取时间线上最新的状态消息ID
statuses = connection.zrevrange('%s%s' % (timeline, uid),
(page - 1) * count, page * count - 1)
pipe = connection.pipeline(True)
... | 21af458155d7de793b420047178507d1f77296d2 | 39,758 |
def new(key,mode=MODE_ECB,IV=None,counter=None,segment_size=None):
"""Create a new cipher object
CAST using pycrypto for algo and pycryptoplus for ciphermode
key = raw string containing the keys
mode = python_AES.MODE_ECB/CBC/CFB/OFB/CTR/CMAC, default is ECB
IV = IV as a raw string, de... | 1985045a3ebf52d923d18a34ef1dffe2051bc314 | 39,759 |
import warnings
def ensure_all_columns_are_used(num_vars_accounted_for,
dataframe,
data_title='long_data'):
"""
Ensure that all of the columns from dataframe are in the list of used_cols.
Will raise a helpful UserWarning if otherwise.
Pa... | 0470503c8adac107f85dd628409fc3ca8de641d3 | 39,761 |
import typing
import collections
def with_role_slash_option(
name: str, description: str, /, *, default: typing.Any = _UNDEFINED_DEFAULT, pass_as_kwarg: bool = True
) -> collections.Callable[[_SlashCommandT], _SlashCommandT]:
"""Add a role option to a slash command.
For information on this function's par... | aaa3a2736ee5aadc275251d359be72ed90ca34fe | 39,762 |
from typing import Union
from typing import Optional
def gaussian_timeseries(
mean: Union[float, np.ndarray] = 0.0,
std: Union[float, np.ndarray] = 1.0,
start: Optional[Union[pd.Timestamp, int]] = pd.Timestamp("2000-01-01"),
end: Optional[Union[pd.Timestamp, int]] = None,
length: Optional[int] = N... | 3b58d4efe0e9ca49ec86b0328bd464fb8842e628 | 39,763 |
from typing import Iterator
import ray
import logging
import psutil
import types
import itertools
import math
def ppipe(
records: Iterator[dict],
*funcs,
records_in_memory: int or None = None,
processes: int or None = None,
) -> Iterator[dict]:
"""
A multi-threaded parallel pip... | 07f5add4b155b796d9f00f20383205ad9ee056c9 | 39,765 |
from fsm.fsmspec import FSMSpecification
def get_specs():
"""
Get FSM specifications stored in this file.
"""
spec = FSMSpecification(
name='lessonseq',
hideTabs=True,
title='Take the courselet core lessons',
pluginNodes=[START, LESSON, ASK, ASSESS, ERRORS, END],
)
... | d041d03b3a016fa419571de17f40122f15ed1764 | 39,767 |
def at_least_major_version(major):
"""is the major version (e.g. X, for version X.Y.Z) greater than or equal to the major version integer supplied?"""
return MAJOR >= int(major) | 7b5c8fda717786c060fe9fc99fc0c1219a114087 | 39,768 |
def arrayizeDict(g):
"""Transforms a dict with unique sequential integer indices into an array"""
mk = max(g.keys())
ga = [None] * mk
for k, v in g.items():
ga[k - 1] = v
return ga | d2da3848436be8d47b3f338797eefd87cfa4344c | 39,769 |
def resnetv2_50x1_vit(pretrained=False, strict=False, progress=False, **kwargs):
""" ResNetv2-50 from ViT-B/16 hybrid model from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
"""
# create a ResNetV2 w/o pr... | 37a8a2ebd0ec59e123042b1e0ee3267cff4484b3 | 39,771 |
def pickwords(filename):
"""This function chooses a random word from a chosen wordlist.
:param filename: the wordlist that the function should search.
:return: returns the randomly chosen word.
"""
word = choice(open(filename, 'r').readlines()).rstrip('\r\n')
return word | 1583263b73b6e772c302a761129ce73d17216862 | 39,772 |
import math
def savitsky_wetted(hull):
"""
This is a function based on Daniel Savitsky 1964 / 1976 paper to calculate wetted area
:param hull: Hull Object
:return: wetted area information
"""
v = hull.state.v
beta_d = hull.beta_d
beta = deg_to_rad(beta_d)
trim_d = hull.state.t... | 1c9f07de2d55f8ec7022673e707f60c16495473c | 39,774 |
from typing import List
def get_stage_names(json_data: dict) -> List[str]:
""" Returns the names of the stages within the Frew model.
Parameters
----------
json_data : dict
A Python dictionary of the data held within the json model file.
Returns
-------
stage_names : List[str]
... | 8adf6c8684d11b25c45f2e329285809187175e76 | 39,775 |
import json
def administrator_reporter_spin(request):
"""
纺织类
:param request:
:return:
"""
title_msg = '查询所有纺织大类学员'
param_result = search_parameter(request, 'spin')
if 'school_term' in param_result:
if param_result['school_term'] is None:
message = '尚未添加->报考... | 593d483f597b7bb59e5c2a4c59a0688acb86c886 | 39,776 |
def evaluate(hps, logdir, traindir, subset="valid", return_val=False):
"""Evaluation."""
hps.batch_size = 100
with tf.Graph().as_default():
with tf.device("/cpu:0"):
with tf.variable_scope("model") as var_scope:
eval_model = RealNVP(hps)
summary_writer = t... | a7d46e58ab4c4e7b384a41a0bc21bb5ef90f2c1b | 39,777 |
from typing import List
def V_param_mat_prod(
param: Parameter, mat: Tensor, savefield: str, subsampling: List[int] = None
):
"""Multiply with the GGN(MC) matrix square root ``V`` defined by ``param``.
Args:
param: Parameter defining ``Vᵀ``.
mat: Matrix to be multiplied with ``V``.
... | a7c9a07bf7a88fdd3c1bd8728d37c9e8b1da025e | 39,778 |
import logging
import json
def templates(cluster, stdout_writer, config):
"""
input (ignored):
[]
output:
{'templates': [{'attributes': {'cyclecloudhost': ['Boolean', 1],
'mem': ['Numeric', '2048'],
'ncores': ['Numeric', '4'],
... | c462042488fe923574e529f824e716504b83a8fe | 39,779 |
def preprocess_adj(H, variable_weight=False):
"""
calculate G from hypgraph incidence matrix H
:param H: hypergraph incidence matrix H
:param variable_weight: whether the weight of hyperedge is variable
:return: G
"""
H = np.array(H)
n_edge = H.shape[1]
# the weight of the hyper... | 1097d9200f145f3a26e885a251254655f326e008 | 39,780 |
from typing import Counter
def findWordFreq (word_list, names, threshold = 20, directory=None):
"""
Count the word frequency in each element of the list.
Filter out the common words that do not provide any valuable information.
Keep keywords.
:param word_list: A list where each element is str... | aafe7e7a36c6e6c3fa7d3eb87fd0b796e199f052 | 39,782 |
import time
def Bokeh_Fig_WebCOMPLEX(IRGASON_name):
""" Entradas:
import numpy as npIRGAS
ON_name --> str, Nombre de la carpeta de las estaciones IRGASON:
[
IRGASON_Candelaria,
IRGASON_Federico_Carrasquilla,
IRGASON_SENA,
IRGASON_CASD_10M,
IRGASON_ITM,
... | dd5d60cbdbeb59b2ab755f160e11ef383f066eaf | 39,784 |
def patient_add(request):
"""
Add new patient
"""
if request.method == "POST":
form = AddPatientForm(request.POST)
if form.is_valid():
patient = form.save()
request.session['patient_id'] = patient.id
# return redirect('patient_info', patient_id=patient... | 305078d2ab32ca376918f78c70cff00e9f750345 | 39,785 |
def merge_window():
"""window for merging experiments. will deal with either root growth or germination data,
but not both at the same time."""
# the table of experiments
explist = [
[sg.Table(headings=['Experiments', ], display_row_numbers=False,
auto_size_columns=False, va... | 79db03c5805223dd3d64b12eab75d2fae5c13739 | 39,786 |
def grid_sample(input, grid, mode='bilinear'):
"""Given an :attr:`input` and a flow-field :attr:`grid`, computes the
`output` using input pixel locations from the grid.
Uses bilinear interpolation to sample the input pixels.
Currently, only spatial (4 dimensional) inputs are supported.
For each ou... | 2bdbe73eb279614f87035d179f1c6d0b0edaa20d | 39,787 |
from datetime import datetime
def add_memory(mem_kind, mem_value):
"""Add a memory"""
mem = Memory()
mem.kind = mem_kind
mem.value = mem_value
mem.update = datetime.today()
mem.user = 0
session.add(mem)
session_commit()
return mem.key | 67fc2463abad542b79f3e46e3584fe74d2853b9b | 39,788 |
from typing import Dict
from typing import List
from typing import Any
def make_global_data_policy(
policy_name: str, policy_config: Dict, tagger: Tagger
) -> GlobalDataPolicy:
"""
Returns a GlobalDataPolicy object containing lists of actions and circumstances.
Actions define what the policy restricts... | 257f0671ef5b7b64b135c4c0b12e154698690436 | 39,789 |
def get_values(units, *args):
"""
Return the values of Quantity objects after optionally converting to units.
Parameters
----------
units : str or `~astropy.units.Unit` or None
Units to convert to. The input values are converted to ``units``
before the values are returned.
args ... | 462e336fa2f4bcdfd77ba43658c37cf4c6782c75 | 39,791 |
def generate_input(data,t):
"""
Compute the index word vector for the given Data.
Arguments: data (list of sentences)
t (The Keras instance that Tokenize the words)
"""
encoded_docs = t.texts_to_sequences(data)
max_length = max_length_pad(encoded_docs)
return (encoded_docs... | 0ce0ac0f559173993b26cfc4e024eb2c6d289935 | 39,792 |
def read(filename):
"""Read the input file for rules and return the list of rules and the number of line errors."""
l = list()
with open (filename, 'r') as f:
ruleErrorCount = 0
for line in f:
#rule = parseRule(line)
try:
rule = Rule(line)
... | a471673f58f9e59b79e82a0d4d7e4a5d15c9e860 | 39,793 |
def cli(ctx, library_id, filesystem_paths, folder_id="", file_type="auto", dbkey="?", link_data_only="", roles=""):
"""Upload a set of files already present on the filesystem of the Galaxy server to a library.
Output:
"""
return ctx.gi.libraries.upload_from_galaxy_filesystem(library_id, filesystem_pa... | c0b269344da39a2ae9f43280ec1d7bf69a6a345c | 39,794 |
def iou_score_single(
y_true: np.ndarray,
y_pred: np.ndarray,
k: int | None = None,
excluded_labels: list[int] | None = None,
) -> float:
"""Compute intersection over union of a class `k`.
Parameters
----------
y_true
A np.ndarray of shape `(h, w)` representing the ground truth
... | f324053d867df76d53ca4d2f30bede1a4f07fbbd | 39,795 |
def get_uptime():
"""
Get uptime
"""
try:
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
uptime_time = str(timedelta(seconds=uptime_seconds))
data = uptime_time.split('.', 1)[0]
except Exception as err:
data =... | fc783a24b7239c43b69c44ea30b62465a775761d | 39,798 |
import numpy
def h2e(az, za, lat):
"""
Horizon to equatorial.
Convert az/za (radian) to HA/DEC (degrees, degrees)
given an observatory latitude (degrees)
"""
sa = numpy.sin(az)
ca = numpy.cos(az)
se = numpy.sin(numpy.pi / 2.0 - za)
ce = numpy.cos(numpy.pi / 2.0 - za)
sp = numpy... | 89f82c0035eaf9b73d3c2adf07b2ed1145c822f9 | 39,799 |
from typing import Dict
from typing import List
def negative_binomial_graph(state: str, data: Dict[str, Dict[int, List[float]]]) -> str:
"""A function to display a negative binomial regression model graphically"""
pd.options.mode.chained_assignment = None
# First, creating a pandas dataframe for our dat... | b56a62f254304bae8adc1fa3b9c8ee41b567ec58 | 39,801 |
def get_user_name():
"""Return eser name from console.
Returns:
user_name (string): name of user from console
"""
return prompt.string('May I have your name? ') | 24693959973e03827c5a705b14afcbb181dbe81e | 39,802 |
def RMSEerror(bpmES, bpmGT, timesES=None, timesGT=None):
""" RMSE: """
diff = bpm_diff(bpmES, bpmGT, timesES, timesGT)
n,m = diff.shape # n = num channels, m = bpm length
df = np.zeros(n)
for j in range(m):
for c in range(n):
df[c] += np.power(diff[c,j],2)
# -- final RMSE
... | 246108c13efedc6508cc5722a668879e6708482b | 39,803 |
def decompress_word(word):
"""
Returns the delta values stored on a word.
Outliers are retrieved as -((1<<mode)-1)
"""
GRABS_PER_MODE = (0,28,14,10,7,6,5,4)
FULLMASK = (0,0b1,0b11,0b111,0b1111,0b11111,0b111111,0b1111111)
if (word>>30)==0b00:
mode = 3
elif (word>>30)==0b01:
... | 5fb92bacccd31aaadd7f60947607bb7e59b261c7 | 39,804 |
def _add_metadata_as_attrs_da(data, units, description, dtype_out_vert):
"""Add metadata attributes to DataArray"""
if dtype_out_vert == 'vert_int':
if units != '':
units = '(vertical integral of {0}): {0} kg m^-2)'.format(units)
else:
units = '(vertical integral of quant... | 3bdead2b0b341a065ef1e147660605c9c591c0df | 39,805 |
def concat(inputs, axis=0, **kwargs):
"""Concatenate the inputs along the given axis.
All dimensions except the :attr:`axis` should be same:
```python
x1 = dragon.ones(shape=(2, 3))
x2 = dragon.zeros(shape=(2, 4))
y = dragon.concat([x1, x2], axis=1) # Ok
z = dragon.concat([x1, x2], axis=0... | 454a097fdd767f7d55b5458b8e102ddd99b58612 | 39,807 |
def plot_umatrix(
u_matrix: np.ndarray,
n_rows: int,
n_colums: int,
cmap: str = "Greys",
fontsize: int = 18,
) -> plt.Axes:
"""Plot u-matrix.
Parameters
----------
u_matrix : np.ndarray
U-matrix containing the distances between all nodes of the
unsupervised SOM. Shap... | fce91af934f57807215dcb2dc54161ca5c2af0ee | 39,808 |
def _search_in_render_layer_all():
""" 全てのViewLayerのレンダリングプロパティを取得
Returns:
[type]: [description]
"""
render_layer_settings = {}
render_layer_settings["scene_use_freestyle"] = bpy.context.scene.render.use_freestyle
render_layer_settings["linestyle_names"] = _get_linestyle_names()
... | c3bc2104769e2a4357ab1155258bf9b4565e796e | 39,811 |
def load_uvarint_b(buffer):
"""
Variable int deserialization, synchronous from buffer.
:param buffer:
:return:
"""
result = 0
idx = 0
byte = 0x80
while byte & 0x80:
byte = buffer[idx]
result += (byte & 0x7F) << (7 * idx)
idx += 1
return result | f45534114fa310c027e9ff7627a41bfd51950b48 | 39,812 |
def read_frame_file(file_name, start_time, end_time, channel=None, buffer_time=1, **kwargs):
""" A function which accesses the open strain data
This uses `gwpy` to download the open data and then saves a cached copy for
later use
Parameters
----------
file_name: str
The name of the fra... | f0bd4aefe86cacaedb32ef04161f5dd037f896af | 39,813 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.