content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import argparse
def handle_program_options():
"""
Uses the built-in argparse module to handle command-line options for the
program.
:return: The gathered command-line options specified by the user
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(description="Convert Sa... | 288a21889d97bb01622c1dd113646f99f7a73559 | 3,647,200 |
def start_v_imp(model, lval: str, rval: str):
"""
Calculate starting value for parameter in data given data in model.
For Imputer -- just copies values from original data.
Parameters
----------
model : Model
Model instance.
lval : str
L-value name.
rval : str
R-v... | 113266955e5115b0eb43d32feaa506a2b0c93e14 | 3,647,201 |
def get_image_features(X, y, appearance_dim=32):
"""Return features for every object in the array.
Args:
X (np.array): a 3D numpy array of raw data of shape (x, y, c).
y (np.array): a 3D numpy array of integer labels of shape (x, y, 1).
appearance_dim (int): The resized shape of the app... | fa5cb730227b20b54b8d25270550c9dae9fc1348 | 3,647,202 |
def deactivate_text(shell: dict, env_vars: dict) -> str:
"""Returns the formatted text to write to the deactivation script
based on the passed dictionaries."""
lines = [shell["shebang"]]
for k in env_vars.keys():
lines.append(shell["deactivate"].format(k))
return "\n".join(lines) | 0a75134a55bf9cd8eceb311c48a5547ad373593d | 3,647,203 |
from typing import get_origin
def is_dict(etype) -> bool:
""" Determine whether etype is a Dict """
return get_origin(etype) is dict or etype is dict | a65af54bf6b24c94906765c895c899b18bf5c1eb | 3,647,204 |
import scipy
def t_plot_parameters(thickness_curve, section, loading, molar_mass, liquid_density):
"""Calculates the parameters from a linear section of the t-plot."""
slope, intercept, corr_coef, p, stderr = scipy.stats.linregress(
thickness_curve[section],
loading[section])
# Check if ... | 46d2f65cac5a424b2054359dc8b083d3a2138cc6 | 3,647,205 |
import requests
def get_data(stock, start_date):
"""Fetch a maximum of the 100 most recent records for a given
stock starting at the start_date.
Args:
stock (string): Stock Ticker
start_date (int): UNIX date time
"""
# Build the query string
request_url = f"https://api.pushs... | aafdc913d80346e82a21767cdb7b5e40f2376857 | 3,647,206 |
def depart_people(state, goal):
"""Departs all passengers that can depart on this floor"""
departures = []
for departure in state.destin.items():
passenger = departure[0]
if passenger in goal.served and goal.served[passenger]:
floor = departure[1]
if state.lift_at == ... | f3a18ad9a6f884a57d0be1d0e27b3dfeeb95d736 | 3,647,207 |
def get_topic_for_subscribe():
"""
return the topic string used to subscribe for receiving future responses from DPS
"""
return _get_topic_base() + "res/#" | 346841c7a11f569a7309b087baf0d621a63b8ae9 | 3,647,208 |
from Crypto import Random
def generate_AES_key(bytes = 32):
"""Generates a new AES key
Parameters
----------
bytes : int
number of bytes in key
Returns
-------
key : bytes
"""
try:
return Random.get_random_bytes(bytes)
except ImportError:
print('PyCryp... | 4435aeea860bb3bca847156de0626c2cacde93e0 | 3,647,209 |
def remove_deploy_networkIPv6_configuration(user, networkipv6, equipment_list):
"""Loads template for removing Network IPv6 equipment configuration, creates file and
apply config.
Args: NetworkIPv6 object
Equipamento objects list
Returns: List with status of equipments output
"""
data = d... | eb0d33cbc4b3963388a768f9ce0a950c3b66cbe0 | 3,647,210 |
import os
import argparse
def extant_file(x):
"""
'Type' for argparse - checks that file exists but does not open.
Parameters
----------
x : str
Candidate file path
Returns
-------
str
Validated path
"""
if not os.path.isfile(x):
# ArgumentTypeError ... | 3b54d821d020c00e566460b95daeb037406becb9 | 3,647,211 |
def can_pay_with_two_coins(denoms, amount):
""" (list of int, int) -> bool
Return True if and only if it is possible to form amount, which is a
number of cents, using exactly two coins, which can be of any of the
denominations in denoms.
>>> can_pay_with_two_coins([1, 5, 10, 25], 35)
True
... | c0634d22095480d1a010f763d646453dc08d4476 | 3,647,212 |
def make_column_kernelizer(*transformers, **kwargs):
"""Construct a ColumnKernelizer from the given transformers.
This is a shorthand for the ColumnKernelizer constructor; it does not
require, and does not permit, naming the transformers. Instead, they will
be given names automatically based on their t... | cfddec675782a6e70d1921372961abbb7853fa09 | 3,647,213 |
def plugin_info():
""" Returns information about the plugin.
Args:
Returns:
dict: plugin information
Raises:
"""
return {
'name': 'PT100 Poll Plugin',
'version': '1.9.2',
'mode': 'poll',
'type': 'south',
'interface': '1.0',
'config': _DEF... | f6d54b5ff64013ae17364db604cf1cb6b5204aba | 3,647,214 |
def get_engine(isolation_level=None):
"""
Creates an engine with the given isolation level.
"""
# creates a shallow copy with the given isolation level
if not isolation_level:
return _get_base_engine()
else:
return _get_base_engine().execution_options(isolation_level=isolation_le... | 32e055b2a4a1d0e7ecbc591218bb61c721113a09 | 3,647,215 |
from selenium.webdriver import PhantomJS
def phantomjs_driver(capabilities, driver_path, port):
"""
Overrides default `phantomjs_driver` driver from pytest-selenium.
Default implementation uses ephemeral ports just as our tests but
it doesn't provide any way to configure them, for this reason we basi... | 5c6453f4d753cd765fa7c9fff47b61c6c6efac04 | 3,647,216 |
import numpy
def to_TH1x(
fName,
fTitle,
data,
fEntries,
fTsumw,
fTsumw2,
fTsumwx,
fTsumwx2,
fSumw2,
fXaxis,
fYaxis=None,
fZaxis=None,
fNcells=None,
fBarOffset=0,
fBarWidth=1000,
fMaximum=-1111.0,
fMinimum=-1111.0,
fNormFactor=0.0,
fContour=N... | c268c6f7ea7e875bb1049940cac45bdec48afdcb | 3,647,217 |
import argparse
import textwrap
def parse_args():
"""
Parse and validate the command line arguments, and set the defaults.
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
description='Utility commands for handle.net EPIC persistent identifiers')
... | e639098ac7e629a4a78c3c1242bcc9f785186b7c | 3,647,218 |
import time
def parse(address, addr_spec_only=False, strict=False, metrics=False):
"""
Given a string, returns a scalar object representing a single full
mailbox (display name and addr-spec), addr-spec, or a url.
If parsing the entire string fails and strict is not set to True, fall back
to tryin... | b6516d530892a7db405b816987598ce53a0dc776 | 3,647,219 |
import requests
def unfreeze_file(user, data):
""" unfreeze a file.
:return: status code, response data
"""
r = requests.post('%s/unfreeze' % URL, json=data, auth=(user, PASS), verify=False)
return r.status_code, r.json() | 4ee59dd44f42685a02907dec766dc8026f939da2 | 3,647,220 |
def prompt_url(q):
"""
:param q: The prompt to display to the user
:return: The user's normalized input. We ensure there is an URL scheme, a domain, a "/" path,
and no trailing elements.
:rtype: str
"""
return prompt(q, _url_coerce_fn) | dfe810a4552c880d71efabffb2f9167bfce0ad8a | 3,647,221 |
def eval_mnl_logsums(choosers, spec, locals_d, trace_label=None):
"""
like eval_nl except return logsums instead of making choices
Returns
-------
logsums : pandas.Series
Index will be that of `choosers`, values will be
logsum across spec column values
"""
trace_label = tra... | d9b00c2f5f436a0825cbe3bdd60c6b2257c769b3 | 3,647,222 |
def find_zeroed_indices(adjusted, original):
"""Find the indices of the values present in ``original`` but missing in ``adjusted``.
Parameters
----------
adjusted: np.array
original: array_like
Returns
-------
Tuple[np.ndarray]
Indices of the values present in ``original`` but ... | c01b91ec8be0d1bc22aad9042328a451b7424996 | 3,647,223 |
def inventory_update(arr1, arr2):
"""Add the inventory from arr2 to arr1.
If an item exists in both arr1 and arr2, then
the quantity of the item is updated in arr1.
If an item exists in only arr2, then the item
is added to arr1. If an item only exists in
arr1, then that item remains unaffected.... | febba1d2dac6c79fabf4e8aaad8c0fd482478b50 | 3,647,224 |
import re
from bs4 import BeautifulSoup
def racaty(url: str) -> str:
""" Racaty direct link generator
based on https://github.com/SlamDevs/slam-mirrorbot"""
dl_url = ''
try:
link = re.findall(r'\bhttps?://.*racaty\.net\S+', url)[0]
except IndexError:
raise DirectDownloadLinkExcepti... | 8c0df1dd9bf96fcb63be7f59db20ae6c9e4cef00 | 3,647,225 |
import logging
import os
import types
def get_logger(
name='mltk',
level='INFO',
console=False,
log_file=None,
log_file_mode='w',
parent:logging.Logger=None
):
"""Get or create a logger, optionally adding a console and/or file handler"""
logger = logging.getLogger(name)
if len(... | f4126c317ddda806354505ea7defa23686084f2a | 3,647,226 |
from typing import Tuple
from typing import List
import argparse
import sys
def _parse_cli_args() -> Tuple[str, List[str]]:
"""Parses CLI args to return device name and args for unittest runner."""
parser = argparse.ArgumentParser(
description="Runs a GDM + unittest reboot test on a device. All "
... | 07b2b8c8223f789fca2099f432afede7aee3ef78 | 3,647,227 |
from typing import List
def build_tree(tree, parent, counts, ordered_ids):
"""
Recursively splits the data, which contained in the tree object itself
and is indexed by ordered_ids.
Parameters
----------
tree: Tree object
parent: TreeNode object
The last... | 8957ef481ef6b2ba02b6e60c97165a25231d89ae | 3,647,228 |
def get_perf_measure_by_group(aif_metric, metric_name):
"""Get performance measures by group."""
perf_measures = ['TPR', 'TNR', 'FPR', 'FNR', 'PPV', 'NPV', 'FDR', 'FOR', 'ACC']
func_dict = {
'selection_rate': lambda x: aif_metric.selection_rate(privileged=x),
'precision': lambda x: aif_metr... | d4b861c882d6f5502798d211c2ab1322e19cf9b2 | 3,647,229 |
from datetime import datetime
def hello_world(request):
"""Return a greeting."""
return HttpResponse('Hello, world!{now}'.format(
now=datetime.now().strftime('%b %dth, %Y : %M HttpResponses')
)) | bcdf4c504d44883c7afc75c8a76ff052cd0b246d | 3,647,230 |
import mimetypes
import zlib
def getfile(id, name):
"""
Retorna um arquivo em anexo.
"""
mime = mimetypes.guess_type(name)[0]
if mime is None:
mime = "application/octet-stream"
c = get_cursor()
c.execute(
"""
select files.ticket_id as ticket_id,
files.si... | 1ce8322301b33a0d6762aa545344d4c0fe38269c | 3,647,231 |
def get_default_wavelet():
"""Sets the default wavelet to be used for scaleograms"""
global DEFAULT_WAVELET
return DEFAULT_WAVELET | 0c403b5b7a21bedbd55c0cbd6faa6a3648c3a0cc | 3,647,232 |
def check_output(file_path: str) -> bool:
"""
This function checks an output file, either from geomeTRIC or
from Psi4, for a successful completion keyword. Returns
True if the calculation finished successfully, otherwise
False.
"""
with open(file_path, "r") as read_file:
text = read_... | 2f0dea67216aff945b1b0db74e0131022acc3019 | 3,647,233 |
def dumps(value):
"""
Dumps a data structure to TOML source code.
The given value must be either a dict of dict values, a dict,
or a TOML file constructed by this module.
"""
if not isinstance(value, TOMLFile):
raise RuntimeError(
'Can only dump a TOMLFile instance loaded by... | f92b906b502bc2b0ba2b8bf3840083bafce14086 | 3,647,234 |
def calc_graph(dict_graph):
"""
creates scatter of comfort and curves of constant relative humidity
:param dict_graph: contains comfort conditions to plot, output of comfort_chart.calc_data()
:type dict_graph: dict
:return: traces of scatter plot of 4 comfort conditions
:rtype: list of plotly.g... | 19a277db0f59e2b871130099eab3b714bd5b94b9 | 3,647,235 |
import sys
def index():
"""Display a user's account information."""
if not current_user.is_authenticated:
return redirect(url_for("account.login"))
cancel_reservation_form = CancelReservationForm()
if cancel_reservation_form.validate_on_submit():
cancel_id = int(cancel_reservation_f... | 12784a21c3229102c450dd6612bd10f45e7643bd | 3,647,236 |
def generate_arrays(df, resize=True, img_height=50, img_width=200):
""" Generates image array and labels array from a dataframe """
num_items = len(df)
images = np.zeros((num_items, img_height, img_width), dtype=np.float32)
labels = [0] * num_items
for i in range(num_items):
input_... | 2a50fd84d5b8da2845205b65cd12f61868bd421d | 3,647,237 |
def compute_cosine_distance(Q, feats, names):
"""
feats and Q: L2-normalize, n*d
"""
dists = np.dot(Q, feats.T)
# print("dists:",dists)
# exit(1)
idxs = np.argsort(dists)[::-1]
rank_dists = dists[idxs]
rank_names = [names[k] for k in idxs]
return (idxs, rank_dists, rank_n... | e15007fb6fc73aab27db00d7cf283300077dd1c7 | 3,647,238 |
def phase(ifc, inc_pt, d_in, normal, z_dir, wvl, n_in, n_out):
""" apply phase shift to incoming direction, d_in, about normal """
try:
d_out, dW = ifc.phase(inc_pt, d_in, normal, z_dir, wvl, n_in, n_out)
return d_out, dW
except ValueError:
raise TraceEvanescentRayError(ifc, inc_pt, ... | 6289674f20718ed4e1e78b1a4da0fe5d4b89df75 | 3,647,239 |
from typing import Iterator
def generate_udf(spec: "rikai.spark.sql.codegen.base.ModelSpec"):
"""Construct a UDF to run sklearn model.
Parameters
----------
spec : ModelSpec
the model specifications object
Returns
-------
A Spark Pandas UDF.
"""
def predict(model, X):
... | ceab18240abc73c361108b859817723c08bdd0e3 | 3,647,240 |
def ssl_loss_mean_teacher(labels_x, logits_x, logits_teacher, logits_student):
"""
Computes two cross entropy losses based on the labeled and unlabeled data.
loss_x is referring to the labeled CE loss and loss_u to the unlabeled CE loss.
Args:
labels_x: tensor, contains labels correspondi... | 016192ea6cf1002a0aa8735003e76a7c2af7526c | 3,647,241 |
from typing import Tuple
def _sch_el(self, *wert, **kwargs):
"""Element einer Schar; für einen Parameter"""
if kwargs.get('h'):
print("\nElement einer Schar von Matrizen\n")
print("Aufruf matrix . sch_el( wert )\n")
print(" matrix Matrix")
... | 8e88e04ee6e4f1b4be658c120a1bc66060aafc81 | 3,647,242 |
import os
def check_directory(path, read=False, write=False, execute=False):
"""Does that path exist and can the current user rwx."""
if os.path.isdir(path) and check_mode(path, read=read, write=write, execute=execute):
return True
else:
return False | cbfdaed4b33a47c040829404edca39ff1aed36a2 | 3,647,243 |
def scsilun_to_int(lun):
"""
There are two style lun number, one's decimal value is <256 and the other
is full as 16 hex digit. According to T10 SAM, the full 16 hex digit
should be swapped and converted into decimal.
For example, SC got zlinux lun number from DS8K API, '40294018'. And it
should... | 2022938ccb5abbc89d5fb6f5f109d629e980c0ba | 3,647,244 |
def ordered_indices(src_sizes,tgt_sizes,common_seed,shuffle=True,buckets=None):
"""Return an ordered list of indices. Batches will be constructed based
on this order."""
if shuffle:
indices = np.random.RandomState(common_seed).permutation(len(src_sizes)).astype(np.int64)
else:
indices = ... | 469d7f963134d7df9c72be07182e7ba4e2533472 | 3,647,245 |
import io
def get_predictions(single_stream, class_mapping_dict, ip, port, model_name):
"""Gets predictions for a single image using Tensorflow serving
Arguments:
single_stream (dict): A single prodigy stream
class_mapping_dict (dict): with key as int and value as class name
ip (str):... | 631c21878df03c240d32556279d9b31ebc6d723f | 3,647,246 |
import itertools
def interaction_graph(matrix):
"""Create a networkx graph object from a (square) matrix.
Parameters
----------
matrix : numpy.ndarray
| Matrix of mutual information, the information for the edges
is taken from the upper matrix
Returns
-------
graph : ne... | d1da8b6f0e269c1118f56840173e7895d5efb587 | 3,647,247 |
import os
def tags_filter(osm_pbf, dst_fname, expression, overwrite=True):
"""Extract OSM objects based on their tags.
The function reads an input .osm.pbf file and uses `osmium tags-filter`
to extract the relevant objects into an output .osm.pbf file.
Parameters
----------
osm_pbf : str
... | 60fb579bcfccb80dbd66ebb50d8478b4f718b2db | 3,647,248 |
import os
def bound_n_samples_from_env(n_samples: int):
"""Bound number of samples from environment variable.
Uses environment variable `PYPESTO_MAX_N_SAMPLES`.
This is used to speed up testing, while in application it should not
be used.
Parameters
----------
n_samples: Number of sample... | c578a16ab698b5921604100c5f5d04574363b4b8 | 3,647,249 |
import torch
def weight_inter_agg(num_relations, self_feats, neigh_feats, embed_dim, weight, alpha, n, cuda):
"""
Weight inter-relation aggregator
Reference: https://arxiv.org/abs/2002.12307
:param num_relations: number of relations in the graph
:param self_feats: batch nodes features or embedding... | c664bd88fbd8abf30b050ca93c264a3e5ead147b | 3,647,250 |
def ho2ro(ho):
"""Axis angle pair to Rodrigues-Frank vector."""
return Rotation.ax2ro(Rotation.ho2ax(ho)) | be3ce1dd6ac9e0815a4cb50ff922f0816320fcae | 3,647,251 |
def get_ratio(old, new):
# type: (unicode, unicode) -> float
"""Return a "similiarity ratio" (in percent) representing the similarity
between the two strings where 0 is equal and anything above less than equal.
"""
if not all([old, new]):
return VERSIONING_RATIO
if IS_SPEEDUP:
r... | 28648934701445c9066e88b787465ccc21aa6ba5 | 3,647,252 |
def sample2D(F, X, Y, mask=None, undef_value=0.0, outside_value=None):
"""Bilinear sample of a 2D field
*F* : 2D array
*X*, *Y* : position in grid coordinates, scalars or compatible arrays
*mask* : if present must be a 2D matrix with 1 at valid
and zero at non-valid points
*undef_va... | 746782b7712ff28f76db280e9c55977e81a370a5 | 3,647,253 |
import time
def read(file=None, timeout=10, wait=0.2, threshold=32):
"""Return the external temperature.
Keyword arguments:
file -- the path to the 1-wire serial interface file
timeout -- number of seconds without a reading after which to give up
wait -- number of seconds to wait after a failed r... | 93d409c6d2d019ba90bb61a5faa6d2fb761ed8a5 | 3,647,254 |
def rotations_to_radians(rotations):
"""
converts radians to rotations
"""
return np.pi * 2 * rotations | 15beacbccbbe6d22ac4f659aa5cf22a4e63b503e | 3,647,255 |
def _expect_ket(oper, state):
"""Private function to calculate the expectation value of
an operator with respect to a ket.
"""
oper, ket = jnp.asarray(oper), jnp.asarray(state)
return jnp.vdot(jnp.transpose(ket), jnp.dot(oper, ket)) | c7b261852f0e77bda7dcb3cae53939f637e1dca7 | 3,647,256 |
def resnet152(pretrained=False, last_stride=1, model_path=''):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet(pretrained=pretrained... | ad2837271ef98861dc8f2c3eae9687fc71d435b6 | 3,647,257 |
def check_wheel_move_during_closed_loop(data, wheel_gain=None, **_):
""" Check that the wheel moves by approximately 35 degrees during the closed-loop period
on trials where a feedback (error sound or valve) is delivered.
Metric: M = abs(w_resp - w_t0) - threshold_displacement, where w_resp = position at r... | 6b696158a086cf899cc23d207b0c6142f1f50a65 | 3,647,258 |
def next_fast_len(target: int) -> int:
"""
Find the next fast size of input data to `fft`, for zero-padding, etc.
SciPy's FFTPACK has efficient functions for radix {2, 3, 4, 5}, so this
returns the next composite of the prime factors 2, 3, and 5 which is
greater than or equal to `target`. (These ar... | e00aa69ffd425489cceef5f50b77c977e18b4a1f | 3,647,259 |
def human_format(val : int, fmt = '.1f') -> str :
""" convert e.g. 1230 -> 1.23k """
units = ['', 'K', 'M', 'G']
base = min(int(np.floor(np.log10(val)))//3, len(units))
if base==0:
return str(val)
val = val/10**(3*base)
res = ('{{:{}}} {}'.format(fmt, units[base])).format(val)
ret... | 73dfffa4f9afaa2c294ebceeabda4947d3a6cbe1 | 3,647,260 |
def select_or_insert(conn, table, id_name, payload, name=None, multi=False, insert=True):
""" Prepare the SQL statements, payload MUST be a list """
log.debug('payload: {}'.format(payload))
if multi is False:
sql_str = ''.join(['SELECT ', id_name, ' FROM ', table, ' WHERE ', name, ' LIKE (%s);'])
... | 0280eb5d3877fa80a9632589e967669fd22254e1 | 3,647,261 |
def random_choice(number: int) -> bool:
"""
Generate a random int and compare with the argument passed
:param int number: number passed
:return: is argument greater or equal then a random generated number
:rtype: bool
"""
return number >= randint(1, 100) | d88e7e23bcff89b0f33a43e34b2ba640589fb0e3 | 3,647,262 |
from typing import Any
def request_l3_attachments(session, apic) -> Any:
"""Request current policy enformation for encap for Outs"""
root = None
uri = f"https://{apic}/api/class/l3extRsPathL3OutAtt.xml"
response = session.get(uri, verify=False)
try:
root = ET.fromstring(response.text)
... | 0623ffde29a67e0f96ec5284b0a27109bff5b1aa | 3,647,263 |
def bet_plot(
pressure,
bet_points,
minimum,
maximum,
slope,
intercept,
p_monolayer,
bet_monolayer,
ax=None
):
"""
Draw a BET plot.
Parameters
----------
pressure : array
Pressure points which will make up the x axis.
bet_points : array
BET-tr... | 751abe12683ceff72066b3b2cd6938d6e9a67507 | 3,647,264 |
from typing import Optional
def paged_response(
*,
view: viewsets.GenericViewSet,
queryset: Optional[QuerySet] = None,
status_code: Optional[int] = None,
):
"""
paged_response can be used when there is a need to paginate a custom
API endpoint.
Usage:
class UsersView(ModelViewS... | 73c38abbedf8f22a57bb6bda1b42d6013520885a | 3,647,265 |
def getObjectPositions(mapData, threshold, findCenterOfMass = True):
"""Creates a segmentation map and find objects above the given threshold.
Args:
mapData (:obj:`numpy.ndarray`): The 2d map to segment.
threshold (float): The threshold above which objects will be selected.
findCent... | d070f70270837ec1b1ff6f29eedc21deb2b4846c | 3,647,266 |
def specific_humidity(p,RH,t,A=17.625,B=-30.11,C=610.94,masked=False):
"""
From Mark G. Lawrence, BAMS Feb 2005, eq. (6)
q = specific_humidity(p,RH,t,A,B,C)
inputs: p = pressure (Pa)
RH = relative humidity (0-1)
t = temperature (K)
keywords: A, B and C are optional fi... | 2cfd4cad24a0f412d8021fdfdbc9874823093dcc | 3,647,267 |
import os
def list_versions():
"""
List the EMDB-SFF versions that are migratable to the current version
:return: status
:return: version_count
"""
version_count = len(VERSION_LIST)
for version in VERSION_LIST[:-1]:
_print('* {version}'.format(version=version))
return os.EX_OK,... | a02a7c74177aec70ec3dae4e6a86ff2ed62465a7 | 3,647,268 |
from typing import Optional
from typing import Literal
def build_parser():
"""
Build a pyparsing parser for our custom topology description language.
:return: A pyparsing parser.
:rtype: pyparsing.MatchFirst
"""
ParserElement.setDefaultWhitespaceChars(' \t')
nl = Suppress(LineEnd())
i... | 1eccb042b18c3c53a69a41e711a4347a6edf55b9 | 3,647,269 |
import math
def decode_owner(owner_id: str) -> str:
"""Decode an owner name from an 18-character hexidecimal string"""
if len(owner_id) != 18:
raise ValueError('Invalid owner id.')
hex_splits = split_by(owner_id, num=2)
bits = ''
for h in hex_splits:
bits += hex_to_bin(h)
test_owner = ''
for seq... | 1460ebe3dfd2f36aa2f5e42b28b2d7651d0d2cee | 3,647,270 |
def _get_back_up_generator(frame_function, *args, **kwargs):
"""Create a generator for the provided animation function that backs up
the cursor after a frame. Assumes that the animation function provides
a generator that yields strings of constant width and height.
Args:
frame_function: A funct... | a395e91864115f69dc0a7d8d8a3bb2eb90d957e9 | 3,647,271 |
from typing import Any
from typing import Optional
def from_aiohttp(
schema_path: str,
app: Any,
*,
base_url: Optional[str] = None,
method: Optional[Filter] = None,
endpoint: Optional[Filter] = None,
tag: Optional[Filter] = None,
operation_id: Optional[Filter] = None,
skip_deprecat... | 11c7d2cf9e19e8876ef45118f3842b51fbc734b9 | 3,647,272 |
import sys
import random
import string
def summarize(fname, start, stop,output_dir):
"""
Process file[start:stop]
start and stop both point to first char of a line (or EOF)
"""
ls_1995_1996 = []
for i in range (1995,2006):
ls_1995_1996.append([])
with open(fname, newline='', enco... | 443855fa4e591b4a40779c7fbb50f3b445a41c64 | 3,647,273 |
def compute_recall(true_positives, false_negatives):
"""Compute recall
>>> compute_recall(0, 10)
0.0
>>> compute_recall(446579, 48621)
0.901815
"""
return true_positives / (true_positives + false_negatives) | 876bee73150d811e6b7c1a5de8d8e4349105c59b | 3,647,274 |
def get_highest_seat_id():
"""
Returns the highest seat ID from all of the boarding passes.
"""
return max(get_seat_ids()) | 0e8f95c9455869d283acfb9d6230c8a6f2ca10eb | 3,647,275 |
def error_function_index(gpu_series, result_series):
"""
utility function to compare GPU array vs CPU array
Parameters
------
gpu_series: cudf.Series
GPU computation result series
result_series: pandas.Series
Pandas computation result series
Returns
-----
double
... | 1886df532808be8e54ffc2448c74fcb415b4424a | 3,647,276 |
def get_tipo_aqnext(tipo) -> int:
"""Solve the type of data used by DJANGO."""
tipo_ = 3
# subtipo_ = None
if tipo in ["int", "uint", "serial"]:
tipo_ = 16
elif tipo in ["string", "stringlist", "pixmap", "counter"]:
tipo_ = 3
elif tipo in ["double"]:
tipo_ = 19
elif... | d5a066b98aa56785c4953a7ec8d7052e572e5630 | 3,647,277 |
from typing import List
from typing import Dict
def fetch_indicators_command(client: Client) -> List[Dict]:
"""Wrapper for fetching indicators from the feed to the Indicators tab.
Args:
client: Client object with request
Returns:
Indicators.
"""
indicators = fetch_indicators(clie... | eb59b68362e0b30fdc5643259a1ddf757b7afce1 | 3,647,278 |
def hr_lr_ttest(hr, lr):
""" Returns the t-test (T statistic and p value), comparing the features for
high- and low-risk entities. """
res = stats.ttest_ind(hr.to_numpy(), lr.to_numpy(), axis=0, nan_policy="omit", equal_var=False)
r0 = pd.Series(res[0], index=hr.columns)
r1 = pd.Series(res[1], inde... | 86ccbbf3119ce7fc809ec68d50b57d514efb29b2 | 3,647,279 |
def _is_empty(str_: str) -> bool:
"""文字列が空か
文字列が空であるかを判別する
Args:
str_ (str): 文字列
Returns:
bool: 文字列が空のときはTrue,
空でないときはFalseを返す.
"""
if str_:
return False
return True | f0eff540767028a80a3042e2d5bc6951ad28fe24 | 3,647,280 |
import random
def energy_generate_random_range_dim2(filepath,dim_1_low,dim_1_high,dim_2_low,dim_2_high,num=500):
"""
6, 8 and 10
"""
queryPool=[]
query=[]
for _ in range(num):
left1 = random.randint(dim_1_low, dim_1_high)
right1 = random.randint(left1, dim_1_high)
query... | cdcafba427dbbab9b9e318f58f54a3a3c834bbd3 | 3,647,281 |
import os
def preprocess(data_folder):
""" Runs the whole pipeline and returns NumPy data array"""
SAMPLE_TIME = 30
CHANNELS = ['EEG Fpz-Cz', 'EEG Pz-Oz']
res_array = []
for path in os.listdir(data_folder):
if path.endswith("PSG.edf"):
full_path = os.path.join(data_folder, pa... | 62e44f384768541715d4254832d32169ea51f533 | 3,647,282 |
from typing import Optional
from typing import Sequence
def get_waas_policies(compartment_id: Optional[str] = None,
display_names: Optional[Sequence[str]] = None,
filters: Optional[Sequence[pulumi.InputType['GetWaasPoliciesFilterArgs']]] = None,
ids: O... | 4ab181b9776226a96b93757feb124c10b68eacc8 | 3,647,283 |
def _get_output_type(output):
"""Choose appropriate output data types for HTML and LaTeX."""
if output.output_type == 'stream':
html_datatype = latex_datatype = 'ansi'
text = output.text
output.data = {'ansi': text[:-1] if text.endswith('\n') else text}
elif output.output_type == 'er... | 4940f931f7ac3b87b68a5e84a5038feea331dac1 | 3,647,284 |
import gc
def cat_train_validate_on_cv(
logger,
run_id,
train_X,
train_Y,
test_X,
metric,
kf,
features,
params={},
num_class=None,
cat_features=None,
log_target=False,
):
"""Train a CatBoost model, validate using cross validation. If `test_X` has
a valid value, ... | d4a1248463d7fa1f9f8f192cc9fa02f8fcdcf020 | 3,647,285 |
def find_left(char_locs, pt):
"""Finds the 'left' coord of a word that a character belongs to.
Similar to find_top()
"""
if pt not in char_locs:
return []
l = list(pt)
while (l[0]-1, l[1]) in char_locs:
l = [l[0]-1, l[1]]
return l | 8e924f301203bcad2936d4cf4d82c6e21cbebb16 | 3,647,286 |
import pathlib
import urllib
def make_file_url(file_id, base_url):
"""Create URL to access record by ID."""
url_parts = list(urlparse.urlparse(base_url))
url_parts[2] = pathlib.posixpath.join(
DATAVERSE_API_PATH, DATAVERSE_FILE_API
)
args_dict = {'persistentId': file_id}
url_parts[4] =... | e4b60f2cfd31a9617ee775d7d8ca0caaa9c692fd | 3,647,287 |
def std_func(bins, mass_arr, vel_arr):
"""
Calculate std from mean = 0
Parameters
----------
bins: array
Array of bins
mass_arr: array
Array of masses to be binned
vel_arr: array
Array of velocities
Returns
---------
std_arr: array
Standard devia... | 13e53952af3106fb7891859f81c146d4bc92703b | 3,647,288 |
def log_neg(rho,mask=[1,0]):
""" Calculate the logarithmic negativity for a density matrix
Parameters:
-----------
rho : qobj/array-like
Input density matrix
Returns:
--------
logneg: Logarithmic Negativity
"""
if rho.type != 'oper':
raise TypeError("In... | b8ed0cd54dd879985ef6265085b789e91beceba7 | 3,647,289 |
def create_polygon(pixels_selected: set, raster_path: str) -> gpd.GeoDataFrame:
"""
It allows to transform each of the indexes of the
pixel data in coordinates for further processing
the answer polygon
Parameters
--------------
pixels_selected: set
Set with the pixels selected for t... | f2484afcfb73a3adbdaaeacf25287c1c2ce1584a | 3,647,290 |
import copy
def read_output(path_elec,path_gas):
"""
Used to read the building simulation I/O file
Args:
path_elec: file path where data is to be read from in minio. This is a mandatory parameter and in the case where only one simulation I/O file is provided, the path to this file should be indi... | 7ec4ce2d9776946e310fd843e722d0189c4ebcb2 | 3,647,291 |
def parse_lmap(filename, goal, values):
"""Parses an LMAP file into a map of literal weights, a LiteralDict object,
the literal that corresponds to the goal variable-value pair, and the
largest literal found in the file."""
weights = {}
max_literal = 0
literal_dict = LiteralDict()
for line i... | db6a0e5f56817e7dd0ef47b5e72b2ea30256b2a3 | 3,647,292 |
def read_image(path: str):
"""
Read an image file
:param path: str. Path to image
:return: The image
"""
return imageio.imread(path) | 8f3342f2454a3d3e821962d7040eebdbaee502cf | 3,647,293 |
def electrolyte_conductivity_Capiglia1999(c_e, T, T_inf, E_k_e, R_g):
"""
Conductivity of LiPF6 in EC:DMC as a function of ion concentration. The original
data is from [1]. The fit is from Dualfoil [2].
References
----------
.. [1] C Capiglia et al. 7Li and 19F diffusion coefficients and therma... | ea487399aba6cd1e70d1b5c84dd6f9294f8754b9 | 3,647,294 |
import random
def random_bdays(n):
"""Returns a list of integers between 1 and 365, with length n.
n: int
returns: list of int
"""
t = []
for i in range(n):
bday = random.randint(1, 365)
t.append(bday)
return t | 7871548db569d435a5975bfa118ad6c262406333 | 3,647,295 |
def int_to_charset(val, charset):
""" Turn a non-negative integer into a string.
"""
if not val >= 0:
raise ValueError('"val" must be a non-negative integer.')
if val == 0: return charset[0]
output = ""
while val > 0:
val, digit = divmod(val, len(charset))
output += chars... | ec30e014aaf42b6cc3904f13776b4226b0b75a5b | 3,647,296 |
def search(tabela, *, parms='*', clause=None):
""" Função que recebe como parâmetro obrigatório o nome da tabela a ser consultada,
como parâmetro padrão recebe os filtros da pesquisa e retorna todas as linhas encontradas """
banco = Banco()
banco.connect()
banco.execute(f"SELECT {parms} FROM {t... | 0cb0dad5fe0661ee7027ab8b43c28b0351d42a48 | 3,647,297 |
import os
from tasks import immath
import numpy as np
from scipy import ndimage
from taskinit import iatool
def make_mask_3d(imagename, thresh, fl=False, useimage=False, pixelmin=0,
major=0, minor=0, pixelsize=0, line=False, overwrite_old=True,
closing_diameter=6, pbimage=None, myres... | 01e625551d7fb6a8492a1f334294b742283600c1 | 3,647,298 |
def hash(data):
"""run the default hashing algorithm"""
return _blacke2b_digest(data) | e12433388a0d392f16a8e11ba812629ed4573ace | 3,647,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.