content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from sktime.forecasting.base import ForecastingHorizon
def check_fh(fh, enforce_relative=False):
"""Validate forecasting horizon.
Parameters
----------
fh : int, list, np.array, pd.Index or ForecastingHorizon
Forecasting horizon specifying the time points to predict.
enforce_relative : bo... | 543eeb74a82039884b895c6f1513a0b7970ffc15 | 52,406 |
def should_install_lzo():
"""
Return true if lzo is enabled via core-site.xml and GPL license (required for lzo) is accepted.
"""
config = Script.get_config()
io_compression_codecs = default("/configurations/core-site/io.compression.codecs", None)
lzo_enabled = io_compression_codecs is not None and "com.had... | 65b844aeb2a4fa9f7d13a6b876ca7b4ae9cb016a | 52,407 |
def optimal_compatible_subset(requests):
"""
Get optimal weighted subset
Uses dynamic programming to get the subset
of the requests with the largest weight
"""
dp_weights = dict()
dp_subsets = dict()
finishes = {r.finish for r in requests}
while finishes:
x = max(finishes)
finishes.remove(x)... | 70562bf5289f1608b7ffe918678cadcc1b956e14 | 52,408 |
async def load_accounts(db, names):
"""`get_accounts`-style lookup for `get_state` compat layer."""
sql = """SELECT id, name, display_name, about, reputation, vote_weight,
created_at, post_count, profile_image, location, website,
cover_image
FROM hive_accou... | 91cafae0ddd2a7e27b2be222147f05d15a57c256 | 52,409 |
def imgMakeMask(inImg, threshold=None, forgroundValue=1):
"""
Generates morphologically smooth mask with given forground value from input image.
If a threshold is given, the binary mask is initialzed using the given threshold...
...Otherwise it is initialized using Otsu's Method.
"""
if thr... | 2e54491735c03f3593d2f96283340c52b5bb4cbc | 52,410 |
import requests
def fetch_vacancies(keyword, town=None, catalogues=None, currency=None, period=0, page=0, count=100):
"""Fetch vacancies from SuperJob API, return in json.
Args:
keyword (str):
search the specific vacancies by keyword
town (int, optional):
search vaca... | 2d10e3e518141fe9eec8d03dd53817a75148a2b0 | 52,411 |
import codecs
def OpenDictionary(filenames):
"""Reads the dictionary into a list
"""
print("Opening the Chinese Notes dictionary")
words = []
for dictfile in filenames.split(","):
with codecs.open(dictfile, 'r', "utf-8") as f:
for line in f:
line = line.strip()
if not line:
... | f9c473254984e36ac8ae49b24d20be484416cf23 | 52,412 |
import requests
def api_request(url, api_key=None):
"""
This function takes a url and returns the parsed json object. If necessary, it submits the auth header
"""
if api_key:
return requests.get(url, headers={'Authorization': 'Token ' + api_key}).json()
else:
return requests.ge... | ea8572d761dffb952b970ab14e73307a02f67ee8 | 52,413 |
import torch
def get_device(gpu_idx: int = 0) -> torch.device:
"""
Get default gpu torch device.
:param gpu_idx:
:return:
"""
device: torch.device = torch.device(f"cuda:{gpu_idx}" if torch.cuda.is_available() else "cpu")
# device: torch.device = torch.device(f"cuda:0" if torch.cuda.is_ava... | acc8e9b65b21045cb0dc9a6fb2942d6dab0ce6a2 | 52,414 |
def subjects(subjects=None,
recursive=False,
include_tables=False,
lang=DEFAULT_LANGUAGE):
"""List subjects from the subject hierarchy.
If subjects is not given, the root subjects will be used.
Returns a generator.
"""
request = Request('subjects', *subjects,... | 0d8903904ab1d324870c1565d64d3b5fa1af66b6 | 52,415 |
def getGOState(*args):
"""Access protected class data to evaluate if the Fuel, Liquid Oxygen (LOX), and Control Panel system state are a 'GO' as a 1 by 3 numpy array. This approach is a secure method to access saved system state values. If the system sensor values are all nominal and all three controller panels ope... | 4fd041bc4786334f03a9ca1ff056c6f5a64c79fd | 52,416 |
def cluster_commit():
"""
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
"""
ret = {"comment": "", "success": False}
cmd = __execute_cmd("riak-admin", "cluster commit")
if cmd["retcode"] != 0:
r... | 56146ab9fe8ea6275ac5de140a301abc7d71bf6e | 52,418 |
from sqlalchemy import inspect
def get_map_from_sqlalchemy(a_object):
"""A SQLAlchemy utility to make a dictionary out of an object"""
# this can be done at the front-end side using node.js and JS
# if the programming was done at the front-end
# A variable assigned to the SQLAlchemy object inspectio... | 5a58fd6c5f65ff9bfd0b1179596d8c89cfee97a9 | 52,419 |
import time
from io import StringIO
def get_tick_data(code=None, date=None, retry_count=3, pause=0.001, src='sn'):
"""
获取分笔数据
Parameters
------
code:string
股票代码 e.g. 600848
date:string
日期 format: YYYY-MM-DD
... | b66ba33b6e0bbba61f7a003181d3237165f86df3 | 52,420 |
def config_template_files():
""" Fixture for the config template files """
template_file = {
"input": TEST_DATADIR / "templates/config/sparcc.j2",
"output": TEST_DATADIR / "templates/config/sparcc.config",
}
data = {
"compute_correlations": {"niters": 10},
"resampling": {... | ddb31f9ab029d19dc9017e620893ed118ca232bb | 52,421 |
def normalize_ascii(j_string):
"""
Normalize a double-width ascii string, converting all characters to
their single-width counterparts.
:param six.text_type j_string:
The string to convert.
:return:
The converted string.
"""
result = []
for char in j_string:
... | bbdf1d88f69d923f7ee6ac8df4c284547ed0c16a | 52,422 |
def part_2(data: list[str]) -> int:
""" Figure out the sequence of closing characters for incomplete lines.
Start with a total score of 0. Then, for each character, multiply the total score by 5
and then increase the total score by the point value given for the character.
Returns middle sco... | 33f61dfcdbe351a862e794bf56365c1e4e2840e7 | 52,423 |
def checkfile(file):
"""Checks file to to make sire itsx and itsxpress exited with an exit code of
O and that ITSx did not throw a fatal error message
Args:
file: data file path
Returns:
Bool: True
Raises:
AssertError: if two lines with Exit Status 0 are not present
ValueError: if ITSx returned a fatal... | 62f5aa5be467be99c5be324c3104c623bfae2701 | 52,424 |
def product(id):
"""Display selected product"""
if request.method == "GET":
product = db.session.query(Product).get(id)
addons = db.session.query(ProductAddon).all()
return render_template("product.html", error=check_error(), user=session, addons=addons, product=product)
else: # Edit... | dc8b2b5b9096101fcfedd2f138d751dfb4667853 | 52,425 |
def is_string(s):
"""Check if the argument is a string which works for both Python 2 and 3."""
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str) | f40bb9d9128807d3f932e2ac3ec5c1355c3347ab | 52,427 |
def retry(exception_to_check, attempts=3):
"""Decorator to retry a function upon exception.
If the decorated function emits an exception that matches exception_to_check,
the function will be repeated. This will happen a maximum of 'attempts' times.
If none of the attempts were successful, this function raises ... | 99ee08871636b185cf569b84b44f83b349113f25 | 52,428 |
def get_all_task_queue():
"""返回所有原子队列的key
返回类型:list
"""
task_queue = "ztq:queue:task:"
return get_keys(task_queue) | 712b706ce17554042b70f93631f56ada64b33d68 | 52,429 |
def print_permissions(permissions):
"""Prints out a users permissions"""
table = formatting.Table(['keyName', 'Description'])
for perm in permissions:
table.add_row([perm['keyName'], perm['name']])
return table | 6589344a8ca90abd9a85afc058ea44e549cc639b | 52,430 |
def create_cloud_xyz32(header, points):
"""
Create a sensor_msgs.msg.PointCloud2 message with (x, y, z) fields.
:param header: The point cloud header. (Type: std_msgs.msg.Header)
:param points: The point cloud points. (Type: Iterable)
:return: The point cloud as sensor_msgs.msg.PointCloud2.
"""... | 789a86174c3ddc687e735977465c0ebf75f9658c | 52,431 |
import utool as ut
def _test_buffered_generator_general2(
bgfunc,
bgargs,
fgfunc,
target_looptime=1.0,
serial_cheat=1,
buffer_size=2,
show_serial=True,
):
"""
# We are going to generate output of bgfunc in the background while
# fgfunc is running in the foreground. fgfunc takes... | dd086a48b59f4540302fe40b081887ee96f6e5b3 | 52,432 |
def cast_in_array(arg):
"""casts argument into np.array"""
if isinstance(arg, np.ndarray):
return arg
msg = f"Can not cast type({type(arg)}), {arg} in array of floats.\n"
try:
arr = np.array(arg)
except Exception as exc:
raise exc(msg)
arr = np.array(0)
if not ... | 45fe2ee75a7a62a6915f29be30ffe730ad9fa38b | 52,433 |
def check_login() :
""" check if the user is correctly logged. This function is called everytime a user function is called """
if not session.get('workspace_contract') and not session.get('username') :
abort(403)
return True | 734067198b7230165b8c4c9d3cb824ed9d970d39 | 52,434 |
def validator_key(validator_account_and_key):
"""Private key of the validator running the confirmation sender."""
_, key = validator_account_and_key
return key | 365120ee93d30f191a51153505f8164cc588a74f | 52,435 |
def nn50(nni=None, rpeaks=None):
"""Find number of NN interval differences which are greater 50ms (NN50) and ratio between NN50 and total amount of
NN intervals.
References: [Electrophysiology1996], [Ewing1984]
Docs: https://pyhrv.readthedocs.io/en/latest/_pages/api/time.html#nn50-nn50
Parameters
----------
n... | 61d55d365e24dc9c0d48de34068409de07a30d25 | 52,436 |
import typing
import ctypes
def get_random(file_handle: typing.TextIO, length: int = 32) -> bytes:
"""Request random bytes from /dev/nsm."""
if length < 1 or length > 256:
raise ValueError('GetRandom supports length between 1 and 256 inclusive.')
nsm_key = 'GetRandom'
request_data = cbor2.dum... | 51e47a954d4021160c8e18000dcffe7c41f06be9 | 52,437 |
import pandas as pd
def todataframe(table, index=None, exclude=None, columns=None,
coerce_float=False, nrows=None):
"""
Load data from the given `table` into a
`pandas <http://pandas.pydata.org/>`_ DataFrame. E.g.::
>>> import petl as etl
>>> table = [('foo', 'bar', 'baz')... | 9588a547fec8e4f532b89a36969764bf3bd13a86 | 52,438 |
def load(instream, where=None):
"""Load a Windows .FON file."""
data = instream.read()
mz_header = _MZ_HEADER.from_bytes(data)
if mz_header.magic not in (b'MZ', b'ZM'):
raise FileFormatError('MZ signature not found. Not a Windows .FON file')
ne_magic = data[mz_header.ne_offset:mz_header.ne_o... | 363416f69b613f3b7b76d2073682ab2b5ea1e42d | 52,439 |
def api_get_instances_by_nemea_module_name(module_name):
"""
Returns instances of given NEMEA module
"""
# verify that module exists
nm_model.get_by_name(module_name)
insts = i_model.get_by_nemea_module_name(module_name)
return json_resp(insts) | 74fdbd465c1d0e79422ff3b5ff5191067c696587 | 52,441 |
from typing import Dict
from typing import Callable
from typing import Any
def dispatch_value(default_func):
"""Decorator to select a function implementation according to the value of its fist parameter"""
registry: Dict[type, Callable[..., Any]] = {}
default: Callable[..., Any] = default_func
def re... | de460bc64f17dc5bb24a6995c87f3c4da938b50c | 52,442 |
import requests
from datetime import datetime
from typing import Mapping
from typing import Any
def run_retrohunt(http_session: requests.AuthorizedSession, version_id: str,
start_time: datetime.datetime,
end_time: datetime.datetime) -> Mapping[str, Any]:
"""Run a retrohunt.
Ar... | ba2b54732339e661b7a19b95055cf843ed0a6eb4 | 52,443 |
def calc_theta(pref_cood, local_connectivity_dic, xt=139.69167, yt=35.68944):
""" Returns array of the bearing of a linke between two prefectures.
Parameters
----------
pref_cood : dict[str, Tuple[float, float]]
Dictionary of coordinates of all 47 prefectures.
local_connectivity_dic : dic... | efab02ede396ab1e5c03966928937ae1c4570dac | 52,444 |
def encode_int(value):
"""
Encode integer value into RLP format
:param value: int value
:return: RLP encoded bytes
"""
if value == 0:
s = b""
else:
s = int_to_big_endian(value)
if len(s) == 1 and safe_ord(s[0]) < 128:
return s
return get_length_prefix_str(... | 1a32bbca7409e93323cab3c1c6985eef058a8cff | 52,445 |
def ood_detection(y_hat: Prediction, _, y_hat_ood: Prediction, __,
score_type: str = 'AUROC', uncertainty_type: str = 'aleatoric') -> Tensor:
"""convenience function which computes the OOD APR/AUROC scores from model predictions on ID and OOD data based on estimates of 'aleatoric' or 'epistemic' u... | dd51946e911e565e79ec8114bd94d10e445874cf | 52,447 |
from datetime import datetime
def summer_start(timestamp):
"""
Returns 00:00:01 on the Sunday following the 2nd Saturday of April for
the year given in «timestamp», which is the end of Piedmont's Summer period.
"""
year = timestamp.year
apr_7th = datetime(year=year, month=4, day=7, second=1)
... | 0f9a1ac81942606b48a8dee9eb468c25ac6469c8 | 52,448 |
def oval_entity_is_extvar(elem):
"""Check if OVAL entity represented by XML element is OVAL
<external_variable> element
Return: True if <external_variable>, False otherwise"""
return elem.tag == '{%s}external_variable' % oval_ns | f73b76913f8f43d09502514a20e8527d2510920a | 52,449 |
def dispatch_file(file: File):
"""
Dispatch file by extension.
"""
if file.extension in ["jpg", "png", "svg", "gif"]:
return _prepare_image(file)
return """
<div class='panel panel-default'>
<div class='panel-body'>
<p>{}</p>
<a class='btn... | 342716cbf6fe30aae237e09d2d1e38dfdfe395f6 | 52,450 |
def next_day(date, dayOfWeek):
"""
:rtype: Column
>>> from pysparkling import Context, Row
>>> from pysparkling.sql.session import SparkSession
>>> spark = SparkSession(Context())
>>> spark.range(1, 10).select(next_day(concat(lit("2019-11-0"), col("id")), "Mon")).show()
+-------------------... | 399fff8eadfe3505c70269b70e519213142c5527 | 52,451 |
def check_sqlalchemy_results_are_equal(results1, results2):
"""Compare two lists of SQLAlchemy results to see if they are equal"""
list1 = [sqlalchemy_obj_to_dict(item) for item in results1]
list2 = [sqlalchemy_obj_to_dict(item) for item in results2]
return list1 == list2 | 6ad8652babcb984e3e10ffd6b1f4b198abdf20fa | 52,452 |
def dp_longest_palindrome(dp, S, i, j):
"""
Recursive function for finding the longest palindromic
subsequence from a string using a modified version
of the algorithm above
"""
if i == j:
return S[i]
if (i, j) in dp:
return dp[(i, j)]
if S[i] == S[j]:
if i + 1 == j:
dp[([i, j])] = 2 *... | 92d20e8960bffad7254450e93951789fdb6ac306 | 52,453 |
def prediction_measurement_significance(measurement, \
measurement_statistical_error, \
measurement_systematic_error, \
prediction, \
prediction_statistical_err... | c0a3b33da340a59e705718e11f432292dc445b01 | 52,454 |
def add(x, y):
"""
add
:param x:
:param y:
:return:
"""
return x + y | 3d883dd7b5379830c0502209e15ca3db2e5702af | 52,455 |
def index():
"""
Get the index page
"""
return render_template("index.html"), 200 | d97ec0e3dcf24d2d382be20b1d8f0b1714254136 | 52,456 |
def extract_structure_from_csv(csv_file):
"""
Load csv file that contains folder structure information and return it as pandas.datafram.
Parameters
----------
csv_file: str
The file to be loaded.
Returns
-------
pandas.dataframe
A dataframe containing the essential ... | 0951b2e521f2ba240f65f70c211224c08f5475e5 | 52,457 |
import torch
def get_available_devices():
"""Return CPU and, if present, GPU device.
Returns:
[torch.device]: Available devices for `torch`.
"""
devices = [torch.device("cpu")]
if torch.cuda.is_available():
devices.append(torch.device("cuda"))
return devices | a97b5601792d8d1fa87e9c353f87cdcb6497dcf4 | 52,458 |
import random
def disruptive_uniform_crossover(dna1, dna2):
"""disruptive uniform crossover
uniformly crossover genes between dna1 and dna2,
with children guaranteed to be different from parents,
if the number of differences between parents is larger than 1
"""
differences = sum(1 for i, j in... | f8ba3f3fe95818d126e3449c88f7cb190708a305 | 52,460 |
def getSplicingEntropy(gene_data):
"""
Calculates splicing entropy and frequency for a given gene
Arguments:
tp_data = DataFrame of splicing mutations in given gene
Returns:
splicingEntropy
fi = highest splicing entropy
"""
sp_data = getSplicingData(gene_data)
[splic... | f8285960cf3503beabbe1d40a6aa4cf2a8347689 | 52,461 |
def getbitlen(bint):
"""
Returns the number of bits encoding an integer
"""
return bint.bit_length() | f6ae3253e767382959d372eb5e4612fb85c89ffc | 52,463 |
def lookstr(table, limit=0, **kwargs):
"""Like :func:`petl.util.vis.look` but use str() rather than repr() for data
values.
"""
kwargs['vrepr'] = str
return look(table, limit=limit, **kwargs) | e3ae0cdd09be47b33328bf2d3e19ada03e520738 | 52,464 |
def do_breaks(probes, segments, min_probes=1):
"""List the targeted genes in which a copy number breakpoint occurs."""
intervals = get_gene_intervals(probes)
bpoints = get_breakpoints(intervals, segments, min_probes)
return pd.DataFrame.from_records(bpoints,
columns=... | 97061c71920b7c6e584070af82d5daa40a4efdea | 52,465 |
def convert_dcc_translation(translation):
"""
Converts given tpDcc translation into a translation that DCC can manage
NOTE: tpDcc uses Y up coordinate axes as the base reference axis
:param translation: list(float, float, float)
:return: list(float, float, float)
"""
if get_up_axis_name().l... | ced1006c939be20a991d0862881d65326abfe1f9 | 52,466 |
import tdub.rex
import tdub.config
def rex_stacks(rex_dir, chisq, internal, thesis, png, n_test):
"""Generate plots from TRExFitter result."""
outdir = PosixPath(rex_dir) / "matplotlib"
outdir.mkdir(exist_ok=True)
tdub.config.init_meta_table()
tdub.config.init_meta_logy()
if thesis:
td... | 04d2b953a09f422627d18ab6e1280bf1eebe7272 | 52,469 |
from nevow.context import RequestContext, PageContext
from nevow.testutil import FakeRequest
def flatten(stan, ctx=None):
"""Given the stan and the optional context, return a string containing the
representation of the tree in the given context.
"""
if ctx is None:
ctx = PageContext(tag=None, ... | 55ae1713336e2f7beaa3e05aa9d30a418cfb4789 | 52,470 |
def tenant_is_valid(request):
"""Function will return either True or False depending if a subdomain exists or not."""
return JsonResponse({
'access-granted':True
}) | 665ed42f8417a928eeb0d50c62e96401087dffc8 | 52,471 |
def fp_type02_1(cxt: DecoderContext, fmt: FormatF):
""" CVTF.{LD, LS, ULD, ULS} | NEGF.{D,S} | RECIPF.{D,S} | TRNCF.{DL, DUL, DUW, DW, SL, SUL, SUW, SW} """
# 11 27 4 0 20 16
# 0 0 00001 10010 CVTF.LD
# 0 w 00001 00010 CVTF.LS
# 0 0 10001 10010 CVTF.ULD
# 0 w 10001 00010 ... | 806372bb01c4d70ca60ba0244f07ed9b199f6bd0 | 52,472 |
def coors_in_cylinder(x, y, z, centre, axis, radius, length, inside=True):
"""
Select coordinates in a cylinder given by centre, axis and length.
"""
vec = nm.vstack((x, y, z)) - centre
drv = nm.cross(axis, vec, axisb=0)
dr = nm.sqrt(nm.sum(drv * drv, 1))
dl = nm.dot(axis, vec)
if ... | b0b68d09a307bcc3aeda91f627a3e84d70b4d26a | 52,474 |
import inspect
def check_elasticity_parameters( parameterDict ):
"""
Check the elasticity parameters to make sure they are
allowable.
:param dict parameterDict: A dictionary of parameters
"""
#Create a list of constraint equations
constraintEquations = [ le_pce.evaluate_g1, le_pce.eval... | 1e3627c444d18d6b54f685d4731df039e4d0c09e | 52,475 |
def random_walk_z(N, y, W1, W2):
"""
A random walk method for sampling the inactive variables from a polytope.
**See Also**
domains.sample_z
"""
m, n = W1.shape
s = np.dot(W1, y).reshape((m, 1))
# linear program to get starting z0
if np.all(np.zeros((m, 1)) <= 1-s) and np.all(np.z... | 2d0b1f96c857274d600ae9b8a6fb73571a81b729 | 52,476 |
def get_delay_val(clock_diff,poly_diff,seconds_ref_clock,seconds_ref_poly,seconds,seconds_offset,v=0,diff_pol=1):
"""
Compute delays at seconds_offset+seconds, considering the offsets for each polynomial (seconds_ref_clock and seconds_ref_poly).
Parameters
----------
clock_diff : list of float... | 8c063a855640d66d76928aea07ebc6f31012fbb3 | 52,478 |
def merge_defaultdicts_list(dicts):
"""
Merge one or several default dictionaries
that have list as their values
into a single one
"""
keys = [key for d in dicts for key in d.keys()]
res_dict = defaultdict(list)
for key in set(keys):
res_dict[key] = merge_length_list([d[key] fo... | 9ddb65d694f3547445f0ff2bed6337130cc2a4f1 | 52,479 |
def calc_word_value(word):
"""given a word calculate its value using LETTER_SCORES"""
word_value = 0
for letter in word:
word_value += LETTER_SCORES[letter.upper()]
return word_value | 5b29f565730b06d056fed4609b1151d072535eb0 | 52,480 |
def calc_word_value(word, score=0):
"""Calculate the value of the word entered into function
using imported constant mapping LETTER_SCORES"""
for w in word:
if not w.isalpha():
continue
score += LETTER_SCORES[w.upper()]
return score | 0ba32b0109dfdfcf4dccba5399841819a46f5e8e | 52,481 |
import six
def bi2bt(num):
"""将无符号整数转换为字节序"""
MSBin = b''
while num > 0:
# if six.PY2:
# MSBin = chr(num % 256) + MSBin
# elif six.PY3:
MSBin = six.int2byte(num % 256) + MSBin
num >>= 8
return MSBin | 87d65b017d7c3ea4129fb7f9cfb14cc17055a437 | 52,483 |
def load_dataset_hierarchical(maxlen,
max_sentence_len):
"""
"""
train_data = 'data/delicious/train-data.dat'
train_labels = 'data/delicious/train-label.dat'
val_data = 'data/delicious/valid-data.dat'
val_labels = 'data/delicious/valid-label.dat'
test_data = 'data/delicious/test-data.dat'
test_labels = 'data/d... | 0340ccb327e40aeed752b91c50d9d5fa45e31c85 | 52,485 |
import types
def get_display_name(entity):
"""
Gets the display name for the given :tl:`User`,
:tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise.
"""
if isinstance(entity, types.User):
if entity.last_name and entity.first_name:
return '{} {}'.format(entity.first_na... | c72836c4e9ab44cd67a2cb086516b26caade2bb8 | 52,487 |
def calc_max_cpu(records):
""" Returns the CPU usage at the max temperature, ever
:param records: a list of records of min, max temp and associated CPU avg load
:return: a record with the highest recorded temperature, and the associated list of CPU loads
"""
max_temp = 0
cpu_loads = []
for ... | bee21fadb3fcf9cdbbce79f6281f48350b3ffceb | 52,488 |
import random
def integer_or_decimal(entropy, signed):
"""Returns integer or non-integer decimal; 50% probability of each."""
if random.choice([False, True]):
# Represent it as a decimal so that arithmetic operations are supported:
return display.Decimal(integer(entropy, signed))
else:
return non_in... | 023f47da150c3d3c9d115dce218d46ca53ef350b | 52,489 |
def index(request): # 定义请求需要跳转到的网页
"""学习笔记的主页"""
return render(request, 'learning_logs/index.html') | 95696bfab0fcffb4bcfcb3ae789493dad995d14a | 52,490 |
def get_auth_token():
"""Use the heroku auth:token command to fetch the user's API token.
By using the heroku CLI itself we remove the requirement to set up
an environment variable for the token.
"""
r = sarge.capture_stdout('heroku auth:token')
if r.returncode == 0:
return r.stdout.te... | 095f98d65ad68cee8911756ee74421c4d5e2c82b | 52,491 |
from typing import List
def sort_by_deg(G: nx) -> List[tuple]:
"""
Returns sorted list of nodes by degree
"""
return sorted(nx.degree(G), key=lambda vk: vk[1]) | 0058338cbb83233c5506fae0c9b96da785f7ada8 | 52,493 |
def resnet_qc_101(pretrained=False, **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNetQC(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model_ft = models.resnet101(pretrained=True)
mo... | 4ec69021d8cf6c0f8e0db1e36b3c51e0281285af | 52,494 |
import astropy.units as u
def ROI_def(xylnht):
"""
:param xylnht: X, Y, length, height in arcsec
:return: Array containing [x0, xf, y0, yf]
"""
if xylnht[2] < 0:
raise ValueError("Please input positive length and/or height")
x = xylnht[0] * u.arcsec
y = xylnht[1] * u.arcsec
l... | 066a247362635b6b9885b0357115eb5253f05a53 | 52,495 |
def is_norm(layer, exclude=None):
"""Check if a layer is a normalization layer.
Args:
layer (nn.Module): The layer to be checked.
exclude (type | tuple[type]): Types to be excluded.
Returns:
bool: Whether the layer is a norm layer.
"""
if exclude is not None:
if not... | 71c30db3814bb12589267cbb878f5c877b174fb0 | 52,499 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
# Database setup
common_db_configure(settings)
# Add some default settings (would be nicer to do this programatically)
f = "route_url = pyramid_jinja2.filters:route_url_filter"
settings['jinja2.fi... | 1d51148ec8ce2ca2a1753b45170d6e83a12fe022 | 52,500 |
import yaml
def wsgi_server(config_path):
"""create wsgi server given a config path"""
with open(config_path) as fp:
config = yaml.load(fp)
tile_server = create_tileserver_from_config(config)
return tile_server | 557f84ccbae734a5598dbefce8a22e0b5ad64679 | 52,501 |
def all_task_types_for_sequence(sequence, client=default):
"""
return the list of task_tyes for given asset and current user.
"""
sequence = normalize_model_parameter(sequence)
path = "user/sequences/%s/task-types" % sequence["id"]
task_types = raw.fetch_all(path, client=client)
return sort_... | bd0b665a8045dd53c30092ff29af90a78a2170e3 | 52,502 |
def find_most_probable_dates(text):
"""
Find in text the patterns that are the most probable to be the date of the documents and return them as
a list match objects, along with the code that characterize the date.
text : the text to be analyzed
Return : (match_list, code)
match_list : the list o... | bcfb36e4d5017c9746b761f5c263c853be037ef6 | 52,503 |
import scipy
def gensettings(T, Z=300, EED=1e-6, n=5e19, yMax=5):
"""
Generate appropriate DREAM settings.
T: Electron temperature.
Z: Effective charge of plasma.
EEc: Electric field (in units of critical electric field).
n: Electron density.
yMax: Maximum momentum (normalized t... | 123ef49d540c11d3bbe3620a75de0ca48357b641 | 52,504 |
import random
def get_fitness(individual, hash_table, environment, rerun=0):
"""
Gets fitness from hash table if possible, otherwise gets it from simulation
rerun = 0 means never rerun
rerun = 1 means rerun with diminishing probability
rerun = 2 means rerun always
"""
values = hash_table.f... | 648814b573af3237d5d6f3ed9aaff73fbc0e2e40 | 52,505 |
import itertools
def grid_params(dict):
""" Generate all possible combinations (cartesian product) of the hyperparameter values
Returns:
A new dictionary with a grid of all the possible hyperparameter combinations
"""
keys = dict.keys()
val_arr = []
for key in keys:
val_arr.appen... | ca8fdd49d094c3e43e08614c32a40c2d4f020748 | 52,506 |
def datetime_to_str(dt):
"""
Convert default datetime format to str & remove digits after int part of seconds
"""
result = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-7]
return result | 5a08bb546f8afc8a6dbbbf827389f86d8004de28 | 52,507 |
from typing import List
def longest_substring_using_nested_for_loop(s: str) -> int:
"""
Given a string s, find the length of the longest substring without repeating characters.
https://leetcode.com/problems/longest-substring-without-repeating-characters/
3946 ms 14.2 MB
>>> longest_substring_usin... | 996ce5fcb956012cb75fef35c6bec8be6ecad461 | 52,508 |
def neighborhood_values(image: np.ndarray, r: int, c: int, mode: str):
"""
Get values of pixels in the neighborhood of the current position
"""
assert mode in {'forward', 'reverse', 'search', 'forward4'}
neighborhood = []
for (supp_r, supp_c) in neighborhood_idxs(image, r, c, mode):
if... | 8185aefdac574bd7287d76d9f5df7b50e3aa8abc | 52,509 |
def get_fit3_treatment():
"""
Returns fit file for unit tests.
"""
info_path = InfoPath(
path='temp_data',
dir_name="a04_height3_treatment",
sub_dir_name=InfoPath.DO_NOT_CREATE
)
iters = get_iters()
data = get_data3_tr... | 71bcb7c6f2726256221031529270e2888c981539 | 52,510 |
def _get_string_value(dictionary, key, default=None):
"""Return the valid string value for key in dictionary or default."""
if isinstance(dictionary, dict) and isinstance(key, str):
value = dictionary.get(key)
if _is_valid(value):
return value
return default | 5bcefc4a8a118dc933ded99a03ef62ca285ef6fe | 52,511 |
def children_intent_handler(handler_input):
"""Handler for Hello World Intent."""
# type: (HandlerInput) -> Response
speech_text = 'Aus meiner Ehe mit Eleonore gingen sechs Kinder hervor, wovon der 1459 geborene Maximilian und die 1465 geborene Kunigunde überlebten.'
try:
if ENABLE_TWEETS:
... | af0edee370ae2d3c99988a901d3a61adaff86745 | 52,512 |
from pathlib import Path
def generate_notebook(
notebook: dict, credentials: Credentials, package_versions: dict, path: Path
) -> None:
"""
Modifies a notebook so that the Relevanceclient has the proper credentials.
Updates notebook to latest RelevanceAI SDK version.
"""
notebook["metadata"][... | 25c92ffbc025bb0d7761dd08cdd3119fd9c7d9a6 | 52,515 |
def create_app() -> Application:
"""
Creates a new instance of the application.
"""
app = Application.create(
name='Auth API',
secret=INTERNAL_TOKEN_SECRET,
health_check_path='/health',
)
# -- OpenID Connect Login ------------------------------------------------
# ... | de7a213a6c337808ab932c14dd40d4bc379b6cb5 | 52,516 |
import re
def isSane(filename):
"""Check whether a file name is sane, in the sense that it does not contain any "funny" characters"""
if filename == '':
return False
funnyCharRe = re.compile('[\t/ ;,$#]')
m = funnyCharRe.search(filename)
if m is not None:
return False
if filena... | d9e8bac7ebad1fd2af024f8880e255fcb40db68c | 52,517 |
def get_list_of_keys( d, *keys ):
"""
crea un nuevo dicionario con el subconjunto de llaves
Parameters
==========
d: dict
keys: tuple
Examples
========
>>>origin = { 'a': 'a', 'b': 'b': 'c': 'c' }
>>>get_list_of_keys( origin, 'b', 'c' )
{ 'b': 'b': 'c': 'c' }
"""
re... | c20291f2b3fe720ccf25e9a08dde15927fce97fb | 52,518 |
def _nearest_cluster_distance(distances_row, labels, i):
"""Calculate the mean nearest-cluster distance for sample i.
Parameters
----------
distances_row : array, shape = [n_samples]
Pairwise distance matrix between sample i and each sample.
labels : array, shape = [n_samples]
labe... | 1fe20cfddf336dab54aaa4140427b93c6cbf89c1 | 52,519 |
def condense_residual_matrix(matrix, sequential_diffs, data_density):
"""
Condense the residuals from a residual matrix to three columns
that represent how far out the prediction was, the number of data points,
and the observed residual.
Args:
matrix: (np.ndarray)
sequential_diffs:
... | 36e3202269f230849df0afe2801a7586ab4c7862 | 52,521 |
from pathlib import Path
def lfn_list(wb, lfn: str = ''):
"""Completer function : for a given lfn return all options for latest leaf"""
if not wb: return []
if not lfn: lfn = '.' # AlienSessionInfo['currentdir']
list_lfns = []
lfn_path = Path(lfn)
base_dir = '/' if lfn_path.parent.as_posix() ... | 997a11088e0ff198c4b4db38f420ae30784a4232 | 52,522 |
def unmap(roi_db):
"""
For each entry in a database, unmap the labels and bounding box targets
back to the full canvas size.
"""
for db in roi_db:
db['labels'] = _unmap(db['labels'], db['total_anchors'], db['idx_inside'], fill=-1)
db['bbox_targets'] = _unmap(db['bbox_targets'], db['... | c148fe25aaaae8c2f16d7ea5882bd07d216b62c9 | 52,523 |
import csv
import itertools
def csv_read_row(filename, n):
""" Read and return nth row of a csv file, counting from 1. """
with open(filename, 'r') as f:
reader = csv.reader(f)
return next(itertools.islice(reader, n-1, n)) | a95cf8ed35b61acff418a02bfa5f8285f589e6d6 | 52,524 |
def load_proto(fpath, proto_type):
"""Load the protobuf
Args:
fpath: The filepath for the protobuf
Returns:
protobuf: A protobuf of the model
"""
with open(fpath, "rb") as f:
return proto_type().FromString(f.read()) | 7b6bcf6d2e56f2ca4087a9ec769b16a986511c55 | 52,525 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.