content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
async def app_exception_handler(request, exc):
"""
Error handler for AppException errors.
Logs the AppException error detected and returns the
appropriate message and details of the error.
"""
logger.debug(exc)
return JSONResponse(
Response(success=False, error_code=422, message=s... | 5,334,900 |
def test_websocket_worker(hook, start_proc):
"""Evaluates that you can do basic tensor operations using
WebsocketServerWorker"""
kwargs = {"id": "fed", "host": "localhost", "port": 8766, "hook": hook}
process_remote_worker = start_proc(WebsocketServerWorker, kwargs)
time.sleep(0.1)
x = torch.o... | 5,334,901 |
def test_Gaussian2D():
"""
Test rotated elliptical Gaussian2D model.
https://github.com/astropy/astropy/pull/2038
"""
model = models.Gaussian2D(100, 1.7, 3.1, x_stddev=3.3, y_stddev=5.0,
theta=np.pi/6.)
y, x = np.mgrid[0:5, 0:5]
g = model(x, y)
g_ref = [[77.... | 5,334,902 |
def search_book(doc, request):
"""This function also runs in a separate process."""
pattern = _make_search_re_pattern(request)
try:
for n in range(request.from_page, request.to_page + 1):
resultset = []
sect = doc[n].section.title
for pos, snip in search(pattern, ... | 5,334,903 |
def db_query_map(db_or_el, query, func_match, func_not) -> tuple:
"""
Helper function to find elems from query and transform them,
to generate 2 lists of matching/not-matching elements.
"""
expr = parse_query_expr(query)
elems1, elems2 = [], []
for el in _db_or_elems(db_or_el):
m = e... | 5,334,904 |
def route(pattern, method = HTTP_METHOD.GET):
"""
Decorator to declare the routing rule of handler methods.
"""
def decorator(func):
frm = inspect.stack()[1]
class_name = frm[3]
module_name = frm[0].f_back.f_globals["__name__"]
full_class_name = module_name + '.' + class_... | 5,334,905 |
def div_q(a: ElementModPOrQorInt, b: ElementModPOrQorInt) -> ElementModQ:
"""Compute a/b mod q."""
b = _get_mpz(b)
inverse = invert(b, _get_mpz(get_small_prime()))
return mult_q(a, inverse) | 5,334,906 |
def donoho_gavish_threshold(shape, sigma):
"""
(Gavish and Donoho, 2014)
Parameters
----------
shape: tuple (n_samples, n_features)
Shape of the data matrix.
sigma: float
Estiamte of the noise standard deviation.
Output
------
sigular_value_threshold: float
"... | 5,334,907 |
def main(args):
"""
Script to turn specific simulation data into Pandas Dataframes
"""
## Reading all elements and converting to python dictionary
param_dict = vars(args)
## Checking for correct input
param_vals_test(param_dict)
## Adding extra variables
param_dict = add_to_dict(para... | 5,334,908 |
def pyarrow_to_r_schema(
obj: 'pyarrow.lib.Schema'
):
"""Create an R `arrow::Schema` object from a pyarrow Schema.
This is sharing the C/C++ object between the two languages.
The returned object depends on the active conversion rule in
rpy2. By default it will be an `rpy2.robjects.Environment`.... | 5,334,909 |
def plot_ovlp_stats(jobdir, nproc):
"""Plot 5' and 3' Overlap distributions"""
log.info("Generating overlap plots")
overlaps = get_overlaps(jobdir, nproc)
ovlp_dict = {}
for ovlp in overlaps:
rid, length, fiveprime, threeprime = ovlp.split()
ovlp_dict[rid] = fiveprime, threeprime
... | 5,334,910 |
def validate_days(year, month, day):
"""validate no of days in given month and year
>>> validate_days(2012, 8, 31)
31
>>> validate_days(2012, 8, 32)
31
"""
total_days = calendar.monthrange(year, month)
return (total_days[1] if (day > total_days[1]) else day) | 5,334,911 |
def copy_dir_tree(src, dst, verbose=False):
"""Copies directory structure under src to dst."""
if verbose:
print('Copying dir-structure {} to {}'.format(src, dst))
for src_dir, sub_dirs, basenames in tf.io.gfile.walk(src):
rel_dir = os.path.relpath(src_dir, src)
dst_dir = os.path.jo... | 5,334,912 |
def test_get_recoveries_no_tags():
"""the get_recoveries() method of the report object should gracefully return
None if no tags where associated with this report. (I'm not sure why
there is a report if there are not tags')
"""
report = ReportFactory()
tags = report.get_recoveries()
assert ... | 5,334,913 |
def save_to_s3(bucket_name, file_name, data):
""" Saves data to a file in the bucket
bucket_name - - The name of the bucket you're saving to
file_name - - The name of the file
dat - - data to be saved """
s3 = boto3.resource('s3')
obj = s3.Object(bucket_name, file_name)
resp = ob... | 5,334,914 |
def linsearch_fun_BiCM_exp(xx, args):
"""Linsearch function for BiCM newton and quasinewton methods.
This is the linesearch function in the exponential mode.
The function returns the step's size, alpha.
Alpha determines how much to move on the descending direction
found by the algorithm.
:param ... | 5,334,915 |
def getCountryName(countryID):
"""
Pull out the country name from a country id.
If there's no "name" property in the object, returns null
"""
try:
countryObj = getCountry(countryID)
return(countryObj['name'])
except:
pass | 5,334,916 |
def _pic_download(url, type):
"""
图片下载
:param url:
:param type:
:return:
"""
save_path = os.path.abspath('...') + '\\' + 'images'
if not os.path.exists(save_path):
os.mkdir(save_path)
img_path = save_path + '\\' + '{}.jpg'.format(type)
img_data = base64.b64decode(url)
... | 5,334,917 |
def run_search(args):
"""Run a search from a given RadVel setup file
Args:
args (ArgumentParser): command line arguments
"""
config_file = args.setupfn
conf_base = os.path.basename(config_file).split('.')[0]
P, post = radvel.utils.initialize_posterior(config_file)
if args.mstar i... | 5,334,918 |
def get_placeholder(default_tensor=None, shape=None, name=None):
"""Return a placeholder_wirh_default if default_tensor given, otherwise a new placeholder is created and return"""
if default_tensor is not None:
return default_tensor
else:
if shape is None:
raise ValueError('One o... | 5,334,919 |
def test_http_processor_propagate_error_records(sdc_builder, sdc_executor, http_client, one_request_per_batch):
"""
Test when the http processor stage has the config option "Records for remaining statuses" set. To test this we
force the URL to be a not available so we get a 404 response from the moc... | 5,334,920 |
def test_make_map_plot_no_polygons(test_data_shape):
""" Tests that the make_map_plot function can run on data that has no
polygons.
"""
no_polygons = [
s for s in test_data_shape if not isinstance(s["shape"], Polygon)
]
make_map_plot(no_polygons) | 5,334,921 |
def get_targets(args):
"""
Gets the list of targets for cmake and kernel/build.sh
:param args: The args variable generated by parse_parameters
:return: A string of targets suitable for cmake or kernel/build.sh
"""
if args.targets:
targets = args.targets
elif args.full_toolchain:
... | 5,334,922 |
def print_results(
args: Any, processor: EYAMLProcessor, yaml_file: str,
yaml_paths: List[Tuple[str, YAMLPath]], document_index: int
) -> None:
"""Dump search results to STDOUT with optional and dynamic formatting."""
in_expressions = len(args.search)
print_file_path = not args.nofile
print_expr... | 5,334,923 |
def test_view_translate_invalid_locale(client, resource_a, settings_debug):
"""
If the project is valid but the locale isn't, redirect home.
"""
# this doesnt seem to redirect as the comment suggests
response = client.get(
'/invalid-locale/%s/%s/'
% (resource_a.project.slug, resource... | 5,334,924 |
def modify_db_cluster(event, context):
"""
When we restore the database from a production snapshot,
we don't know the passwords. So, modify the postgres password here
so we can work with the database.
:param event:
:param context:
:return:
"""
logger.info(event)
rds_client.modif... | 5,334,925 |
def compPlayHand(hand, wordList, n):
"""
Allows the computer to play the given hand, following the same procedure
as playHand, except instead of the user choosing a word, the computer
chooses it.
1) The hand is displayed.
2) The computer chooses a word.
3) After every valid word: the word ... | 5,334,926 |
def _format_warning(message, category, filename, lineno, line=None): # noqa: U100, E501
"""
Simple format for warnings issued by ProPlot. See the
`internal warning call signature \
<https://docs.python.org/3/library/warnings.html#warnings.showwarning>`__
and the `default warning source code \
<https://... | 5,334,927 |
def piocheCarte(liste_pioche, x):
""" Cette fonction renvoie le nombre x de cartes de la pioche.
Args:
x (int): Nombre de cartes à retourner.
Returns:
list: Cartes retournées avec le nombre x.
"""
liste_carte = []
for i in range(x):
liste_carte.append(liste_pioche[i])
... | 5,334,928 |
def is_process_running(pid):
"""Returns true if a process with pid is running, false otherwise."""
# from
# http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
try:
os.kill(pid, 0)
except OSError:
return False
else:
return Tru... | 5,334,929 |
def cost_logistic(p, x, y):
"""
Sum of absolute deviations of obs and logistic function
:math:`L/(1+exp(-k(x-x0)))`
Parameters
----------
p : iterable of floats
parameters (`len(p)=3`)
- `p[0]` = L = Maximum of logistic function
- `p[1]` = k = Steepness of logistic... | 5,334,930 |
def get_price(token: str, sellAmount=1000000000000000000):
"""
get_price uses the 0x api to get the most accurate eth price for the token
:param token: token ticker or token address
:param buyToken: token to denominate price in, default is WETH
:param sellAmount: token amount to sell in base unit, ... | 5,334,931 |
def _change_matplotlib_colours(text_color=_TEXT_COLOUR, bg_colour=_BG_COLOUR):
"""Change matplotlib default colors for ALL graphs produced in current session.
- 'text_colour' sets the colour of all text, as well as axes colours and
axis tick mark colours.
- 'bg_colour' changes the backgro... | 5,334,932 |
async def test_ObserveHeadRacket():
"""监听拍头事件demo
监听拍头事件,当机器人头部被拍击时,上报拍头类型
当机器人头部被双击时,停止监听,并跳一个舞蹈
# ObserveHeadRacketResponse.type:
# class HeadRacketType(enum.Enum):
# SINGLE_CLICK = 1 # 单击
# LONG_PRESS = 2 # 长按
# DOUBLE_CLICK = 3 # 双击
"""
# 创建监听
obser... | 5,334,933 |
def inv_exportlog():
"""Exports a csv file formatted for Profitek's inventory task list.
"""
date = datetime.today().strftime('%Y%m%d')
scanner_terminal = escape(session["scanner_terminal"])
allscanners = escape(request.form.get('allscanners','yes'))
if 'yes' in allscanners.lower():
#g... | 5,334,934 |
def send_command(InstanceIds=None, Targets=None, DocumentName=None, DocumentHash=None, DocumentHashType=None, TimeoutSeconds=None, Comment=None, Parameters=None, OutputS3Region=None, OutputS3BucketName=None, OutputS3KeyPrefix=None, MaxConcurrency=None, MaxErrors=None, ServiceRoleArn=None, NotificationConfig=None):
... | 5,334,935 |
def test_extract():
""" Test extract packet information from raw bytes. """
# These raw bytes are from the ReadCentral packet built in test_build()
raw_payload = bytearray(b'\x10\x00\x00\x00\x0c\x00\x10\x00\x0c\x00\x09\x00\x04\x00\x0a\x00\x0c\x00\x00\x00\x1c\x00'
b'\x00\x00\x00\x... | 5,334,936 |
def _get_all_errors_if_unrecognized_properties(model: dict, props: list) -> iter:
"""Get error messages if the model has unrecognized properties."""
def get_error_if_property_is_unrecognized(key):
if key not in props:
return f"unrecognized field named '{key}' found in model '{model}'"
... | 5,334,937 |
def clear_context():
"""Helper to clear any thread local contexts."""
import talisker.sentry
Context.clear()
talisker.sentry.clear() | 5,334,938 |
def no_holders(disk):
"""Return true if the disk has no holders."""
holders = os.listdir('/sys/class/block/' + disk + '/holders/')
return len(holders) == 0 | 5,334,939 |
def write_data(data) -> None:
"""
write json data to the data file
Args:
data: json data
"""
with open(data_file, 'w') as data_io:
json.dump(data, data_io) | 5,334,940 |
def main(fn):
"""Call fn with command line arguments. Used as a decorator.
The main decorator marks the function that starts a program. For example,
@main
def my_run_function():
# function body
Use this instead of the typical __name__ == "__main__" predicate.
"""
if inspect.stack... | 5,334,941 |
def rows(f, null_value=None, columns=None, comments=True, header=False):
"""
Parses a tsv file.
:param f: the file handler
:param null_value: value to interpret as a None
:param columns: which columns to return
:param comments: skip comments ?
:param header: has the tsv header ?
:return: selected columns for ea... | 5,334,942 |
def test_list_non_positive_integer_min_length_4_nistxml_sv_iv_list_non_positive_integer_min_length_5_2(mode, save_output, output_format):
"""
Type list/nonPositiveInteger is restricted by facet minLength with
value 10.
"""
assert_bindings(
schema="nistData/list/nonPositiveInteger/Schema+Inst... | 5,334,943 |
def shellutil(device, facts):
"""
In the `facts` dictionary will set the following keys:
* facts['hostname']: device hostname
"""
systime = device.rpc.get('Cisco-IOS-XR-shellutil-oper:system-time/uptime')
uptime = _jsonpath(systime, 'data/system-time/uptime')
facts['hostname'] = _json... | 5,334,944 |
def get_get_single_endpoint_schema(class_name, id_field_where_type, response_schema):
"""
:param class_name:
:param id_field_where_type:
:param response_schema:
"""
return {
"tags": [class_name],
"description": f"Get a {class_name} model representation",
"parameters": [... | 5,334,945 |
def overlapping_template_matching(
sequence,
template_size: Optional[int] = None,
blocksize: Optional[int] = None,
matches_ceil: Optional[int] = None,
):
"""Overlapping matches to template per block is compared to expected result
The sequence is split into blocks, where the number of overlappin... | 5,334,946 |
def _extract_options(config, options, *args):
"""Extract options values from a configparser, optparse pair.
Options given on command line take precedence over options read in the
configuration file.
Args:
config (dict): option values read from a config file through
configparser
... | 5,334,947 |
def _calc_fans(shape):
"""
:param shape: tuple with the shape(4D - for example, filters, depth, width, height)
:return: (fan_in, fan_out)
"""
if len(shape) == 2:
# Fully connected layer (units, input)
fan_in = shape[1]
fan_out = shape[0]
elif len(shape) in {3, 4, 5}:
... | 5,334,948 |
def train_collision(net: nn.Module, full_props: List[c.CollisionProp], args: Namespace) -> Tuple[int, float, int, float]:
""" The almost completed skeleton of training Collision Avoidance/Detection networks using ART.
:return: trained_epochs, train_time, certified, final accuracies
"""
logging.info(net)... | 5,334,949 |
def statRobustness(compromised, status):
"""produce data for robustness stats"""
rob = {0:{"empty":0, "login based":0, "top 10 common":0, "company name":0},
1:{"top 1000 common":0, "login extrapolation":0, "company context related":0, "4 char or less":0},
2:{"top 1M common":0, "6 char or... | 5,334,950 |
def test_create_datetime_index():
"""Tests ability to create an array of datetime objects from distinct
arrays of input paramters"""
arr = np.ones(4)
dates = pytime.create_datetime_index(year=2012*arr, month=2*arr,
day=28*arr, uts=np.arange(0, 4))
assert d... | 5,334,951 |
def ns_diff(newstr, oldstr):
"""
Calculate the diff.
"""
if newstr == STATUS_NA:
return STATUS_NA
# if new is valid but old is not we should return new
if oldstr == STATUS_NA:
oldstr = '0'
new, old = int(newstr), int(oldstr)
return '{:,}'.format(max(0, new - old)) | 5,334,952 |
def get_crab(registry):
"""
Get the Crab Gateway
:rtype: :class:`crabpy.gateway.crab.CrabGateway`
# argument might be a config or a request
"""
# argument might be a config or a request
regis = getattr(registry, 'registry', None)
if regis is None:
regis = registry
return re... | 5,334,953 |
def create_meal():
"""Create a new meal.
---
tags:
- meals
parameters:
- in: body
name: body
schema:
id: Meal
properties:
name:
type: string
description: the name of the meal
description:
type... | 5,334,954 |
def buscaBinariaIterativa(alvo, array):
""" Retorna o índice do array em que o elemento alvo está contido.
Considerando a coleção recebida como parâmetro, identifica e retor-
na o índice em que o elemento especificado está contido. Caso esse
elemento não esteja presente na coleção, retorna -1. Utiliza ... | 5,334,955 |
async def test_percent_conv():
"""Test percentage conversion."""
assert util.percent_conv(0.12) == 12.0
assert util.percent_conv(0.123) == 12.3 | 5,334,956 |
def test_url_to_widget_info_regex():
"""Test regex for parsing the source object name, source object id,
widget name, mapped object name, mapped object id from URL."""
urls = [
("https://grc-test.appspot.com/dashboard/",
"dashboard", "", "", "", ""),
("https://grc-test.appspot.com/dashboard#... | 5,334,957 |
def setHomePath(homePath):
"""Seth the env variable HOME"""
# Do some sanity/defensive stuff
if homePath == None:
raise Exception("homePath=None.")
elif len(homePath) == 0:
raise Exception("len(homePath)=0.")
# We do some special stuff on windows
if platform.system() == "Windows... | 5,334,958 |
def sync_out_streams():
"""Just flush all stdin and stderr to make streams go in sync"""
sys.stderr.flush()
sys.stdout.flush() | 5,334,959 |
def empiricalcdf(data, method='Hazen'):
"""Return the empirical cdf.
Methods available:
Hazen: (i-0.5)/N
Weibull: i/(N+1)
Chegodayev: (i-.3)/(N+.4)
Cunnane: (i-.4)/(N+.2)
Gringorten: (i-.44)/(N+.12)
California: (i-1)/N
Where i goes from ... | 5,334,960 |
def CCT_to_xy_Kang2002(CCT):
"""
Returns the *CIE XYZ* tristimulus values *CIE xy* chromaticity coordinates
from given correlated colour temperature :math:`T_{cp}` using
*Kang et al. (2002)* method.
Parameters
----------
CCT : numeric or array_like
Correlated colour temperature :mat... | 5,334,961 |
def tel_information(tel_number):
"""
check and return a dictionary that has element of validation and operator of number
if number is not valid it return validation = 'False' and operator = 'None'
"""
validation = is_valid(tel_number)
operator = tel_operator(tel_number)
info_dict = {'valida... | 5,334,962 |
def load_file(file_name: pathlib.Path) -> Dict[str, Any]:
"""
Load JSON or YAML file content into a dict.
This is not intended to be the default load mechanism. It should only be used
if a OSCAL object type is unknown but the context a user is in.
"""
content_type = FileContentType.to_content_t... | 5,334,963 |
def DocumentPlugin():
"""
:return: document plugin class
"""
from tests.test_plugins.documentations_plugin import DocumentPlugin
return DocumentPlugin | 5,334,964 |
def read_in(file_index, normalized):
"""
Reads in a file and can toggle between normalized and original files
:param file_index: patient number as string
:param normalized: boolean that determines whether the files should be normalized or not
:return: returns npy array of patient data across 4 leads... | 5,334,965 |
def emitfuncs():
"""emit functions to access node fields"""
printf("int %Pop_label(NODEPTR_TYPE p) {\n"
"%1%Passert(p, PANIC(\"NULL tree in %Pop_label\\n\"));\n"
"%1return OP_LABEL(p);\n}\n\n");
printf("STATE_TYPE %Pstate_label(NODEPTR_TYPE p) {\n"
"%1%Passert(p, PANIC(\"NULL tree in %Pstate_label\\n\"));\n"
"%1retu... | 5,334,966 |
def remove_extended(text):
""" remove Chinese punctuation and Latin Supplement.
https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)
"""
# latin supplement: \u00A0-\u00FF
# notice: nbsp is removed here
lsp_pattern = re.compile(r'[\x80-\xFF]')
text = lsp_pattern.sub('... | 5,334,967 |
def appointment_letter(request, tid):
"""Display the appointment letter."""
paf = get_object_or_404(Operation, pk=tid)
return render(
request, 'transaction/appointment_letter.html', {'paf': paf},
) | 5,334,968 |
def sample():
"""
Sample command
""" | 5,334,969 |
def balance_targets(sentences: Iterable[Sentence], method: str = "downsample_o_cat", shuffle=True) \
-> Iterable[Sentence]:
"""
Oversamples and/or undersamples training sentences by a number of targets.
This is useful for linear shallow classifiers, that are prone to simply overfit the most-occurrin... | 5,334,970 |
def create_subscription(post, user, sub_type=None, update=False):
"""
Creates subscription to a post. Returns a list of subscriptions.
"""
subs = Subscription.objects.filter(post=post.root, user=user)
sub = subs.first()
default = Subscription.TYPE_MAP.get(user.profile.message_prefs,
... | 5,334,971 |
def discriminator_loss(real_output, fake_output, batch_size):
"""
Computes the discriminator loss after training with HR & fake images.
:param real_output: Discriminator output of the real dataset (HR images).
:param fake_output: Discriminator output of the fake dataset (SR images).
:param batch_siz... | 5,334,972 |
def NNx(time, IBI, ibimultiplier=1000, x=50):
"""
computes Heart Rate Variability metrics NNx and pNNx
Args:
time (pandas.DataFrame column or pandas series): time column
IBI (pandas.DataFrame column or pandas series): column with inter beat intervals
ibimultiplier... | 5,334,973 |
def datetimeobj_YmdHMS(value):
"""Convert timestamp string to a datetime object.
Timestamps strings like '20130618120000' are able to be converted by this
function.
Args:
value: A timestamp string in the format '%Y%m%d%H%M%S'.
Returns:
A datetime object.
Raises:
Value... | 5,334,974 |
def make_roc_curves(args):
"""
NAME
make_roc_curves
PURPOSE
Given some collection pickles, this script
produces the one roc plot that will be put someplace in the SW system
paper.
COMMENTS
FLAGS
-h Print this message
INPUTS
... | 5,334,975 |
def drawBoundingBoxes(ax, x, y, z, w, l, h, r, col='b', linewidth=2):
"""
Draws bounding boxe lines to given axis
Params:
(x, y, z): center point coordinates of an object
(w, l, h): width, length and height of the bounding box / object
r: rotation in radians
"""
# Do this, b... | 5,334,976 |
def home():
"""List devices."""
devices = Device.query.all()
return render_template('devices/home.html', devices=devices) | 5,334,977 |
def translate_value(document_field, form_value):
"""
Given a document_field and a form_value this will translate the value
to the correct result for mongo to use.
"""
value = form_value
if isinstance(document_field, ReferenceField):
value = document_field.document_type.objects.get(id=for... | 5,334,978 |
def error_404(error):
"""Custom 404 Error Page"""
return render_template("error.html", error=error), 404 | 5,334,979 |
def sum_num(n1, n2):
"""
Get sum of two numbers
:param n1:
:param n2:
:return:
"""
return(n1 + n2) | 5,334,980 |
def listb(containerclient):
"""
cette fonction retourne la liste des blobs contenu un container
elle prend en paramètre un container
"""
blob_list=containerclient.list_blobs()
for blob in blob_list:
print(blob.name) | 5,334,981 |
def intensity_slice_volume(kernel_code,
image_variables,
g_variables,
blockdim,
bound_box,
vol_dim,
voxel_size,
poses,
... | 5,334,982 |
def mean_filter(img, kernel_size):
"""take mean value in the neighbourhood of center pixel.
"""
return cv2.blur(img, ksize=kernel_size) | 5,334,983 |
def main():
"""Return the module instance."""
return AnsibleModule(
argument_spec=dict(
data=dict(default=None),
path=dict(default=None, type=str),
file=dict(default=None, type=str),
)
) | 5,334,984 |
def load_RegNetwork_interactions(
root_dir: Optional[Path] = None,
) -> pd.DataFrame:
"""
Loads RegNetwork interaction datafile. Downloads the file first if not already present.
"""
file = _download_RegNetwork(root_dir)
return pd.read_csv(
file, delimiter="\t", header=None, names=["g1", ... | 5,334,985 |
def hxlspec_main(args, stdin=STDIN, stdout=sys.stdout, stderr=sys.stderr):
""" Run hxlspec with command-line arguments.
Args:
args (list): a list of command-line arguments
stdin (io.IOBase): alternative standard input (mainly for testing)
stdout (io.IOBase): alternative standard output ... | 5,334,986 |
def search_restaurant(house_list,
filter_by_distance=True,
search_range=3,
sort=True,
top_k=100,
save_csv=False,
offline_save=True):
"""Scraping restaurant information from opentable.c... | 5,334,987 |
def get_model_config(model, dataset):
"""Map model name to model network configuration."""
if 'cifar10' == dataset.name:
return get_cifar10_model_config(model)
if model == 'vgg11':
mc = vgg_model.Vgg11Model()
elif model == 'vgg16':
mc = vgg_model.Vgg16Model()
elif model == 'vgg19':
mc = vgg_mo... | 5,334,988 |
def flacwrite(x, fs, bits, flacfile, normalize=False, compress=True):
"""
まずwavで吐く→flacをコマンド呼び出しして処理
"""
open(flacfile, 'w').close() # lock file
wavfile = chext(flacfile, "wav")
wavwrite(x, fs, bits, wavfile, normalize, compress)
command = [FLACPATH, "--delete-input-file", wavfile, "-f", "-o... | 5,334,989 |
def dev(session: nox.Session) -> None:
"""
Sets up a python development environment for the project.
This session will:
- Create a python virtualenv for the session
- Install the `virtualenv` cli tool into this environment
- Use `virtualenv` to create a global project virtual environment
- ... | 5,334,990 |
def utc_now():
"""Return current utc timestamp
"""
now = datetime.datetime.utcnow()
return int(now.strftime("%s")) | 5,334,991 |
def rrc_filter(alpha, length, osFactor, plot=False):
"""
Generates the impulse response of a root raised cosine filter.
Args:
alpha (float): Filter roll-off factor.
length (int): Number of symbols to use in the filter.
osFactor (int): Oversampling factor (number of samples per symbol... | 5,334,992 |
def test_unknown_metadata_arg():
"""Unrecognized metadata options should result in an error"""
search = fixture_dir('listing', 'valid-json')
result = npc.commands.listing.make_list(search, fmt='md', metadata='asdf')
assert not result.success | 5,334,993 |
def get_available_services(project_dir: str):
"""Get standard services bundled with stakkr."""
services_dir = file_utils.get_dir('static') + '/services/'
conf_files = _get_services_from_dir(services_dir)
services = dict()
for conf_file in conf_files:
services[conf_file[:-4]] = services_dir ... | 5,334,994 |
def build_insert(table, to_insert):
"""
Build an insert request.
Parameters
----------
table : str
Table where query will be directed.
to_insert: iterable
The list of columns where the values will be inserted.
Returns
-------
str
Built query.
"""
sq... | 5,334,995 |
def get_reference_data(fname):
"""
Load JSON reference data.
:param fname: Filename without extension.
:type fname: str
"""
base_dir = Path(__file__).resolve().parent
fpath = base_dir.joinpath('reference', 'data', fname + '.json')
with fpath.open() as f:
return json.load(f) | 5,334,996 |
def _is_l10n_ch_isr_issuer(account_ref, currency_code):
""" Returns True if the string account_ref is a valid a valid ISR issuer
An ISR issuer is postal account number that starts by 01 (CHF) or 03 (EUR),
"""
if (account_ref or '').startswith(ISR_SUBSCRIPTION_CODE[currency_code]):
return _is_l10... | 5,334,997 |
def little_endian_uint32(i):
"""Return the 32 bit unsigned integer little-endian representation of i"""
s = struct.pack('<I', i)
return struct.unpack('=I', s)[0] | 5,334,998 |
def evaluate_scores(scores_ID, scores_OOD):
"""calculates classification performance (ROCAUC, FPR@TPR95) based on lists of scores
Returns:
ROCAUC, fpr95
"""
labels_in = np.ones(scores_ID.shape)
labels_out = np.zeros(scores_OOD.shape)
y = np.concatenate([labels_in, labels_out])
s... | 5,334,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.