content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def secp256k1_multiply(n):
"""Performs elliptic curve point multiplication to compute n * G.
See here:
http://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication
"""
return n * G | 5,286,700 |
def valid_json(formcls, field):
"""Validate field data as a json.
:param formcls (object): The form class.
:param field (str): The list of ips.
"""
json.loads(field.data) | 5,286,701 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up number entities dynamically through discovery."""
def _constructor(device_state: DeviceState) -> list[Entity]:
return [
PeriodicVentingTime(... | 5,286,702 |
def load_amphur(request):
""" Amphur Dependent/Chained Dropdown List """
province_id = request.GET.get('province')
amphur_list = Amphur.objects.filter(
province_id=province_id).order_by('name')
return render(request, 'app_sme12/form_partial/amphur_dropdown_list_options.html', {'amphur_list': amp... | 5,286,703 |
def read_files(dir_path):
"""Read file in the input directory and yield the text."""
for file_pth in map(lambda x: os.path.join(dir_path, x), os.listdir(dir_path)):
if os.path.isfile(file_pth):
with open(file_pth, 'r', encoding='utf-8') as f:
yield (file_pth, f.read()) | 5,286,704 |
def _clone_functional_model(model, input_tensors=None, layer_fn=_clone_layer):
"""Clone a functional `Model` instance.
Model cloning is similar to calling a model on new inputs,
except that it creates new layers (and thus new weights) instead
of sharing the weights of the existing layers.
Input layers are a... | 5,286,705 |
def connectMSExchange(server):
"""
Creates a connection for the inputted server to a Microsoft Exchange server.
:param server | <smtplib.SMTP>
:usage |>>> import smtplib
|>>> import projex.notify
|>>> smtp = smtplib.SMTP('mail.server.com')
... | 5,286,706 |
def test_GET_request_chunked_no_content_length(httpserver, chunked_flag):
"""
Test that a chunked response does not include a Content-length header
"""
httpserver.serve_content(
('TEST!', 'test'),
headers={'Content-type': 'text/plain', 'Transfer-encoding': 'chunked'},
chunked=chu... | 5,286,707 |
def cohort_selection(definition, db_client):
""" Select the persons id that fall into the citeria provided
for thr cohort.
"""
sql_condition = []
for component in definition:
value = VALUE in component
if component[TABLE].lower() == OBSERVATION_TABLE:
condition = ""
... | 5,286,708 |
def to_pickle_distributed(
self,
filepath_or_buffer,
compression: CompressionOptions = "infer",
protocol: int = pickle.HIGHEST_PROTOCOL,
storage_options: StorageOptions = None,
):
"""
Pickle (serialize) object to file.
This experimental feature provides parallel writing into multiple pi... | 5,286,709 |
def test_create_test_incident_command_happy(mocker, incidents, attachment, expected):
"""
Given: a file with list-format of valid incidents with labels
a file with single valid incident without labels
a list of valid incidents with labels with attachment,
an empty file witho... | 5,286,710 |
def _conv_bn_relu(
filters,
kernel_size,
strides=(1, 1),
padding="same",
kernel_regularizer=kernel_regularizer,
):
"""Helper to build a conv -> BN -> relu block
"""
def f(input):
conv = tf.layers.conv2d(
input,
filters=filters,
kernel_size=kerne... | 5,286,711 |
def test_atomic_non_positive_integer_total_digits_1_nistxml_sv_iv_atomic_non_positive_integer_total_digits_2_4(mode, save_output, output_format):
"""
Type atomic/nonPositiveInteger is restricted by facet totalDigits with
value 5.
"""
assert_bindings(
schema="nistData/atomic/nonPositiveIntege... | 5,286,712 |
def calc_curve_bootstrap(curve, metric, y, preds, n_bootstrap, seed=12345, stratified=True, alpha=95):
"""
Parameters
----------
curve : function
Function, which computes the curve.
metric : fucntion
Metric to compute, e.g. AUC for ROC curve or AP for PR curve
y : numpy.array
... | 5,286,713 |
def connect(host=None, database=None, user=None, password=None, **kwargs):
"""Create a database connection."""
host = host or os.environ['PGHOST']
database = database or os.environ['PGDATABASE']
user = user or os.environ['PGUSER']
password = password or os.environ['PGPASSWORD']
return psycopg2... | 5,286,714 |
def debug(text, *args, **kwargs):
"""Print message to debug output"""
logging.debug(resolve(text, *args, **kwargs)) | 5,286,715 |
def set_winsize(fdesc, row, col, xpix=0, ypix=0):
"""Set window size."""
if sys.platform == "win32":
return
winsize = struct.pack("HHHH", row, col, xpix, ypix)
fcntl.ioctl(fdesc, termios.TIOCSWINSZ, winsize) | 5,286,716 |
def to_b58_string(multihash):
"""
Convert the given multihash to a base58 encoded string
:param bytes multihash: multihash to base58 encode
:return: base58 encoded multihash string
:rtype: str
:raises: `TypeError`, if the `multihash` has incorrect type
"""
if not isinstance(multihash, b... | 5,286,717 |
def use_tex(use_serif=True, overwrite=True, preamble=None):
"""Configure pyplot to use LaTeX for text rendering."""
if plt.rcParams['text.usetex'] and not overwrite:
print("Will not override tex settings ...")
return
print("Will use tex for rendering ...")
if preamble is None:
... | 5,286,718 |
def test_post(client):
"""Check that the test endpoint returns a result."""
view_result = client.post("/api/v1/tests/test")
assert view_result.status_code == 200
print(view_result.data)
result = json.loads(view_result.data)
assert result.get("success", False) | 5,286,719 |
def run_in_docker(
command: str, docker_options="", capture_output=False, text=None
) -> subprocess.CompletedProcess:
"""Run command in Docker."""
command = command.strip()
print("+ ", command)
env = os.environ.copy()
env["PWD"] = cwd_for_docker_volume()
return subprocess.run(
f"{doc... | 5,286,720 |
def get_logger(name, level=logging.INFO):
"""
Get a logger and load logging.yaml config file if exists
"""
# Set a basic level of logging
logging.basicConfig(level=level)
# Get the path to the logging config yaml
dir_py_file = os.path.dirname(os.path.realpath(__file__))
dir_project = os... | 5,286,721 |
def make_request(url: str) -> HTTPMessage:
"""
Send a get request to the url passed in and return
the headers in the response
Args:
url (str): url to send GET request to
Returns:
HTTPMessage: http response object
"""
with urllib.request.urlopen(url, timeout=30) as conn:
... | 5,286,722 |
def poly0g_to_poly01(polygon, grid_side):
"""
[0, grid_side] coordinates to [0, 1].
Note: we add 0.5 to the vertices so that the points
lie in the middle of the cell.
"""
result = (polygon.astype(np.float32) + 0.5) / grid_side
return result | 5,286,723 |
def image_loader(path):
"""Image Loader helper function."""
return Image.open(path.rstrip("\n")).convert('RGB') | 5,286,724 |
def main():
"""Generate an automated test case."""
print('Reading and shuffling names...')
males = read_names('Test/male-names.txt')
females = read_names('Test/female-names.txt')
assert len(males) == len(females)
preferences = construct_pref(males, females)
print('Writing json to file...')
... | 5,286,725 |
async def pbal(ctx):
"""Find out how much money you have"""
id = str(ctx.message.author.id)
if id in amounts and pickels:
await ctx.send("```You have " + str(pickels[id]) +" in the frige.```")
else:
await ctx.send("```You do not have an account```") | 5,286,726 |
def retrieve_item(item_id):
"""
This is a stubbed method of retrieving a resource. It doesn't actually do anything.
"""
return {
"id": item_id,
"brand_name": "Clean Breathing",
"name": "Air Purifier",
"weight": 12.3,
} | 5,286,727 |
def max_drop_in_simulated_observation(
event_duration: int,
observation_size: int,
noise_sigma: float,
corr_array: np.ndarray) -> float:
"""Returns the maximum drop from a simulated observation.
An observation consisting only of correlated gaussian noise is
created and exhau... | 5,286,728 |
def tau_of_N(microns, column, v0=0, temperature=20, width=1.0, velocity=0.0, orthopara=3):
"""
Return the optical depth of an H2 line as a function of wavelength...
(absorption)
"""
grounden = h2level_energy(0,0)
alllevelpop = np.sum([exp(-(h2level_energy(v,j)-grounden)/(k*temperature)) for v in... | 5,286,729 |
def witness_dag_from_root(root, xsys, get_links=lambda y: map(lambda e: set({e}), y), strict=False):
"""Builds the witness DAG as in Englert (2014) from a sequence of 2-opt steps"""
# add a node for each edge in the initial tour with arbitrary timestamp {1,..,n}
_, y = xsys[root]
links = [find_next_li... | 5,286,730 |
def add_to_startup(file_path: str):
"""file_path を、PC立ち上げ時に実行するように設定
もしファイルパスを指定しなければ、このファイルを登録
# TODO: venv=Trueなら仮想環境を立ち上げてから実行
"""
import getpass
USER_NAME = getpass.getuser()
assert os.path.exists(file_path), "指定されたfile_pathがありません: " + file_path
abs_file_path = os.path.abspath(file... | 5,286,731 |
def create_instance(test_id, config, args):
"""
Invoked by TestExecutor class to create a test instance
@test_id - test index number
@config - test parameters from, config
@args - command line args
"""
return TestPeerReachability(test_id, config, args) | 5,286,732 |
def get_graphs_np(graphs: GraphsTuple, indices=List[int]) -> GraphsTuple:
"""Gets a new graphstuple (numpy) based on a list of indices."""
node_indices = np.insert(np.cumsum(graphs.n_node), 0, 0)
node_slice = np.concatenate(
[np.arange(node_indices[i], node_indices[i + 1]) for i in indices])
nod... | 5,286,733 |
def one_hot(Y, C):
"""
:param Y: -- shape of (1, number of examples)
:param C: -- number of classes of Y
:return:
Y_oh -- shape of (C, number of examples)
"""
m = Y.shape[1]
Y_oh = np.zeros((C, m))
for i in range(m):
Y_oh[Y[0,i],i] = 1
return Y_oh | 5,286,734 |
def parse_input_data(input_data, hdu_in=None):
"""
Parse input data to return a Numpy array and WCS object.
"""
if isinstance(input_data, six.string_types):
return parse_input_data(fits.open(input_data), hdu_in=hdu_in)
elif isinstance(input_data, HDUList):
if len(input_data) > 1 and... | 5,286,735 |
def _plotlyGraphCore(data: GraphData, title, legend):
"""Internal function for plotly graphing, users should call plotlyGraph() instead"""
try:
import plotly.express as px
except ImportError:
raise ImportError("Plotly is required to use this graph. Install with `pip install plotly`")
... | 5,286,736 |
def alg_to_song(algorithm, num_qubits=None,
num_samples=40, mapping=maps.default_map,
name="alg", tempo=100):
"""
Make a song from an algorithm. Markovian sample the algorithm, then map
to a Song object.
algorithm: list of Gate objects and/or string gates. E... | 5,286,737 |
def encode_categorical_data_with_vocabulary(
train_data: np.ndarray,
test_data: Optional[np.ndarray] = None,
unknown_item_idx: int = 0,
) -> tuple[np.ndarray, Optional[np.ndarray], list[Any]]:
"""Encode the categorical data by using vocabulary mapping.
Args:
train_data: The series (or array... | 5,286,738 |
def filter_sides(segmentation):
"""Remove hedges on left and right hand side.
Also remove anything from the edge of the hedge
to the closest edge of the image.
"""
ydim, xdim = segmentation.shape
mid_point = xdim // 2
for i in segmentation.identifiers:
region = segmentation.region_b... | 5,286,739 |
def log_file_name(extension):
"""
Create a file name in the logfiles directory, based on current data and time
Requires the computer to have an RTC or synched clock
"""
now = datetime.now()
# Linux
file_name = '%0.4d%0.2d%0.2d-%0.2d%0.2d%0.2d' % (now.year, now.month, now.day, now.hour, now.m... | 5,286,740 |
def generate_transactions(
num_transactions, unique_items, items_row=(1, 100), seed=None
):
"""
Generate synthetic transactions.
"""
if seed:
random.seed(seed)
else:
random.seed()
items = list(range(unique_items))
for _ in range(num_transactions):
items_this_row... | 5,286,741 |
def test_setup_optimizer_kwargs_warns(data_fixture):
"""Ensures a warning is emitted if extra keyword arguments are passed to the setup."""
x, y = data_fixture
with pytest.warns(DeprecationWarning):
_algorithm_setup._setup_optimizer(y, 'asls', [whittaker], None, True, x_data=x) | 5,286,742 |
def arc(data: bytes) -> int:
"""
Compute a CRC-16 checksum of data with the arc algorithm.
:param bytes data: The data to be computed
:return: The checksum
:rtype: int
:raises TypeError: if the data is not a bytes-like object
"""
_ensure_bytes(data)
return _crc_16_arc(data) | 5,286,743 |
def main():
"""
This code, which must run on the ROBOT:
1. Constructs a robot, an MQTT SENDER, and a DELEGATE to respond
to messages FROM the LAPTOP sent TO the ROBOT via MQTT.
2. Stays in an infinite loop while a listener (for MQTT messages)
runs in the background, "delegating... | 5,286,744 |
def check_replication(master_vals, slave_vals, options):
"""Check replication among a master and a slave.
master_vals[in] Master connection in form: user:passwd@host:port:socket
or login-path:port:socket
slave_vals[in] Slave connection in form user:passwd@host:port:socket
... | 5,286,745 |
def _incremental_mean_and_var(X, last_mean, last_variance, last_sample_count):
"""
Note. Most of this script is taken from scikit-learn, except for the last line.
--- Original doc ---
Calculate mean update and a Youngs and Cramer variance update.
last_mean and last_variance are statistics compute... | 5,286,746 |
def _calculate_expected_result(
dist_per_cell, numeric_values, numeric_values_scale, input_mask_float, logits_aggregation, config
):
"""
Calculates the expected result given cell and aggregation probabilities.
Args:
dist_per_cell (`tfp.distributions.Bernoulli`):
Cell selection distr... | 5,286,747 |
def fit_unbinned(f_likelihood, data, start_guess, min_method=None, bounds=None):
"""
unbinned max likelihood fit to data with given likelihood func
"""
if method is None:
method="L-BFGS-B" # minimization method, see docs
result = minimize(
neg_log_like, # function to minimize
... | 5,286,748 |
def load_data(n_pca=3):
"""Data Loader
:param n_pca: number of pca components, defaults to 3
:type n_pca: int, optional
"""
path = f'../dataRBC/RBC_r28L_T100R100_pca{n_pca}_enc_data.txt.gz'
traj_data = pd.read_csv(path, header=None).values
traj_data = traj_data.reshape(-1, 200, n_pca)
... | 5,286,749 |
def load_object(fname,zip=0,nofind=0,verbose=0):
"""Loads an object from disk. By default, this handles zipped files
and searches in the usual places for OCRopus. It also handles some
class names that have changed."""
if not nofind:
fname = ocropus_find_file(fname)
if verbose:
print(... | 5,286,750 |
def _viz_sites_and_gauss_partition():
""" function to:
(1) demonstrate site tags
(2) give information about Gaussian function
"""
exmpl = ['vac_refs/'+f for f in ['Cu111_0H2O_01', 'Cu211_0H2O_01']]
for f in exmpl:
surface = tuple([int(e) for e in f.split('/')[-1].split('_')[0][2:... | 5,286,751 |
def delete_attachment(self, request, form):
""" Delete a notice attachment. """
layout = Layout(self, request)
notice = self.linked_official_notices[0]
if notice.state == 'accepted' or notice.state == 'published':
if not request.is_secret(self):
request.message(
_("... | 5,286,752 |
def geoloc(ip_address: str) -> dict:
""" Return {'lat':, 'lon':} values for {ip_address} """
ip_details = method_ipinfo(ip_address)
return {'lat': ip_details['latitude'], 'lon': ip_details['longitude']} | 5,286,753 |
def TreeImportanceArray(reg):
"""Get important array if `reg` is tree regression."""
return reg.feature_importances_ | 5,286,754 |
def _get_test_stats_with_mi(feature_names):
"""Get stats proto for MI test."""
result = statistics_pb2.DatasetFeatureStatistics()
for feature_name in feature_names:
feature_proto = text_format.Parse(
"""
custom_stats {
name: "max_sklearn_adjusted_mutual_information"
... | 5,286,755 |
def date_range(start: Literal["20130101"], periods: int, tz: Literal["US/Eastern"]):
"""
usage.dask: 2
usage.xarray: 1
"""
... | 5,286,756 |
def test_children_of_tree(ktree_four_nodes):
"""Checks different parts of nodes ."""
assert ktree_four_nodes.root.val == 1
assert ktree_four_nodes.root.children[0].val == 2
assert ktree_four_nodes.root.children[1].val == 3
assert ktree_four_nodes.root.children[2].val == 4
assert ktree_four_nodes... | 5,286,757 |
def ride(self: Client, riders_or_rides: str) -> RideProxy:
"""Delegates to a
:py:class:`mcipc.rcon.be.commands.ride.RideProxy`
"""
return RideProxy(self, 'ride', riders_or_rides) | 5,286,758 |
def process_data(event_id, st, sampling_rate, pre_filt=(1.2, 2, 8, 10), water_level=100,
folder_name="default_folder", save_processed=True):
"""
Function to process the raw data stream
Args:
event_id (str): Event ID -> Ideally should be time stamp YYYY-MM-DDTHH:MM:SS.000
st ... | 5,286,759 |
def _check_headers(headers: Any) -> Dict:
"""Check headers format an validate content type.
:param headers: configured headers
:return Dict: request headers
"""
if headers is None:
headers = {}
if 'Content-Type' not in headers.keys():
headers['Content-Type'] = 'application/jso... | 5,286,760 |
def average_test_disorder(data, test_classifier, target_classifier):
"""Given a list of points, a feature-test Classifier, and a Classifier
for determining the true classification of each point, computes and returns
the disorder of the feature-test stump."""
test_disorder = 0
test_classifications = ... | 5,286,761 |
def test_snippets() -> bool:
"""Test all code snippets in *.snip files."""
here = os.getcwd()
fixture = CompilerFixture()
fail = False
for i in glob.glob(here + "/*.snip"):
print("=" * 20)
print(i)
try:
fixture.run_file(i)
except Exception as e:
... | 5,286,762 |
def seed_initial_offsets_peaks(y, noise, rect_area=500, prominence_knockdown_factor=0.03):
"""
Generate the locations of the seeds for the initial fit. Place a seed at each of the peaks.
Determine peak location from smoothed version of signal. Smooth signal by cross correlating it with rect.
Args:
... | 5,286,763 |
def ReadNetString(fp):
"""Reads a net string from the File object fp, returning the string in
unicode.
A net string has the format <len>:<str>,
where <len> is decimal of the length of <str>, and comma ends the string.
Returns:
The unicode string contained in the netstring, or '' if... | 5,286,764 |
def to_str(obj):
"""Attempts to convert given object to a string object
"""
if not isinstance(obj, str) and PY3 and isinstance(obj, bytes):
obj = obj.decode('utf-8')
return obj if isinstance(obj, string_types) else str(obj) | 5,286,765 |
def get_middle_value(my_list):
"""Return the middle value from a list after sorting.
:param list my_list: List of sortable values"""
return sorted(my_list)[len(my_list) // 2]
"""Convert an integer resolution in base-pairs to a nicely formatted string.
:param int window_size: Integer resolution ... | 5,286,766 |
def ll2m(lat, lon):
"""Lat/lon to meters"""
x = lon * 20037508.34 / 180.0
y = math.log(math.tan((90.0 + lat) *
math.pi / 360.0)) / (math.pi / 180.0)
y = y * 20037508.34 / 180
return (x, y) | 5,286,767 |
def write_graph(graph, file_obj):
"""Write the graph in graphml format to the file.
Note that we use graphml format because it's the only one I could find that
preserves all the graph and vertex attributes.
You can write multiple graphs to the same file and graph_reader will do the
work to split things for ... | 5,286,768 |
def bilinterp(x, y, nx_tuple, ny_tuple, x_tuple, y_tuple, fxy):
"""
Bilinear interpolation: Given nx-tuple + 1 x-points,
ny-tuple + 1 y-points, x_tuple and y_tuple,
routine finds f(x, y) = fxy at (x, y) in (x_tuple, y_tuple).
Assumes x_tuple and y_tuple are increasing arrays.
"""... | 5,286,769 |
def get_version():
"""Return version of the dynamic link library.
Wraps:
int DWGetVersion();"""
return _get_version() | 5,286,770 |
def edu_plotter(func):
"""Decorator to apply to all plotting functions in OGGM-Edu.
Parameters
----------
func : function
the function or method to decorate
Returns
-------
the decorated function
"""
@wraps(func)
def context_wrapper(
*args,
sns_context=... | 5,286,771 |
def test_create_flag_and_retrieve_if_in(db):
"""Create a User object."""
db.bind({User})
users = []
for member in Access:
if member is Access.INVALID:
continue
users.append(User.repository.create(name="me", access=member))
# Retrieve the ones with the READ flag.
db... | 5,286,772 |
def load_sample_data(name):
"""
Load an example dataset from the GMT server.
The data are downloaded to a cache directory (usually ``~/.gmt/cache``) the
first time you invoke this function. Afterwards, it will load the data from
the cache. So you'll need an internet connection the first time around... | 5,286,773 |
def rip_svgi(content: str, embed_styles: bool = False) -> str:
"""
Rips SVG content (single diagram) and scripts for interaction out of HTML
:param content: HTML page content in text format
:param embed_styles: If specified as True then mentioned styles would be downloaded and embedded into SVG
... | 5,286,774 |
async def ungban(un_gban):
""" .ungban """
#
chat = await un_gban.get_chat()
admin = chat.admin_rights
creator = chat.creator
#
if not admin and not creator:
await un_gban.edit(NO_ADMIN)
return
#
try:
from userbot.modules.sql_helper.gban_sql import ungba... | 5,286,775 |
def get_info(request):
"""
Obtiene
"""
info = "Backend"
if UserToken.get_headquar_id(request.session):
try:
sede = Headquar.objects.get(
id=UserToken.get_headquar_id(request.session))
info = "%s-%s" % (sede.enterprise.name, sede.name)
except:... | 5,286,776 |
def prune_by_lbh(seq_list: list, seq_length: int, q: Sequence, kim_reduction: float = 0.75,
keogh_reduction: float = 0.25):
"""
Prune the sequences based on LB_Kim and LB_Keogh lower bound. First the sequences are pruned using LB_Kim
reduction factor and then using LB_Keogh reduction factor... | 5,286,777 |
def keyDataIdsInit():
"""
Initializes the key data klasses. This function is called from the init
function and the application should not call it directly.
Returns : 0 on success or a negative value if an error occurs.
"""
return xmlsecmod.keyDataIdsInit() | 5,286,778 |
def cli(drivername, mfname, devicetype, author):
""" Create sal driver staging from template """
templatedir = os.path.join(scriptdir, templates[devicetype][0])
destdir = os.path.join(scriptdir, "../../", templates[devicetype][1], drivername)
destdir = os.path.abspath(destdir)
if os.path.isdir(dest... | 5,286,779 |
def derive_awarding_agency_data(obj, sub_tier_dict, office_dict):
""" Deriving awarding sub tier agency name, awarding agency name, and awarding agency code
Args:
obj: a dictionary containing the details we need to derive from and to
sub_tier_dict: a dictionary containing all the da... | 5,286,780 |
def _image_to_ground_plane_perform(r_tgt_coa, r_dot_tgt_coa, arp_coa, varp_coa, gref, uZ):
"""
Parameters
----------
r_tgt_coa : numpy.ndarray
r_dot_tgt_coa : numpy.ndarray
arp_coa : numpy.ndarray
varp_coa : numpy.ndarray
gref : numpy.ndarray
uZ : numpy.ndarray
Returns
----... | 5,286,781 |
def encode_string_text(text):
"""Replace special symbols with corresponding entities or magicwords."""
text = text.replace("<", "<")
text = text.replace(">", ">")
text = text.replace("[", "[")
text = text.replace("]", "]")
text = text.replace("{", "{")
text = text.replace(... | 5,286,782 |
def compute_input_planes(input_channels, merging_strategy, inputs, abs_nodes):
"""Compute the number of input planes."""
if len(inputs) == 0: # this is an input node
return input_channels
inplanes = 0
for i in inputs:
if merging_strategy == EdgeMerge.CAT:
inplanes += abs_nod... | 5,286,783 |
def test_01_setup():
"""
sample init init attr, state, action space
:return:
"""
names = ['gender', 'age']
vals = {'gender': ['M', 'F', 'U'],
'age': ['0-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-*']}
attr_set = AttrSet(names, vals)
state_set = StateSet(['date', '... | 5,286,784 |
def run_all_simulations(material, config):
"""Simulate helium void fraction, gas loading, and surface area.
Args:
material (sqlalchemy.orm.query.Query): material to be analyzed.
Depending on properties specified in config, adds simulated data for helium
void fraction, gas loading, heat of adso... | 5,286,785 |
async def test_state_without_turnon(hass, remote):
"""Test for state property."""
await setup_samsungtv(hass, MOCK_CONFIG_NOTURNON)
assert await hass.services.async_call(
DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID_NOTURNON}, True
)
state = hass.states.get(ENTITY_ID_NOTURNON)
a... | 5,286,786 |
def make_aware(value, timezone=None):
"""
Make a naive datetime.datetime in a given time zone aware.
:param value: datetime
:param timezone: timezone
:return: localized datetime in settings.TIMEZONE or timezone
"""
if timezone is None:
timezone = TIMEZONE
# Check that we won't... | 5,286,787 |
def parse_reflections_array(array: np.array) -> Tuple:
"""
Helper method for parsing reflections without exporting to ".CSV"
Parse an reflection array of GSASII defined as:
index explanation
0,1,2 h,k,l (float)
3 (int) multiplicity
4 (float) d-space, Å
5 (float) pos, two-theta
6 (fl... | 5,286,788 |
def log(txt):
"""Logs messages to a log file if WSGI_LOG env var is defined."""
log_file = os.environ.get('WSGI_LOG')
if log_file:
with open(log_file, 'a+', encoding='utf-8') as f:
txt = txt.replace('\r\n', '\n')
f.write('%s: %s%s' % (datetime.datetime.now(), txt, '' if... | 5,286,789 |
def get_dbconn(db_dsn):
"""Connects to the MongoDB server and returns a database handler."""
def _ensure_indexes(db):
"""
Ensures that an index exists on specified collections.
Definitions:
index_by_collection = {
'collection_name': [
('field_name_1'... | 5,286,790 |
def _params_to_ints(qs):
"""Convert a (string) list of string ids to a list of integers"""
return [int(str_id) for str_id in qs.split(',')] | 5,286,791 |
def _prepare_hyperparams(free_hyperparams: typing.Sequence, hyperparameter_values: typing.Dict) -> typing.Tuple[typing.Sequence, typing.Set[str]]:
"""
Values in ``hyperparameter_values`` should be serialized as JSON, as obtained by JSON-serializing
the output of hyper-parameter's ``value_to_json_structure``... | 5,286,792 |
def est_croissante2(l : List[float]) -> bool:
""" ... cf. ci-dessus ...
"""
# Résultat
b : bool = True
# Indice courant
i : int = 0
while (i < len(l) - 1) and b:
b = l[i] < l[i + 1]
i = i + 1
return b | 5,286,793 |
def compose(f, g):
"""
Compose two filter f and g.
:param f: Outer filter function.
:type f: filter function.
:param g: Inner filter function.
:type g: filter function.
:return: lambda x: f(g(x))
:rtype: filter function.
"""
def filter_fn(df):
df = g(df)
if len... | 5,286,794 |
def Device(device_name):
"""Returns the taurus device for the given device name
It is a shortcut to::
import taurus.core.taurusmanager
manager = taurus.core.taurusmanager.TaurusManager()
factory = manager.getFactory()
device = factory.getDevice(device_name)
:param device_... | 5,286,795 |
def write(obj, data=None, **kwargs):
"""Write a value in to loader source
:param obj: settings object
:param data: vars to be stored
:param kwargs: vars to be stored
:return:
"""
if obj.VAULT_ENABLED_FOR_DYNACONF is False:
raise RuntimeError(
"Vault is not configured \n"... | 5,286,796 |
def show_random_elements(dataset, num_examples=10):
"""Show random elements from a dataset.
Args:
dataset (datasets.Dataset): The dataset from which examples
have to be sampled.
num_examples (int, optional): The number of examples to be sampled.
... | 5,286,797 |
def load_data(self, name):
"""Load data given a data path.
This is a low level method that will search through the various
search paths until it's able to load a value. This is typically
only needed to load *non* model files (such as _endpoints and
_retry). If you need to load model files, you sho... | 5,286,798 |
def stop_list_to_link_list(stop_list):
"""
[a, b, c, d] -> [(a,b), (b,c), (c,d)]
"""
return list(zip(stop_list[:-1], stop_list[1:])) | 5,286,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.