content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_thumbnail_requirements(thumbnail_sizes):
""" Takes a list of dictionaries with "width", "height", and "method" keys
and creates a map from image media types to the thumbnail size, thumnailing
method, and thumbnail media type to precalculate
Args:
thumbnail_sizes(list): List of dicts w... | 5,296,800 |
def get_connected_regions_light(input_flow, strict=False):
"""
:param input_flow: the binary mask array, with shape [x, y, z], pid_id
:param strict: whether diagonal pixel is considered as adjacent.
:return: a dict, with key 1, 2, 3, ... (int), value is list of location: {1: [(x1, y1, z1), (x2, y2, z2),... | 5,296,801 |
def change_password(username: str, password: str):
"""Change the password of a user.
NOTE: This process invalidates already existing user sessions.
\b
Args:
username: user to change password for
"""
user = User.get_by_username(username)
if not user:
click.echo('User does n... | 5,296,802 |
def main():
"""ostag, OpenStack node marking tool."""
args = parse_args()
if len(args.tag) > 0 and len(args.pin) > 0:
print("You can't use both tagging and pins at the same time")
exit(1)
conn = setup_openstack_api()
hint_enabled = (len(args.hint) > 0)
if args.clear:
cl... | 5,296,803 |
def disconnect():
"""Disconnect from server"""
if request.sid:
sid, stage, part, port = socket_sessions.get(request.sid)
if sid:
# Remove client from the list of connected clients in socket_sessions but keep the client object in socket_clients
# This way if client reconne... | 5,296,804 |
def policy_decision():
"""Determines whether a request is allowed or not
Args:
The function uses HTTP request directly. These argument must be contained in the request:
thing_id (str): identification of the thing
thing_type (str): type of the thing
action (str): get,delete, or c... | 5,296,805 |
def VirtualMachine_Shutdown(VIServer, VirtualMachineList):
"""VMs Shutdown Funktion
Faehrt die OS auf den VMs asyncron runter.
Wenn die VMWare Tools nich installiert sind, werden die VMs mit dem Befehl "Power Off" heruntergefahren.
"""
for VirtualMachineEntry in VirtualMachineList:
VirtualMa... | 5,296,806 |
def test_validate_email_mixed_case_domain():
"""
If the domain portion of the email is mixed case, it should be
converted to lowercase.
"""
email = "Test@ExaMple.com"
expected = "Test@example.com"
serializer = serializers.EmailSerializer()
assert serializer.validate_email(email) == expe... | 5,296,807 |
def calc_num_nodes(np, ppn=1, threshold=0, name=None):
"""Calculate the number of required nodes with optional utilization check.
:param np:
Number of required processing units (e.g. CPUs, GPUs).
:param ppn:
Number of processing units available per node.
:param threshold:
(optio... | 5,296,808 |
def get_status(req_sheet, row_num):
""" Accessor for JIRA Key
Args:
req_sheet: A variable holding an Excel Workbook sheet in memory.
row_num: A variable holding the row # of the data being accessed.
Returns:
A string value of the Notes
"""
return (req_sheet['G' + str(row_... | 5,296,809 |
def validate(model, criterion, valset, iteration, batch_size, n_gpus,
collate_fn, distributed_run, rank):
"""Handles all the validation scoring and printing"""
model.eval()
with torch.no_grad():
val_sampler = DistributedSampler(valset) if distributed_run else None
val_loader = D... | 5,296,810 |
def get_permissions(limit=None, offset=None):
"""Get permissions"""
session = current_app.appbuilder.get_session
total_entries = session.query(func.count(Permission.id)).scalar()
query = session.query(Permission)
actions = query.offset(offset).limit(limit).all()
return action_collection_schema.d... | 5,296,811 |
def build_data_loader(
X: List[str],
y: List[List[str]],
batch_size: int,
tokenizer: BPETokenizer,
) -> torch.utils.data.DataLoader:
"""Build data loader.
Args:
X: list of textual data.
y: list of tags (TODO).
batch_size: how many samples in a single batc... | 5,296,812 |
def extract_wikipedia_id(url: Union[str, ParseResult, None]) -> Optional[str]:
""" extract Wikipedia ID from URL """
url = parse_url(url, ("en.wikipedia.org", "en.m.wikipedia.org"))
return (
unquote_plus(url.path[6:]) or None
if url and url.path.startswith("/wiki/")
else None
) | 5,296,813 |
def summation(num) -> int:
"""This function makes numbers summation."""
return sum(range(1, num + 1)) | 5,296,814 |
def SaveArrayWithGeo( array, src_filename, dst_filename, format ):
"""
SaveArrayWithGeo(): Saves an Array (array) with Georeferencing from another file (src_flnm), save it in file (dst_flnm) with format (format)
SaveArrayWithGeo( self, array, src_filename, dst_filename, format )
"""
#From warmerdam at p... Thu Ma... | 5,296,815 |
def main():
"""Go Main Go"""
mesosite = get_dbconn('coop')
mcursor = mesosite.cursor()
# Get max date
current = {}
mcursor.execute("SELECT monthdate, anom_34, soi_3m from elnino")
for row in mcursor:
current[row[0]] = dict(anom_34=row[1], soi_3m=row[2])
url = "http://www.cpc.nc... | 5,296,816 |
def get_mapshape_from_searchmap(hashtable):
"""Suppose keys have the form (x, y). We want max(x), max(y)
such that not necessarily the key (max(x), max(y)) exists
Args:
hashtable(dict): key-value pairs
Returns:
int, int: max values for the keys
"""
ks = hashtable.keys()
h = max([y... | 5,296,817 |
def det(a, b):
"""
Calculate the determinent between two vectors
@param[a] One vector represented as [x,y]
@param[b] One vector represented as [x,y]
"""
return a[0] * b[1] - a[1] * b[0] | 5,296,818 |
def find_rar(path):
""" This function is designed to find the most appropriate file to use when extracting and/or
processing releases. This is designed for use with torrent clients and their various "on complete"
functionality.
This function will always return the largest file found under a directory, ... | 5,296,819 |
def test_fft():
"""
Kymatio, (C) 2018-present. The Kymatio developers.
https://github.com/kymatio/kymatio/blob/master/kymatio/tests/scattering1d/
test_tensorflow_backend_1d.py
"""
if not got_tf:
return None if run_without_pytest else pytest.skip()
def coefficent(n):
return np... | 5,296,820 |
def GetOSVersion():
"""Retrieve the current OS version from machine.
Returns:
os_version: string, like '10.9.5' or '10.10'.
Raises:
GmacpyutilException: command failed to execute.
GmacpyutilException: os_version does not match expected formatting.
"""
cmd = ['sw_vers', '-productVersion']
out, e... | 5,296,821 |
def env_to_bool(environment_variable: str) -> bool:
""" Translate an environment variable to a boolean value, accounting for minor
variations (case, None vs. False, etc.)
"""
env_value = getenv(environment_variable)
return bool(env_value) and str(env_value).lower() not in ["false", "none"] | 5,296,822 |
def make_var_with_poisson(infile, units, maskfile=None, gain=None, rdnoise=0.,
texp=None, origbkgd=0., epsilon=None, hext=0,
statcent=None, statsize=None, outfile=None,
outtype='var', outsnr=None, returnvar=True,
ver... | 5,296,823 |
def dtype_limits(image, clip_negative=True):
"""Return intensity limits, i.e. (min, max) tuple, of the image's dtype.
Parameters
----------
image : ndarray
Input image.
clip_negative : bool
If True, clip the negative range (i.e. return 0 for min intensity)
even if the image ... | 5,296,824 |
def get_test_data(fname, as_file_obj=True, mode='rb'):
"""Access a file from MetPy's collection of test data."""
path = POOCH.fetch(fname)
# If we want a file object, open it, trying to guess whether this should be binary mode
# or not
if as_file_obj:
return open(path, mode)
return path | 5,296,825 |
def runline(y, n, dn):
"""Perform local linear regression on a channel of EEG data.
A re-implementation of the ``runline`` function from the Chronux package
for MATLAB [1]_.
Parameters
----------
y : np.ndarray
A 1-D array of data from a single EEG channel.
n : int
Length o... | 5,296,826 |
def start_game():
"""start a new game"""
if not __has_argparse:
__print_argparse_warning()
args = {}
else:
args = parse_cli_args()
if args['version']:
print_version_and_exit()
if not debug:
Game(**args).loop() | 5,296,827 |
def ConsecutiveArrays(arr, step=1):
"""
Finds consecutive subarrays satisfying monotonic stepping with step in array.
Returns on each array element the island index (starting from 1).
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: f... | 5,296,828 |
def normalize(X : np.ndarray, feature_axis = 1) -> np.ndarray:
"""
对数据进行归一化 \n
:param feature_axis: 各特征所在的维度 \n
feature_axis = 1 表示每列是不同的特征 \n
"""
if not feature_axis:
X = X.T
_sum = np.sum(X, axis = 0)
for j in range(len(_sum)):
if _sum[j] > 1e-100:
X[:, j] /= _sum[j]
else:
X[... | 5,296,829 |
def table_to_image(
data: pd.DataFrame, titile: str = ""
) -> io.BytesIO:
"""Create image with rate table.
"""
dia = data.plot()
if titile:
ax.set_title(titile)
buffer = io.BytesIO()
img = dia.get_figure()
img.savefig(buffer)
buffer.seek(0)
return buffer | 5,296,830 |
def update_item(id: str,
item_update: ItemUpdate = Body(
..., example=ItemFactory.updated_mock_item)):
"""
update an item
"""
item = item_service.get_item(id)
if not item:
raise HTTPException(status_code=404, detail="Item not found.")
return item_servi... | 5,296,831 |
def fetch_events_ldi(base_url='https://ldi.upenn.edu'):
"""
Fetch events from Leonard & Davis Institute, https://ldi.upenn.edu
"""
events = []
page_soup = BeautifulSoup(requests.get(
urljoin(base_url, '/events')).content, 'html.parser')
try:
pages = page_soup.find('ul', attrs={'... | 5,296,832 |
def splitdata_n_max(data, n_max):
""" split N into n_max - sized bins """
data = np.array(data).flatten()
N = len(data)
data_splited = []
for i in range(np.int64(np.ceil(N/n_max))):
start = i*n_max
stop = np.min([(i+1)*n_max, N])
data_splited.append(data[start:stop])
ret... | 5,296,833 |
def comments_search(posts,comments):
"""
:param posts1:Список со словарями, в которых данные публикаций
:param comments:Список со словарями, в которых данные комментариев
:return:Измененные список posts, с комментариями к постам с статусом sponsored
"""
for post in posts:
post['comms'] ... | 5,296,834 |
def update_weights(batch, batch_dic):
"""
Readjust weights so they sum to 1.
Args:
batch_dic (dict): Dictionary with extra conformer
information about the batch
batch (dict): Batch dictionary
Returns:
new_weights (torch.Tensor): renormalized weights
"""
old_... | 5,296,835 |
def scaled_dot_product_attention(q, k, v, mask):
"""Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must be br... | 5,296,836 |
def get_client_lease_status_raw(client_row=None):
"""list the raw status of client leases."""
theRawLeaseStatus = u'UNKNOWN'
try:
# should probably move to config file
filepath = str("/var/lib/misc/dnsmasq.leases")
if (utils.xisfile(filepath) is True):
theRawLeaseStatus = utils.readFile(filepath)
except Ex... | 5,296,837 |
def __edfdv__(fp, e, kv, dt):
"""
:param fp:
:param e:
:param kv:
:param dt:
:return:
"""
return np.exp(-1j * kv * dt * e[:, None]) * fp | 5,296,838 |
def design_pts_from_ranges(ranges: np.ndarray,
thetas: np.ndarray):
"""
Args:
ranges (np.ndarray, shape=(C,), dtype=np.float32): range per camera ray
thetas (np.ndarray, shape=(C,), dtype=np.float32): in degrees and in increasing order in [-fov/2, fov/2]
... | 5,296,839 |
def import_us_states():
"""
This file:
http://www.census.gov/geo/cob/bdy/st/st00ascii/st99_d00_ascii.zip
From here: http://www.census.gov/geo/www/cob/ascii_info.html
Contains two files with shapes of the states in easy parse format - just
need to parse and find max and min lat and lon to get bo... | 5,296,840 |
def test_lacpd_load_balance(topology, step):
"""Test LAG load balance with l2, l3 and l4 hash algorithms."""
# VID for testing
test_vlan = '256'
# LAG ID for testing
test_lag = '2'
# Ports for testing
test_port_tcp = 778
test_port_udp = 777
times_to_send = 150
# interfaces to be ... | 5,296,841 |
def _dict_as_called(function, args, kwargs):
""" return a dict of all the args and kwargs as the keywords they would
be received in a real function call. It does not call function.
"""
names, args_name, kwargs_name, defaults = inspect.getargspec(function)
# assign basic args
params = {}
... | 5,296,842 |
def idcst2(x, expk0, expk1):
"""compute inverse discrete cosine-sine transformation
This is equivalent to idxct(idxst(x)^T)^T
"""
if x.is_cuda:
output = dct_cuda.idcst2(x.view([-1, x.size(-1)]), expk0, expk1)
else:
output = dct_cpp.idcst2(x.view([-1, x.size(-1)]), expk0, expk1, torch... | 5,296,843 |
def test_configure_event_publication_specific_topics(mqtt_client):
"""Test configure event publication method with specific topics."""
topics = [
"onvif:Device/axis:IO/VirtualPort",
"onvif:Device/axis:Status/SystemReady",
"axis:Storage//.",
]
mqtt_client.configure_event_publicati... | 5,296,844 |
def is_match(pattern: Any, expr: Expr) -> bool:
"""Returns whether or not an expression matches a pattern."""
if isinstance(pattern, Star):
raise ValueError('`Star` pattern must be inside of a sequence.')
for _ in matcher(pattern)(expr, {}, id_success):
return True
return False | 5,296,845 |
def add(a, b):
"""The add function.
Args:
a (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix.
b (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix.
Returns:
sum of `a` and `b`.
"... | 5,296,846 |
def export_file(isamAppliance, name, filepath, check_mode=False, force=False):
"""
Exporting a User Mapping CDAS file
"""
ret_obj = search(isamAppliance, name=name)
id = ret_obj['data']
if id == {}:
logger.info("User Mapping CDAS file '{0}' does not exists. Skipping export file.".for... | 5,296,847 |
def create_authy_user(email, country_code, phone):
"""
Creates a user with the Authy API
:param email: email to be associated with the user.
Used by the API for account recovery
:param country_code: country code for the phone number
:param phone: national format phone number
:returns: ... | 5,296,848 |
def version():
"""
The function that gets invoked by the subcommand "version"
"""
click.echo(
f"Python {platform.python_version()}\n"
f"flask_request_uid {__version__}"
) | 5,296,849 |
def check_remote_vcs():
"""
Check if the vcs-url is reachable.
Returns
-------
check_result: bool
Result for the remote vcs to check.
"""
try:
status = urllib.request.urlopen(VCS_SETTINGS['url']).getcode()
check_result = True if status == 200 else False
except:
... | 5,296,850 |
def describe_all_dataset(msg_flag=False):
"""
Calls the build_dictionary function and prints description of all datasets from that.
"""
dict1=build_dataset_dictionary(msg_flag=msg_flag)
for k,v in dict1.items():
print(f"{k}: {v[0]}")
print('='*100) | 5,296,851 |
def new_program_rest(request):
"""Create new Program object via REST API.
Return: lib.entities.entity.ProgramEntity
"""
yield _common_fixtures(request.fixturename) | 5,296,852 |
async def referer_checker(request: Request):
"""Check the referer header."""
if not request.raw_url.startswith(b'/status'):
config = request.app.system_config.get_config('referer', dict)
# {
# "force": bool,
# "allowed_referer": []
# }
referer = request.he... | 5,296,853 |
def jsonify(*args, **kwargs):
"""Improved json response factory"""
indent = None
status = kwargs.pop('_status', 200)
mime = kwargs.pop('_mime', 'application/json')
# Check for an argument passed, otherwise dict() the kwargs
data = args[0] if args else dict(kwargs)
# Format pretty print ... | 5,296,854 |
def pull_data_for_tickers(
tickers,
tiingo_api_key,
start_date=None,
end_date=None,
save_to='',
check_existing=True,
):
"""
Persist all the available data for each of the ticker in ticker_list
"""
n_tickers = len(tickers)
bar = progressbar.ProgressBar(
maxval=n_ticke... | 5,296,855 |
def test_sub_account_universal_transfer_without_fromAccountType():
"""Tests the API endpoint to transfer asset within master account without fromAccountType"""
params = {
"fromAccountType": "",
"toAccountType": "COIN_FUTURE",
"asset": "BNB",
"amount": 10.1,
"clientTranId... | 5,296,856 |
def AddAcceleratorArgs(parser):
"""Adds Accelerator-related args."""
parser.add_argument(
'--accelerator',
type=arg_parsers.ArgDict(spec={
'type': str,
'count': int,
}, required_keys=['type'], max_length=2),
metavar='type=TYPE,[count=COUNT]',
help="""\
Attache... | 5,296,857 |
def edmonds_karp(graph, source, destination):
"""Find maximum flow between two vertices in a weighted graph.
Args:
graph: Undirected or directed graph where every edge has property
'capacity' that indicates how many units may flow through it.
source: Source vertex.
destinati... | 5,296,858 |
def _get_all_names(tree):
"""
Return list of all words.
:param tree: _ast.Module object
:return: list with words
"""
return (node.id for node in ast.walk(tree) if isinstance(node, ast.Name)) | 5,296,859 |
def intersect_layers_columns(layers, columns):
"""
Iterator that makes layers on each column and yields the corresponding
pyto.scene.CleftRegion object.
Simply intersects layers with each of the columns. Respects inset attribute.
Arguments:
- layers: (CleftRegions) cleft layers
- colu... | 5,296,860 |
def download_image_link(link, dir_path, prefix = ''):
"""Use urllib to download asset
Args:
link (str):
dir_path (str):
prefix (str):
Returns:
bool
"""
print(f'download_image_link: from "{link}"')
try:
o = urlparse(link)
ref = o.scheme +... | 5,296,861 |
def rot_mat2rot_angle(rot_mat):
""" Return the angle corresponding to the given 2D rotation matrix."""
return np.arctan2(rot_mat[1, 0], rot_mat[0, 0]) | 5,296,862 |
def normalize(array):
"""
Normalize a 1d numpy array between [0,1]
Parameters
----------
array: ndarray
the array to normalize
Returns
-------
ndarray
the normalized array
"""
ptp = np.ptp(array)
if ptp != 0:
return (array - np.min(array)) / np.ptp(... | 5,296,863 |
def setup_logger(cfg):
"""setup loggers"""
logfmt = '%(message)s'
max_bytes = int(cfg["file-max-size"].split('M')[0]) * 1024 * 1024
file_logger.setLevel(logging.INFO)
file_logger.propagate = False
lh = logging.handlers.RotatingFileHandler(
cfg["file"],
maxBytes=max_byte... | 5,296,864 |
def heatmap(matrix, highlight_index=None, labels_left=None, labels_right=None, path=None):
"""
:param matrix: (n x n)
:param highlight_index: (n x 2)
:return:
"""
fig, ax = plt.subplots()
ax = sns.heatmap(matrix, ax=ax, linewidths=.5, cbar=False,
yticklabels=["%.1f" % l ... | 5,296,865 |
def read_file_info(file, hdrnum, print_trace=None, content_mode="translated", content_type="simple",
outstream=sys.stdout, errstream=sys.stderr):
"""Read information from file
Parameters
----------
file : `str`
The file from which the header is to be read.
hdrnum : `int`
... | 5,296,866 |
def get_dataset(config, key, *,
num_tasks):
""""Get dataset."""
if config.env.name == 'gym' or config.env.name == 'random':
return MDPDataset(config, key, num_tasks=num_tasks)
elif config.env.name == 'pw':
return DistributedSampleDataset(config, key, num_tasks=num_tasks)
else:
raise ... | 5,296,867 |
def write_packet(conn, data):
"""Write a packet to a connection"""
pickled = pickle.dumps(data)
size = struct.pack("I", len(pickled))
_write_on_socket(conn, size)
_write_on_socket(conn, pickled) | 5,296,868 |
def km2_by_state(list_of_park_dicts):
"""
This function takes a list of national park data (e.g. the returned value from
<read_csv_file>), and returns a new dictionary that contains the summed
area (in kilometers squared) of national parks in each state. The output
dictionary should have the format:... | 5,296,869 |
def run_locally_or_on_slurm(
tasks: List[Task],
results_dir: pathlib.Path,
slurm_dir: pathlib.Path,
):
"""Run tasks locally or on slurm, based on command line args.
Tasks whose target_file_name already exists will be skipped.
Currently slurm not supported, local only.
Arguments:
tasks: ... | 5,296,870 |
def getRuleCount( lstRules, policy_name ):
"""
This function return the rule count for a given policy
indicated by policy_name
Parameters:
- IN : 1. List containing all the rules
2. Name of the policy
- Out: # of rules in the policy.
"""
count = 0
for x in lstRules:
if x.split(',')[0] == poli... | 5,296,871 |
def send_format(catfact):
"""
Format's the catfact into a the message to send content string
"""
return """
Thank you for subscribing to CatFacts™
Did you know:
```
{}```
Type "UNSUBSCRIBE" to unsubscribe from future catfacts.
""".format(catfact) | 5,296,872 |
def setup_ssh(tn_conn):
"""Function to enable SSH on the device
:param tn_conn: the Telnet connection
:type tn_conn: class:Telnet
:return: 0 if the function succeeded, 1 if it failed, or 2 if there was an error.
:rtype: int
:raises ex: raises a runtime error
"""
rval = lu.FAIL
try... | 5,296,873 |
def pretrain_and_finetune(models_dict: torch.nn.ModuleDict,
pretrain_train_loader: DataLoader,
pretrain_eval_loader: DataLoader,
pretrain_epochs: int,
finetune_train_loader: DataLoader,
fine... | 5,296,874 |
def pred_V(src, dest=None, start=None, end=None):
"""Sub-processing calls the matlab function to predict V/I
Parameters
----------
src : str
hdf5 file contain forward modeling parameters
dest : str, default None
Copy hdf5 file to new destination. The default is not to copy
start... | 5,296,875 |
def test_retry_exhausted():
"""Test retry."""
exceptions_in = [
RuntimeError("what?"),
NotImplementedError("how?"),
RuntimeError("no!"),
NotImplementedError("when?"),
]
actual = []
expected = [1.0, 1.5]
def sleep(wait: float):
actual.append(wait)
@r... | 5,296,876 |
def rm_file( path ):
""" Remove the specified file
"""
logr.info( synctype = 'RMFILE',
src = str( path ) )
os.unlink( path ) | 5,296,877 |
def build_d_layer(flow, name, num_outputs=3):
"""
arXiv:1703.10593v1
d64
"""
with tf.variable_scope(name):
weights_initializer = tf.truncated_normal_initializer(stddev=0.02)
flow = tf.contrib.layers.convolution2d(
inputs=flow,
num_outputs=num_outputs,
... | 5,296,878 |
def drop_infreq_labels(seqs, labels):
"""Filter out infrequent labels."""
label_vocab, label_counts = np.unique(labels, return_counts=True)
is_dropped = {}
for i in xrange(len(label_vocab)):
logging.info('Found label %s, with count %d.', label_vocab[i],
label_counts[i])
if label_counts[... | 5,296,879 |
def show_function_info(func):
"""関数情報表示用デコレータ関数
:param func: 対象関数
:return: wrappaer関数
"""
@wraps(func)
def wrapper(*args, **kwargs):
"""内部ラッパー関数
"""
print('--------------------------------------------------------------')
print(f'Name: {func.__name__}')
pri... | 5,296,880 |
def datacite_format_contributors(contributors):
""" Format a list of contributors to match the datacite schema
:param contributors_list: list of OSFUsers to format
:return: formatted json for datacite
"""
creators = []
for contributor in contributors:
name_identifiers = [
{
... | 5,296,881 |
def get_drought_stress_days(culture_id, trial_dates, climate_data, soilVolume,
availMoistCap, precipitation, irrigation,
stress_threshold=10.0, flowerDate='2012-07-01'):
"""
calculates the number of drought stress days before and after the flowering
da... | 5,296,882 |
def ppo(env_fn, actor_critic=MLPActorCritic, ac_kwargs=dict(), seed=0,
steps_per_epoch=4000, epochs=50, gamma=0.99, clip_ratio=0.2, pi_lr=3e-4,
vf_lr=1e-3, train_pi_iters=80, train_v_iters=80, lam=0.97, max_ep_len=1000,
target_kl=0.01, logger_kwargs=dict(), save_freq=10):
"""
Proximal Po... | 5,296,883 |
def _compute_and_update_PI_kernel(
i,
T_A,
T_B,
m,
QT_even,
QT_odd,
QT_first,
M_T,
Σ_T,
μ_Q,
σ_Q,
k,
ignore_trivial,
excl_zone,
profile,
indices,
compute_QT,
):
"""
A Numba CUDA kernel to update the matrix profile and matrix profile indices
... | 5,296,884 |
def errorhandler(e):
"""Handle error"""
return apology(e.name, e.code) | 5,296,885 |
def start():
"""
Start Quota Manager
"""
first_time = True
automatic_bricks = []
automatic_pass = 0
while True:
brick_path = os.environ.get("BRICK_PATH", None)
if brick_path is not None:
if brick_path.lower() == 'auto':
# Getting the bricks is expe... | 5,296,886 |
def _detect_light_colab_theme() -> bool:
"""Detect if it's light theme in Colab."""
try:
get_ipython # type: ignore
except NameError:
return False
ipython = get_ipython() # noqa: F821
if "google.colab" in str(ipython.__class__):
try:
from google.colab import out... | 5,296,887 |
def effect_from_model(model, ref, ref_rc, alt, alt_rc, methods, mutation_positions, out_annotation_all_outputs,
extra_args=None, **argv):
"""Convenience function to execute multiple effect predictions in one call
# Arguments
model: Keras model
ref: Input sequence with the ... | 5,296,888 |
def list_semantic_shift_tokens(snapshot_emb):
"""
Check which tokens have undergone a continuous semantic shift over time (ignoring new words).
Inputs:
- snapshot_emb [dict: {str: SimplePretrainedEmbeddings}]: embedding snapshots for all snapshot dates (as computed with compute_emb_snapshots)
... | 5,296,889 |
def inception_resnet_block(x, scale, block_type, block_idx, activation='relu'):
"""Inception-ResNet block.
"""
if block_type == 'block35':
branch_0 = conv2d_bn(x, 32, 1)
branch_1 = conv2d_bn(x, 32, 1)
branch_1 = conv2d_bn(branch_1, 32, 3)
branch_2 = conv2d_bn(x, 32, 1)
... | 5,296,890 |
def get_frame_acc(seconds_fr,num_frame,fs,samples_per_channel_in_frame,list_acc_frontiers,acc_time):
"""
Returns the index of the accumulation period corresponding to this frame, the relative number of the frame into the acc period,
and the seconds corresponding to the first sample.
Parameters
... | 5,296,891 |
def Search_Form():
"""Render the search form"""
return render_template("search.html") | 5,296,892 |
def canonize(request):
"""Enforce a certain scheme and hostname. Store these on request as well.
"""
scheme = request.headers.get('X-Forwarded-Proto', 'http') # per Heroku
host = request.headers['Host']
bad_scheme = scheme != canonical_scheme
bad_host = bool(canonical_host) and (host != canonica... | 5,296,893 |
def function_mask_wrapper(func, x0, mask, arg, kwarg, x):
"""
Wrapper function for Python function using a mask.
To be used with partial:
`obj = partial(function_mask_wrapper, func, x0, mask, arg, kwarg)`
This allows then calling obj with only the non-masked parameters:
`fx = obj(x)`
... | 5,296,894 |
def main():
"""
Calculate and output the solutions based on the real puzzle input.
"""
data = aocd.get_data(year=2015, day=15)
ingredients = read_ingredients(data)
print(f"Part 1: {best_possible_cookie_score(ingredients)}")
print(f"Part 2: {best_possible_cookie_score(ingredients, exact_calo... | 5,296,895 |
def filt_velocity_boundary(
x, y, melt=None, blon=186, blat=-82.68, dlon=13, dlat=0.06, return_index=False
):
"""
params for 3km grid: blon=186, blat=-82.68, dlon=13, dlat=0.06
"""
X, Y = np.meshgrid(x, y)
lon, lat = transform_coord(3031, 4326, X, Y)
lon[lon < 0] += 360
(ii, jj) = np.whe... | 5,296,896 |
def generateRules(L, supportData, minConf=0.7):
"""
Generate rules of (k)-itemset implied by (k-1)-itemset
:param L: list of all Lk
:param supportData: dict of support data value
:param minConf: minimum confidence of rule interested in
:return: list of all the rules implied by L
"""
... | 5,296,897 |
def get_pronoun(pronoun, gender='MALE', sep='_'):
""" Gets the correct gender pronoun
Arguments:
pronoun {str} -- HE_SHE pronoun that needs to be converted
Keyword Arguments:
gender {str} -- [description] (default: {'MALE'})
sep {str} -- [description] (default: {'_'})
... | 5,296,898 |
def is_fill_compute_el(obj):
"""Object contains executable methods 'fill' and 'compute'."""
return hasattr(obj, 'fill') and hasattr(obj, 'compute') \
and callable(obj.fill) and callable(obj.compute) | 5,296,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.