content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _get_block_timestamp_from_web3(
web3: Web3,
block_number: int,
) -> int:
"""
Gets the timestamp of a block from the blockchain.
will raise an exception if the block is not found.
"""
return web3.eth.getBlock(block_number).timestamp | dd0210c1250c0c3d955e3965b35dab700ad817a4 | 3,611,600 |
def round_float(value, precision=1):
"""
Returns the float as a string, rounded to the specified precision and
with trailing zeroes (and . if no decimals) removed.
"""
return str(round(value, precision)).rstrip("0").rstrip(".") | afa167709c73b2c536a795c0e38975e212311210 | 3,611,601 |
def stripMakeCodeHeader(incoming):
"""strip off byte header generated by makecode"""
pos = incoming.rfind("\\x")+4
header = incoming[:pos] #TODO: unused
body = incoming[pos:-1]
return body | 23fc4c600b96fa939bcdc45d592e2a823dd73c7f | 3,611,602 |
def get_etcd_client():
"""
Gets the Etcd Client instance using host and port defined in
TOTEM_ETCD_SETTINGS
:return: Instance of etcd.Client
:rtype: etcd.Client
"""
return etcd.Client(host=TOTEM_ETCD_SETTINGS['host'],
port=TOTEM_ETCD_SETTINGS['port']) | aa25a0610d44cc84d85e149ecd9b0c948b8aa9f1 | 3,611,603 |
def _widen_hsv_color_range(color_range, proportion):
"""Widens range by proportion
new lower bound = old - (old * proportion / 2)
new upper bound = old + (old * proportion / 2)
"""
new_range = [[None, None, None], [None, None, None]]
max_values = [180, 255, 255] # h, s ,v
for i in range(3):
... | f4a1f9867cbe34b92ee8d157c6a277780712c587 | 3,611,604 |
import subprocess
import locale
def run(command):
"""Returns (return-code, stdout, stderr)"""
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)
output, err = p.communicate()
rc = p.returncode
if PY3:
enc = locale.getpreferred... | 7905ca52bb717fc7c55a034b2cd17e025c8b8d0e | 3,611,605 |
from datetime import datetime
def date(candidate: str) -> datetime.date:
"""Converts ECMWF-format date strings into a `datetime.date`.
Accepted absolute date formats:
- YYYY-MM-DD
- YYYYMMDD
- YYYY-DDD, where DDD refers to the day of the year
For example:
- 2021-10-31
- 19700101
... | 9cbe50172a70d68e0ac2fdc33ed0716e27333dda | 3,611,606 |
def test_game(game,team):
"""Broken out so we can test for all kinds of variations once we build the variation list."""
return (team.lower() in [game["competitions"][0]["competitors"][0]["team"]["location"].lower(),
game["competitions"][0]["competitors"][1]["team"]["location"].lower(),
game["competitions"][0]["co... | 7e35d434415ba5cb94fd02f119bd59f5f98898fb | 3,611,607 |
def calculate_parse_metrics(gold_corpus, annotated_corpus):
"""Calculate POS/UAS/LAS accuracy based on gold and annotated sentences."""
check.Eq(len(gold_corpus), len(annotated_corpus), 'Corpora are not aligned')
num_tokens = 0
num_correct_pos = 0
num_correct_uas = 0
num_correct_las = 0
for ... | bd51d29a2debd4553d1e3f80e0b6dfb813602efb | 3,611,608 |
import numpy
def ifftn(x1, s=None, axes=None, norm=None):
"""
Compute the N-dimensional inverse discrete Fourier Transform.
Multi-dimensional arrays computed as batch of 1-D arrays
Limitations
-----------
Parameter ``norm`` is unsupported.
Parameter ``x1`` supports ``dpnp.int32``, ``dpnp... | 3582a38d713230c4125464163feaf8c2511c2a27 | 3,611,609 |
import re
def get_summary(icalendar_text: str):
"""Get the first SUMMARY: line from an iCalendar text.
Do not care about the line being continued.
"""
match = re.search(SUMMARY_PATTERN, icalendar_text)
return match[1] | 34b75d9e6614075fcafb900b0d8f05fd5714d3e8 | 3,611,610 |
def sched_var(func):
"""This decorator marks the given function as a scheduler variable. The
function must take no arguments (other than self)."""
# The scheduler plugin class will search for these.
func.is_sched_var = True
func.is_deferable = False
# Wrap the function function so it keeps it'... | 99a01aa59ec633cf8d0cd06258f0d726d21df6f7 | 3,611,611 |
import logging
def posgres_raw(query_sql, query_args=None, *, as_dict=True, alias=None, filterData=None, modifyData=None, **kwargs):
""" Returns the answer to a raw sql statement to ther database.
table (str) - Which table to get data from
Example Input: posgres_select("SELECT * FROM property")
Example Input: ... | 11168f2e882674bb967841c48f84e55c08496e56 | 3,611,612 |
def file_upload_url():
""" file_upload_url: returns url to upload files
Args: None
Returns: string url to file_upload endpoint
"""
return FILE_UPLOAD_URL.format(domain=DOMAIN) | 4ac3a8f20fd212d4f9c28697a793bb6d8759e38d | 3,611,613 |
def parse_command_line(version=None,
self_description=None,
version_date=None,
default_config_file_path=None,
):
"""parse command line arguments
Also add current version and version date to description
"""
# de... | fbf9613087d7a629f56d4b1f6260b71ab36e283f | 3,611,614 |
def test_jax_scan_multiple_output():
"""Test a scan implementation of a SEIR model.
SEIR model definition:
S[t+1] = S[t] - B[t]
E[t+1] = E[t] +B[t] - C[t]
I[t+1] = I[t+1] + C[t] - D[t]
B[t] ~ Binom(S[t], beta)
C[t] ~ Binom(E[t], gamma)
D[t] ~ Binom(I[t], delta)
"""
def binomln... | f1ec485ce7a731871a1de5c4b456cb44a641737d | 3,611,615 |
def appium_bytes(value, encoding):
"""
Return a bytes-like object. Has _appium_ prefix to avoid overriding built-in bytes.
:param value: A value to convert
:type value: string
:param encoding: A encoding which will convert to
:type encoding: string
:return: A bytes-like object
:rtype:... | b7acc045584ffad834bb24f30fe930736f55d699 | 3,611,616 |
from typing import List
import csv
def read_sts_inputs(path: str) -> List[str]:
"""Read input texts from a tsv file, formatted like the official STS benchmark"""
inputs = []
with open(path, 'r', encoding='utf8') as fh:
reader = csv.reader(fh, delimiter='\t', quoting=csv.QUOTE_NONE)
for row... | 6af4e934d648b550298e71584eaf47e4267316ac | 3,611,617 |
from pathlib import Path
import os
def get_size(path: Path,
decimal_places: int = 1) -> float:
"""
Get file size in MB, rounded to decimal_places.
:param path: Path to the file.
:param decimal_places: int, count of sighs after dor in result value.
:return: float, rounded size of the... | 63271b95f353b201a625e76cb4b5c3015d987ae4 | 3,611,618 |
def extract_keys(dict, keys, no_key_val=_sentinel):
"""Removes the specified keys from the given dictionary, and returns a dictionary containing those key:value
pairs. Default behaviour is to ignore those keys which can't be found in the original dictionary. The optional
argument :no_key_val: can be set to ... | eb420734b1969e8a01b47caef023443d0e1f48e7 | 3,611,619 |
def resnet101(num_classes, pretrained=False, dropout1=0.25, dropout2=0.25, alpha=0.25, gamma=2.0,
loss_with_no_bboxes=False, no_bboxes_alpha=0.5, no_bboxes_gamma=2, **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
... | 688e0ded410033c63c3db6c10f65a334447a2b97 | 3,611,620 |
def vuvu_to_vuhw(vuvu):
"""
Function to transform between top left and bottom right corner box representation (vuvu) to
center_dimensions box representation (vuhw) .
:param vuvu: N x 4 tensor represeting v_min, u_min, v_max, u_max, the corners of the bounding boxes.
:return: vuhw: N x 4 tensor rep... | a9dc162d1b7d8d66099f2fb500d808e10d492809 | 3,611,621 |
import asyncio
async def async_unload_entry(hass, config_entry):
"""Unload an AirVisual config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(config_entry, component)
for component in PLATFORMS
... | 14b761200e6ec54340f6543e447d7c240ebfb5ca | 3,611,622 |
def application_doesnt_match(service, custom_application, custom_app_plan, lifecycle_hooks, request):
"""Second application that doesn't match jwt claim check policy"""
plan = custom_app_plan(rawobj.ApplicationPlan(blame(request, "aplan")), service)
application = custom_application(rawobj.Application(blame(... | 19b6ef733e505522423d88f9de14ef753854cde3 | 3,611,623 |
def delete_appliance_for_rediscovery(
self,
ne_pk: str,
) -> bool:
"""Delete an appliance from Orchestrator for rediscovery
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - appliance
- DELETE
- /appliance/delete... | 8be2817f55408314ef27baac022801059f3f2340 | 3,611,624 |
from typing import List
import os
def get_motif_pwm(motif_file: str,
args_obj: Findmotif,
cores: int,
debug: bool
) -> List[Motif]:
"""Construction of Motif object from PWM file.
The motif PWM is processed in order to obtain the corresponding scoring
... | 794f14a691170892946a3836b0b07392fece0772 | 3,611,625 |
def increase_index(idx: str) -> str:
"""Increases an index by one unit.
If the index is numeric, in the range '00' to '98', it adds one
to the index and returns an index in the range '01' to '99'.
If the index is already '99', there is an Exception error.
If the index is alphanumeric, with the fir... | 1bcaa8d27ed83d295197c4f398e77d49ad47bb6d | 3,611,626 |
def compare_flow_fields(F1, F2, n_min=1):
"""Compare two flow fields.
"""
# Compute the element-by-element difference
dX_diff = F1.dX_fit - F2.dX_fit
dX_diff_mag = np.linalg.norm(dX_diff, axis=2) # n_grid x n_grid
# Filter by the number of observations. Find the number of observations for
... | 26dc0cd321861050899cfe5e0189966eff6efd4f | 3,611,627 |
import itertools
def rollup_dataseries(dataseries):
"""
Rollup dataseries.
Roll up a sites data series by parameter group if a series has them. Data
types for the parameter group is the join of the data types for each measured
parameter code. Similarly, the start and end dates are the earliest an... | 9ac13333d05a6410b1fd4497528f8eca6d1d7f45 | 3,611,628 |
def determine_smallest_atom_index_in_scan(atom1: 'rdkit.Chem.rdchem.Atom',
atom2: 'rdkit.Chem.rdchem.Atom',
) -> int:
"""
Determine the smallest atom index in mol connected to ``atom1`` which is not ``atom2``.
Returns a heav... | dd15837711401f52ff9ab3f561b4d82556990a9c | 3,611,629 |
import os
import six
def load_project(project_directory, prefix='', new_targets_location=None,
repository_name='default'):
"""
<Purpose>
Return a Project object initialized with the contents of the metadata
files loaded from 'project_directory'.
<Arguments>
project_directory:
The path to ... | e38e535556a352377357356d6fb155816892e76b | 3,611,630 |
import requests
import os
def get_patches(run_local):
"""Returns the list of patch files located in the adabot/patches
directory.
"""
return_list = []
if not run_local:
contents = requests.get(
"https://api.github.com/repos/adafruit/adabot/contents/patches"
)
if... | 0468e6bac4cb8158f7074ba1d1d8f0b833448176 | 3,611,631 |
def quartiles(xs):
"""Divisions between quartiles."""
return quantiles(xs, 0.25, 0.5, 0.75) | 599d8a81c8b7774096eb2f062448cf8dd4818a17 | 3,611,632 |
from datetime import datetime
import time
def formatTimeFromNow(secs=0):
""" Properly Format Time that is `x` seconds in the future
:param int secs: Seconds to go in the future (`x>0`) or the
past (`x<0`)
:return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`)
... | 9723ab0656ff4017412ab1fbd5465375ec8df1af | 3,611,633 |
from datetime import datetime
def get_utc_timestamp() -> Text:
"""Get utc timestamp.
Returns:
Text: utc timestamp
"""
return str(datetime.datetime.utcnow().timestamp() * 1000) | 85de30cf745c545dadc26d7dbc6c866238e6c5cf | 3,611,634 |
def ConvolutionalVAE(*args, **kwargs):
"""
Constructs a Convolutional VAE.
References
[1]. Oktay, Ozan, et al. “Attention U-Net: Learning Where to Look for the Pancreas.” ArXiv:1804.03999 [Cs], May 2018. arXiv.org, http://arxiv.org/abs/1804.03999.
>>> import deeply
>>> model = deeply.hub("... | fd082d63e2940dc07a2ce007b8f4da251411c834 | 3,611,635 |
def to_2d_np(a: ndarray, type: str="col") -> ndarray:
"""
Turns a 1D Tensor into 2D
"""
assert a.ndim == 1, \
"Input tensors must be 1 dimensional"
if type == "col":
return a.reshape(-1, 1)
elif type == "row":
return a.reshape(1, -1) | 07933cd3851d65b61034b3b3d7b9caa46b809c1e | 3,611,636 |
import os
import pickle
def read_dictionary(vocab_path):
"""
:param vocab_path:
:return:
"""
vocab_path = os.path.join(vocab_path)
with open(vocab_path, 'rb') as fr:
word2id = pickle.load(fr)
print('vocab_size:', len(word2id))
return word2id | e2bedf9407d1da14f91a0786ca7b13b6218cbc9d | 3,611,637 |
def get_category(main_category, detail_category, region, **filters):
"""
Scrape OtoDom search results based on supplied parameters.
:param main_category: "wynajem" or "sprzedaz", should not be empty
:param detail_category: "mieszkanie", "dom", "pokoj", "dzialka", "lokal", "haleimagazyny", "garaz", or
... | 20f5f2dc49e23e76c47a6ab8225f18a3ed717457 | 3,611,638 |
def standardize_parameter_type(original_type):
"""Standardize parameter type descriptions
Args:
original_type (str): The original type
Returns:
str: The standarized type name
"""
original_type = original_type.lower()
if 'unc' in original_type:
return 'uncertainty'
i... | 49a93bebd8ee4918bdf420ee8c285d6574a3d3d0 | 3,611,639 |
def _get_pd_fields(d, files, r_prefix):
"""Retrieve form fields representing a product."""
fields = ['id', 'name', 'price', 'quantity_per_package', 'unit', 'quantity_limit', 'quantum', 'unit_weight',
'place', 'described', 'description', 'image-modified']
raw = {f: d.get("%s-%s" % (r_prefix, f)... | ca74209aaf5eb502c5366efba09031aeead1d70c | 3,611,640 |
import sys
import argparse
def parse_args(args=sys.argv[1:]):
""" Get the parsed arguments specified on this script.
"""
parser = argparse.ArgumentParser(description="")
parser.add_argument(
'output_path',
action='store',
type=str,
help='Path to output file.')
ret... | ab73265f334cb3e31c0debfe55039ad51e1615eb | 3,611,641 |
def insert_xlnx_pragmas(lines):
"""Insert HLS pragmas for Xilinx program
Replace the comments of "// hls_pipeline" and "// hls_unroll" with
HLS pragmas
For "// hls pipeline", find the previous for loop before hitting any "}".
Insert "#pragma HLS PIPELINE II=1" below the for loop.
For "// hls un... | 9ad5e5253473ecbcf82d4e739b7c6d7dd82ba7c6 | 3,611,642 |
def check_unboundness(A_times_delta_x):
"""Check if LP is unbounded
"""
if np.all(A_times_delta_x <= 0):
logger.info('LP is unbounded')
return True
else:
return False | c8a91036fd3768b1774fba650796886d8eafa913 | 3,611,643 |
from typing import Tuple
import torch
import math
def real_fourier_basis(n: int) -> Tuple[torch.Tensor, torch.Tensor]:
"""Make a Fourier basis.
Args:
n: The basis size
Returns:
An array of shape `(n_domain, n_funs)` containing the basis functions, and an
array containing the spec... | 704aacf8e34f2713ee5e01b8c0de2350c8e03ae2 | 3,611,644 |
def to_output_type(array, output_type, order='F'):
"""Used to convert arrays while creating datasets
for testing.
Parameters
----------
array : array
Input array to convert
output_type : string
Type of to convert to
Returns
-------
Converted array
"""
if out... | 701691824ddd2364ff6770d93d13389cf8aa4dc4 | 3,611,645 |
def _define_names(d_t, d_y, treatment_names, output_names):
"""
Helper function to get treatment and output names
Parameters
----------
d_t: tuple of int
Tuple of number of treatment (exclude control in discrete treatment scenario).
d_y: tuple of int
Tuple of number of outcome.
... | a475968ed70070175f5ef164d1748def62548c9d | 3,611,646 |
import urllib3
def scrape_lat_lon_fly(stationID):
"""
Add latitude, longitude and elevation data to the stationID that is
inputted as the argument to the function. Boom.
:param stationID: str
a unique identifier for the weather underground personal
weather station
:return: (latitud... | e1a78f3adfb7ce890306d31deba4e15410bb079c | 3,611,647 |
from typing import List
from typing import Callable
def _add_standard_processes(process_registry: ProcessRegistry, process_ids: List[str]):
"""
Add standard processes as implemented by the openeo-processes-python project.
"""
def wrap(process: Callable):
"""Adapter to connect the kwargs style... | da5b162fdc8002670864cd1e1e5069b40f0d8a8b | 3,611,648 |
def __num_children(self, vertex=None):
"""
Get the the number of children of the given vertices.
If :attr:`vertex` is ``None``, the function will return the number of children of every non leaf
node of the tree.
:param vertex: a vertex index or a 1d array of vertex indices
(default to ``np... | e1385a67cfc79dd1fa18805c85e8e2fd59336c16 | 3,611,649 |
from datetime import datetime
def parse_time_interval(time_start, time_end):
"""created time values for time_start and time_end, while time_end
will be replaced with time_start+ a duration if the duration is
given in time_end. The format of the duration is intuitive through
the timeparse module. YOu c... | b4348e1995514030528fad9330d726eb5079d758 | 3,611,650 |
def _as_vw_string(x, y=None):
"""Convert {feature: value} to something _VW understands
Parameters
----------
x : {<feature>: <value>}
y : int or float
"""
result = str(y)
x = " ".join(["%s:%f" % (key, value) for (key, value) in list(x.items())])
return result + " | " + x | 89e10d3bb8ad47ad4add6baee83280fa700ca65e | 3,611,651 |
from io import StringIO
import csv
def _read_header(f, header_param):
"""
Read and parse data from 1st line of a file.
:param f: :func:`file` or :class:`~StringIO.StringIO` object from which to
read 1st line.
:type f: file
:param header_param: Parameters used to parse the data from the he... | 294bb6846384378b1dd9950e649757a6448089d0 | 3,611,652 |
def classifier_layer_fn(in_dim, out_dim, layer_name, fn=tf.nn.relu):
"""Build a function for a neural network classifier layer."""
with tf.name_scope(layer_name + '_vars'):
weights, biases = classifier_variables(in_dim, out_dim)
def nn_layer_ops(x):
with tf.name_scope(layer_name + '_ops')... | ce0f153f033ab603373763368edc4e70d5b53590 | 3,611,653 |
def svn_client_revprop_get(*args):
"""
svn_client_revprop_get(char propname, svn_string_t propval, char URL, svn_opt_revision_t revision,
svn_revnum_t set_rev,
svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t
"""
return apply(_client.svn_client_revprop_get, args) | b4725ec347ea9fbd7ab15d0a2ffb10112907b5b3 | 3,611,654 |
import argparse
def get_args():
"""Gte cmomnda-lnei amguntsre"""
parser = argparse.ArgumentParser(
description="Let's change some vowels",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("input", metavar="str", help="Text or a file")
parser.add_argu... | c3cda6c80b7ccef2af40656f411063e9457aecaf | 3,611,655 |
import typing
def do_action(view: View, defx: Defx,
action_name: str, context: Context) -> bool:
"""
Do "action_name" action.
"""
if not defx._source:
return True
actions: typing.Dict[str, ActionTable] = defx._source.kind.get_actions()
if action_name not in actions:
... | bb45de3c896b7bdcef8d40236a5743517d5230d1 | 3,611,656 |
from numpy import where
def qinit(x,y):
"""
Dam break
"""
eta = where(x<10, 40., 0.)
return eta | aa81ca9782917ce730ec70f4281a7b708c368308 | 3,611,657 |
def parkinson_volatility(high_prices, low_prices, window, time_scale=1, plot=False):
"""
Estimando a volatilidade a partir dos preços de Alta e de Baixa
Args:
high (pd.DataFrame): série de preços de alta de uma ação
low (pd.DataFrame): série de preços de baixa de uma ação
window (in... | 49b0f4b10eb80d17a801660c04cfe32e9d9e7dd9 | 3,611,658 |
import sys
def in_notebook():
"""
Returns ``True`` if the module is running in IPython kernel,
``False`` if in IPython shell or other Python shell.
"""
return "ipykernel" in sys.modules | ca8d703a399dfa8ee0bb0bdb42d9af8e657f5549 | 3,611,659 |
def DatetimeToUTCMillis(date):
"""Converts a datetime object to milliseconds since the epoch in UTC.
Args:
date: A datetime to convert.
Returns:
The number of milliseconds since the epoch, in UTC, represented by the input
datetime.
"""
return DatetimeToUTCMicros(date) / 1000 | 0020e7b15ee0e7ff541d4e1691940e4114de42c5 | 3,611,660 |
from typing import AsyncIterable
from typing import Optional
from typing import Union
from typing import IO
from typing import List
async def _async_forward(async_chunks: AsyncIterable,
out: Optional[Union[TeeCapture, IO[str]]]
) -> Optional[str]:
"""Prints/capture... | 2e9d861cd905a2f4576e6ba026e98bfccb8b80c2 | 3,611,661 |
def _try_parse_int(value: str):
"""
try parse integer from string
param value: string to parse
return int
"""
try:
return int(value)
except ValueError:
raise ValueError("Cannot parse int from string") | 50b4f5c3d3e703c2c6c329e2f1abb25a948e488d | 3,611,662 |
import numpy as np
def df_to_latex(
df,
col_aligns="",
header="",
caption="",
bold_max_cols=None,
na_rep="-",
supertabular=False,
midrule_after=None):
"""Converts a pandas dataframe into a latex table.
:col_aligns: Optional format string for... | 6f073dd35c343a81e3222ac2e90fea2c2f5bd1d1 | 3,611,663 |
def _gather_shape_rule(operand, indices, *, dimension_numbers,
slice_sizes, unique_indices, indices_are_sorted,
mode, fill_value):
"""Validates the well-formedness of the arguments to Gather.
The code implements the checks based on the detailed operation semantics of
... | 052ac40add46eadc3e0d4cd43096290cf5d86c62 | 3,611,664 |
def tf_mixed_norm_solver(M, G, alpha_space, alpha_time, wsize=64, tstep=4,
n_orient=1, maxit=200, tol=1e-8, log_objective=True,
active_set_size=None, debias=True, return_gap=False,
verbose=None):
"""Solve TF L21+L1 inverse solver with BCD an... | 12dd13a8d45ef4afd0b515b4c4d6dcdf82f3c154 | 3,611,665 |
def stddev(in_list):
"""
Calculates standard deviation of given list
:param in_list: list of values
:return: float rounded to 5 decimal places
"""
var = zvariance.variance(in_list)
std_dev = sqrt(var)
return round(std_dev, 5) | 8225b943b87ea2c966b130fd5afc9b06d6306b8e | 3,611,666 |
def retrieve_single_timeseries(ticker, secs=60, ndays=5):
"""
Grabs data from Google finance. It retrieves the data for `ticker` at
`secs` intervals for the most recent `ndays`. The fields it retrieves
for each interval is (time, open price, close price, volume of trade)
Parameters
----------
... | 95fc69f4920d92895d2c9f8a8e852f78f2a06a8d | 3,611,667 |
def select_os(parsed_host: dict):
"""
Out of all suggested OSs for the given host from Nmap, select the most
likely one using cosine similarity string matching. First a string of
relevant information is created, second the OS whose information is the
most similar to the matching string is returned.
... | 4216686c724e1738471c939d567befc3d6f1c08d | 3,611,668 |
def index_settings(shards=5, refresh_interval=None):
"""Configure an index in ES with support for text transliteration."""
return {
"index": {
"number_of_shards": shards,
"refresh_interval": refresh_interval,
"analysis": {
"analyzer": {
... | 29028b545da2e5ee2b0239029d34f863d1d9d943 | 3,611,669 |
def create_gray_frame(frame):
"""Create and return an undistorted grayscale image"""
h, w = frame.shape[:2]
new_matrix, _ = cv2.getOptimalNewCameraMatrix(Pose.camera_matrix,
Pose.dist_coeffs,
(w, h), 1, (w, h... | 748aff0f5a02a7a98bc56f2c46645c59b630c4a7 | 3,611,670 |
def make_nan_inf_summary(df: pd.DataFrame, max_loss: float) -> pd.DataFrame:
"""
makes a summary fot the the amount of nan and infinity values in the given data frame
will throw a ValueError if the percent of nan and inf is greater than the given threshold
prints a summary of the nan's and inf of there ... | 0ea0be6a822861e5896176cf96d5a6bb9d50954f | 3,611,671 |
def choose_downloaded_komoot_tour():
"""
Choose a previously downloaded tour. Tour can be passed to
:func:`komoog.gpx.convert_tour_to_gpx_tracks`
afterwards.
"""
tours = read_tours()
for idx in range(len(tours)):
print(f"({idx+1}) {tours[idx]['name']}")
tour_id = int(input("To... | 66cf0878728fab6fa6265d61f2a488dde2478091 | 3,611,672 |
import collections
import sys
import os
def get_data_hsla(obsid, targ):
"""
Given an HSLA observation ID, returns the spectral data. If a
coadd-level spectrum, must supply the target name via the 'targ'
parameter.
:param obsid: The HSLA grism observation ID to retrieve the data from.
:type ... | fa53bda220e08867e6e4e4d9dc05282fe83f8636 | 3,611,673 |
from datetime import datetime
def list_(limit: int = None, offset: int = None,
siri_route_ids: str = None, siri_route__line_refs: str = None, siri_route__operator_refs: str = None,
journey_ref_prefix: str = None,
journey_refs: str = None,
vehicle_refs: str = None,
sch... | 86fc2ce2a2609e6f2325f755c64812c8bbd093ba | 3,611,674 |
def fit_cpmfgp_with_dataset(dataset, *args, **kwargs):
""" Fits and returns a CPMFGP. """
config = dataset.config
mfgp_fitter = cpgp.CPMFGPFitter(dataset.ZZ_train, dataset.XX_train, dataset.YY_train,
fidel_space=config.fidel_space, domain=config.domain,
fidel_space_kernel_ordering=config.fidel_space_order... | 4478386e52d121d32951d84152c77e50bb5f4408 | 3,611,675 |
import time
def test_approach(approach: str, sample_no: int, func, args: tuple) -> str:
""" For a given Sample #sample_no evaluates an approach by running func with provided args and logs run time """
res = f"{approach.capitalize()} Programming Approach for the Example #{sample_no}\n"
start = time.time()+... | ef34e7552a887fd4bee221a5d80bb3d5ab0003a9 | 3,611,676 |
def call_command(cmd, verbosity="ERROR"):
"""
simple wrapper for call command
"""
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate("get output")
rc = p.returncode
if not rc == 0:
raise Exception("{0} ==> command: {1}".format(err, " ".join(cmd)))
return output | 2b153bb00f920fb9c5509fa6f76953073a8eec49 | 3,611,677 |
def walk(i, j):
"""
Walks through the String without crossing the boundaries,
making sure that i < j-1
"""
if i < j - 1:
i += 1
# It is necessary to check again if i < j-1, after we incremented i
if i < j - 1:
j -= 1
return i, j | 1597c41408179f5a371ec14e36494ec5ee3a7aa0 | 3,611,678 |
def run(configbase, filebase, options, progname):
"""
Command line tool to create and display ROs managed by the Overlay RO service.
"""
status = 0
# Create new Overlay RO and returns its URI
with HTTP_Session(options.serviceuri) as rovsession:
try:
rovsession.doRequest(optio... | de8d13f7f520dcf728f73c5485d50494ae631d79 | 3,611,679 |
def equation_loglogw2(x, a, b, c, d, e):
"""Equation form for loglogw2 """
return exp(a + b * log(log(x+1)) + (sqrt(x) * (c/2))) | 662fa157f5b4073780f5bbb383841867af7f6cd7 | 3,611,680 |
import uuid
def converter_spark_em_pandas(df):
"""
Converte o dataframe Spark em Pandas, adicionando uma coluna
de identificador unico e deterministico para cada linha da tabela
"""
data = df.toPandas()
data["ID_REGISTRO_TABELA"] = data.apply(
lambda row: uuid.uuid5(
uuid.UUID('a658b648-167e-4d4... | 99febbc364025afb39772fa6008f5b4217f394ae | 3,611,681 |
def kwargs_to_str(kwargs):
""" Returns a string of the form '(kw1=val1, kw2=val2)'. """
if len(kwargs) == 0:
return ""
else:
return "(" + ", ".join(f"{k}={v}" for k, v in kwargs.items()) + ")" | 39d50d77620061b99861fb7a1fea77ae2a2dc376 | 3,611,682 |
def get_crypt_key():
"""
Lazily generate the crypt key and return it
"""
# pylint: disable=global-statement
global __CRYPT_KEY__
if not __CRYPT_KEY__:
__CRYPT_KEY__ = _get_system_uuid()
return __CRYPT_KEY__ | b95972e33deb86450295da8440a6fe9213b3aed3 | 3,611,683 |
def index():
"""
Parameters:
----------
None.
Returns
--------
A rendered version of index.html and a http response code 200
The function renders the index page for the app
"""
global core_module
if not core_module: core_module = core_module()
... | 897b29517b9f8e566cd853eb81c529c3aac78001 | 3,611,684 |
def fpH(pH, c_Na, c_acide):
"""
Calcule la valeur de la fonction dont la racine correspond à l'équilibre
de la solution.
Entrée :
pH
c_Na (mol/L)
c_acide (mol/L)
Sortie :
valeur de la fonction
"""
Ke = 10**(- pKe)
Ka = 10**(... | 7ece0157f041057344239f0901f50c62dbc34719 | 3,611,685 |
from ..... import Tensor
from typing import Any
from typing import Dict
def local_decomposition(
x: ShareTensor,
ring_size: int,
bitwise: bool,
seed_id_locations: str,
node: Any,
read_permissions: Dict[Any, Any],
) -> None:
"""Performs local decomposition to generate shares of shares.
... | bdf3f546ffc78cd3b6de58d95ade282d336cf334 | 3,611,686 |
def detect(source, config=None, path=None):
"""Analyze and detect minimum versions from source code. A default config will be used if it isn't
specified. If path is specified, it will occur in errors instead of the default '<unknown>'.
"""
visitor = visit(source, config, path)
if isinstance(visitor, SourceVis... | a71d576c877aa1ed9284b40f7047926833a5da98 | 3,611,687 |
def set_coredump_network_config(
host,
username,
password,
dump_ip,
protocol=None,
port=None,
host_vnic="vmk0",
dump_port=6500,
esxi_hosts=None,
credstore=None,
):
"""
Set the network parameters for a network coredump collection.
Note that ESXi requires that the dump... | a047c3f4c5ed866c34fd65c10cb251d04bbb3f52 | 3,611,688 |
def Verification(verification_list, value):
"""
Essa função verifica se algum jogador já venceu a partida,
retorna um valor booleano que determina o próximo jogador.
:param verification_list:
:param value:
:return bool:
"""
cont = 0 # define um contador.
for i in DIM.WIN: # verifi... | f90b6c53a385d409d6b2f973d7bac61d6dc58529 | 3,611,689 |
import json
def train_agent(env_config_path, agent_config_path, num_episodes):
"""train agent"""
f1, f2 = open(env_config_path), open(agent_config_path)
env_config, agent_config = json.load(f1), json.load(f2)
env, agent = config(env_config, agent_config)
evaluation = MyEvaluation(env, agent, outpu... | e02e20491c068bd9fb8c403ce74fb47eae07121e | 3,611,690 |
def add_CRUD_pset(pset, sm, model_name):
"""Adds the ServerModel CRUD function to the Primitve Set
Parameters
----------
pset : PrimitiveSet
the primitive set for adding the controller functions
sm : ServerModel
the ServerModel with the CRUD functions
model_name : str
... | f0960c3b96789adfa2e56039ca7c072819438984 | 3,611,691 |
def to_litres(gallons):
"""Convert US gallons to metric litres"""
return 3.78541 * gallons | d1a7be6f01c89b848128218cbec19913e76658cd | 3,611,692 |
def fit_prior(n, p0=0.05):
"""
todo: check if there are similar magic numbers
https://github.com/svpcom/hyperloglog/blob/master/hyperloglog/hll.py
...
if p == 4: return 0.673
if p == 5: return 0.697
if p == 6: return 0.709
return 0.7213 / (1.0 + 1.079 / (1 << p))
"""
return 4 -... | 59d762295da5968907948f70c1358f94cf58ed16 | 3,611,693 |
import requests
def get_nioshtic_wikidata_mapping():
"""
Retrieves a mapping between NIOSHTIC and Wikidata identifiers from the
Wikidata Query Service, query.wikidata.org
@return dictionary {nioshtic: {identifier_label: value}}
"""
prefix = 'http://www.wikidata.org/entity/'
q = (
... | 7216f8ed354bb394e39ceb906d41e19d1e41e589 | 3,611,694 |
import uuid
from datetime import datetime
def create_new_fabric_person_from_token(headers, check_unique=False):
"""
Extract info from identity token and create a FabricPerson entry for this person,
including a new UUID. Return a PeopleLong based on that info.
:param headers: request headers with cooki... | 83f76bec65c644aaf79708d33d98a43d64806a05 | 3,611,695 |
def _gsspp(X,p,n,fun=ss):
"""
Generalized Spatial Sign Pre-Processing for Centred Data
"""
return(np.multiply(X,fun(_norms(X),p,n))) | bfa85e78bdffed7e152dbde1c9590f5bee52dd40 | 3,611,696 |
import random
import copy
def distr_labeldata_unequal(label_data, num_workers):
"""
Idea:
1. For each label, distribute disproportionate allocation to workers.
2. Apply the worker's allocation to label_data and store in distr_labeldata,
where the keys are workers and the values are the labeled... | dab112ba98e9d5d68fbb519f1c7e3f2a6ea24e17 | 3,611,697 |
import sys
def parse(elem):
"""
Traverse the json structure and return a dictionary with the following structure:
{ Bookmark Name: Bookmark Url }
"""
for obj in elem:
if obj["type"] == "url":
if obj["name"] in result:
print(f"Error: duplicate {obj['name']} is ov... | 9dd058ad5e4bbd037b8b72d115caed9f8a0b0913 | 3,611,698 |
def random_conv_encode(k, generator_matrix, memory, p=0.5):
"""
Generates a random sequence of k-bits, each Bernoulli(p) and then encodes
them convolutionally. Returns the original sequence, and the convolutionally
encoded one, using the generator matrix and memory.
"""
message_bits = generate_random_binar... | 1419fcda911f0d52161b0e8091ef076e86efc1b7 | 3,611,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.