content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def solve_part_one(id_list: list) -> int:
"""
Calculates the checksum for a list of IDs
:param id_list: Python list containing a list of ID strings
:return: Checksum as defined by the problem
"""
from collections import Counter
twos, threes = 0, 0
for id in id_list:
id_counter =... | 71,800 |
def search(lookup):
"""
Search for a reference on arXiv.org given a lookup string. Since the arXiv.org api can return mutiple references
for a single query, this function raises an error in the case that more than one reference was returned.
:param lookup: String with the lookup to search for on ar... | 71,801 |
def write_deltafiles(statedir, chrootdir, version, manifest, previous_manifest):
"""Output deltafiles content to the state directory."""
out_path = os.path.join(statedir, "www", "update", version, "delta")
if not os.path.isdir(out_path):
os.makedirs(out_path, exist_ok=True)
for val in manifest['... | 71,802 |
def id_in_use(id_key, id_key_value, dict):
"""
Return true if an ID is already in use.
"""
for value in dict.values():
if value[id_key] == id_key_value:
return True
return False | 71,803 |
def is_prerelease(version_str):
"""
Checks if the given version_str represents a prerelease version.
"""
return any([c.isalpha() for c in version_str]) | 71,804 |
def _wrap_with_after(responder, action, action_args, action_kwargs, is_async):
"""Execute the given action function after a responder method.
Args:
responder: The responder method to wrap.
action: A function with a signature similar to a resource responder
method, taking the form ``... | 71,805 |
def text_analysis(request: dict = Body(..., examples=analysis_examples),
#index: str = Path(default='country')
):
"""
The *analyze* endpoint allows you test out how your data will be analyzed and indexed.
The default behaviour is for your search terms to be analyz... | 71,806 |
def class_name_to_resource_name(class_name: str) -> str:
"""Converts a camel case class name to a resource name with spaces.
>>> class_name_to_resource_name('FooBarObject')
'Foo Bar Object'
:param class_name: The name to convert.
:returns: The resource name.
"""
s = re.sub('(.)([A-Z][a-z]+... | 71,807 |
def datetime_to_date(dt, org):
"""
Convert a datetime to a date using the given org's timezone
"""
return dt.astimezone(org.timezone).date() | 71,808 |
def raw_updates():
"""Test 5: Database Updates"""
connection = dbraw_engine.connect()
try:
num_queries = request.args.get('queries', 1, type=int)
if num_queries < 1:
num_queries = 1
if num_queries > 500:
num_queries = 500
worlds = []
rp = part... | 71,809 |
def correlate(x1, x2, mode='valid'):
"""
Cross-correlation of two 1-dimensional sequences.
For full documentation refer to :obj:`numpy.correlate`.
Limitations
-----------
Input arrays are supported as :obj:`dpnp.ndarray`.
Size and shape of input arrays are supported to be equal.
Pramet... | 71,810 |
def virtual_machine_names_to_container_names(configuration):
"""
convert virtual machine names to container names using configuration
Args:
configuration: user final configuration
Returns:
list of container name in array
"""
return [
"{0}_{1}".format(
configu... | 71,811 |
def write_comments(outstream, comments, comm_char, is_global=False):
"""Write out the comments attached to a given font item."""
if comments:
if not is_global:
outstream.write('\n')
for line in comments:
outstream.write('{} {}\n'.format(comm_char, line))
if is_glo... | 71,812 |
def index():
"""For testing the application on the browser during development"""
return jsonify({'message': 'This is the home page'}) | 71,813 |
def current_server_id() -> str:
"""Helper to get the current server id"""
rsp = requests.get("http://localhost:10000/api/servers")
if rsp.status_code != 200:
raise ValueError("Failed to fetch current server id")
return rsp.json()['current_server'] | 71,814 |
async def test_event_simple(
bus: lightbus.path.BusPath, dummy_api, stream_use, redis_client, worker: Worker
):
"""Full event integration test"""
bus.client.set_features([Feature.EVENTS])
bus.client.register_api(dummy_api)
event_transport_pool = bus.client.transport_registry.get_event_transport("de... | 71,815 |
def get_pandas_read_csv_and_dropna_code():
"""
Get a simple code snipped that loads the adult_easy data and runs dropna
"""
code = cleandoc("""
import os
import pandas as pd
from mlinspect.utils import get_project_root
train_file = os.path.join(str(get_pr... | 71,816 |
def _update_classifier_training_jobs_status(job_ids, status):
"""Checks for the existence of the model and then updates it.
Args:
job_ids: list(str). List of ID of the ClassifierTrainingJob domain
objects.
status: str. The status to which the job needs to be updated.
Raises:
... | 71,817 |
def test_general_acquisition_info_smoke(testmeta):
"""Smoke test for parsing.general_acquisition_info.
It should return a str description when provided valid inputs.
"""
desc = parsing.general_acquisition_info(testmeta)
assert isinstance(desc, str) | 71,818 |
def mean_std_cross_val_scores(model, X_train, y_train, **kwargs):
"""
Returns mean and std of cross validation
Parameters
----------
model :
scikit-learn model
X_train : numpy array or pandas DataFrame
X in the training data
y_train :
y in the training data
Retu... | 71,819 |
def main(argv):
"""Go Main Go"""
os.chdir("../tmp")
# Which webcam, establish existing lat/lon and pan0
cid = argv[1]
camera = vbcam.get_vbcam(cid)
camera.zoom(40.0)
camera.tilt(0.0)
out = Image.new("RGB", (720, 480))
i = 0
for ang in range(-160, 180, 40):
print("Workin... | 71,820 |
def needs_dataset(*names, default=None):
"""
Decorator for skipping methods when the needed atomic data is not available
"""
non_ion_datasets = ['abundance', 'ip', 'ioneq']
names = [f'_{n}' if n not in non_ion_datasets else f'{n}' for n in names]
def decorator(func):
@wraps(func)
... | 71,821 |
def linkcode_resolve(domain, info):
"""Oddly this function is required for the linkcode extension."""
if domain != "py":
return None
if not info["module"]:
return None
filename = info["module"].replace(".", "/")
return "https://github.com/farisachugthai/dynamic_ipython/%s.py" % file... | 71,822 |
def get_name(main_title, folder, sep="_"):
""" Obtains the next valid name basd on given filename and count
Args:
main_title (str): Main portion to define naming scheme.
folder (str): Folder to be stored in. No '/' or '\' required.
sep (str): A separator between maint_title and count.
... | 71,823 |
def _read_airports_file(input_file=None):
"""Read the airports file."""
if input_file is None:
input_file = get_test_data('airport-codes.csv', as_file_obj=False)
df = pd.read_csv(input_file)
station_map = pd.DataFrame({'id': df.ident.values, 'synop_id': 99999,
'la... | 71,824 |
def subsetter(unittest_adapter, output_dir):
"""
This function test the subset process. It use the functions in
the global object adapter to do the subset process. At the end
of this function, use assert to check if the subsetted file exist.
"""
adapter = unittest_adapter.adapter
message = ... | 71,825 |
def archive_training_modules(tar_ball_path: Path):
"""
Create a tar ball for SageMaker training job. The tar ball will include
- modules training.*
- emo_classifier/resources/emotions.txt and __init__.py
- modules emo_classifier.*
- modules emo_classifier.classifiers.*
:param tar_ball_path... | 71,826 |
def argparse_add_verbose(parser: argparse.ArgumentParser) -> None:
"""Add an option for setting the verbosity level."""
parser.add_argument(
"-v",
"--verbose",
action="store_const",
const=logging.DEBUG,
default=logging.INFO,
help="show debugging information",
... | 71,827 |
def out_edge_node_mapper(
nodes: List[GraphVizNode]
) -> Dict[str, List[GraphVizNode]]:
"""
A function that maps a published topic to the publisher node
@params:
nodes: The list of nodes of the graph
@return: A dictionary where the key is the published topic path
and the value... | 71,828 |
def CircularHarmonicCaDihedralConstraints(a,b,c,d,value,tol):
"""
Returns properly formated string for declaring harmonic
dihedral angle constraints between CA carbons of resiedues
a, b, c and d at angle "value", and "tol" standard deviation.
Angles of 0 and 360 are treated as being next to each oth... | 71,829 |
def decode_unicode_hook(json_pairs):
"""
Given json pairs, properly encode strings into utf-8 for general usage
:param json_pairs: dictionary of json key-value pairs
:return: new dictionary of json key-value pairs in utf-8
"""
if version_info >= (3, 0): # is 3.X
return dict(json_pairs)
... | 71,830 |
def small_movies():
"""
Runs once per session. Provides the content of small_movies.json.
"""
with open("./datasets/small_movies.json", "r", encoding="utf-8") as movie_file:
yield json.loads(movie_file.read()) | 71,831 |
def write_ports(dot, node):
"""Output table rows for the gozintas and gozoutas.
This vectors off into subfunctions for the different cases:
- n in, 0 out
- 0 in, n out
- only a single column of inputs or outputs
- n in, 1 out
- 1 in, n out
- two columns, ... | 71,832 |
def test_get_nodes(default_nodes, client): # pylint: disable=unused-argument
"""Test listing existing nodes."""
response = client.get("/nodes")
assert response.status_code == 200
assert len(response.json()) == 4 | 71,833 |
def create_sample(G, sample_size, z_size, seed):
"""
Create a sample.
returns
-------
A set saple z.
"""
torch.manual_seed(seed)
fixed_z = np.random.uniform(-1, 1, size=(sample_size, z_size))
fixed_z = torch.from_numpy(fixed_z).float()
if gpu_available:
fixed_z = fix... | 71,834 |
def get_data_day(data: pd.DataFrame) -> np.array(int):
"""Get weekday/weekend designation value from data.
:param pd.DataFrame data: the data to get day of week from.
:return: (*np.array*) -- indicates weekend or weekday for every day.
"""
return data["If Weekend"] | 71,835 |
def next_mesh_data_loader_uuid():
"""Return the next uuid of a mesh data loader."""
global mesh_data_loader_counter
mesh_data_loader_counter = (mesh_data_loader_counter + 1) % (1 << 60)
return mesh_data_loader_counter | 71,836 |
def generate_emb_features(data, ft_model, window_size=5):
"""method for generating embeddings features
Args:
data: dict representation of conll file
ft_model: fasttext embeddings
window_size: how many neighbors to use
Returns:
dict: key: mention_id value: embedding_features... | 71,837 |
def log(input_t):
"""
Element-wise natural logarithm.
"""
return log_op(input_t) | 71,838 |
def fetch_incidents(client: Client, last_run: Dict[str, Any], args: Dict[str, Any],
call_from_test=False) -> Tuple[dict, list]:
"""
This function is called for fetching incidents.
This function gets all policies, then after using ThreadPoolExecutor, for each policy in all policie... | 71,839 |
def _exponential_timeout_generator(initial, maximum, multiplier, deadline):
"""A generator that yields exponential timeout values.
Args:
initial (float): The initial timeout.
maximum (float): The maximum timeout.
multiplier (float): The multiplier applied to the timeout.
deadlin... | 71,840 |
def guess_gender(name):
"""
Given a person's name guess their gender.
Returns either ``'m'`` or ``'f'``.
"""
names = name.split()
if names[0] == 'Sankt':
first_name = names[1]
else:
first_name = names[0]
try:
return _GENDER_EXCEPTIONS[first_name]
except KeyEr... | 71,841 |
def test_gcview_enable():
""" test_gcview_enable: --gcview-enable switch creates the default trace output file """
# remove any existing trace files
time, proc, stdout_str = run_command(v8,['--gcview-enable','./fib.js'])
# assertions exit code 0 and output file exists
assert proc.returncode == 0
... | 71,842 |
def index():
"""Return the main page."""
restaurants = ["amelie_nyc", "lovemama_nyc", "upstate_nyc"]
return render_template("index.html", restaurants=restaurants) | 71,843 |
def stefan_boltzmann(radius, temperature):
"""Calculate the luminosity for a spherical blackbody following from
Stefan-Boltzmann.
Parameters
----------
radius: float
The radius of the sphere.
temperature: float
The temperature of the blackbody.
Returns
-------
lum: ... | 71,844 |
def put_keys_in_numerical_order(keys):
"""
Takes a list of hookup keys in the format of prefix+number:revision and puts them in number order.
Returns the ordered list of keys
"""
keylib = {}
n = None
for k in keys:
colon = k.find(':')
for i in range(len(k)):
try:
... | 71,845 |
def test_random_single_image():
""" Just make sure the image_plot function doesn't crash.
"""
shap.image_plot(np.random.randn(3, 20, 20), np.random.randn(3, 20, 20), show=False) | 71,846 |
def parse_input() -> list[int]:
"""
Parses the input and returns a list of depth measurements.
"""
with open(INPUT_FILE, "r") as f:
return [int(line) for line in f] | 71,847 |
def apply_smoothing(image, kernel_size=5):
"""
kernel_size must be postivie and odd
"""
return cv2.GaussianBlur(image, (kernel_size, kernel_size), 0) | 71,848 |
def convert_trie_to_flat_paths(trie, prefix=None):
"""Converts the directory structure in the given trie to flat paths, prepending a prefix to each."""
result = {}
for name, data in trie.iteritems():
if prefix:
name = prefix + "/" + name
if len(data) and not "results" in data:
... | 71,849 |
def build_cptp_data(db_path, db_name):
"""Builds training sets files for the SPMF library.
Training sets files created using the DB. A training set file in the format expected by the
java SPMF library: ' -1 ' between each number within a sequence and ' -2' to end a sequence
(see `SPMF/CPT+ docs <http:/... | 71,850 |
def reflection_matrix(
point: np.ndarray,
normal: np.ndarray
) -> np.ndarray:
"""
Return matrix to mirror at plane defined by point and normal vector.
Reference: https://en.wikipedia.org/wiki/Transformation_matrix#Reflection_2
"""
normal = unit_vector(normal[:3])
M = np.identity(4)
... | 71,851 |
def draw_hexagon(image=None, coordinates=None,
radius=None, thickness=None,
color_hex=None,
radius_dot=None, color_dot=None,
polygon_bool=None, draw_dots_bool=None):
"""
Generate a regular hexagon on a given image canvas with dots along the edge
:param image: Pillow/... | 71,852 |
def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
"""
Compute the trimmed standard error of the mean.
This function finds the standard error of the mean for given
values, ignoring values outside the given `limits`.
Parameters
----------
a : array_like
array of value... | 71,853 |
def _parse_ligand_sdf(input_file):
"""
Function to parse a series of ligands - return RDKit mols.
:param input_file: the file to parse
:param input_type: the type of ligands
:return: the molecules parsed
"""
mols = Chem.SDMolSupplier(input_file)
return mols | 71,854 |
def end_session(message, websocket, metadata):
"""Set session is over and add to the device/app collection."""
api_key = metadata.get('apiKey', '')
ConfigManager.datastore_interface.set_session_over(
api_key, metadata['deviceName'], metadata['appName'],
metadata['startTime'])
ConfigManag... | 71,855 |
def get_anomalies_confidence_interval(
ts: "TSDataset",
model: Union[Type["ProphetModel"], Type["SARIMAXModel"]],
interval_width: float = 0.95,
in_column: str = "target",
**model_params,
) -> Dict[str, List[pd.Timestamp]]:
"""
Get point outliers in time series using confidence intervals (est... | 71,856 |
def near_blur_intensity_localization_fv(data3dr, voxelsize_mm, seeds=None, unique_cls=None): # scale
"""
Use organ_localizator features plus intensity features
:param data3dr:
:param voxelsize_mm:
:param seeds:
:param unique_cls:
:return:
"""
import scipy
import numpy as ... | 71,857 |
def tsa_factory(y: Y_TYPE, s: dict, k: int, a: A_TYPE = None,
t: T_TYPE = None, e: E_TYPE = None,
p:int=TSA_P_DEFAULT, d:int=TSA_D_DEFAULT, q:int=TSA_D_DEFAULT) -> ([float], Any, Any):
""" Extremely simple univariate, fixed p,d,q ARIMA model that is re-fit e... | 71,858 |
def topic_select(config: Config, expander_container=st.sidebar, **kwargs) -> str:
"""
Through this function a topic is selected.
If we are either not in story_mode or if a topic is already selected,
a topic can be selected in a selectbox in the sidebar
(compact_topic_selector()).
Otherwise a t... | 71,859 |
def main():
"""
Main function that gathers the arguments from the command line with :func:`parse_cli()` and execute the function :func:`run()`.
"""
args = parse_cli()
run(args.filename, args.p, args.equal) | 71,860 |
def signature_generation(msg, private_key):
"""
Generates signature for a given message. Note that it will most likely
return different signature even for the same message, since it uses a random
integer as a parameter for generating the sign. This can be avoided by using
the hash of the message as... | 71,861 |
def wrap_numbers(input_dict, name):
"""Given an `input_dict` and a function `name`, adjust the numbers
which "wrap" (restart from zero) across different calls by adding
"old value" to "new value" and return an updated dict.
"""
with _wn.lock:
return _wn.run(input_dict, name) | 71,862 |
def run_custom_method(doctype, name, custom_method):
"""cmd=run_custom_method&doctype={doctype}&name={name}&custom_method={custom_method}"""
bean = webnotes.bean(doctype, name)
controller = bean.get_controller()
if getattr(controller, custom_method, webnotes._dict()).is_whitelisted:
call(getattr(controller, custo... | 71,863 |
def headers_to_table(headers, filenames=None, keywords=None, empty_value=None,
lower_keywords=False, logger=logger):
"""Read a bunch of headers and return a table with the values."""
# TODO: Refactor to better performance
hlist = []
actual = 0
for head in headers:
hlist.... | 71,864 |
def dict_remove_empty(d):
"""remove keys that have [] or {} or as values"""
new = {}
for k, v in d.iteritems():
if not (v == [] or v == {}):
new[k] = v
return new | 71,865 |
def tfrt_http_archive(name, sha256, urls, **kwargs):
"""Downloads and creates Bazel repos for dependencies.
This is a swappable replacement for http_archive() that offers some
additional features. It also helps ensure best practices are followed.
File arguments are relative to the TFRT repository by d... | 71,866 |
def destroy(parameters):
"""
Destroys a vm forcefully
"""
logger.debug("Inside destroy() function")
vm_id = parameters['vm_id']
vm_details = current.db.vm_data[vm_id]
logger.debug(str(vm_details))
try:
domain = getVirshDomain(vm_details)
if domain.info()[0] == VIR_DOMAIN_... | 71,867 |
def test_geoid_offset():
"""
Returns test result of reference and computed geoid comparison
"""
# ref file contains 32x32 points issued from proj 6.2
ref_file = absolute_data_path("ref_output/egm96_15_ref_hgt.nc")
geoid_ref = xr.open_dataset(ref_file)
# create a zero elevation Dataset with... | 71,868 |
def subscribe(body: SubscriptionInput = None):
"""Subscription for receiving a notification about discovery and KB updates.
# noqa: E501
:param subscription_input: Subscription information.
:type subscription_input: dict | bytes
:rtype: SubscriptionOutput
"""
logger.debug("Entry: subscri... | 71,869 |
def sigmoid_activation(x):
"""Commpute the sigmoid activation value for a given input.
Args:
x (array): input data point
Returns:
float: sigmoid activation value
"""
return 1.0 / (1 + np.exp(-x)) | 71,870 |
def satellite_locations(tles, dt):
"""
compute locations for the center of the satellite footprint for the given list of TLEs
for every second in the given date
:param tles: list of TLEs retrieved from the space-track.org API (see fetch_TLE())
:param dt: datetime retrive a lat,lon location for eve... | 71,871 |
def config(img: Dict[str, int],
pad: Dict[str, int],
maxp_side: int, conv: Dict[str, int]
) -> None:
""" send configuration """
# CFG_IR_IMG_W
dut.prep("cfg_data", [concat_cfg1(img['width']-1)])
dut.prep("cfg_addr", [5])
dut.prep("cfg_valid", [1])
io = dut.tick(... | 71,872 |
def read(f, normalized=True):
"""MP3 to numpy array"""
a = pydub.AudioSegment.from_mp3(f)
y = np.array(a.get_array_of_samples())
if a.channels == 2:
y = y.reshape((-1, 2))
if normalized:
return a.frame_rate, np.float32(y) / 2**15
else:
return a.frame_rate, y | 71,873 |
def check_on_pr(name, summary, success=True):
"""Create/Update a check on current pull request.
The check runs are aggregated by their name, so newer check will update the
older check with the same name.
Requires environment variable 'KOKORO_GITHUB_PULL_REQUEST_NUMBER' to indicate which pull request
... | 71,874 |
def maintenance(jobname):
"""Performs server maintenance, e.g. executed regularly by the server itself (localhost)
Returns:
200 OK: text/plain (on success)
403 Forbidden (if not localhost)
500 Internal Server Error (on error)
"""
global logger
report = []
try:
us... | 71,875 |
def auth() -> None:
"""Authenticate with Contxt.""" | 71,876 |
def find(id=None, _cleaner=None, populate_rooms=False, populate_cleaner=False, populate_feedbacks=True):
""" TODO: populate_rooms has no test coverage
Populates feedbacks list as default (acts as if feedbacks in embedded documents)
"""
query = {}
if id:
query['_id'] = sanitize_id(id)
if _cleaner:
query['_cle... | 71,877 |
def GeneticModel03(x,y, popSize, iters, mutsPerKid, dbkids=False, natCouples=1 ,clonekids=0):
"""
This is an hybrid model from Model01 and Model02.
Params:
x(np.array): x coordinate array.
y(np.array): y coordinate array.
popSize(int): Size of the population.
... | 71,878 |
def show_img(img,
ax=None,
vmin=None,
vmax=None,
interpolation=None,
title_=None,
cbar_orientation='horizontal',
plot_colormap='jet',
plot_size=(12,7),
sig_digits=2,
plot_aspect=None,
... | 71,879 |
def downscale_mean(arr, red):
"""
Downscale an image by the local mean
Parameters
----------
arr: 2D numpy.array
Array to reduce
red: int, or couple
Factor by how much the array is reduced.
If couple, the first factor reduces in x, and the second in y.
... | 71,880 |
def H(qbit: QbitVal) -> Gate:
"""
Hadamard gate.
:param qbit: parameter.
:return: Gate.
"""
root2 = 1 / Sqrt(Real(2))
return Gate('H',
[qbit],
H_matrix,
mapping=lambda q: QbitVal((q.alpha + q.beta) * root2,
... | 71,881 |
def run_svm_one_vs_rest_on_MNIST():
"""
Trains svm, classifies test data, computes test error on test set
Returns:
Test error for the binary svm
"""
train_x, train_y, test_x, test_y = get_MNIST_data()
train_y[train_y != 0] = 1
test_y[test_y != 0] = 1
pred_test_y = one_vs_rest_sv... | 71,882 |
def read_toml(tomlpath: AnyStr) -> XgmContainer:
"""read an XgmContainer from a toml file and its content files
:param tomlpath: path to the toml file
:return: XgmContainer instance read from tomlpath
"""
tomldir = os.path.dirname(tomlpath)
with open(tomlpath, "rt", encoding="utf-8") as tomlfil... | 71,883 |
def patch():
"""Patch click"""
import click
click.types.ParamType.complete = param_type_complete
click.types.Choice.complete = choice_complete
click.core.MultiCommand.get_command_short_help = multicommand_get_command_short_help
click.core._bashcomplete = _shellcomplete | 71,884 |
async def assets(create_asset, issue_asset, default_account):
"""Create some assets to use in tests."""
await create_asset("USD", 3)
await create_asset("GOLD", 3)
await issue_asset("USD", 1000, default_account) | 71,885 |
def check_expEstimates(theta, deltaT, binSize, T, numTrials, data_mean, data_var,\
maxTimeLag, numTimescales, numIter = 500, plot_it = 1):
"""Preprocessing function to check if timescales from exponential fits are reliable for the given data.
Parameters
-----------
the... | 71,886 |
def fit_galaxy_sky_multi(galaxy0, datas, weights, ctrs, psfs, regpenalty,
factor):
"""Fit the galaxy model to multiple data cubes.
Parameters
----------
galaxy0 : ndarray (3-d)
Initial galaxy model.
datas : list of ndarray
Sky-subtracted data for each epoch ... | 71,887 |
def image_upload(request):
"""
This method return the wangEditor image upload data
You should implement this method by your self
{
// errno 即错误代码,0 表示没有错误。
// 如果有错误,errno != 0,可通过下文中的监听函数 fail 拿到该错误码进行自定义处理
errno: 0,
// data 是一个数组,返回若干图片的线上地址
data: [
'图片1地址',
'... | 71,888 |
def scale_unscaled_ramp(rmin: Union[int, float, str], rmax: Union[int, float, str], unscaled: RAMP_SPEC) -> RAMP_SPEC:
"""
Take a unscaled (normalised) ramp that covers values from 0.0 to 1.0 and scale it linearly to cover the
provided range.
:param rmin: The new minimum value for the ramp range.
:... | 71,889 |
def get_class_name(obj):
"""
Returns the name of the class of the given object
:param obj: the object whose class is to be determined
:return: the name of the class as a string
"""
return obj.__class__.__name__ | 71,890 |
def encode_bytes(bytes):
"""Encodes bytes as Base64 unicode string."""
return b64encode(bytes).decode('utf-8') | 71,891 |
def get_starcheck_catalog_at_date(date, starcheck_db=None, timelines_db=None):
"""
For a given date, return a dictionary describing the starcheck catalog that should apply.
The content of that dictionary is from the database tables that parsed the starcheck report.
A catalog is defined as applying, in t... | 71,892 |
def result_aggregator(aggregator_fn: ResultAggregatorFn):
"""Transform previous aggregate and list of results into an aggregated
single result. Called by load model function
Args:
aggregator_fn (ResultAggregatorFn): Aggregator function
"""
def wrapper(fn):
set_scenario_attribute(fn... | 71,893 |
def handle_backward(left_entry_box, right_entry_box, mqtt_sender):
"""
Tells the robot to move using the speeds in the given entry boxes,
but using the negatives of the speeds in the entry boxes.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: ... | 71,894 |
def convert_to_ipa(phrase, specialized=True):
"""Takes a piece of text and transibes it to the
International Phonetic Alphabet (IPA).
Note: some changes to transcription were made depending on the
system, to not have these changed, set <specialized> to false.
"""
conversions = {
"oʊ":... | 71,895 |
def lower_walls_plumed(*args, **kwargs):
"""A restraint that is zero if the argument is below a certain threshold.
The restraint potential energy is given by
kappa * ((arg - at + offset) / eps)**exp
if arg - at + offset is less than 0, and 0 otherwise.
Parameters
----------
arg : tor... | 71,896 |
def test_init_name():
"""Test deserialization of fields with init_name."""
class Entity:
def __init__(self, another_field):
self.field = another_field
schema = fields.Namespace("http://schema.org/")
class EntitySchema(JsonLDSchema):
field = fields.Boolean(schema.field, ini... | 71,897 |
def query_record( rec_id: str ) -> dict:
""" Handles api call for GET reference-data and associated referent-data.
Called by views.data_records() """
log.debug( 'starting query_record()' )
assert type(rec_id) == str
data = { 'rec': {}, 'entrants': [] }
if rec_id == None:
data = json.... | 71,898 |
def export_nearby_wells(
req: WellsExport
):
"""
finds wells near to a point
fetches distance data using the Wally database,
combines it with screen data from GWELLS and
filters based on well list in request
"""
point_parsed = json.loads(req.point)
export_wells = req.export_well... | 71,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.