text
stringlengths 3
1.05M
|
|---|
/**
* Copyright 2017 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Services} from '../../services';
import {devAssert} from '../../log';
import {
layoutRectEquals,
layoutRectLtwh,
layoutRectsOverlap,
layoutRectsRelativePos,
} from '../../layout-rect';
/** @enum {number} */
export const PositionObserverFidelity = {
HIGH: 1,
LOW: 0,
};
/** @const @private */
const LOW_FIDELITY_FRAME_COUNT = 4;
/**
* TODO (@zhouyx): rename relativePos to relativePositions
* The positionObserver returned position value which includes the position rect
* relative to viewport. And viewport rect which always has top 0, left 0, and
* viewport width and height.
* @typedef {{
* positionRect: ?../../layout-rect.LayoutRectDef,
* viewportRect: !../../layout-rect.LayoutRectDef,
* relativePos: string,
* }}
*/
export let PositionInViewportEntryDef;
export class PositionObserverWorker {
/**
* @param {!../ampdoc-impl.AmpDoc} ampdoc
* @param {!Element} element
* @param {!PositionObserverFidelity} fidelity
* @param {function(?PositionInViewportEntryDef)} handler
*/
constructor(ampdoc, element, fidelity, handler) {
/** @const {!Element} */
this.element = element;
/** @const {function(?PositionInViewportEntryDef)} */
this.handler_ = handler;
/** @type {!PositionObserverFidelity} */
this.fidelity = fidelity;
/** @type {number} */
this.turn =
(fidelity == PositionObserverFidelity.LOW)
? Math.floor(Math.random() * LOW_FIDELITY_FRAME_COUNT)
: 0;
/** @type {?PositionInViewportEntryDef} */
this.prevPosition_ = null;
/** @private {!../viewport/viewport-impl.Viewport} */
this.viewport_ = Services.viewportForDoc(ampdoc);
}
/**
* Call to trigger an entry handler
* @param {!PositionInViewportEntryDef} position
* @private
*/
trigger_(position) {
const prevPos = this.prevPosition_;
if (
prevPos &&
layoutRectEquals(prevPos.positionRect, position.positionRect) &&
layoutRectEquals(prevPos.viewportRect, position.viewportRect)
) {
// position didn't change, do nothing.
return;
}
devAssert(
position.positionRect,
'PositionObserver should always trigger entry with clientRect'
);
const positionRect =
/** @type {!../../layout-rect.LayoutRectDef} */ (position.positionRect);
// Add the relative position of the element to its viewport
position.relativePos = layoutRectsRelativePos(
positionRect,
position.viewportRect
);
if (layoutRectsOverlap(positionRect, position.viewportRect)) {
// Update position
this.prevPosition_ = position;
// Only call handler if entry element overlap with viewport.
this.handler_(position);
} else if (this.prevPosition_) {
// Need to notify that element gets outside viewport
// NOTE: This is required for inabox position observer.
this.prevPosition_ = null;
position.positionRect = null;
this.handler_(position);
}
}
/**
* To update the position of entry element when it is ready.
* Called when updateAllEntries, or when first observe an element.
* @param {boolean=} opt_force
*/
update(opt_force) {
if (!opt_force) {
if (this.turn != 0) {
this.turn--;
return;
}
if (this.fidelity == PositionObserverFidelity.LOW) {
this.turn = LOW_FIDELITY_FRAME_COUNT;
}
}
const viewportSize = this.viewport_.getSize();
const viewportBox = layoutRectLtwh(
0,
0,
viewportSize.width,
viewportSize.height
);
this.viewport_.getClientRectAsync(this.element).then(elementBox => {
this.trigger_(
/** @type {./position-observer-worker.PositionInViewportEntryDef}*/ ({
positionRect: elementBox,
viewportRect: viewportBox,
relativePos: '',
})
);
});
}
}
|
import React from "react";
const LogoutButton = () => {
const logout = async () => {
const domain = "ambient-coder.us.auth0.com";
const clientId = "your-client-id";
const returnTo = "http://localhost:3000";
const response = await fetch(
`https://${domain}/logout?client_id=${clientId}&returnTo=${returnTo}`,
{ redirect: "manual" }
);
window.location.replace(response.url);
};
return (
<button className="Login-button" onClick={() => logout()}>
Log out
</button>
);
};
export default LogoutButton;
|
from random import Random
l = [2, 3, 5, 7, 11]
for x in l:
print(x)
s = "Hallo!"
for c in s:
print(c)
class Wuerfel(object):
def __init__(self):
self.r = Random()
def __iter__(self):
return self
def __next__(self):
return self.r.randint(1, 6)
#w = Wuerfel()
#for a in w:
# print(a)
# Generator für Fibonacci-Zahlen
# 1 1
# 2
# 3
# 5
# 8
# 13
def fib():
a = 1
b = 1
while (True):
(a, b) = (b, a + b)
yield a
f = fib()
l = []
for i in range(10):
l.append(next(f))
print(l)
|
from neuralnetwork import *
if __name__ == '__main__':
X = numpy.array([
[0, 0],
[0, 1],
[1, 0],
[1, 1],
])
T = numpy.array([
[0], [1], [1], [0],
])
N = X.shape[0]
input_size = X.shape[1]
hidden_size = 2
output_size = 2
epsilon = 0.1
mu = 0.9
epoch = 10000
nn = Neural(input_size, hidden_size, output_size)
nn.train(X, T, epsilon, mu, epoch)
nn.error_graph()
C, Y = nn.predict(X)
for i in range(N):
x, t, c = X[i, :], T[i, :], C[i]
print("x: {}\n".format(x))
print("t: {}\n".format(t))
print("c: {}\n".format(c))
|
/*
* Use of this source code is governed by an Apache license that can be
* found in the LICENSE file.
*/
/**
* Class handling server discussion with client
* @param {[type]} rtcServer [description]
*/
function GameServer(rtcServer){
var that = this;
this.rtcServer = rtcServer;
//Master gamestate
this.gameState = {};
this.registerEvents();
}
/**
* Special log to append the Class name beforehand
* @param {...[type]} params [description]
* @return {[type]} [description]
*/
GameServer.prototype.log = function(...params){
let args = ["[==GAMESERVER==]"].concat(params);
console.log.apply(console, args);
};
/**
* Registering network calls made by clients
* @return {[type]} [description]
*/
GameServer.prototype.registerEvents = function(){
//DEFAULT GAME CALLS
var onEasyrtcMsg = function(connectionObj, msg, socketCallback, next){
this.gameState[msg.msgData.roomName] = this.gameState[msg.msgData.roomName] || {clients : {}};
switch(msg.msgType){
case "clientConnect":
case "gameStateUpdated":
this.gameState[msg.msgData.roomName].clients[msg.msgData.clientState.ID] = msg.msgData.clientState;
socketCallback({msgType : "gameState", msgData : {gameState : this.gameState[msg.msgData.roomName]}}); //nice
next(null);
break;
case "getGameState":
socketCallback({msgType : "gameState", msgData : {gameState : this.gameState[msg.msgData.roomName]}}); //nice
next(null);
break;
case "clientDisconnect":
delete this.gameState[msg.msgData.roomName].clients[msg.msgData.clientState.ID];
this.rtcServer.events.emit("gameState", connectionObj, msg, socketCallback, next);
next(null);
break;
default:
this.rtcServer.events.emitDefault("easyrtcMsg", connectionObj, msg, socketCallback, next);
break;
}
};
this.rtcServer.events.on("easyrtcMsg", onEasyrtcMsg.bind(this));
};
module.exports = GameServer;
|
// -------------------------------------------------------------------------
// @FileName : NFMailPlugin.h
// @Author : LvSheng.Huang
// @Date : 2016-12-18
// @Module : NFMailPlugin
//
// -------------------------------------------------------------------------
#ifndef NF_MAIL_PLUGIN_H
#define NF_MAIL_PLUGIN_H
///
#include "NFComm/NFPluginModule/NFIPlugin.h"
#include "NFComm/NFPluginModule/NFIPluginManager.h"
class NFMailPlugin : public NFIPlugin
{
public:
NFMailPlugin(NFIPluginManager* p)
{
pPluginManager = p;
}
virtual const int GetPluginVersion() override;
virtual const std::string GetPluginName() override;
virtual void Install() override;
virtual void Uninstall() override;
};
#endif
|
#include "hashfunc.h"
/*
** FNV-1a
** https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function
*/
uint32_t fnv1a(const char* data, int len){
static const uint32_t PRIME = 16777619;
static const uint32_t OFFSET = 2166136261;
int i;
uint32_t result = OFFSET;
for(i=len-1; i>=0; i--){
result ^= data[i];
result *= PRIME;
}
return result;
}
/*
** DJB2
** http://www.cse.yorku.ca/~oz/hash.html
*/
uint32_t hashfunc(const char* data, int len){
int i;
uint32_t result = 5381;
for(i=len-1; i>=0; i--){
result += (result << 5) + data[i];
}
return result;
}
|
#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 SINA Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# @author: Zhongyue Luo, SINA Corporation.
#
"""Extracts OpenStack config option info from module(s)."""
import imp
import os
import re
import socket
import sys
import textwrap
from oslo.config import cfg
from ironic.openstack.common import gettextutils
from ironic.openstack.common import importutils
gettextutils.install('ironic')
STROPT = "StrOpt"
BOOLOPT = "BoolOpt"
INTOPT = "IntOpt"
FLOATOPT = "FloatOpt"
LISTOPT = "ListOpt"
MULTISTROPT = "MultiStrOpt"
OPT_TYPES = {
STROPT: 'string value',
BOOLOPT: 'boolean value',
INTOPT: 'integer value',
FLOATOPT: 'floating point value',
LISTOPT: 'list value',
MULTISTROPT: 'multi valued',
}
OPTION_COUNT = 0
OPTION_REGEX = re.compile(r"(%s)" % "|".join([STROPT, BOOLOPT, INTOPT,
FLOATOPT, LISTOPT,
MULTISTROPT]))
PY_EXT = ".py"
BASEDIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
"../../../../"))
WORDWRAP_WIDTH = 60
def generate(srcfiles):
mods_by_pkg = dict()
for filepath in srcfiles:
pkg_name = filepath.split(os.sep)[1]
mod_str = '.'.join(['.'.join(filepath.split(os.sep)[:-1]),
os.path.basename(filepath).split('.')[0]])
mods_by_pkg.setdefault(pkg_name, list()).append(mod_str)
# NOTE(lzyeval): place top level modules before packages
pkg_names = filter(lambda x: x.endswith(PY_EXT), mods_by_pkg.keys())
pkg_names.sort()
ext_names = filter(lambda x: x not in pkg_names, mods_by_pkg.keys())
ext_names.sort()
pkg_names.extend(ext_names)
# opts_by_group is a mapping of group name to an options list
# The options list is a list of (module, options) tuples
opts_by_group = {'DEFAULT': []}
for pkg_name in pkg_names:
mods = mods_by_pkg.get(pkg_name)
mods.sort()
for mod_str in mods:
if mod_str.endswith('.__init__'):
mod_str = mod_str[:mod_str.rfind(".")]
mod_obj = _import_module(mod_str)
if not mod_obj:
continue
for group, opts in _list_opts(mod_obj):
opts_by_group.setdefault(group, []).append((mod_str, opts))
print_group_opts('DEFAULT', opts_by_group.pop('DEFAULT', []))
for group, opts in opts_by_group.items():
print_group_opts(group, opts)
print "# Total option count: %d" % OPTION_COUNT
def _import_module(mod_str):
try:
if mod_str.startswith('bin.'):
imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:]))
return sys.modules[mod_str[4:]]
else:
return importutils.import_module(mod_str)
except ImportError as ie:
sys.stderr.write("%s\n" % str(ie))
return None
except Exception:
return None
def _is_in_group(opt, group):
"Check if opt is in group."
for key, value in group._opts.items():
if value['opt'] == opt:
return True
return False
def _guess_groups(opt, mod_obj):
# is it in the DEFAULT group?
if _is_in_group(opt, cfg.CONF):
return 'DEFAULT'
# what other groups is it in?
for key, value in cfg.CONF.items():
if isinstance(value, cfg.CONF.GroupAttr):
if _is_in_group(opt, value._group):
return value._group.name
raise RuntimeError(
"Unable to find group for option %s, "
"maybe it's defined twice in the same group?"
% opt.name
)
def _list_opts(obj):
def is_opt(o):
return (isinstance(o, cfg.Opt) and
not isinstance(o, cfg.SubCommandOpt))
opts = list()
for attr_str in dir(obj):
attr_obj = getattr(obj, attr_str)
if is_opt(attr_obj):
opts.append(attr_obj)
elif (isinstance(attr_obj, list) and
all(map(lambda x: is_opt(x), attr_obj))):
opts.extend(attr_obj)
ret = {}
for opt in opts:
ret.setdefault(_guess_groups(opt, obj), []).append(opt)
return ret.items()
def print_group_opts(group, opts_by_module):
print "[%s]" % group
print
global OPTION_COUNT
for mod, opts in opts_by_module:
OPTION_COUNT += len(opts)
print '#'
print '# Options defined in %s' % mod
print '#'
print
for opt in opts:
_print_opt(opt)
print
def _get_my_ip():
try:
csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
csock.connect(('8.8.8.8', 80))
(addr, port) = csock.getsockname()
csock.close()
return addr
except socket.error:
return None
def _sanitize_default(s):
"""Set up a reasonably sensible default for pybasedir, my_ip and host."""
if s.startswith(BASEDIR):
return s.replace(BASEDIR, '/usr/lib/python/site-packages')
elif BASEDIR in s:
return s.replace(BASEDIR, '')
elif s == _get_my_ip():
return '10.0.0.1'
elif s == socket.gethostname():
return 'ironic'
elif s.strip() != s:
return '"%s"' % s
return s
def _print_opt(opt):
opt_name, opt_default, opt_help = opt.dest, opt.default, opt.help
if not opt_help:
sys.stderr.write('WARNING: "%s" is missing help string.\n' % opt_name)
opt_type = None
try:
opt_type = OPTION_REGEX.search(str(type(opt))).group(0)
except (ValueError, AttributeError) as err:
sys.stderr.write("%s\n" % str(err))
sys.exit(1)
opt_help += ' (' + OPT_TYPES[opt_type] + ')'
print '#', "\n# ".join(textwrap.wrap(opt_help, WORDWRAP_WIDTH))
try:
if opt_default is None:
print '#%s=<None>' % opt_name
elif opt_type == STROPT:
assert(isinstance(opt_default, basestring))
print '#%s=%s' % (opt_name, _sanitize_default(opt_default))
elif opt_type == BOOLOPT:
assert(isinstance(opt_default, bool))
print '#%s=%s' % (opt_name, str(opt_default).lower())
elif opt_type == INTOPT:
assert(isinstance(opt_default, int) and
not isinstance(opt_default, bool))
print '#%s=%s' % (opt_name, opt_default)
elif opt_type == FLOATOPT:
assert(isinstance(opt_default, float))
print '#%s=%s' % (opt_name, opt_default)
elif opt_type == LISTOPT:
assert(isinstance(opt_default, list))
print '#%s=%s' % (opt_name, ','.join(opt_default))
elif opt_type == MULTISTROPT:
assert(isinstance(opt_default, list))
if not opt_default:
opt_default = ['']
for default in opt_default:
print '#%s=%s' % (opt_name, default)
print
except Exception:
sys.stderr.write('Error in option "%s"\n' % opt_name)
sys.exit(1)
def main():
if len(sys.argv) < 2:
print "usage: %s [srcfile]...\n" % sys.argv[0]
sys.exit(0)
generate(sys.argv[1:])
if __name__ == '__main__':
main()
|
/*
* Kendo UI Web v2014.1.318 (http://kendoui.com)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-web
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public License (GPL) version 3.
* For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html
*/
!function(e,define){define([],e)}(function(){return function(e){var t=e.kendo||(e.kendo={cultures:{}});t.cultures["rw-RW"]={name:"rw-RW",numberFormat:{pattern:["-n"],decimals:2,",":" ",".":",",groupSize:[3],percent:{pattern:["-n %","n %"],decimals:2,",":" ",".":",",groupSize:[3],symbol:"%"},currency:{pattern:["$-n","$ n"],decimals:2,",":" ",".":",",groupSize:[3],symbol:"RWF"}},calendars:{standard:{days:{names:["Ku wa mbere","Ku wa kabiri","Ku wa gatatu","Ku wa kane","Ku wa gatanu","Ku wa gatandatu","Ku cyumweru"],namesAbbr:["mbe.","kab.","gat.","kan.","gat.","gat.","cyu."],namesShort:["mb","ka","ga","ka","ga","ga","cy"]},months:{names:["Mutarama","Gashyantare","Werurwe","Mata","Gicurasi","Kamena","Nyakanga","Kanama","Nzeli","Ukwakira","Ugushyingo","Ukuboza",""],namesAbbr:["Mut","Gas","Wer","Mat","Gic","Kam","Nya","Kan","Nze","Ukwa","Ugu","Uku",""]},AM:["saa moya z.m.","saa moya z.m.","SAA MOYA Z.M."],PM:["saa moya z.n.","saa moya z.n.","SAA MOYA Z.N."],patterns:{d:"M/d/yyyy",D:"dddd, MMMM dd, yyyy",F:"dddd, MMMM dd, yyyy h:mm:ss tt",g:"M/d/yyyy h:mm tt",G:"M/d/yyyy h:mm:ss tt",m:"MMMM dd",M:"MMMM dd",s:"yyyy'-'MM'-'dd'T'HH':'mm':'ss",t:"h:mm tt",T:"h:mm:ss tt",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"MMMM, yyyy",Y:"MMMM, yyyy"},"/":"/",":":":",firstDay:0}}}}(this),window.kendo},"function"==typeof define&&define.amd?define:function(e,t){t()});
|
#ifndef FUNCOES_H_INCLUDED
#define FUNCOES_H_INCLUDED
#include <iostream>
#include <cmath>
using namespace std;
float norma(float *v);
float dot(float *v1, float *v2);
float angulo_vetores(float *v1, float *v2);
float distancia(float *v1, float *v2);
float distancia_point_line(float *p0, float *p1, float *p2);
float *ponto_medio(float *v1, float *v2);
/**
** Produto vetorial entre dois vetores
** v3 eh normalizado
**/
void crossNorm(float x1, float y1, float z1, float x2, float y2, float z2, float (&v)[3]);
float *rotation_Axis_Vector(float *v, float theta, float Ux, float Uy, float Uz);
void normalize(float (&v)[3]);
void normalize(float *v);
float *getMin(float v1[3], float v2[3]);
float *getMax(float v1[3], float v2[3]);
#endif // FUNCOES_H_INCLUDED
|
/*! AdminLTE app.js
* ================
* Main JS application file for AdminLTE v2. This file
* should be included in all pages. It controls some layout
* options and implements exclusive AdminLTE plugins.
*
* @Author Almsaeed Studio
* @Support <http://www.almsaeedstudio.com>
* @Email <support@almsaeedstudio.com>
* @version 2.3.3
* @license MIT <http://opensource.org/licenses/MIT>
*/
function _init(){"use strict";$.AdminLTE.layout={activate:function(){var a=this;a.fix(),a.fixSidebar(),$(window,".wrapper").resize(function(){a.fix(),a.fixSidebar()})},fix:function(){var a=$(".main-header").outerHeight()+$(".main-footer").outerHeight(),b=$(window).height(),c=$(".sidebar").height();if($("body").hasClass("fixed"))$(".content-wrapper, .right-side").css("min-height",b-$(".main-footer").outerHeight());else{var d;b>=c?($(".content-wrapper, .right-side").css("min-height",b-a),d=b-a):($(".content-wrapper, .right-side").css("min-height",c),d=c);var e=$($.AdminLTE.options.controlSidebarOptions.selector);"undefined"!=typeof e&&e.height()>d&&$(".content-wrapper, .right-side").css("min-height",e.height())}},fixSidebar:function(){return $("body").hasClass("fixed")?("undefined"==typeof $.fn.slimScroll&&window.console&&window.console.error("Error: the fixed layout requires the slimscroll plugin!"),void($.AdminLTE.options.sidebarSlimScroll&&"undefined"!=typeof $.fn.slimScroll&&($(".sidebar").slimScroll({destroy:!0}).height("auto"),$(".sidebar").slimscroll({height:$(window).height()-$(".main-header").height()+"px",color:"rgba(0,0,0,0.2)",size:"3px"})))):void("undefined"!=typeof $.fn.slimScroll&&$(".sidebar").slimScroll({destroy:!0}).height("auto"))}},$.AdminLTE.pushMenu={activate:function(a){var b=$.AdminLTE.options.screenSizes;$(document).on("click",a,function(a){a.preventDefault(),$(window).width()>b.sm-1?$("body").hasClass("sidebar-collapse")?$("body").removeClass("sidebar-collapse").trigger("expanded.pushMenu"):$("body").addClass("sidebar-collapse").trigger("collapsed.pushMenu"):$("body").hasClass("sidebar-open")?$("body").removeClass("sidebar-open").removeClass("sidebar-collapse").trigger("collapsed.pushMenu"):$("body").addClass("sidebar-open").trigger("expanded.pushMenu")}),$(".content-wrapper").click(function(){$(window).width()<=b.sm-1&&$("body").hasClass("sidebar-open")&&$("body").removeClass("sidebar-open")}),($.AdminLTE.options.sidebarExpandOnHover||$("body").hasClass("fixed")&&$("body").hasClass("sidebar-mini"))&&this.expandOnHover()},expandOnHover:function(){var a=this,b=$.AdminLTE.options.screenSizes.sm-1;$(".main-sidebar").hover(function(){$("body").hasClass("sidebar-mini")&&$("body").hasClass("sidebar-collapse")&&$(window).width()>b&&a.expand()},function(){$("body").hasClass("sidebar-mini")&&$("body").hasClass("sidebar-expanded-on-hover")&&$(window).width()>b&&a.collapse()})},expand:function(){$("body").removeClass("sidebar-collapse").addClass("sidebar-expanded-on-hover")},collapse:function(){$("body").hasClass("sidebar-expanded-on-hover")&&$("body").removeClass("sidebar-expanded-on-hover").addClass("sidebar-collapse")}},$.AdminLTE.tree=function(a){var b=this,c=$.AdminLTE.options.animationSpeed;$(document).on("click",a+" li a",function(a){var d=$(this),e=d.next();if(e.is(".treeview-menu")&&e.is(":visible")&&!$("body").hasClass("sidebar-collapse"))e.slideUp(c,function(){e.removeClass("menu-open")}),e.parent("li").removeClass("active");else if(e.is(".treeview-menu")&&!e.is(":visible")){var f=d.parents("ul").first(),g=f.find("ul:visible").slideUp(c);g.removeClass("menu-open");var h=d.parent("li");e.slideDown(c,function(){e.addClass("menu-open"),f.find("li.active").removeClass("active"),h.addClass("active"),b.layout.fix()})}e.is(".treeview-menu")&&a.preventDefault()})},$.AdminLTE.controlSidebar={activate:function(){var a=this,b=$.AdminLTE.options.controlSidebarOptions,c=$(b.selector),d=$(b.toggleBtnSelector);d.on("click",function(d){d.preventDefault(),c.hasClass("control-sidebar-open")||$("body").hasClass("control-sidebar-open")?a.close(c,b.slide):a.open(c,b.slide)});var e=$(".control-sidebar-bg");a._fix(e),$("body").hasClass("fixed")?a._fixForFixed(c):$(".content-wrapper, .right-side").height()<c.height()&&a._fixForContent(c)},open:function(a,b){b?a.addClass("control-sidebar-open"):$("body").addClass("control-sidebar-open")},close:function(a,b){b?a.removeClass("control-sidebar-open"):$("body").removeClass("control-sidebar-open")},_fix:function(a){var b=this;$("body").hasClass("layout-boxed")?(a.css("position","absolute"),a.height($(".wrapper").height()),$(window).resize(function(){b._fix(a)})):a.css({position:"fixed",height:"auto"})},_fixForFixed:function(a){a.css({position:"fixed","max-height":"100%",overflow:"auto","padding-bottom":"50px"})},_fixForContent:function(a){$(".content-wrapper, .right-side").css("min-height",a.height())}},$.AdminLTE.boxWidget={selectors:$.AdminLTE.options.boxWidgetOptions.boxWidgetSelectors,icons:$.AdminLTE.options.boxWidgetOptions.boxWidgetIcons,animationSpeed:$.AdminLTE.options.animationSpeed,activate:function(a){var b=this;a||(a=document),$(a).on("click",b.selectors.collapse,function(a){a.preventDefault(),b.collapse($(this))}),$(a).on("click",b.selectors.remove,function(a){a.preventDefault(),b.remove($(this))})},collapse:function(a){var b=this,c=a.parents(".box").first(),d=c.find("> .box-body, > .box-footer, > form >.box-body, > form > .box-footer");c.hasClass("collapsed-box")?(a.children(":first").removeClass(b.icons.open).addClass(b.icons.collapse),d.slideDown(b.animationSpeed,function(){c.removeClass("collapsed-box")})):(a.children(":first").removeClass(b.icons.collapse).addClass(b.icons.open),d.slideUp(b.animationSpeed,function(){c.addClass("collapsed-box")}))},remove:function(a){var b=a.parents(".box").first();b.slideUp(this.animationSpeed)}}}if("undefined"==typeof jQuery)throw new Error("AdminLTE requires jQuery");$.AdminLTE={},$.AdminLTE.options={navbarMenuSlimscroll:!0,navbarMenuSlimscrollWidth:"3px",navbarMenuHeight:"200px",animationSpeed:500,sidebarToggleSelector:"[data-toggle='offcanvas']",sidebarPushMenu:!0,sidebarSlimScroll:!0,sidebarExpandOnHover:!1,enableBoxRefresh:!0,enableBSToppltip:!0,BSTooltipSelector:"[data-toggle='tooltip']",enableFastclick:!0,enableControlSidebar:!0,controlSidebarOptions:{toggleBtnSelector:"[data-toggle='control-sidebar']",selector:".control-sidebar",slide:!0},enableBoxWidget:!0,boxWidgetOptions:{boxWidgetIcons:{collapse:"fa-minus",open:"fa-plus",remove:"fa-times"},boxWidgetSelectors:{remove:'[data-widget="remove"]',collapse:'[data-widget="collapse"]'}},directChat:{enable:!0,contactToggleSelector:'[data-widget="chat-pane-toggle"]'},colors:{lightBlue:"#3c8dbc",red:"#f56954",green:"#00a65a",aqua:"#00c0ef",yellow:"#f39c12",blue:"#0073b7",navy:"#001F3F",teal:"#39CCCC",olive:"#3D9970",lime:"#01FF70",orange:"#FF851B",fuchsia:"#F012BE",purple:"#8E24AA",maroon:"#D81B60",black:"#222222",gray:"#d2d6de"},screenSizes:{xs:480,sm:768,md:992,lg:1200}},$(function(){"use strict";$("body").removeClass("hold-transition"),"undefined"!=typeof AdminLTEOptions&&$.extend(!0,$.AdminLTE.options,AdminLTEOptions);var a=$.AdminLTE.options;_init(),$.AdminLTE.layout.activate(),$.AdminLTE.tree(".sidebar"),a.enableControlSidebar&&$.AdminLTE.controlSidebar.activate(),a.navbarMenuSlimscroll&&"undefined"!=typeof $.fn.slimscroll&&$(".navbar .menu").slimscroll({height:a.navbarMenuHeight,alwaysVisible:!1,size:a.navbarMenuSlimscrollWidth}).css("width","100%"),a.sidebarPushMenu&&$.AdminLTE.pushMenu.activate(a.sidebarToggleSelector),a.enableBSToppltip&&$("body").tooltip({selector:a.BSTooltipSelector}),a.enableBoxWidget&&$.AdminLTE.boxWidget.activate(),a.enableFastclick&&"undefined"!=typeof FastClick&&FastClick.attach(document.body),a.directChat.enable&&$(document).on("click",a.directChat.contactToggleSelector,function(){var a=$(this).parents(".direct-chat").first();a.toggleClass("direct-chat-contacts-open")}),$('.btn-group[data-toggle="btn-toggle"]').each(function(){var a=$(this);$(this).find(".btn").on("click",function(b){a.find(".btn.active").removeClass("active"),$(this).addClass("active"),b.preventDefault()})})}),function(a){"use strict";a.fn.boxRefresh=function(b){function c(a){a.append(f),e.onLoadStart.call(a)}function d(a){a.find(f).remove(),e.onLoadDone.call(a)}var e=a.extend({trigger:".refresh-btn",source:"",onLoadStart:function(a){return a},onLoadDone:function(a){return a}},b),f=a('<div class="overlay"><div class="fa fa-refresh fa-spin"></div></div>');return this.each(function(){if(""===e.source)return void(window.console&&window.console.log("Please specify a source first - boxRefresh()"));var b=a(this),f=b.find(e.trigger).first();f.on("click",function(a){a.preventDefault(),c(b),b.find(".box-body").load(e.source,function(){d(b)})})})}}(jQuery),function(a){"use strict";a.fn.activateBox=function(){a.AdminLTE.boxWidget.activate(this)},a.fn.toggleBox=function(){var b=a(a.AdminLTE.boxWidget.selectors.collapse,this);a.AdminLTE.boxWidget.collapse(b)},a.fn.removeBox=function(){var b=a(a.AdminLTE.boxWidget.selectors.remove,this);a.AdminLTE.boxWidget.remove(b)}}(jQuery),function(a){"use strict";a.fn.todolist=function(b){var c=a.extend({onCheck:function(a){return a},onUncheck:function(a){return a}},b);return this.each(function(){"undefined"!=typeof a.fn.iCheck?(a("input",this).on("ifChecked",function(){var b=a(this).parents("li").first();b.toggleClass("done"),c.onCheck.call(b)}),a("input",this).on("ifUnchecked",function(){var b=a(this).parents("li").first();b.toggleClass("done"),c.onUncheck.call(b)})):a("input",this).on("change",function(){var b=a(this).parents("li").first();b.toggleClass("done"),a("input",b).is(":checked")?c.onCheck.call(b):c.onUncheck.call(b)})})}}(jQuery);
|
export default require('./vi/home.json')
|
# Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from CIM16.IEC61970.Core.PowerSystemResource import PowerSystemResource
class ControlArea(PowerSystemResource):
"""A <b>control area </b>is a grouping of <b>generating units</b> and/or loads and a cutset of tie lines (as <b>terminals</b>) which may be used for a variety of purposes including automatic generation control, powerflow solution area interchange control specification, and input to load forecasting. Note that any number of overlapping control area specifications can be superimposed on the physical model.A <b>control area </b>is a grouping of <b>generating units</b> and/or loads and a cutset of tie lines (as <b>terminals</b>) which may be used for a variety of purposes including automatic generation control, powerflow solution area interchange control specification, and input to load forecasting. Note that any number of overlapping control area specifications can be superimposed on the physical model.
"""
def __init__(self, type="Forecast", pTolerance=0.0, netInterchange=0.0, ControlAreaGeneratingUnit=None, TieFlow=None, EnergyArea=None, *args, **kw_args):
"""Initialises a new 'ControlArea' instance.
@param type: The type of control area defintion used to determine if this is used for automatic generation control, for planning interchange control, or other purposes. Values are: "Forecast", "AGC", "Interchange"
@param pTolerance: Active power net interchange tolerance
@param netInterchange: The specified positive net interchange into the control area.
@param ControlAreaGeneratingUnit: The generating unit specificaitons for the control area.
@param TieFlow: The tie flows associated with the control area.
@param EnergyArea: The energy area that is forecast from this control area specification.
"""
#: The type of control area defintion used to determine if this is used for automatic generation control, for planning interchange control, or other purposes. Values are: "Forecast", "AGC", "Interchange"
self.type = type
#: Active power net interchange tolerance
self.pTolerance = pTolerance
#: The specified positive net interchange into the control area.
self.netInterchange = netInterchange
self._ControlAreaGeneratingUnit = []
self.ControlAreaGeneratingUnit = [] if ControlAreaGeneratingUnit is None else ControlAreaGeneratingUnit
self._TieFlow = []
self.TieFlow = [] if TieFlow is None else TieFlow
self._EnergyArea = None
self.EnergyArea = EnergyArea
super(ControlArea, self).__init__(*args, **kw_args)
_attrs = ["type", "pTolerance", "netInterchange"]
_attr_types = {"type": str, "pTolerance": float, "netInterchange": float}
_defaults = {"type": "Forecast", "pTolerance": 0.0, "netInterchange": 0.0}
_enums = {"type": "ControlAreaTypeKind"}
_refs = ["ControlAreaGeneratingUnit", "TieFlow", "EnergyArea"]
_many_refs = ["ControlAreaGeneratingUnit", "TieFlow"]
def getControlAreaGeneratingUnit(self):
"""The generating unit specificaitons for the control area.
"""
return self._ControlAreaGeneratingUnit
def setControlAreaGeneratingUnit(self, value):
for x in self._ControlAreaGeneratingUnit:
x.ControlArea = None
for y in value:
y._ControlArea = self
self._ControlAreaGeneratingUnit = value
ControlAreaGeneratingUnit = property(getControlAreaGeneratingUnit, setControlAreaGeneratingUnit)
def addControlAreaGeneratingUnit(self, *ControlAreaGeneratingUnit):
for obj in ControlAreaGeneratingUnit:
obj.ControlArea = self
def removeControlAreaGeneratingUnit(self, *ControlAreaGeneratingUnit):
for obj in ControlAreaGeneratingUnit:
obj.ControlArea = None
def getTieFlow(self):
"""The tie flows associated with the control area.
"""
return self._TieFlow
def setTieFlow(self, value):
for x in self._TieFlow:
x.ControlArea = None
for y in value:
y._ControlArea = self
self._TieFlow = value
TieFlow = property(getTieFlow, setTieFlow)
def addTieFlow(self, *TieFlow):
for obj in TieFlow:
obj.ControlArea = self
def removeTieFlow(self, *TieFlow):
for obj in TieFlow:
obj.ControlArea = None
def getEnergyArea(self):
"""The energy area that is forecast from this control area specification.
"""
return self._EnergyArea
def setEnergyArea(self, value):
if self._EnergyArea is not None:
self._EnergyArea._ControlArea = None
self._EnergyArea = value
if self._EnergyArea is not None:
self._EnergyArea.ControlArea = None
self._EnergyArea._ControlArea = self
EnergyArea = property(getEnergyArea, setEnergyArea)
|
'''Utility used for transforming a list of extracted data for use in tests'''
import copy
def extract_in_data(extracted_data, **kwargs_extra_data):
extracted_request_data = []
for ddx, data in enumerate(extracted_data):
output_extract = {'data': copy.deepcopy(data)}
for key in kwargs_extra_data.keys():
output_extract[key] = kwargs_extra_data[key][ddx]
extracted_request_data.append(output_extract)
return extracted_request_data
|
import sys
import numpy as np
from typing import *
import scipy.linalg as sla
import scipy.sparse as sparse
import jax.numpy.linalg as nla
import matplotlib.pyplot as mplt
import scipy.sparse.linalg as ssl
from sklearn.utils import shuffle
from sklearn.cluster import KMeans
from scipy.sparse.csr import csr_matrix
from scipy.sparse.dia import dia_matrix
from sklearn.metrics import silhouette_score
from sklearn.metrics.pairwise import rbf_kernel
from scipy.spatial.distance import squareform, pdist
EPSILON = 1e-10 # avoid DivideByZero errors
MEM_PREC = 3 # for memory profiling output
import warnings; warnings.filterwarnings('ignore')
def algo0(S: np.ndarray, k: int, seed: int=None)-> Tuple[np.ndarray, int]:
'''
Params:
- S : {s1, s2, ..., sN}, where si ∊ R^d ==> S ∊ R^(n x d)
- k : number of clusters
- action: {'f': KMeans.fit(), 'p': KMeans.predict()}
- preds: precomputed classifier for predictions, ignored if action != 'p'
- seed: random seed for sampling - default is None
Returns:
- preds: predicted label array
'''
return KMeans(n_clusters=k, random_state=seed).fit_predict(np.real(S)), sys.getsizeof(S)
def algo1(S: np.ndarray, k: int, style: str='ng', seed: int=None)-> Tuple[np.ndarray, int]:
'''
Params:
- S : {s1, s2, ..., sN}, where si ∊ R^d ==> S ∊ R^(n x d)
- k : number of clusters
- action: {'f': KMeans.fit(), 'p': KMeans.predict()}
- preds: precomputed classifier for predictions, ignored if action != 'p'
- style: {'ng': Ng et. al 2001, 'cho': Choromanska et al. 2013}
- seed: random seed for sampling - default is None
Returns:
- preds: predicted label array
'''
X: csr_matrix; L: np.ndarray; global EPSILON
A: np.ndarray = rbf_kernel(squareform(pdist(S))) # A ∊ R^(n x n)
np.fill_diagonal(A,0)
dvals: np.ndarray = 1/(np.sqrt(np.sum(A, axis=1)) + EPSILON)
d: dia_matrix = sparse.dia_matrix(np.diag(dvals)) # d ∊ R^(n x n)
if style.lower() == "ng":
L = d@A@d # L ∊ R^(n x n), unnormalized
vals, vecs = nla.eig(L)
X = vecs[:,np.argsort(vals)[-k:]] # X ∊ R^(n x k) --> k LARGEST eigenvectors
elif style.lower() == "cho":
L = np.eye(S.shape[0]) - d@A@d # L ∊ R^(n x n), normalized
vals, vecs = nla.eig(L)
X = vecs[:,np.argsort(vals)[-k:]] # X ∊ R^(n x k) --> k SMALLEST eigenvectors
return KMeans(n_clusters=k,random_state=seed).fit_predict(np.real(X)), sys.getsizeof(A)
def algo3(S: np.ndarray, l: int, r: int, k: int, seed: int=None)-> Tuple[np.ndarray, int]:
'''
Params:
- S : {s1, s2, ..., sN}, where si ∊ R^d ==> S ∊ R^(n x d)
- k : number of clusters
- l : number of columns sampled
- r : rank approximation
- action: {'f': KMeans.fit(), 'p': KMeans.predict()}
- preds: precomputed classifier for predictions, ignored if action != 'p'
- style: {'ng': Ng et. al 2001, 'cho': Choromanska et al. 2013}
- seed: random seed for sampling - default is None
Returns:
- preds: predicted label array
'''
global EPSILON; h = np.sqrt(l/S.shape[0]); p = min(l, S.shape[1])
if not k <= r <= l <= S.shape[0]: exit("Rank cannot be larger than column sample size")
col_idxs: np.ndarray = np.random.choice(S.shape[1], p, replace=False)
A: np.ndarray = rbf_kernel(S)[:,col_idxs] # A ∊ R^(n x l)
np.fill_diagonal(A,0)
Dvals: np.ndarray = 1/(np.sqrt(np.sum(A, axis=1)) + EPSILON)
dvals: np.ndarray = 1/(np.sqrt(np.sum(A, axis=0)) + EPSILON)
D: dia_matrix = sparse.dia_matrix((Dvals.T, [0]), shape=(Dvals.size, Dvals.size))
d: dia_matrix = sparse.dia_matrix((dvals.T, [0]), shape=(dvals.size, dvals.size))
C: np.ndarray = sparse.csr_matrix(np.eye(S.shape[0],p)) - h * D@A@d # C ∊ R^(n x l), not sparse
W: np.ndarray = C[col_idxs,:] # W ∊ R^(l x l), not sparse
EW, UW = sla.eig(W) # EW ∊ R^(l x l), UW ∊ R^(l x l)
r_idxs: np.ndarray = np.argsort(EW)[:r]
UWr: dia_matrix = sparse.dia_matrix(UW[:, r_idxs]) # UWr ∊ R^(l x r)
EWr: dia_matrix = sparse.dia_matrix(np.diag(EW[r_idxs])) # EWr ∊ R^(r x r)
Ut: np.ndarray = h * C@UWr@ssl.inv(EWr) # Ut ∊ R^(n x r)
Y = sla.svd(Ut)[0][:,-k:] # vh ∊ R^(n x k) --> top k *unitary* eigenvectors
return KMeans(n_clusters=k, random_state=seed).fit_predict(np.real(Y)), sys.getsizeof(A)
def plot_clustering(X: np.ndarray, true_labels: np.ndarray, pred_labels: np.ndarray)-> None:
'''
Utility function: Plot predictions after clustering
Params
- X: Dataset to be plotted
- true_labels: Actual label array
- pred_labels: Predicted label array
'''
utls, upls = np.unique(true_labels), np.unique(pred_labels)
(_,a), cs = mplt.subplots(2), shuffle(['b','g','r','c','m','y','k','w'])
if upls.shape != utls.shape: upls = utls
print(X.shape, pred_labels.shape, true_labels.shape, upls.shape, utls.shape)
for ki in range(utls.size):
p, t = X[pred_labels==upls[ki],:], X[true_labels==utls[ki],:]
a[0].scatter(t[:,0], t[:,1],c=cs[ki],s=5, marker='.')
a[1].scatter(p[:,0], p[:,1], c=cs[ki],s=5, marker='.')
a[0].set_title('Original Clustering')
a[1].set_title("Nystrom Clustering")
mplt.subplots_adjust(hspace=1, wspace=1); mplt.show()
def cluster0(data: np.ndarray, labels: np.ndarray=None, n_clusters: int=None,
fit_seed: int=None, score_seed: int=None)-> Tuple[np.ndarray, np.ndarray]:
if labels is None: labels = np.zeros(data.shape[0])
if n_clusters is None: n_clusters = np.unique(labels).size
preds, size = algo0(data, n_clusters, seed=fit_seed)
score = silhouette_score(data, preds, metric='euclidean', random_state=score_seed)
return preds, score, size
def cluster1(data: np.ndarray, labels: np.ndarray=None, n_clusters: int=None,
fit_seed: int=None, score_seed: int=None)-> Tuple[np.ndarray, np.ndarray]:
if labels is None: labels = np.zeros(data.shape[0])
if n_clusters is None: n_clusters = np.unique(labels).size
preds, size = algo1(data, n_clusters, style='ng', seed=fit_seed)
score = silhouette_score(data, preds, metric='euclidean', random_state=score_seed)
return preds, score, size
def cluster3(data: np.ndarray, l: int, r: int, labels: np.ndarray=None,
n_clusters: int=None, fit_seed: int=None, score_seed: int=None)-> Tuple[np.ndarray, np.ndarray]:
if labels is None: labels = np.zeros(data.shape[0])
if n_clusters is None: n_clusters = np.unique(labels).size
preds, size = algo3(data, l, r, n_clusters, seed=fit_seed)
score = silhouette_score(data, preds, metric='euclidean', random_state=score_seed)
return preds, score, size
|
/*
* Lets the user navigate laterally through a sequence of child elements.
*
* basic-carousel is an implementation of the carousel user interface pattern,
* commonly used for navigating between images, pages, and other elements.
* This pattern presents the user with a linear sequence of elements, only one of
* which is shown at a time. The user can navigate to the next/previous element
* with a variety of input methods.
*
* basic-carousel uses its children as the elements the user will navigate through.
* In a typical use, a basic-carousel can be used to navigate between a sequence of
* images:
*
* <basic-carousel>
* <img src="image1.jpg">
* <img src="image2.jpg">
* <img src="image3.jpg">
* </basic-carousel>
*
* The child elements can be of any type — they are not restricted to images.
*
* This component attempts to meet the [Gold Standard for web components]
* (https://github.com/webcomponents/gold-standard/wiki) so that it is generally
* as flexible and robust as standard HTML elements. For example, it meets the
* "Content Changes" criteria: the carousel will adapt to new child elements added
* or removed at runtime.
*
* Currently, this component does not meet the Gold Standard criteria "Size to
* Content". As a result, for the time being, **you must manually set a size on
* this component**. Two approaches are to: 1) stretch the component across
* whatever surface it is contained within, or 2) set it to be larger than the
* largest child element you want to display. The former approach is more common,
* and can be achieved with CSS styling such as:
*
* html {
* height: 100%;
* }
*
* body {
* display: -webkit-flex;
* display: flex;
* height: 100%;
* margin: 0;
* }
*
* basic-carousel {
* -webkit-flex: 1;
* flex: 1;
* }
*
* Alternatively, you can use a separate component,
* [basic-carousel-fit](http://github.com/basic-web-components/basic-carousel-fit),
* which is designed to automatically size itself to its largest child elements.
*
* The standard basic-carousel component supports navigation via the following
* input methods:
*
* * Keyboard. When the carousel has focus, the user can press Left, Right, Home,
* or End. These navigate to the expected element.
* * Touch. On mobile and other touch-enabled devices, the user can drag left or
* right.
* * Trackpad. The user can swipe left or right on a trackpad to navigate.
*
* basic-carousel supports a variety of optional user interface accessories:
* * [basic-arrow-direction](http://github.com/basic-web-components/basic-arrow-direction).
* This adds prominent left and right arrow buttons on the side of the carousel.
* * [basic-page-dots](http://github.com/basic-web-components/basic-page-dots).
* This adds a series of small dots below the carousel to indicate the user's
* current position in the sequence.
*
* See those components for more details, but in general you can construct a common
* carousel with both arrow buttons and dots like so:
*
* <basic-arrow-direction target="child">
* <basic-page-dots target="child">
* <basic-carousel>
* <img src="image1.jpg">
* <img src="image2.jpg">
* <img src="image3.jpg">
* <img src="image4.jpg">
* <img src="image5.jpg">
* </basic-carousel>
* </basic-page-dots>
* </basic-arrow-direction>
*
* For universal access, basic-carousel automatically adds a variety of
* [ARIA](http://www.w3.org/WAI/intro/aria) properties to itself and to child
* elements. This helps users navigate the sequence of elements in the carousel
* using assistive technologies.
*
* @class Carousel
*/
import ElementBase from 'core-component-mixins/src/ElementBase';
import ChildrenContent from '../../mixins/ChildrenContent';
import CollectiveElement from '../../mixins/CollectiveElement';
import ContentItems from '../../mixins/ContentItems';
import DirectionSelection from '../../mixins/DirectionSelection';
import Generic from '../../mixins/Generic';
import ItemsAccessible from '../../mixins/ItemsAccessible';
import ItemSelection from '../../mixins/ItemSelection';
import Keyboard from '../../mixins/Keyboard';
import KeyboardDirection from '../../mixins/KeyboardDirection';
import SlidingViewport from '../SlidingViewport/SlidingViewport';
import SwipeDirection from '../../mixins/SwipeDirection';
import TrackpadDirection from '../../mixins/TrackpadDirection';
let base = ElementBase.compose(
ChildrenContent,
CollectiveElement,
ContentItems,
DirectionSelection,
Generic,
ItemSelection,
ItemsAccessible,
Keyboard,
KeyboardDirection,
SwipeDirection,
TrackpadDirection
);
export default class Carousel extends base {
attachedCallback() {
if (super.attachedCallback) { super.attachedCallback(); }
// HACK
this.itemsChanged();
this.selectionRequired = true;
}
get position() {
return this.$.viewport.position;
}
set position(value) {
if ('position' in base.prototype) { super.position = value; }
this.$.viewport.position = value;
}
get selectedItem() {
return super.selectedItem;
}
set selectedItem(item) {
if ('selectedItem' in base.prototype) { super.selectedItem = item; }
this.$.viewport.selectedItem = item;
}
showTransition(show) {
if (super.showTransition) { super.showTransition(); }
return this.$.viewport.showTransition(show);
}
get template() {
return `
<style>
:host {
display: -webkit-flex;
display: flex;
}
basic-sliding-viewport {
display: -webkit-flex;
display: flex;
-webkit-flex: 1;
flex: 1;
}
</style>
<basic-sliding-viewport id="viewport">
<content></content>
</basic-sliding-viewport>
`;
}
}
document.registerElement('basic-carousel', Carousel);
|
"""Test subsampling utilities."""
import pytest
from backpack.extensions import BatchGrad
from vivit.extensions import SqrtGGNExact
from vivit.utils.subsampling import (
merge_extensions,
merge_multiple_subsamplings,
merge_subsamplings,
sample_output_mapping,
)
def test_sample_output_mapping():
"""Test mapping from samples to output indices."""
assert sample_output_mapping(None, None) is None
assert sample_output_mapping([0, 1], None) == [0, 1]
assert sample_output_mapping([0, 1], [2, 1, 0]) == [2, 1]
assert sample_output_mapping([0, 0], [2, 1, 0]) == [2, 2]
assert sample_output_mapping([2, 0], [2, 1, 0]) == [0, 2]
with pytest.raises(ValueError):
sample_output_mapping([2, 1, 0], [0, 1])
with pytest.raises(ValueError):
sample_output_mapping(None, [0, 1])
def test_merge_subsamplings():
"""Test merging of sub-samplings."""
assert merge_subsamplings(None, None) is None
assert merge_subsamplings(None, [0, 1]) is None
assert merge_subsamplings([0, 1], [2, 3]) == [0, 1, 2, 3]
assert merge_subsamplings([0, 1], [0, 1]) == [0, 1]
assert merge_subsamplings([0, 3, 1], [7, 0]) == [0, 1, 3, 7]
def test_multiple_subsamplings():
"""Test merging of multiple sub-samplings."""
assert merge_multiple_subsamplings([1, 0]) == [0, 1]
assert merge_multiple_subsamplings([0, 0, 4, 2], [0, 0, 8], [4, 2]) == [0, 2, 4, 8]
assert merge_multiple_subsamplings([0, 0, 4, 2], None, [4, 2]) is None
assert merge_multiple_subsamplings(None, [0, 1], None) is None
with pytest.raises(ValueError):
merge_multiple_subsamplings()
def test_merge_extensions():
"""Test merging of sub-sampled extensions."""
assert merge_extensions(
[(BatchGrad, None), (BatchGrad, [0, 1]), (SqrtGGNExact, [0])]
) == {BatchGrad: None, SqrtGGNExact: [0]}
assert merge_extensions(
[(BatchGrad, [2, 5, 0, 0]), (BatchGrad, [0, 1]), (SqrtGGNExact, [1, 0])]
) == {
BatchGrad: [0, 1, 2, 5],
SqrtGGNExact: [0, 1],
}
assert merge_extensions(
[(BatchGrad, [2, 5, 0, 0]), (BatchGrad, [0, 1]), (BatchGrad, [1, 1, 0])]
) == {
BatchGrad: [0, 1, 2, 5],
}
|
"""
Django settings for the_beat_live_28569 project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import environ
import logging
env = environ.Env()
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DEBUG", default=False)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str("SECRET_KEY")
ALLOWED_HOSTS = env.list("HOST", default=["*"])
SITE_ID = 1
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = env.bool("SECURE_REDIRECT", default=False)
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites'
]
LOCAL_APPS = [
'home',
'modules',
'users.apps.UsersConfig',
]
THIRD_PARTY_APPS = [
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'bootstrap4',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'django_extensions',
'drf_yasg',
'storages',
# start fcm_django push notifications
'fcm_django',
# end fcm_django push notifications
]
INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'the_beat_live_28569.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'web_build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'the_beat_live_28569.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
if env.str("DATABASE_URL", default=None):
DATABASES = {
'default': env.db()
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware']
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend'
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'web_build/static')]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# allauth / users
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
ACCOUNT_UNIQUE_EMAIL = True
LOGIN_REDIRECT_URL = "users:redirect"
ACCOUNT_ADAPTER = "users.adapters.AccountAdapter"
SOCIALACCOUNT_ADAPTER = "users.adapters.SocialAccountAdapter"
ACCOUNT_ALLOW_REGISTRATION = env.bool("ACCOUNT_ALLOW_REGISTRATION", True)
SOCIALACCOUNT_ALLOW_REGISTRATION = env.bool("SOCIALACCOUNT_ALLOW_REGISTRATION", True)
REST_AUTH_SERIALIZERS = {
# Replace password reset serializer to fix 500 error
"PASSWORD_RESET_SERIALIZER": "home.api.v1.serializers.PasswordSerializer",
}
REST_AUTH_REGISTER_SERIALIZERS = {
# Use custom serializer that has no username and matches web signup
"REGISTER_SERIALIZER": "home.api.v1.serializers.SignupSerializer",
}
# Custom user model
AUTH_USER_MODEL = "users.User"
EMAIL_HOST = env.str("EMAIL_HOST", "smtp.sendgrid.net")
EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "")
EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# AWS S3 config
AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", "")
AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", "")
AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", "")
AWS_STORAGE_REGION = env.str("AWS_STORAGE_REGION", "")
USE_S3 = (
AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY and
AWS_STORAGE_BUCKET_NAME and
AWS_STORAGE_REGION
)
if USE_S3:
AWS_S3_CUSTOM_DOMAIN = env.str("AWS_S3_CUSTOM_DOMAIN", "")
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_DEFAULT_ACL = env.str("AWS_DEFAULT_ACL", "public-read")
AWS_MEDIA_LOCATION = env.str("AWS_MEDIA_LOCATION", "media")
AWS_AUTO_CREATE_BUCKET = env.bool("AWS_AUTO_CREATE_BUCKET", True)
DEFAULT_FILE_STORAGE = env.str(
"DEFAULT_FILE_STORAGE", "home.storage_backends.MediaStorage"
)
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
# start fcm_django push notifications
FCM_DJANGO_SETTINGS = {
"FCM_SERVER_KEY": env.str("FCM_SERVER_KEY", "")
}
# end fcm_django push notifications
# Swagger settings for api docs
SWAGGER_SETTINGS = {
"DEFAULT_INFO": f"{ROOT_URLCONF}.api_info",
}
if DEBUG or not (EMAIL_HOST_USER and EMAIL_HOST_PASSWORD):
# output email to console instead of sending
if not DEBUG:
logging.warning("You should setup `SENDGRID_USERNAME` and `SENDGRID_PASSWORD` env vars to send emails.")
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
|
var request = require('request');
var containers_actions = {
get_available_port: function(exitCode){
var send = {};
request.get({
url: 'http://localhost:5000/containers/availablePort',
}, function(error, response, body){
if(error){
send["routerStatus"] = "Failure";
send["routerMessage"] = "Internal Error";
return exitCode(send);
}
else{
var output = JSON.parse(body);
if (output["routerStatus"] == "Success"){
send["routerStatus"] = "Success";
send["info"] = {};
send["info"] = output["info"];
return exitCode(send);
}
else{
send["routerStatus"] = "Failure";
send["routerMessage"] = "Apps VM route failed";
return exitCode(send);
}
}
});
},
deploy_container: function(app_id, image_tag, port, exitCode){
var send = {};
request.get({
url: 'http://localhost:5000/containers/deploy/' + app_id + '/' + image_tag + '/' + port,
}, function(error, response, body){
if(error){
send["routerStatus"] = "Failure";
send["routerMessage"] = "Internal Error";
return exitCode(send);
}
else{
var output = JSON.parse(body);
if (output["routerStatus"] == "Success"){
send["routerStatus"] = "Success";
send["info"] = {}
send["info"] = output["info"];
return exitCode(send);
}
else{
send["routerStatus"] = "Failure";
send["routerMessage"] = "Apps VM route failed";
return exitCode(send);
}
}
});
}
}
module.exports.containers_actions = containers_actions;
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class UsagesOperations(object):
"""UsagesOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.storage.v2021_04_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list_by_location(
self,
location, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.UsageListResult"]
"""Gets the current usage count and the limit for the resources of the location under the
subscription.
:param location: The location of the Azure Storage resource.
:type location: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either UsageListResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.storage.v2021_04_01.models.UsageListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.UsageListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-04-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_location.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
'location': self._serialize.url("location", location, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('UsageListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_location.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Storage/locations/{location}/usages'} # type: ignore
|
'use strict';
const getDocsUrl = require('./utils/get-docs-url');
const isMathPow = node => {
const {callee} = node;
return (
callee.type === 'MemberExpression' &&
callee.object.type === 'Identifier' &&
callee.object.name === 'Math' &&
callee.property.type === 'Identifier' &&
callee.property.name === 'pow'
);
};
const parseArgument = (context, arg) => {
if (arg.type === 'Identifier') {
return arg.name;
}
return context.getSourceCode().getText(arg);
};
const fix = (context, node, fixer) => {
const base = parseArgument(context, node.arguments[0]);
const exponent = parseArgument(context, node.arguments[1]);
const replacement = `${base} ** ${exponent}`;
return fixer.replaceText(node, replacement);
}
const create = context => {
return {
CallExpression(node) {
if (isMathPow(node)) {
context.report({
node,
message: 'Prefer the exponentiation operator over `Math.pow()`.',
fix: fixer => fix(context, node, fixer),
});
}
}
};
};
module.exports = {
create,
meta: {
docs: {
url: getDocsUrl(__filename)
},
fixable: 'code'
}
};
|
//
// ESPTouchTask.h
// EspTouchDemo
//
// Created by 白 桦 on 4/14/15.
// Copyright (c) 2015 白 桦. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ESPTouchResult.h"
#import "ESPTouchDelegate.h"
#define DEBUG_ON YES
@interface ESPTouchTask : NSObject
@property (atomic,assign) BOOL isCancelled;
/**
* Constructor of EsptouchTask
*
* @param apSsid
* the Ap's ssid
* @param apBssid
* the Ap's bssid
* @param apPassword
* the Ap's password
* @param isSsidHidden
* whether the Ap's ssid is hidden
*/
- (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString *)apPwd andIsSsidHiden: (BOOL) isSsidHidden;
/**
* Constructor of EsptouchTask
*
* @param apSsid
* the Ap's ssid
* @param apBssid
* the Ap's bssid
* @param apPassword
* the Ap's password
* @param isSsidHidden
* whether the Ap's ssid is hidden
* @param timeoutMillisecond(it should be >= 15000+6000)
* millisecond of total timeout
* @param context
* the Context of the Application
*/
- (id) initWithApSsid: (NSString *)apSsid andApBssid: (NSString *) apBssid andApPwd: (NSString *)apPwd andIsSsidHiden: (BOOL) isSsidHidden andTimeoutMillisecond: (int) timeoutMillisecond;
/**
* Interrupt the Esptouch Task when User tap back or close the Application.
*/
- (void) interrupt;
/**
* Note: !!!Don't call the task at UI Main Thread
*
* Smart Config v2.4 support the API
*
* @return the ESPTouchResult
*/
- (ESPTouchResult*) executeForResult;
/**
* Note: !!!Don't call the task at UI Main Thread
*
* Smart Config v2.4 support the API
*
* It will be blocked until the client receive result count >= expectTaskResultCount.
* If it fail, it will return one fail result will be returned in the list.
* If it is cancelled while executing,
* if it has received some results, all of them will be returned in the list.
* if it hasn't received any results, one cancel result will be returned in the list.
*
* @param expectTaskResultCount
* the expect result count(if expectTaskResultCount <= 0,
* expectTaskResultCount = INT32_MAX)
* @return the NSArray of EsptouchResult
* @throws RuntimeException
*/
- (NSArray*) executeForResults:(int) expectTaskResultCount;
/**
* set the esptouch delegate, when one device is connected to the Ap, it will be called back
* @param esptouchDelegate when one device is connected to the Ap, it will be called back
*/
- (void) setEsptouchDelegate: (NSObject<ESPTouchDelegate> *) esptouchDelegate;
@end
|
"""
They copy() method returns a shallow copy of the dictionary.
dict.copy():
copy() method doesn't take any parameters.
"""
original = {1: 'one', 2: 'two'}
new = original.copy()
print('Original: ', original)
print('New: ', new)
# difference between 'copy' and '='
# copy
original = {1: 'one', 2: 'two'}
new = original.copy()
new.clear()
print('Original: ', original)
print('New: ', new)
original = {1: 'one', 2: 'two'}
new = original.copy()
original.clear()
print('Original: ', original)
print('New: ', new)
# =
original = {1: 'one', 2: 'two'}
new = original
new.clear()
print('Original: ', original)
print('New: ', new)
|
import unittest
from test import support
import gc
import weakref
import operator
import copy
import pickle
from random import randrange, shuffle
import warnings
import collections
import collections.abc
import itertools
class PassThru(Exception):
pass
def check_pass_thru():
raise PassThru
yield 1
class BadCmp:
def __hash__(self):
return 1
def __eq__(self, other):
raise RuntimeError
class ReprWrapper:
'Used to test self-referential repr() calls'
def __repr__(self):
return repr(self.value)
class HashCountingInt(int):
'int-like object that counts the number of times __hash__ is called'
def __init__(self, *args):
self.hash_count = 0
def __hash__(self):
self.hash_count += 1
return int.__hash__(self)
class TestJointOps:
# Tests common to both set and frozenset
def setUp(self):
self.word = word = 'simsalabim'
self.otherword = 'madagascar'
self.letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
self.s = self.thetype(word)
self.d = dict.fromkeys(word)
def test_new_or_init(self):
self.assertRaises(TypeError, self.thetype, [], 2)
self.assertRaises(TypeError, set().__init__, a=1)
def test_uniquification(self):
actual = sorted(self.s)
expected = sorted(self.d)
self.assertEqual(actual, expected)
self.assertRaises(PassThru, self.thetype, check_pass_thru())
self.assertRaises(TypeError, self.thetype, [[]])
def test_len(self):
self.assertEqual(len(self.s), len(self.d))
def test_contains(self):
for c in self.letters:
self.assertEqual(c in self.s, c in self.d)
self.assertRaises(TypeError, self.s.__contains__, [[]])
s = self.thetype([frozenset(self.letters)])
self.assertIn(self.thetype(self.letters), s)
def test_union(self):
u = self.s.union(self.otherword)
for c in self.letters:
self.assertEqual(c in u, c in self.d or c in self.otherword)
self.assertEqual(self.s, self.thetype(self.word))
self.assertEqual(type(u), self.basetype)
self.assertRaises(PassThru, self.s.union, check_pass_thru())
self.assertRaises(TypeError, self.s.union, [[]])
for C in set, frozenset, dict.fromkeys, str, list, tuple:
self.assertEqual(self.thetype('abcba').union(C('cdc')), set('abcd'))
self.assertEqual(self.thetype('abcba').union(C('efgfe')), set('abcefg'))
self.assertEqual(self.thetype('abcba').union(C('ccb')), set('abc'))
self.assertEqual(self.thetype('abcba').union(C('ef')), set('abcef'))
self.assertEqual(self.thetype('abcba').union(C('ef'), C('fg')), set('abcefg'))
# Issue #6573
x = self.thetype()
self.assertEqual(x.union(set([1]), x, set([2])), self.thetype([1, 2]))
def test_or(self):
i = self.s.union(self.otherword)
self.assertEqual(self.s | set(self.otherword), i)
self.assertEqual(self.s | frozenset(self.otherword), i)
try:
self.s | self.otherword
except TypeError:
pass
else:
self.fail("s|t did not screen-out general iterables")
def test_intersection(self):
i = self.s.intersection(self.otherword)
for c in self.letters:
self.assertEqual(c in i, c in self.d and c in self.otherword)
self.assertEqual(self.s, self.thetype(self.word))
self.assertEqual(type(i), self.basetype)
self.assertRaises(PassThru, self.s.intersection, check_pass_thru())
for C in set, frozenset, dict.fromkeys, str, list, tuple:
self.assertEqual(self.thetype('abcba').intersection(C('cdc')), set('cc'))
self.assertEqual(self.thetype('abcba').intersection(C('efgfe')), set(''))
self.assertEqual(self.thetype('abcba').intersection(C('ccb')), set('bc'))
self.assertEqual(self.thetype('abcba').intersection(C('ef')), set(''))
self.assertEqual(self.thetype('abcba').intersection(C('cbcf'), C('bag')), set('b'))
s = self.thetype('abcba')
z = s.intersection()
if self.thetype == frozenset():
self.assertEqual(id(s), id(z))
else:
self.assertNotEqual(id(s), id(z))
def test_isdisjoint(self):
def f(s1, s2):
'Pure python equivalent of isdisjoint()'
return not set(s1).intersection(s2)
for larg in '', 'a', 'ab', 'abc', 'ababac', 'cdc', 'cc', 'efgfe', 'ccb', 'ef':
s1 = self.thetype(larg)
for rarg in '', 'a', 'ab', 'abc', 'ababac', 'cdc', 'cc', 'efgfe', 'ccb', 'ef':
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s2 = C(rarg)
actual = s1.isdisjoint(s2)
expected = f(s1, s2)
self.assertEqual(actual, expected)
self.assertTrue(actual is True or actual is False)
def test_and(self):
i = self.s.intersection(self.otherword)
self.assertEqual(self.s & set(self.otherword), i)
self.assertEqual(self.s & frozenset(self.otherword), i)
try:
self.s & self.otherword
except TypeError:
pass
else:
self.fail("s&t did not screen-out general iterables")
def test_difference(self):
i = self.s.difference(self.otherword)
for c in self.letters:
self.assertEqual(c in i, c in self.d and c not in self.otherword)
self.assertEqual(self.s, self.thetype(self.word))
self.assertEqual(type(i), self.basetype)
self.assertRaises(PassThru, self.s.difference, check_pass_thru())
self.assertRaises(TypeError, self.s.difference, [[]])
for C in set, frozenset, dict.fromkeys, str, list, tuple:
self.assertEqual(self.thetype('abcba').difference(C('cdc')), set('ab'))
self.assertEqual(self.thetype('abcba').difference(C('efgfe')), set('abc'))
self.assertEqual(self.thetype('abcba').difference(C('ccb')), set('a'))
self.assertEqual(self.thetype('abcba').difference(C('ef')), set('abc'))
self.assertEqual(self.thetype('abcba').difference(), set('abc'))
self.assertEqual(self.thetype('abcba').difference(C('a'), C('b')), set('c'))
def test_sub(self):
i = self.s.difference(self.otherword)
self.assertEqual(self.s - set(self.otherword), i)
self.assertEqual(self.s - frozenset(self.otherword), i)
try:
self.s - self.otherword
except TypeError:
pass
else:
self.fail("s-t did not screen-out general iterables")
def test_symmetric_difference(self):
i = self.s.symmetric_difference(self.otherword)
for c in self.letters:
self.assertEqual(c in i, (c in self.d) ^ (c in self.otherword))
self.assertEqual(self.s, self.thetype(self.word))
self.assertEqual(type(i), self.basetype)
self.assertRaises(PassThru, self.s.symmetric_difference, check_pass_thru())
self.assertRaises(TypeError, self.s.symmetric_difference, [[]])
for C in set, frozenset, dict.fromkeys, str, list, tuple:
self.assertEqual(self.thetype('abcba').symmetric_difference(C('cdc')), set('abd'))
self.assertEqual(self.thetype('abcba').symmetric_difference(C('efgfe')), set('abcefg'))
self.assertEqual(self.thetype('abcba').symmetric_difference(C('ccb')), set('a'))
self.assertEqual(self.thetype('abcba').symmetric_difference(C('ef')), set('abcef'))
def test_xor(self):
i = self.s.symmetric_difference(self.otherword)
self.assertEqual(self.s ^ set(self.otherword), i)
self.assertEqual(self.s ^ frozenset(self.otherword), i)
try:
self.s ^ self.otherword
except TypeError:
pass
else:
self.fail("s^t did not screen-out general iterables")
def test_equality(self):
self.assertEqual(self.s, set(self.word))
self.assertEqual(self.s, frozenset(self.word))
self.assertEqual(self.s == self.word, False)
self.assertNotEqual(self.s, set(self.otherword))
self.assertNotEqual(self.s, frozenset(self.otherword))
self.assertEqual(self.s != self.word, True)
def test_setOfFrozensets(self):
t = map(frozenset, ['abcdef', 'bcd', 'bdcb', 'fed', 'fedccba'])
s = self.thetype(t)
self.assertEqual(len(s), 3)
def test_sub_and_super(self):
p, q, r = map(self.thetype, ['ab', 'abcde', 'def'])
self.assertTrue(p < q)
self.assertTrue(p <= q)
self.assertTrue(q <= q)
self.assertTrue(q > p)
self.assertTrue(q >= p)
self.assertFalse(q < r)
self.assertFalse(q <= r)
self.assertFalse(q > r)
self.assertFalse(q >= r)
self.assertTrue(set('a').issubset('abc'))
self.assertTrue(set('abc').issuperset('a'))
self.assertFalse(set('a').issubset('cbs'))
self.assertFalse(set('cbs').issuperset('a'))
def test_pickling(self):
for i in range(pickle.HIGHEST_PROTOCOL + 1):
p = pickle.dumps(self.s, i)
dup = pickle.loads(p)
self.assertEqual(self.s, dup, "%s != %s" % (self.s, dup))
if type(self.s) not in (set, frozenset):
self.s.x = 10
p = pickle.dumps(self.s, i)
dup = pickle.loads(p)
self.assertEqual(self.s.x, dup.x)
def test_iterator_pickling(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
itorg = iter(self.s)
data = self.thetype(self.s)
d = pickle.dumps(itorg, proto)
it = pickle.loads(d)
# Set iterators unpickle as list iterators due to the
# undefined order of set items.
# self.assertEqual(type(itorg), type(it))
self.assertIsInstance(it, collections.abc.Iterator)
self.assertEqual(self.thetype(it), data)
it = pickle.loads(d)
try:
drop = next(it)
except StopIteration:
continue
d = pickle.dumps(it, proto)
it = pickle.loads(d)
self.assertEqual(self.thetype(it), data - self.thetype((drop,)))
def test_deepcopy(self):
class Tracer:
def __init__(self, value):
self.value = value
def __hash__(self):
return self.value
def __deepcopy__(self, memo=None):
return Tracer(self.value + 1)
t = Tracer(10)
s = self.thetype([t])
dup = copy.deepcopy(s)
self.assertNotEqual(id(s), id(dup))
for elem in dup:
newt = elem
self.assertNotEqual(id(t), id(newt))
self.assertEqual(t.value + 1, newt.value)
def test_gc(self):
# Create a nest of cycles to exercise overall ref count check
class A:
pass
s = set(A() for i in range(1000))
for elem in s:
elem.cycle = s
elem.sub = elem
elem.set = set([elem])
def test_subclass_with_custom_hash(self):
# Bug #1257731
class H(self.thetype):
def __hash__(self):
return int(id(self) & 0x7fffffff)
s=H()
f=set()
f.add(s)
self.assertIn(s, f)
f.remove(s)
f.add(s)
f.discard(s)
def test_badcmp(self):
s = self.thetype([BadCmp()])
# Detect comparison errors during insertion and lookup
self.assertRaises(RuntimeError, self.thetype, [BadCmp(), BadCmp()])
self.assertRaises(RuntimeError, s.__contains__, BadCmp())
# Detect errors during mutating operations
if hasattr(s, 'add'):
self.assertRaises(RuntimeError, s.add, BadCmp())
self.assertRaises(RuntimeError, s.discard, BadCmp())
self.assertRaises(RuntimeError, s.remove, BadCmp())
def test_cyclical_repr(self):
w = ReprWrapper()
s = self.thetype([w])
w.value = s
if self.thetype == set:
self.assertEqual(repr(s), '{set(...)}')
else:
name = repr(s).partition('(')[0] # strip class name
self.assertEqual(repr(s), '%s({%s(...)})' % (name, name))
def test_cyclical_print(self):
w = ReprWrapper()
s = self.thetype([w])
w.value = s
fo = open(support.TESTFN, "w")
try:
fo.write(str(s))
fo.close()
fo = open(support.TESTFN, "r")
self.assertEqual(fo.read(), repr(s))
finally:
fo.close()
support.unlink(support.TESTFN)
def test_do_not_rehash_dict_keys(self):
n = 10
d = dict.fromkeys(map(HashCountingInt, range(n)))
self.assertEqual(sum(elem.hash_count for elem in d), n)
s = self.thetype(d)
self.assertEqual(sum(elem.hash_count for elem in d), n)
s.difference(d)
self.assertEqual(sum(elem.hash_count for elem in d), n)
if hasattr(s, 'symmetric_difference_update'):
s.symmetric_difference_update(d)
self.assertEqual(sum(elem.hash_count for elem in d), n)
d2 = dict.fromkeys(set(d))
self.assertEqual(sum(elem.hash_count for elem in d), n)
d3 = dict.fromkeys(frozenset(d))
self.assertEqual(sum(elem.hash_count for elem in d), n)
d3 = dict.fromkeys(frozenset(d), 123)
self.assertEqual(sum(elem.hash_count for elem in d), n)
self.assertEqual(d3, dict.fromkeys(d, 123))
def test_container_iterator(self):
# Bug #3680: tp_traverse was not implemented for set iterator object
class C(object):
pass
obj = C()
ref = weakref.ref(obj)
container = set([obj, 1])
obj.x = iter(container)
del obj, container
gc.collect()
self.assertTrue(ref() is None, "Cycle was not collected")
def test_free_after_iterating(self):
support.check_free_after_iterating(self, iter, self.thetype)
class TestSet(TestJointOps, unittest.TestCase):
thetype = set
basetype = set
def test_init(self):
s = self.thetype()
s.__init__(self.word)
self.assertEqual(s, set(self.word))
s.__init__(self.otherword)
self.assertEqual(s, set(self.otherword))
self.assertRaises(TypeError, s.__init__, s, 2);
self.assertRaises(TypeError, s.__init__, 1);
def test_constructor_identity(self):
s = self.thetype(range(3))
t = self.thetype(s)
self.assertNotEqual(id(s), id(t))
def test_set_literal(self):
s = set([1,2,3])
t = {1,2,3}
self.assertEqual(s, t)
def test_set_literal_insertion_order(self):
# SF Issue #26020 -- Expect left to right insertion
s = {1, 1.0, True}
self.assertEqual(len(s), 1)
stored_value = s.pop()
self.assertEqual(type(stored_value), int)
def test_set_literal_evaluation_order(self):
# Expect left to right expression evaluation
events = []
def record(obj):
events.append(obj)
s = {record(1), record(2), record(3)}
self.assertEqual(events, [1, 2, 3])
def test_hash(self):
self.assertRaises(TypeError, hash, self.s)
def test_clear(self):
self.s.clear()
self.assertEqual(self.s, set())
self.assertEqual(len(self.s), 0)
def test_copy(self):
dup = self.s.copy()
self.assertEqual(self.s, dup)
self.assertNotEqual(id(self.s), id(dup))
self.assertEqual(type(dup), self.basetype)
def test_add(self):
self.s.add('Q')
self.assertIn('Q', self.s)
dup = self.s.copy()
self.s.add('Q')
self.assertEqual(self.s, dup)
self.assertRaises(TypeError, self.s.add, [])
def test_remove(self):
self.s.remove('a')
self.assertNotIn('a', self.s)
self.assertRaises(KeyError, self.s.remove, 'Q')
self.assertRaises(TypeError, self.s.remove, [])
s = self.thetype([frozenset(self.word)])
self.assertIn(self.thetype(self.word), s)
s.remove(self.thetype(self.word))
self.assertNotIn(self.thetype(self.word), s)
self.assertRaises(KeyError, self.s.remove, self.thetype(self.word))
def test_remove_keyerror_unpacking(self):
# bug: www.python.org/sf/1576657
for v1 in ['Q', (1,)]:
try:
self.s.remove(v1)
except KeyError as e:
v2 = e.args[0]
self.assertEqual(v1, v2)
else:
self.fail()
def test_remove_keyerror_set(self):
key = self.thetype([3, 4])
try:
self.s.remove(key)
except KeyError as e:
self.assertTrue(e.args[0] is key,
"KeyError should be {0}, not {1}".format(key,
e.args[0]))
else:
self.fail()
def test_discard(self):
self.s.discard('a')
self.assertNotIn('a', self.s)
self.s.discard('Q')
self.assertRaises(TypeError, self.s.discard, [])
s = self.thetype([frozenset(self.word)])
self.assertIn(self.thetype(self.word), s)
s.discard(self.thetype(self.word))
self.assertNotIn(self.thetype(self.word), s)
s.discard(self.thetype(self.word))
def test_pop(self):
for i in range(len(self.s)):
elem = self.s.pop()
self.assertNotIn(elem, self.s)
self.assertRaises(KeyError, self.s.pop)
def test_update(self):
retval = self.s.update(self.otherword)
self.assertEqual(retval, None)
for c in (self.word + self.otherword):
self.assertIn(c, self.s)
self.assertRaises(PassThru, self.s.update, check_pass_thru())
self.assertRaises(TypeError, self.s.update, [[]])
for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')):
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s = self.thetype('abcba')
self.assertEqual(s.update(C(p)), None)
self.assertEqual(s, set(q))
for p in ('cdc', 'efgfe', 'ccb', 'ef', 'abcda'):
q = 'ahi'
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s = self.thetype('abcba')
self.assertEqual(s.update(C(p), C(q)), None)
self.assertEqual(s, set(s) | set(p) | set(q))
def test_ior(self):
self.s |= set(self.otherword)
for c in (self.word + self.otherword):
self.assertIn(c, self.s)
def test_intersection_update(self):
retval = self.s.intersection_update(self.otherword)
self.assertEqual(retval, None)
for c in (self.word + self.otherword):
if c in self.otherword and c in self.word:
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
self.assertRaises(PassThru, self.s.intersection_update, check_pass_thru())
self.assertRaises(TypeError, self.s.intersection_update, [[]])
for p, q in (('cdc', 'c'), ('efgfe', ''), ('ccb', 'bc'), ('ef', '')):
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s = self.thetype('abcba')
self.assertEqual(s.intersection_update(C(p)), None)
self.assertEqual(s, set(q))
ss = 'abcba'
s = self.thetype(ss)
t = 'cbc'
self.assertEqual(s.intersection_update(C(p), C(t)), None)
self.assertEqual(s, set('abcba')&set(p)&set(t))
def test_iand(self):
self.s &= set(self.otherword)
for c in (self.word + self.otherword):
if c in self.otherword and c in self.word:
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
def test_difference_update(self):
retval = self.s.difference_update(self.otherword)
self.assertEqual(retval, None)
for c in (self.word + self.otherword):
if c in self.word and c not in self.otherword:
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
self.assertRaises(PassThru, self.s.difference_update, check_pass_thru())
self.assertRaises(TypeError, self.s.difference_update, [[]])
self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
for p, q in (('cdc', 'ab'), ('efgfe', 'abc'), ('ccb', 'a'), ('ef', 'abc')):
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s = self.thetype('abcba')
self.assertEqual(s.difference_update(C(p)), None)
self.assertEqual(s, set(q))
s = self.thetype('abcdefghih')
s.difference_update()
self.assertEqual(s, self.thetype('abcdefghih'))
s = self.thetype('abcdefghih')
s.difference_update(C('aba'))
self.assertEqual(s, self.thetype('cdefghih'))
s = self.thetype('abcdefghih')
s.difference_update(C('cdc'), C('aba'))
self.assertEqual(s, self.thetype('efghih'))
def test_isub(self):
self.s -= set(self.otherword)
for c in (self.word + self.otherword):
if c in self.word and c not in self.otherword:
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
def test_symmetric_difference_update(self):
retval = self.s.symmetric_difference_update(self.otherword)
self.assertEqual(retval, None)
for c in (self.word + self.otherword):
if (c in self.word) ^ (c in self.otherword):
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
self.assertRaises(PassThru, self.s.symmetric_difference_update, check_pass_thru())
self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
for p, q in (('cdc', 'abd'), ('efgfe', 'abcefg'), ('ccb', 'a'), ('ef', 'abcef')):
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s = self.thetype('abcba')
self.assertEqual(s.symmetric_difference_update(C(p)), None)
self.assertEqual(s, set(q))
def test_ixor(self):
self.s ^= set(self.otherword)
for c in (self.word + self.otherword):
if (c in self.word) ^ (c in self.otherword):
self.assertIn(c, self.s)
else:
self.assertNotIn(c, self.s)
def test_inplace_on_self(self):
t = self.s.copy()
t |= t
self.assertEqual(t, self.s)
t &= t
self.assertEqual(t, self.s)
t -= t
self.assertEqual(t, self.thetype())
t = self.s.copy()
t ^= t
self.assertEqual(t, self.thetype())
def test_weakref(self):
s = self.thetype('gallahad')
p = weakref.proxy(s)
self.assertEqual(str(p), str(s))
s = None
self.assertRaises(ReferenceError, str, p)
def test_rich_compare(self):
class TestRichSetCompare:
def __gt__(self, some_set):
self.gt_called = True
return False
def __lt__(self, some_set):
self.lt_called = True
return False
def __ge__(self, some_set):
self.ge_called = True
return False
def __le__(self, some_set):
self.le_called = True
return False
# This first tries the builtin rich set comparison, which doesn't know
# how to handle the custom object. Upon returning NotImplemented, the
# corresponding comparison on the right object is invoked.
myset = {1, 2, 3}
myobj = TestRichSetCompare()
myset < myobj
self.assertTrue(myobj.gt_called)
myobj = TestRichSetCompare()
myset > myobj
self.assertTrue(myobj.lt_called)
myobj = TestRichSetCompare()
myset <= myobj
self.assertTrue(myobj.ge_called)
myobj = TestRichSetCompare()
myset >= myobj
self.assertTrue(myobj.le_called)
@unittest.skipUnless(hasattr(set, "test_c_api"),
'C API test only available in a debug build')
def test_c_api(self):
self.assertEqual(set().test_c_api(), True)
class SetSubclass(set):
pass
class TestSetSubclass(TestSet):
thetype = SetSubclass
basetype = set
class SetSubclassWithKeywordArgs(set):
def __init__(self, iterable=[], newarg=None):
set.__init__(self, iterable)
class TestSetSubclassWithKeywordArgs(TestSet):
def test_keywords_in_subclass(self):
'SF bug #1486663 -- this used to erroneously raise a TypeError'
SetSubclassWithKeywordArgs(newarg=1)
class TestFrozenSet(TestJointOps, unittest.TestCase):
thetype = frozenset
basetype = frozenset
def test_init(self):
s = self.thetype(self.word)
s.__init__(self.otherword)
self.assertEqual(s, set(self.word))
def test_singleton_empty_frozenset(self):
f = frozenset()
efs = [frozenset(), frozenset([]), frozenset(()), frozenset(''),
frozenset(), frozenset([]), frozenset(()), frozenset(''),
frozenset(range(0)), frozenset(frozenset()),
frozenset(f), f]
# All of the empty frozensets should have just one id()
self.assertEqual(len(set(map(id, efs))), 1)
def test_constructor_identity(self):
s = self.thetype(range(3))
t = self.thetype(s)
self.assertEqual(id(s), id(t))
def test_hash(self):
self.assertEqual(hash(self.thetype('abcdeb')),
hash(self.thetype('ebecda')))
# make sure that all permutations give the same hash value
n = 100
seq = [randrange(n) for i in range(n)]
results = set()
for i in range(200):
shuffle(seq)
results.add(hash(self.thetype(seq)))
self.assertEqual(len(results), 1)
def test_copy(self):
dup = self.s.copy()
self.assertEqual(id(self.s), id(dup))
def test_frozen_as_dictkey(self):
seq = list(range(10)) + list('abcdefg') + ['apple']
key1 = self.thetype(seq)
key2 = self.thetype(reversed(seq))
self.assertEqual(key1, key2)
self.assertNotEqual(id(key1), id(key2))
d = {}
d[key1] = 42
self.assertEqual(d[key2], 42)
def test_hash_caching(self):
f = self.thetype('abcdcda')
self.assertEqual(hash(f), hash(f))
def test_hash_effectiveness(self):
n = 13
hashvalues = set()
addhashvalue = hashvalues.add
elemmasks = [(i+1, 1<<i) for i in range(n)]
for i in range(2**n):
addhashvalue(hash(frozenset([e for e, m in elemmasks if m&i])))
self.assertEqual(len(hashvalues), 2**n)
def zf_range(n):
# https://en.wikipedia.org/wiki/Set-theoretic_definition_of_natural_numbers
nums = [frozenset()]
for i in range(n-1):
num = frozenset(nums)
nums.append(num)
return nums[:n]
def powerset(s):
for i in range(len(s)+1):
yield from map(frozenset, itertools.combinations(s, i))
for n in range(18):
t = 2 ** n
mask = t - 1
for nums in (range, zf_range):
u = len({h & mask for h in map(hash, powerset(nums(n)))})
self.assertGreater(4*u, t)
class FrozenSetSubclass(frozenset):
pass
class TestFrozenSetSubclass(TestFrozenSet):
thetype = FrozenSetSubclass
basetype = frozenset
def test_constructor_identity(self):
s = self.thetype(range(3))
t = self.thetype(s)
self.assertNotEqual(id(s), id(t))
def test_copy(self):
dup = self.s.copy()
self.assertNotEqual(id(self.s), id(dup))
def test_nested_empty_constructor(self):
s = self.thetype()
t = self.thetype(s)
self.assertEqual(s, t)
def test_singleton_empty_frozenset(self):
Frozenset = self.thetype
f = frozenset()
F = Frozenset()
efs = [Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''),
Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''),
Frozenset(range(0)), Frozenset(Frozenset()),
Frozenset(frozenset()), f, F, Frozenset(f), Frozenset(F)]
# All empty frozenset subclass instances should have different ids
self.assertEqual(len(set(map(id, efs))), len(efs))
# Tests taken from test_sets.py =============================================
empty_set = set()
#==============================================================================
class TestBasicOps:
def test_repr(self):
if self.repr is not None:
self.assertEqual(repr(self.set), self.repr)
def check_repr_against_values(self):
text = repr(self.set)
self.assertTrue(text.startswith('{'))
self.assertTrue(text.endswith('}'))
result = text[1:-1].split(', ')
result.sort()
sorted_repr_values = [repr(value) for value in self.values]
sorted_repr_values.sort()
self.assertEqual(result, sorted_repr_values)
def test_print(self):
try:
fo = open(support.TESTFN, "w")
fo.write(str(self.set))
fo.close()
fo = open(support.TESTFN, "r")
self.assertEqual(fo.read(), repr(self.set))
finally:
fo.close()
support.unlink(support.TESTFN)
def test_length(self):
self.assertEqual(len(self.set), self.length)
def test_self_equality(self):
self.assertEqual(self.set, self.set)
def test_equivalent_equality(self):
self.assertEqual(self.set, self.dup)
def test_copy(self):
self.assertEqual(self.set.copy(), self.dup)
def test_self_union(self):
result = self.set | self.set
self.assertEqual(result, self.dup)
def test_empty_union(self):
result = self.set | empty_set
self.assertEqual(result, self.dup)
def test_union_empty(self):
result = empty_set | self.set
self.assertEqual(result, self.dup)
def test_self_intersection(self):
result = self.set & self.set
self.assertEqual(result, self.dup)
def test_empty_intersection(self):
result = self.set & empty_set
self.assertEqual(result, empty_set)
def test_intersection_empty(self):
result = empty_set & self.set
self.assertEqual(result, empty_set)
def test_self_isdisjoint(self):
result = self.set.isdisjoint(self.set)
self.assertEqual(result, not self.set)
def test_empty_isdisjoint(self):
result = self.set.isdisjoint(empty_set)
self.assertEqual(result, True)
def test_isdisjoint_empty(self):
result = empty_set.isdisjoint(self.set)
self.assertEqual(result, True)
def test_self_symmetric_difference(self):
result = self.set ^ self.set
self.assertEqual(result, empty_set)
def test_empty_symmetric_difference(self):
result = self.set ^ empty_set
self.assertEqual(result, self.set)
def test_self_difference(self):
result = self.set - self.set
self.assertEqual(result, empty_set)
def test_empty_difference(self):
result = self.set - empty_set
self.assertEqual(result, self.dup)
def test_empty_difference_rev(self):
result = empty_set - self.set
self.assertEqual(result, empty_set)
def test_iteration(self):
for v in self.set:
self.assertIn(v, self.values)
setiter = iter(self.set)
self.assertEqual(setiter.__length_hint__(), len(self.set))
def test_pickling(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
p = pickle.dumps(self.set, proto)
copy = pickle.loads(p)
self.assertEqual(self.set, copy,
"%s != %s" % (self.set, copy))
def test_issue_37219(self):
with self.assertRaises(TypeError):
set().difference(123)
with self.assertRaises(TypeError):
set().difference_update(123)
#------------------------------------------------------------------------------
class TestBasicOpsEmpty(TestBasicOps, unittest.TestCase):
def setUp(self):
self.case = "empty set"
self.values = []
self.set = set(self.values)
self.dup = set(self.values)
self.length = 0
self.repr = "set()"
#------------------------------------------------------------------------------
class TestBasicOpsSingleton(TestBasicOps, unittest.TestCase):
def setUp(self):
self.case = "unit set (number)"
self.values = [3]
self.set = set(self.values)
self.dup = set(self.values)
self.length = 1
self.repr = "{3}"
def test_in(self):
self.assertIn(3, self.set)
def test_not_in(self):
self.assertNotIn(2, self.set)
#------------------------------------------------------------------------------
class TestBasicOpsTuple(TestBasicOps, unittest.TestCase):
def setUp(self):
self.case = "unit set (tuple)"
self.values = [(0, "zero")]
self.set = set(self.values)
self.dup = set(self.values)
self.length = 1
self.repr = "{(0, 'zero')}"
def test_in(self):
self.assertIn((0, "zero"), self.set)
def test_not_in(self):
self.assertNotIn(9, self.set)
#------------------------------------------------------------------------------
class TestBasicOpsTriple(TestBasicOps, unittest.TestCase):
def setUp(self):
self.case = "triple set"
self.values = [0, "zero", operator.add]
self.set = set(self.values)
self.dup = set(self.values)
self.length = 3
self.repr = None
#------------------------------------------------------------------------------
class TestBasicOpsString(TestBasicOps, unittest.TestCase):
def setUp(self):
self.case = "string set"
self.values = ["a", "b", "c"]
self.set = set(self.values)
self.dup = set(self.values)
self.length = 3
def test_repr(self):
self.check_repr_against_values()
#------------------------------------------------------------------------------
class TestBasicOpsBytes(TestBasicOps, unittest.TestCase):
def setUp(self):
self.case = "bytes set"
self.values = [b"a", b"b", b"c"]
self.set = set(self.values)
self.dup = set(self.values)
self.length = 3
def test_repr(self):
self.check_repr_against_values()
#------------------------------------------------------------------------------
class TestBasicOpsMixedStringBytes(TestBasicOps, unittest.TestCase):
def setUp(self):
self._warning_filters = support.check_warnings()
self._warning_filters.__enter__()
warnings.simplefilter('ignore', BytesWarning)
self.case = "string and bytes set"
self.values = ["a", "b", b"a", b"b"]
self.set = set(self.values)
self.dup = set(self.values)
self.length = 4
def tearDown(self):
self._warning_filters.__exit__(None, None, None)
def test_repr(self):
self.check_repr_against_values()
#==============================================================================
def baditer():
raise TypeError
yield True
def gooditer():
yield True
class TestExceptionPropagation(unittest.TestCase):
"""SF 628246: Set constructor should not trap iterator TypeErrors"""
def test_instanceWithException(self):
self.assertRaises(TypeError, set, baditer())
def test_instancesWithoutException(self):
# All of these iterables should load without exception.
set([1,2,3])
set((1,2,3))
set({'one':1, 'two':2, 'three':3})
set(range(3))
set('abc')
set(gooditer())
def test_changingSizeWhileIterating(self):
s = set([1,2,3])
try:
for i in s:
s.update([4])
except RuntimeError:
pass
else:
self.fail("no exception when changing size during iteration")
#==============================================================================
class TestSetOfSets(unittest.TestCase):
def test_constructor(self):
inner = frozenset([1])
outer = set([inner])
element = outer.pop()
self.assertEqual(type(element), frozenset)
outer.add(inner) # Rebuild set of sets with .add method
outer.remove(inner)
self.assertEqual(outer, set()) # Verify that remove worked
outer.discard(inner) # Absence of KeyError indicates working fine
#==============================================================================
class TestBinaryOps(unittest.TestCase):
def setUp(self):
self.set = set((2, 4, 6))
def test_eq(self): # SF bug 643115
self.assertEqual(self.set, set({2:1,4:3,6:5}))
def test_union_subset(self):
result = self.set | set([2])
self.assertEqual(result, set((2, 4, 6)))
def test_union_superset(self):
result = self.set | set([2, 4, 6, 8])
self.assertEqual(result, set([2, 4, 6, 8]))
def test_union_overlap(self):
result = self.set | set([3, 4, 5])
self.assertEqual(result, set([2, 3, 4, 5, 6]))
def test_union_non_overlap(self):
result = self.set | set([8])
self.assertEqual(result, set([2, 4, 6, 8]))
def test_intersection_subset(self):
result = self.set & set((2, 4))
self.assertEqual(result, set((2, 4)))
def test_intersection_superset(self):
result = self.set & set([2, 4, 6, 8])
self.assertEqual(result, set([2, 4, 6]))
def test_intersection_overlap(self):
result = self.set & set([3, 4, 5])
self.assertEqual(result, set([4]))
def test_intersection_non_overlap(self):
result = self.set & set([8])
self.assertEqual(result, empty_set)
def test_isdisjoint_subset(self):
result = self.set.isdisjoint(set((2, 4)))
self.assertEqual(result, False)
def test_isdisjoint_superset(self):
result = self.set.isdisjoint(set([2, 4, 6, 8]))
self.assertEqual(result, False)
def test_isdisjoint_overlap(self):
result = self.set.isdisjoint(set([3, 4, 5]))
self.assertEqual(result, False)
def test_isdisjoint_non_overlap(self):
result = self.set.isdisjoint(set([8]))
self.assertEqual(result, True)
def test_sym_difference_subset(self):
result = self.set ^ set((2, 4))
self.assertEqual(result, set([6]))
def test_sym_difference_superset(self):
result = self.set ^ set((2, 4, 6, 8))
self.assertEqual(result, set([8]))
def test_sym_difference_overlap(self):
result = self.set ^ set((3, 4, 5))
self.assertEqual(result, set([2, 3, 5, 6]))
def test_sym_difference_non_overlap(self):
result = self.set ^ set([8])
self.assertEqual(result, set([2, 4, 6, 8]))
#==============================================================================
class TestUpdateOps(unittest.TestCase):
def setUp(self):
self.set = set((2, 4, 6))
def test_union_subset(self):
self.set |= set([2])
self.assertEqual(self.set, set((2, 4, 6)))
def test_union_superset(self):
self.set |= set([2, 4, 6, 8])
self.assertEqual(self.set, set([2, 4, 6, 8]))
def test_union_overlap(self):
self.set |= set([3, 4, 5])
self.assertEqual(self.set, set([2, 3, 4, 5, 6]))
def test_union_non_overlap(self):
self.set |= set([8])
self.assertEqual(self.set, set([2, 4, 6, 8]))
def test_union_method_call(self):
self.set.update(set([3, 4, 5]))
self.assertEqual(self.set, set([2, 3, 4, 5, 6]))
def test_intersection_subset(self):
self.set &= set((2, 4))
self.assertEqual(self.set, set((2, 4)))
def test_intersection_superset(self):
self.set &= set([2, 4, 6, 8])
self.assertEqual(self.set, set([2, 4, 6]))
def test_intersection_overlap(self):
self.set &= set([3, 4, 5])
self.assertEqual(self.set, set([4]))
def test_intersection_non_overlap(self):
self.set &= set([8])
self.assertEqual(self.set, empty_set)
def test_intersection_method_call(self):
self.set.intersection_update(set([3, 4, 5]))
self.assertEqual(self.set, set([4]))
def test_sym_difference_subset(self):
self.set ^= set((2, 4))
self.assertEqual(self.set, set([6]))
def test_sym_difference_superset(self):
self.set ^= set((2, 4, 6, 8))
self.assertEqual(self.set, set([8]))
def test_sym_difference_overlap(self):
self.set ^= set((3, 4, 5))
self.assertEqual(self.set, set([2, 3, 5, 6]))
def test_sym_difference_non_overlap(self):
self.set ^= set([8])
self.assertEqual(self.set, set([2, 4, 6, 8]))
def test_sym_difference_method_call(self):
self.set.symmetric_difference_update(set([3, 4, 5]))
self.assertEqual(self.set, set([2, 3, 5, 6]))
def test_difference_subset(self):
self.set -= set((2, 4))
self.assertEqual(self.set, set([6]))
def test_difference_superset(self):
self.set -= set((2, 4, 6, 8))
self.assertEqual(self.set, set([]))
def test_difference_overlap(self):
self.set -= set((3, 4, 5))
self.assertEqual(self.set, set([2, 6]))
def test_difference_non_overlap(self):
self.set -= set([8])
self.assertEqual(self.set, set([2, 4, 6]))
def test_difference_method_call(self):
self.set.difference_update(set([3, 4, 5]))
self.assertEqual(self.set, set([2, 6]))
#==============================================================================
class TestMutate(unittest.TestCase):
def setUp(self):
self.values = ["a", "b", "c"]
self.set = set(self.values)
def test_add_present(self):
self.set.add("c")
self.assertEqual(self.set, set("abc"))
def test_add_absent(self):
self.set.add("d")
self.assertEqual(self.set, set("abcd"))
def test_add_until_full(self):
tmp = set()
expected_len = 0
for v in self.values:
tmp.add(v)
expected_len += 1
self.assertEqual(len(tmp), expected_len)
self.assertEqual(tmp, self.set)
def test_remove_present(self):
self.set.remove("b")
self.assertEqual(self.set, set("ac"))
def test_remove_absent(self):
try:
self.set.remove("d")
self.fail("Removing missing element should have raised LookupError")
except LookupError:
pass
def test_remove_until_empty(self):
expected_len = len(self.set)
for v in self.values:
self.set.remove(v)
expected_len -= 1
self.assertEqual(len(self.set), expected_len)
def test_discard_present(self):
self.set.discard("c")
self.assertEqual(self.set, set("ab"))
def test_discard_absent(self):
self.set.discard("d")
self.assertEqual(self.set, set("abc"))
def test_clear(self):
self.set.clear()
self.assertEqual(len(self.set), 0)
def test_pop(self):
popped = {}
while self.set:
popped[self.set.pop()] = None
self.assertEqual(len(popped), len(self.values))
for v in self.values:
self.assertIn(v, popped)
def test_update_empty_tuple(self):
self.set.update(())
self.assertEqual(self.set, set(self.values))
def test_update_unit_tuple_overlap(self):
self.set.update(("a",))
self.assertEqual(self.set, set(self.values))
def test_update_unit_tuple_non_overlap(self):
self.set.update(("a", "z"))
self.assertEqual(self.set, set(self.values + ["z"]))
#==============================================================================
class TestSubsets:
case2method = {"<=": "issubset",
">=": "issuperset",
}
reverse = {"==": "==",
"!=": "!=",
"<": ">",
">": "<",
"<=": ">=",
">=": "<=",
}
@unittest.skipUnderCinderJIT("eval unsupported")
def test_issubset(self):
x = self.left
y = self.right
for case in "!=", "==", "<", "<=", ">", ">=":
expected = case in self.cases
# Test the binary infix spelling.
result = eval("x" + case + "y", locals())
self.assertEqual(result, expected)
# Test the "friendly" method-name spelling, if one exists.
if case in TestSubsets.case2method:
method = getattr(x, TestSubsets.case2method[case])
result = method(y)
self.assertEqual(result, expected)
# Now do the same for the operands reversed.
rcase = TestSubsets.reverse[case]
result = eval("y" + rcase + "x", locals())
self.assertEqual(result, expected)
if rcase in TestSubsets.case2method:
method = getattr(y, TestSubsets.case2method[rcase])
result = method(x)
self.assertEqual(result, expected)
#------------------------------------------------------------------------------
class TestSubsetEqualEmpty(TestSubsets, unittest.TestCase):
left = set()
right = set()
name = "both empty"
cases = "==", "<=", ">="
#------------------------------------------------------------------------------
class TestSubsetEqualNonEmpty(TestSubsets, unittest.TestCase):
left = set([1, 2])
right = set([1, 2])
name = "equal pair"
cases = "==", "<=", ">="
#------------------------------------------------------------------------------
class TestSubsetEmptyNonEmpty(TestSubsets, unittest.TestCase):
left = set()
right = set([1, 2])
name = "one empty, one non-empty"
cases = "!=", "<", "<="
#------------------------------------------------------------------------------
class TestSubsetPartial(TestSubsets, unittest.TestCase):
left = set([1])
right = set([1, 2])
name = "one a non-empty proper subset of other"
cases = "!=", "<", "<="
#------------------------------------------------------------------------------
class TestSubsetNonOverlap(TestSubsets, unittest.TestCase):
left = set([1])
right = set([2])
name = "neither empty, neither contains"
cases = "!="
#==============================================================================
class TestOnlySetsInBinaryOps:
def test_eq_ne(self):
# Unlike the others, this is testing that == and != *are* allowed.
self.assertEqual(self.other == self.set, False)
self.assertEqual(self.set == self.other, False)
self.assertEqual(self.other != self.set, True)
self.assertEqual(self.set != self.other, True)
def test_ge_gt_le_lt(self):
self.assertRaises(TypeError, lambda: self.set < self.other)
self.assertRaises(TypeError, lambda: self.set <= self.other)
self.assertRaises(TypeError, lambda: self.set > self.other)
self.assertRaises(TypeError, lambda: self.set >= self.other)
self.assertRaises(TypeError, lambda: self.other < self.set)
self.assertRaises(TypeError, lambda: self.other <= self.set)
self.assertRaises(TypeError, lambda: self.other > self.set)
self.assertRaises(TypeError, lambda: self.other >= self.set)
def test_update_operator(self):
try:
self.set |= self.other
except TypeError:
pass
else:
self.fail("expected TypeError")
def test_update(self):
if self.otherIsIterable:
self.set.update(self.other)
else:
self.assertRaises(TypeError, self.set.update, self.other)
def test_union(self):
self.assertRaises(TypeError, lambda: self.set | self.other)
self.assertRaises(TypeError, lambda: self.other | self.set)
if self.otherIsIterable:
self.set.union(self.other)
else:
self.assertRaises(TypeError, self.set.union, self.other)
def test_intersection_update_operator(self):
try:
self.set &= self.other
except TypeError:
pass
else:
self.fail("expected TypeError")
def test_intersection_update(self):
if self.otherIsIterable:
self.set.intersection_update(self.other)
else:
self.assertRaises(TypeError,
self.set.intersection_update,
self.other)
def test_intersection(self):
self.assertRaises(TypeError, lambda: self.set & self.other)
self.assertRaises(TypeError, lambda: self.other & self.set)
if self.otherIsIterable:
self.set.intersection(self.other)
else:
self.assertRaises(TypeError, self.set.intersection, self.other)
def test_sym_difference_update_operator(self):
try:
self.set ^= self.other
except TypeError:
pass
else:
self.fail("expected TypeError")
def test_sym_difference_update(self):
if self.otherIsIterable:
self.set.symmetric_difference_update(self.other)
else:
self.assertRaises(TypeError,
self.set.symmetric_difference_update,
self.other)
def test_sym_difference(self):
self.assertRaises(TypeError, lambda: self.set ^ self.other)
self.assertRaises(TypeError, lambda: self.other ^ self.set)
if self.otherIsIterable:
self.set.symmetric_difference(self.other)
else:
self.assertRaises(TypeError, self.set.symmetric_difference, self.other)
def test_difference_update_operator(self):
try:
self.set -= self.other
except TypeError:
pass
else:
self.fail("expected TypeError")
def test_difference_update(self):
if self.otherIsIterable:
self.set.difference_update(self.other)
else:
self.assertRaises(TypeError,
self.set.difference_update,
self.other)
def test_difference(self):
self.assertRaises(TypeError, lambda: self.set - self.other)
self.assertRaises(TypeError, lambda: self.other - self.set)
if self.otherIsIterable:
self.set.difference(self.other)
else:
self.assertRaises(TypeError, self.set.difference, self.other)
#------------------------------------------------------------------------------
class TestOnlySetsNumeric(TestOnlySetsInBinaryOps, unittest.TestCase):
def setUp(self):
self.set = set((1, 2, 3))
self.other = 19
self.otherIsIterable = False
#------------------------------------------------------------------------------
class TestOnlySetsDict(TestOnlySetsInBinaryOps, unittest.TestCase):
def setUp(self):
self.set = set((1, 2, 3))
self.other = {1:2, 3:4}
self.otherIsIterable = True
#------------------------------------------------------------------------------
class TestOnlySetsOperator(TestOnlySetsInBinaryOps, unittest.TestCase):
def setUp(self):
self.set = set((1, 2, 3))
self.other = operator.add
self.otherIsIterable = False
#------------------------------------------------------------------------------
class TestOnlySetsTuple(TestOnlySetsInBinaryOps, unittest.TestCase):
def setUp(self):
self.set = set((1, 2, 3))
self.other = (2, 4, 6)
self.otherIsIterable = True
#------------------------------------------------------------------------------
class TestOnlySetsString(TestOnlySetsInBinaryOps, unittest.TestCase):
def setUp(self):
self.set = set((1, 2, 3))
self.other = 'abc'
self.otherIsIterable = True
#------------------------------------------------------------------------------
class TestOnlySetsGenerator(TestOnlySetsInBinaryOps, unittest.TestCase):
def setUp(self):
def gen():
for i in range(0, 10, 2):
yield i
self.set = set((1, 2, 3))
self.other = gen()
self.otherIsIterable = True
#==============================================================================
class TestCopying:
def test_copy(self):
dup = self.set.copy()
dup_list = sorted(dup, key=repr)
set_list = sorted(self.set, key=repr)
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.assertTrue(dup_list[i] is set_list[i])
def test_deep_copy(self):
dup = copy.deepcopy(self.set)
##print type(dup), repr(dup)
dup_list = sorted(dup, key=repr)
set_list = sorted(self.set, key=repr)
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.assertEqual(dup_list[i], set_list[i])
#------------------------------------------------------------------------------
class TestCopyingEmpty(TestCopying, unittest.TestCase):
def setUp(self):
self.set = set()
#------------------------------------------------------------------------------
class TestCopyingSingleton(TestCopying, unittest.TestCase):
def setUp(self):
self.set = set(["hello"])
#------------------------------------------------------------------------------
class TestCopyingTriple(TestCopying, unittest.TestCase):
def setUp(self):
self.set = set(["zero", 0, None])
#------------------------------------------------------------------------------
class TestCopyingTuple(TestCopying, unittest.TestCase):
def setUp(self):
self.set = set([(1, 2)])
#------------------------------------------------------------------------------
class TestCopyingNested(TestCopying, unittest.TestCase):
def setUp(self):
self.set = set([((1, 2), (3, 4))])
#==============================================================================
class TestIdentities(unittest.TestCase):
def setUp(self):
self.a = set('abracadabra')
self.b = set('alacazam')
def test_binopsVsSubsets(self):
a, b = self.a, self.b
self.assertTrue(a - b < a)
self.assertTrue(b - a < b)
self.assertTrue(a & b < a)
self.assertTrue(a & b < b)
self.assertTrue(a | b > a)
self.assertTrue(a | b > b)
self.assertTrue(a ^ b < a | b)
def test_commutativity(self):
a, b = self.a, self.b
self.assertEqual(a&b, b&a)
self.assertEqual(a|b, b|a)
self.assertEqual(a^b, b^a)
if a != b:
self.assertNotEqual(a-b, b-a)
def test_summations(self):
# check that sums of parts equal the whole
a, b = self.a, self.b
self.assertEqual((a-b)|(a&b)|(b-a), a|b)
self.assertEqual((a&b)|(a^b), a|b)
self.assertEqual(a|(b-a), a|b)
self.assertEqual((a-b)|b, a|b)
self.assertEqual((a-b)|(a&b), a)
self.assertEqual((b-a)|(a&b), b)
self.assertEqual((a-b)|(b-a), a^b)
def test_exclusion(self):
# check that inverse operations show non-overlap
a, b, zero = self.a, self.b, set()
self.assertEqual((a-b)&b, zero)
self.assertEqual((b-a)&a, zero)
self.assertEqual((a&b)&(a^b), zero)
# Tests derived from test_itertools.py =======================================
def R(seqn):
'Regular generator'
for i in seqn:
yield i
class G:
'Sequence using __getitem__'
def __init__(self, seqn):
self.seqn = seqn
def __getitem__(self, i):
return self.seqn[i]
class I:
'Sequence using iterator protocol'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class Ig:
'Sequence using iterator protocol defined with a generator'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
for val in self.seqn:
yield val
class X:
'Missing __getitem__ and __iter__'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __next__(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class N:
'Iterator missing __next__()'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
class E:
'Test propagation of exceptions'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def __next__(self):
3 // 0
class S:
'Test immediate stop'
def __init__(self, seqn):
pass
def __iter__(self):
return self
def __next__(self):
raise StopIteration
from itertools import chain
def L(seqn):
'Test multiple tiers of iterators'
return chain(map(lambda x:x, R(Ig(G(seqn)))))
class TestVariousIteratorArgs(unittest.TestCase):
def test_constructor(self):
for cons in (set, frozenset):
for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(sorted(cons(g(s)), key=repr), sorted(g(s), key=repr))
self.assertRaises(TypeError, cons , X(s))
self.assertRaises(TypeError, cons , N(s))
self.assertRaises(ZeroDivisionError, cons , E(s))
def test_inline_methods(self):
s = set('november')
for data in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5), 'december'):
for meth in (s.union, s.intersection, s.difference, s.symmetric_difference, s.isdisjoint):
for g in (G, I, Ig, L, R):
expected = meth(data)
actual = meth(g(data))
if isinstance(expected, bool):
self.assertEqual(actual, expected)
else:
self.assertEqual(sorted(actual, key=repr), sorted(expected, key=repr))
self.assertRaises(TypeError, meth, X(s))
self.assertRaises(TypeError, meth, N(s))
self.assertRaises(ZeroDivisionError, meth, E(s))
def test_inplace_methods(self):
for data in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5), 'december'):
for methname in ('update', 'intersection_update',
'difference_update', 'symmetric_difference_update'):
for g in (G, I, Ig, S, L, R):
s = set('january')
t = s.copy()
getattr(s, methname)(list(g(data)))
getattr(t, methname)(g(data))
self.assertEqual(sorted(s, key=repr), sorted(t, key=repr))
self.assertRaises(TypeError, getattr(set('january'), methname), X(data))
self.assertRaises(TypeError, getattr(set('january'), methname), N(data))
self.assertRaises(ZeroDivisionError, getattr(set('january'), methname), E(data))
class bad_eq:
def __eq__(self, other):
if be_bad:
set2.clear()
raise ZeroDivisionError
return self is other
def __hash__(self):
return 0
class bad_dict_clear:
def __eq__(self, other):
if be_bad:
dict2.clear()
return self is other
def __hash__(self):
return 0
class TestWeirdBugs(unittest.TestCase):
def test_8420_set_merge(self):
# This used to segfault
global be_bad, set2, dict2
be_bad = False
set1 = {bad_eq()}
set2 = {bad_eq() for i in range(75)}
be_bad = True
self.assertRaises(ZeroDivisionError, set1.update, set2)
be_bad = False
set1 = {bad_dict_clear()}
dict2 = {bad_dict_clear(): None}
be_bad = True
set1.symmetric_difference_update(dict2)
def test_iter_and_mutate(self):
# Issue #24581
s = set(range(100))
s.clear()
s.update(range(100))
si = iter(s)
s.clear()
a = list(range(100))
s.update(range(100))
list(si)
def test_merge_and_mutate(self):
class X:
def __hash__(self):
return hash(0)
def __eq__(self, o):
other.clear()
return False
other = set()
other = {X() for i in range(10)}
s = {0}
s.update(other)
# Application tests (based on David Eppstein's graph recipes ====================================
def powerset(U):
"""Generates all subsets of a set or sequence U."""
U = iter(U)
try:
x = frozenset([next(U)])
for S in powerset(U):
yield S
yield S | x
except StopIteration:
yield frozenset()
def cube(n):
"""Graph of n-dimensional hypercube."""
singletons = [frozenset([x]) for x in range(n)]
return dict([(x, frozenset([x^s for s in singletons]))
for x in powerset(range(n))])
def linegraph(G):
"""Graph, the vertices of which are edges of G,
with two vertices being adjacent iff the corresponding
edges share a vertex."""
L = {}
for x in G:
for y in G[x]:
nx = [frozenset([x,z]) for z in G[x] if z != y]
ny = [frozenset([y,z]) for z in G[y] if z != x]
L[frozenset([x,y])] = frozenset(nx+ny)
return L
def faces(G):
'Return a set of faces in G. Where a face is a set of vertices on that face'
# currently limited to triangles,squares, and pentagons
f = set()
for v1, edges in G.items():
for v2 in edges:
for v3 in G[v2]:
if v1 == v3:
continue
if v1 in G[v3]:
f.add(frozenset([v1, v2, v3]))
else:
for v4 in G[v3]:
if v4 == v2:
continue
if v1 in G[v4]:
f.add(frozenset([v1, v2, v3, v4]))
else:
for v5 in G[v4]:
if v5 == v3 or v5 == v2:
continue
if v1 in G[v5]:
f.add(frozenset([v1, v2, v3, v4, v5]))
return f
class TestGraphs(unittest.TestCase):
def test_cube(self):
g = cube(3) # vert --> {v1, v2, v3}
vertices1 = set(g)
self.assertEqual(len(vertices1), 8) # eight vertices
for edge in g.values():
self.assertEqual(len(edge), 3) # each vertex connects to three edges
vertices2 = set(v for edges in g.values() for v in edges)
self.assertEqual(vertices1, vertices2) # edge vertices in original set
cubefaces = faces(g)
self.assertEqual(len(cubefaces), 6) # six faces
for face in cubefaces:
self.assertEqual(len(face), 4) # each face is a square
def test_cuboctahedron(self):
# http://en.wikipedia.org/wiki/Cuboctahedron
# 8 triangular faces and 6 square faces
# 12 identical vertices each connecting a triangle and square
g = cube(3)
cuboctahedron = linegraph(g) # V( --> {V1, V2, V3, V4}
self.assertEqual(len(cuboctahedron), 12)# twelve vertices
vertices = set(cuboctahedron)
for edges in cuboctahedron.values():
self.assertEqual(len(edges), 4) # each vertex connects to four other vertices
othervertices = set(edge for edges in cuboctahedron.values() for edge in edges)
self.assertEqual(vertices, othervertices) # edge vertices in original set
cubofaces = faces(cuboctahedron)
facesizes = collections.defaultdict(int)
for face in cubofaces:
facesizes[len(face)] += 1
self.assertEqual(facesizes[3], 8) # eight triangular faces
self.assertEqual(facesizes[4], 6) # six square faces
for vertex in cuboctahedron:
edge = vertex # Cuboctahedron vertices are edges in Cube
self.assertEqual(len(edge), 2) # Two cube vertices define an edge
for cubevert in edge:
self.assertIn(cubevert, g)
#==============================================================================
if __name__ == "__main__":
unittest.main()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-19 20:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('suite', '0002_auto_20170219_0729'),
]
operations = [
migrations.AlterField(
model_name='user',
name='is_active',
field=models.BooleanField(default=True),
),
]
|
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
import sys
import inspect
import shutil
__location__ = os.path.join(os.getcwd(), os.path.dirname(
inspect.getfile(inspect.currentframe())))
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.join(__location__, '../src'))
# -- Run sphinx-apidoc ------------------------------------------------------
# This hack is necessary since RTD does not issue `sphinx-apidoc` before running
# `sphinx-build -b html . _build/html`. See Issue:
# https://github.com/rtfd/readthedocs.org/issues/1139
# DON'T FORGET: Check the box "Install your project inside a virtualenv using
# setup.py install" in the RTD Advanced Settings.
# Additionally it helps us to avoid running apidoc manually
try: # for Sphinx >= 1.7
from sphinx.ext import apidoc
except ImportError:
from sphinx import apidoc
output_dir = os.path.join(__location__, "api")
module_dir = os.path.join(__location__, "../src/thesis")
try:
shutil.rmtree(output_dir)
except FileNotFoundError:
pass
try:
import sphinx
from pkg_resources import parse_version
cmd_line_template = "sphinx-apidoc -f -o {outputdir} {moduledir}"
cmd_line = cmd_line_template.format(outputdir=output_dir, moduledir=module_dir)
args = cmd_line.split(" ")
if parse_version(sphinx.__version__) >= parse_version('1.7'):
args = args[1:]
apidoc.main(args)
except Exception as e:
print("Running `sphinx-apidoc` failed!\n{}".format(e))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo',
'sphinx.ext.autosummary', 'sphinx.ext.viewcode', 'sphinx.ext.coverage',
'sphinx.ext.doctest', 'sphinx.ext.ifconfig', 'sphinx.ext.mathjax',
'sphinx.ext.napoleon']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'thesis'
copyright = u'2020, Mathematical Michael'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '' # Is set by calling `setup.py docs`
# The full version, including alpha/beta/rc tags.
release = '' # Is set by calling `setup.py docs`
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'sidebar_width': '300px',
'page_width': '1200px'
}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
try:
from thesis import __version__ as version
except ImportError:
pass
else:
release = version
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = ""
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'thesis-doc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'user_guide.tex', u'thesis Documentation',
u'Mathematical Michael', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = ""
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- External mapping ------------------------------------------------------------
python_version = '.'.join(map(str, sys.version_info[0:2]))
intersphinx_mapping = {
'sphinx': ('http://www.sphinx-doc.org/en/stable', None),
'python': ('https://docs.python.org/' + python_version, None),
'matplotlib': ('https://matplotlib.org', None),
'numpy': ('https://docs.scipy.org/doc/numpy', None),
'sklearn': ('http://scikit-learn.org/stable', None),
'pandas': ('http://pandas.pydata.org/pandas-docs/stable', None),
'scipy': ('https://docs.scipy.org/doc/scipy/reference', None),
}
|
#pragma once
#include "../utils/Arduboy2Ext.h"
#include "../Utils/Enums.h"
#include "../map/Coordinates.h"
class Key {
public:
Key();
// Properties ..
uint8_t getPosition();
int8_t getXPosition();
int8_t getYPosition(uint8_t yOffset);
uint8_t getImage();
KeyLocation getKeyLocation();
bool isEnabled();
void setEnabled(bool enabled);
void setPath(uint8_t const *path);
void setKeyLocation(KeyLocation keyLocation);
void setFlash(bool value);
// Methods
bool getDisplay();
void updatePosition();
Rect getRect(uint8_t yOffset);
protected:
bool enabled = false;
bool flash = false;
uint8_t position = 0;
uint8_t counter = 0;
uint8_t const *path = nullptr;
KeyLocation keyLocation = KeyLocation::LowerPosition;
};
|
class Base{
constructor(x,y,w,h) {
var options = {
isStatic:true
}
this.w = w
this.h = h
this.body = Bodies.rectangle(x,y,this.w,this.h,options)
World.add(world,this.body)
}
display() {
var pos = this.body.position
push()
fill("red")
rect(pos.x,pos.y,this.w,this.h)
pop()
}
}
|
'use strict';
angular.module('mean-factory-interceptor',[])
.factory('httpInterceptor', ['$q','$location',function ($q,$location) {
return {
'response': function(response) {
if (response.status === 401) {
$location.path('/login');
return $q.reject(response);
}
return response || $q.when(response);
},
'responseError': function(rejection) {
if (rejection.status === 401) {
$location.url('/login');
return $q.reject(rejection);
}
return $q.reject(rejection);
}
};
}
])
//Http Intercpetor to check auth failures for xhr requests
.config(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}]);
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fas';
var iconName = 'calculator';
var width = 448;
var height = 512;
var ligatures = [];
var unicode = 'f1ec';
var svgPathData = 'M400 0H48C22.4 0 0 22.4 0 48v416c0 25.6 22.4 48 48 48h352c25.6 0 48-22.4 48-48V48c0-25.6-22.4-48-48-48zM128 435.2c0 6.4-6.4 12.8-12.8 12.8H76.8c-6.4 0-12.8-6.4-12.8-12.8v-38.4c0-6.4 6.4-12.8 12.8-12.8h38.4c6.4 0 12.8 6.4 12.8 12.8v38.4zm0-128c0 6.4-6.4 12.8-12.8 12.8H76.8c-6.4 0-12.8-6.4-12.8-12.8v-38.4c0-6.4 6.4-12.8 12.8-12.8h38.4c6.4 0 12.8 6.4 12.8 12.8v38.4zm128 128c0 6.4-6.4 12.8-12.8 12.8h-38.4c-6.4 0-12.8-6.4-12.8-12.8v-38.4c0-6.4 6.4-12.8 12.8-12.8h38.4c6.4 0 12.8 6.4 12.8 12.8v38.4zm0-128c0 6.4-6.4 12.8-12.8 12.8h-38.4c-6.4 0-12.8-6.4-12.8-12.8v-38.4c0-6.4 6.4-12.8 12.8-12.8h38.4c6.4 0 12.8 6.4 12.8 12.8v38.4zm128 128c0 6.4-6.4 12.8-12.8 12.8h-38.4c-6.4 0-12.8-6.4-12.8-12.8V268.8c0-6.4 6.4-12.8 12.8-12.8h38.4c6.4 0 12.8 6.4 12.8 12.8v166.4zm0-256c0 6.4-6.4 12.8-12.8 12.8H76.8c-6.4 0-12.8-6.4-12.8-12.8V76.8C64 70.4 70.4 64 76.8 64h294.4c6.4 0 12.8 6.4 12.8 12.8v102.4z';
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
ligatures,
unicode,
svgPathData
]};
exports.faCalculator = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode;
exports.svgPathData = svgPathData;
|
var gulp = require('gulp');
var minify = require('gulp-minify');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
gulp.task('css', function() {
return gulp.src('./src/**/*.css')
.pipe(minify())
.pipe(gulp.dest('./dist/'));
});
gulp.task('js', function() {
return gulp.src('./src/**/*.js')
.pipe(uglify())
.pipe(gulp.dest('./dist/'));
});
gulp.task('html', function() {
return gulp.src('./src/index.html')
.pipe(gulp.dest('./dist/'));
});
gulp.task('watch', function() {
gulp.watch('./src/styles/style.css', ['css']);
gulp.watch('./src/scripts/main.js', ['js']);
gulp.watch('./src/index.html', ['html']);
});
gulp.task('default', ['css', 'js', 'html', 'watch']);
|
int removeDuplicates(int* nums, int numsSize) {
int i, j;
if (numsSize <= 2) {
return numsSize;
}
for (i = 2, j = 2; i != numsSize; i++) {
if (nums[i] == nums[j - 1] && nums[i] == nums[j - 2]) {
} else {
if (j != i) {
nums[j] = nums[i];
}
j++;
}
}
return j;
}
|
import os
import string
import re
import wave
import shutil
from audioset_download_tool import AudioSetDownloader
from cli_manager import CLIManager
from pydub import AudioSegment
import pydub.playback
class Logger():
def __init__(self, audioset_dl: AudioSetDownloader):
self.audioset_dl = audioset_dl
def info(self):
pass
def warn(self, msg):
print('\nWarning:', msg, '\n')
with open(os.path.join(self.audioset_dl.support_files_directory, "warnings.log"), "a+") as log_file:
print(msg, file=log_file)
def error(self):
pass
class AudioProcessor():
def __init__(self, audioset_dl: AudioSetDownloader):
self.audioset_dl = audioset_dl
self.export_dir = os.path.join(os.path.abspath(self.audioset_dl.audios_directory), 'trimmed_files')
self.selected_dir = os.path.join(os.path.abspath(self.audioset_dl.audios_directory), 'selected_files')
self.logger = Logger(self.audioset_dl)
def clean(self):
warning_file = os.path.join(self.audioset_dl.support_files_directory, "warnings.log")
if os.path.exists(warning_file):
os.remove(warning_file)
def trim_audio(self, download_mode):
if CLIManager.args.verbose:
print('Opening input file from:', os.path.abspath(self.audioset_dl.support_files_directory))
gen_log_name = '{}_generated_audios.log'.format(download_mode)
self.clean()
if self.audioset_dl.audio_files_list:
for audio_name in self.audioset_dl.audio_files_list:
self.run_trim(re.search(r'\".+\"', audio_name), gen_log_name)
else:
with open(
os.path.join(os.path.abspath(self.audioset_dl.support_files_directory), gen_log_name)
) as audio_names:
for audio_name in audio_names:
self.run_trim(re.search(r'".+"', audio_name.rstrip('\n')).group().strip('"'), gen_log_name)
def run_trim(self, audio_name, audios_logfile):
print('\nLooking into \'' + audio_name + '\'...\n')
def to_milliseconds(sec_num):
return sec_num * 1e3
try:
for filename, df in self.audioset_dl.get_filtered_df(audios_logfile).items():
assert not (df.duplicated().any()), "Duplicate rows found in data."
mask = df.index[df['name'].isin([audio_name])]
if not (mask.empty):
row = df.loc[mask].squeeze()
if row.ndim != 1:
self.logger.warn(
f'Found files with coinciding names: \'{row.iloc[0]["name"]}\'.Only the last instance which appears in the dataframe will be downloaded and processed.'
)
row = row.iloc[-1]
start_ms = to_milliseconds(row['start_seconds'])
end_ms = to_milliseconds(row['end_seconds'])
print(f'Start Time: {row["start_seconds"]}')
print(f'End Time: {row["end_seconds"]}')
print(f'Duration: {row["end_seconds"] - row["start_seconds"]}\n')
audio = AudioSegment.from_wav(os.path.join(
self.audioset_dl.audios_directory,
filename.replace('.csv', ''),
audio_name
))
trimmed_audio = audio[start_ms:end_ms + 1]
if CLIManager.args.play_mode != "play":
self.export_audio(trimmed_audio, row, filename)
if CLIManager.args.play_mode != "silent":
pydub.playback.play(trimmed_audio)
except FileNotFoundError as e:
print(e)
def export_audio(self, audio_file, audio_info, subdir_name, format_='.wav'):
for attempt in range(10):
try:
subdir_name = subdir_name.replace('.csv', '')
audio_file.export(
os.path.join(self.export_dir, subdir_name, audio_info["name"].replace('.csv', '')),
format=format_.lstrip('.')
)
except FileNotFoundError:
print("Directory Tree apparently doesn't exist. Creating it...\n")
os.makedirs(os.path.join(self.export_dir, subdir_name))
else:
break
def examine_trimmed_audio(self, desired_channels_number, desired_samplerate_number):
def print_caracteristics():
print(f'\nExamining File: "{file_}"')
print(f"\nNumber of Channels: {audio.getnchannels()}")
print(f"Sampling Rate: {audio.getframerate()}")
print(f"Numer of Audio Frames: {audio.getnframes()}")
print(f"Compression Type: {audio.getcompname()}\n")
def clean_selected_folder():
if os.path.exists(self.selected_dir):
shutil.rmtree(self.selected_dir)
os.mkdir(self.selected_dir)
def select_audios(channels_number, samplerate_number):
"""
Place the best audios from the trimmed files in a separated file
"""
if audio.getnchannels() == channels_number and audio.getframerate() >= samplerate_number:
shutil.copy2(
os.path.join(audios_path, file_),
os.path.join(self.audioset_dl.audios_directory, self.selected_dir, file_)
)
print_caracteristics()
assert CLIManager.args.examine, "examine_trimmed_audio method has no input."
if CLIManager.args.examine == 'all':
folders = ('balanced_train_segments', 'eval_segments', 'unbalanced_train_segments')
if CLIManager.args.examine == 'eval':
folders = ('eval_segments',)
if CLIManager.args.examine == 'balanced':
folders = ('balanced_train_segments',)
if CLIManager.args.examine == 'unbalanced':
folders = ('unbalanced_train_segments',)
clean_selected_folder()
for folder in folders:
audios_path = os.path.join(self.export_dir, folder)
for file_ in os.listdir(audios_path):
with wave.open(os.path.join(audios_path, file_), 'rb') as audio:
# print_caracteristics()
select_audios(desired_channels_number, desired_samplerate_number)
def manual_labeler(self, label: str, target_dir=None, revert=False):
"""
As 25.03.19 this function's objective is to label the title of files to be used in training. Since the problem
supposed to be solved is binary, the classes are mutually exclusive.
Encode:
1: Positive class (Audio contains an Emergency Vehicle in it)
0: Negative class (Audio doesn't contain an Emergency Vehicle in it)
"""
if target_dir is None:
target_dir = self.selected_dir
for idx, (dir_path, subdirs, filenames) in enumerate(os.walk(target_dir)):
if idx == 0:
print(f"folders under '{os.path.basename(dir_path)}' which will be also affected:\n")
for dir_ in subdirs:
print(dir_)
print("\n", end="")
confirm = input('confirm? [y]/n\n')
if confirm.lower() == 'n' or confirm.lower() == 'no':
raise SystemExit
if revert:
for filename in filenames:
new_filename = re.sub(f'__{label}__', '', filename)
os.rename(os.path.join(dir_path, filename), os.path.join(dir_path, new_filename))
else:
for filename in filenames:
try:
h1, h2 = filename.rsplit('.', 1)
new_filename = h1 + f'__{label}__.' + h2
os.rename(os.path.join(dir_path, filename), os.path.join(dir_path, new_filename))
except ValueError:
print('File with no extension found.')
raise SystemExit
|
from __future__ import absolute_import
from __future__ import print_function
import sys
import os
# the next line can be removed after installation
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))))
from veriloggen import *
import veriloggen.thread as vthread
def mkLed(numthreads=8):
m = Module('blinkled')
clk = m.Input('CLK')
rst = m.Input('RST')
led = m.Output('LED', 8)
count = vthread.Shared(m.Reg('count', 32, initval=0))
led.assign(count.value)
def myfunc(tid):
count.lock()
print("Thread %d Lock" % tid)
for i in range(20):
pass # sleep
count.write(count.value + 1)
print("Thread %d count = %d" % (tid, count.value))
count.unlock()
print("Thread %d Unlock" % tid)
def blink():
count.write(0)
for tid in range(numthreads):
pool.run(tid, tid)
for tid in range(numthreads):
pool.join(tid)
print("result count = %d" % count.value)
th = vthread.Thread(m, 'th_blink', clk, rst, blink)
pool = vthread.ThreadPool(m, 'th_myfunc', clk, rst, myfunc, numthreads)
fsm = th.start()
return m
def mkTest():
m = Module('test')
# target instance
led = mkLed()
# copy paras and ports
params = m.copy_params(led)
ports = m.copy_sim_ports(led)
clk = ports['CLK']
rst = ports['RST']
uut = m.Instance(led, 'uut',
params=m.connect_params(led),
ports=m.connect_ports(led))
simulation.setup_waveform(m, uut)
simulation.setup_clock(m, clk, hperiod=5)
init = simulation.setup_reset(m, rst, m.make_reset(), period=100)
init.add(
Delay(10000),
Systask('finish'),
)
return m
if __name__ == '__main__':
test = mkTest()
verilog = test.to_verilog('tmp.v')
print(verilog)
sim = simulation.Simulator(test)
rslt = sim.run()
print(rslt)
|
"""
Copyright 2017-2018 Fizyr (https://fizyr.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import keras
from keras.utils import get_file
from . import retinanet
from . import Backbone
from classification_models.keras import Classifiers
class SeBackbone(Backbone):
""" Describes backbone information and provides utility functions.
"""
def __init__(self, backbone):
super(SeBackbone, self).__init__(backbone)
_, self.preprocess_image_func = Classifiers.get(self.backbone)
def retinanet(self, *args, **kwargs):
""" Returns a retinanet model using the correct backbone.
"""
return senet_retinanet(*args, backbone=self.backbone, **kwargs)
def download_imagenet(self):
""" Downloads ImageNet weights and returns path to weights file.
"""
from classification_models.weights import WEIGHTS_COLLECTION
weights_path = None
for el in WEIGHTS_COLLECTION:
if el['model'] == self.backbone and not el['include_top']:
weights_path = get_file(el['name'], el['url'], cache_subdir='models', file_hash=el['md5'])
if weights_path is None:
raise ValueError('Unable to find imagenet weights for backbone {}!'.format(self.backbone))
return weights_path
def validate(self):
""" Checks whether the backbone string is correct.
"""
allowed_backbones = ['seresnet18', 'seresnet34', 'seresnet50', 'seresnet101', 'seresnet152',
'seresnext50', 'seresnext101', 'senet154']
backbone = self.backbone.split('_')[0]
if backbone not in allowed_backbones:
raise ValueError('Backbone (\'{}\') not in allowed backbones ({}).'.format(backbone, allowed_backbones))
def preprocess_image(self, inputs):
""" Takes as input an image and prepares it for being passed through the network.
"""
return self.preprocess_image_func(inputs)
def senet_retinanet(num_classes, backbone='seresnext50', inputs=None, modifier=None, **kwargs):
""" Constructs a retinanet model using a resnet backbone.
Args
num_classes: Number of classes to predict.
backbone: Which backbone to use (one of ('resnet50', 'resnet101', 'resnet152')).
inputs: The inputs to the network (defaults to a Tensor of shape (None, None, 3)).
modifier: A function handler which can modify the backbone before using it in retinanet (this can be used to freeze backbone layers for example).
Returns
RetinaNet model with a ResNet backbone.
"""
# choose default input
if inputs is None:
if keras.backend.image_data_format() == 'channels_first':
inputs = keras.layers.Input(shape=(3, None, None))
else:
# inputs = keras.layers.Input(shape=(224, 224, 3))
inputs = keras.layers.Input(shape=(None, None, 3))
classifier, _ = Classifiers.get(backbone)
model = classifier(input_tensor=inputs, include_top=False, weights=None)
# get last conv layer from the end of each block [28x28, 14x14, 7x7]
if backbone == 'seresnet18' or backbone == 'seresnet34':
layer_outputs = ['stage3_unit1_relu1', 'stage4_unit1_relu1', 'relu1']
elif backbone == 'seresnet50':
layer_outputs = ['activation_36', 'activation_66', 'activation_81']
elif backbone == 'seresnet101':
layer_outputs = ['activation_36', 'activation_151', 'activation_166']
elif backbone == 'seresnet152':
layer_outputs = ['activation_56', 'activation_236', 'activation_251']
elif backbone == 'seresnext50':
layer_outputs = ['activation_37', 'activation_67', 'activation_81']
elif backbone == 'seresnext101':
layer_outputs = ['activation_37', 'activation_152', 'activation_166']
elif backbone == 'senet154':
layer_outputs = ['activation_59', 'activation_239', 'activation_253']
else:
raise ValueError('Backbone (\'{}\') is invalid.'.format(backbone))
layer_outputs = [
model.get_layer(name=layer_outputs[0]).output, # 28x28
model.get_layer(name=layer_outputs[1]).output, # 14x14
model.get_layer(name=layer_outputs[2]).output, # 7x7
]
# create the densenet backbone
model = keras.models.Model(inputs=inputs, outputs=layer_outputs, name=model.name)
# invoke modifier if given
if modifier:
model = modifier(model)
# create the full model
return retinanet.retinanet(inputs=inputs, num_classes=num_classes, backbone_layers=model.outputs, **kwargs)
def seresnet18_retinanet(num_classes, inputs=None, **kwargs):
return senet_retinanet(num_classes=num_classes, backbone='seresnet18', inputs=inputs, **kwargs)
def seresnet34_retinanet(num_classes, inputs=None, **kwargs):
return senet_retinanet(num_classes=num_classes, backbone='seresnet34', inputs=inputs, **kwargs)
def seresnet50_retinanet(num_classes, inputs=None, **kwargs):
return senet_retinanet(num_classes=num_classes, backbone='seresnet50', inputs=inputs, **kwargs)
def seresnet101_retinanet(num_classes, inputs=None, **kwargs):
return senet_retinanet(num_classes=num_classes, backbone='seresnet101', inputs=inputs, **kwargs)
def seresnet152_retinanet(num_classes, inputs=None, **kwargs):
return senet_retinanet(num_classes=num_classes, backbone='seresnet152', inputs=inputs, **kwargs)
def seresnext50_retinanet(num_classes, inputs=None, **kwargs):
return senet_retinanet(num_classes=num_classes, backbone='seresnext50', inputs=inputs, **kwargs)
def seresnext101_retinanet(num_classes, inputs=None, **kwargs):
return senet_retinanet(num_classes=num_classes, backbone='seresnext101', inputs=inputs, **kwargs)
def senet154_retinanet(num_classes, inputs=None, **kwargs):
return senet_retinanet(num_classes=num_classes, backbone='senet154', inputs=inputs, **kwargs)
|
import sys, os
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
from wallet import WalletWidget
from PySide2.QtWidgets import QInputDialog
from PySide2 import QtCore
def test_token(qtbot, monkeypatch):
wallet = WalletWidget()
qtbot.addWidget(wallet)
old_tokens_amount = wallet.token_widget.tokens_layout.count()
address = None
with open('address.txt') as f:
address = f.readline().rstrip()
monkeypatch.setattr(QInputDialog, 'getText', lambda *args: (address, True))
qtbot.mouseClick(wallet.token_widget.watch_token_button, QtCore.Qt.LeftButton)
tokens_amount = wallet.token_widget.tokens_layout.count()
assert tokens_amount == old_tokens_amount + 1
wallet.killThreads()
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, dyndep
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
class TestATen(hu.HypothesisTestCase):
@given(inputs=hu.tensors(n=2), **hu.gcs)
def test_add(self, inputs, gc, dc):
op = core.CreateOperator(
"ATen",
["X", "Y"],
["Z"],
operator="add")
def ref(X, Y):
return [X + Y]
self.assertReferenceChecks(gc, op, inputs, ref)
@given(inputs=hu.tensors(n=2, dtype=np.float16), **hu.gcs_gpu_only)
def test_add_half(self, inputs, gc, dc):
op = core.CreateOperator(
"ATen",
["X", "Y"],
["Z"],
operator="add")
def ref(X, Y):
return [X + Y]
self.assertReferenceChecks(gc, op, inputs, ref)
@given(inputs=hu.tensors(n=1), **hu.gcs)
def test_pow(self, inputs, gc, dc):
op = core.CreateOperator(
"ATen",
["S"],
["Z"],
operator="pow", exponent=2.0)
def ref(X):
return [np.square(X)]
self.assertReferenceChecks(gc, op, inputs, ref)
@given(x=st.integers(min_value=2, max_value=8), **hu.gcs)
def test_sort(self, x, gc, dc):
inputs = [np.random.permutation(x)]
op = core.CreateOperator(
"ATen",
["S"],
["Z", "I"],
operator="sort")
def ref(X):
return [np.sort(X), np.argsort(X)]
self.assertReferenceChecks(gc, op, inputs, ref)
@given(inputs=hu.tensors(n=1), **hu.gcs)
def test_sum(self, inputs, gc, dc):
op = core.CreateOperator(
"ATen",
["S"],
["Z"],
operator="sum")
def ref(X):
return [np.sum(X)]
self.assertReferenceChecks(gc, op, inputs, ref)
@given(**hu.gcs)
def test_ones(self, gc, dc):
op = core.CreateOperator(
"ATen",
[],
["Z"],
operator="ones", type="float", size={2, 4})
def ref():
return [np.ones([2, 4])]
self.assertReferenceChecks(gc, op, [], ref)
@given(**hu.gcs)
def test_index_put(self, gc, dc):
op = core.CreateOperator(
"ATen",
['self', 'indices', 'values'],
["Z"],
operator="index_put")
def ref(self, indices, values):
self[indices] = values
return (self,)
tensor = np.random.randn(3, 3).astype(np.float32)
mask = np.array([[True, True, True], [True, False, False], [True, True, False]])
values = np.random.randn(6).astype(np.float32)
self.assertReferenceChecks(gc, op, [tensor, mask, values], ref)
if __name__ == "__main__":
import unittest
unittest.main()
|
# -*- coding: utf-8 -*-
"""
pygments.styles.stata_dark
~~~~~~~~~~~~~~~~~~~~~~~~~~
Dark style inspired by Stata's do-file editor. Note this is not
meant to be a complete style, just for Stata's file formats.
:copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from typecode._vendor.pygments.style import Style
from typecode._vendor.pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Whitespace, Generic, Text
class StataDarkStyle(Style):
default_style = ''
background_color = "#232629"
highlight_color = "#49483e"
styles = {
Whitespace: '#bbbbbb',
Error: 'bg:#e3d2d2 #a61717',
Text: '#cccccc',
String: '#51cc99',
Number: '#4FB8CC',
Operator: '',
Name.Function: '#6a6aff',
Name.Other: '#e2828e',
Keyword: 'bold #7686bb',
Keyword.Constant: '',
Comment: 'italic #777777',
Name.Variable: 'bold #7AB4DB',
Name.Variable.Global: 'bold #BE646C',
Generic.Prompt: '#ffffff',
}
|
/*
* JavaScript - Input
*
*/
$().ready( function() {
if ($.tools != null) {
var $tab = $("#tab");
var $title = $("#inputForm :input[title], #inputForm label[title]");
// Tab效果
$tab.tabs("table.tabContent, div.tabContent", {
tabs: "input"
});
// 表单提示
$title.tooltip({
position: "bottom right",
effect: "fade"
});
}
});
|
const name = 'Baron David Ward'
const dates = '14th May 1961 - 11th May 2021'
export default {
publicRuntimeConfig: {
name: name,
dates: dates
},
// Target (https://go.nuxtjs.dev/config-target)
target: 'static',
// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
htmlAttrs: {
lang: 'en'
},
get title() {
delete this.title
return this.title = 'In loving memory of ' + name
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Find details on the funeral arrangements for ' + name }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;1,700&family=Pinyon+Script&display=swap' }
]
},
// Global CSS (https://go.nuxtjs.dev/config-css)
css: [
],
// Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
plugins: [
],
// Auto import components (https://go.nuxtjs.dev/config-components)
components: true,
// Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
buildModules: [
],
// Modules (https://go.nuxtjs.dev/config-modules)
modules: [
],
// Build Configuration (https://go.nuxtjs.dev/config-build)
build: {
}
}
|
import pygame as pg
pg.init()
a = pg.font.Font('freesansbold.ttf', 32)
s = pg.Surface((100, 100))
s.fill((255, 255, 255))
s.blit(a.render('hello', True, (0, 0, 0)), (0, 0))
pg.image.save(s, 'C:\\Users\\michael\\desktop\\s.png')
|
// pages/detail/detail.js
var app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
data: app.pageData.detailPage.data
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
|
/*
*
* Layouts actions
*
*/
import { DEFAULT_ACTION } from './constants';
export function defaultAction() {
return {
type: DEFAULT_ACTION,
};
}
|
#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2020, OMRON SINIC X
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of OMRON SINIC X nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Author: Felix von Drigalski, Cristian C. Beltran-Hernandez
import o2ac_routines.helpers as helpers
from o2ac_routines.common import O2ACCommon
import copy
import numpy as np
import rospy
import geometry_msgs.msg
import tf_conversions
from math import pi, radians
from ur_control import conversions
tau = 2.0*pi # Part of math from Python 3.6
class CalibrationClass(O2ACCommon):
"""
These routines check the robots' calibration by moving them to
objects defined in the scene.
"""
def __init__(self):
super(CalibrationClass, self).__init__()
self.a_bot_downward_orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, tau/2))
self.bin_names = ["bin3_1", "bin2_4", "bin2_3", "bin2_2", "bin2_1", "bin1_2", "bin1_1", "bin1_4", "bin1_5", "bin1_3"]
# Neutral downward in the taskboard frames
rospy.sleep(.5) # Use this instead of waiting, so that simulation can be used
def offset_pose_in_own_coordinate_system(self, ps, offset):
"""
ps is the PoseStamped to offset. offset is a Point.
"""
rospy.loginfo("Received pose to offset to TCP link:")
rospy.loginfo(str(ps.pose.position.x) + ", " + str(ps.pose.position.y) + ", " + str(ps.pose.position.z))
rospy.loginfo(str(ps.pose.orientation.x) + ", " + str(ps.pose.orientation.y) + ", " + str(ps.pose.orientation.z) + ", " + str(ps.pose.orientation.w))
m = geometry_msgs.msg.TransformStamped()
m.header.frame_id = ps.header.frame_id
m.child_frame_id = "temp_pose__"
m.transform.translation.x = ps.pose.position.x
m.transform.translation.y = ps.pose.position.y
m.transform.translation.z = ps.pose.position.z
m.transform.rotation.x = ps.pose.orientation.x
m.transform.rotation.y = ps.pose.orientation.y
m.transform.rotation.z = ps.pose.orientation.z
m.transform.rotation.w = ps.pose.orientation.w
self.listener.setTransform(m)
ps_with_offset = geometry_msgs.msg.PoseStamped()
ps_with_offset.header.frame_id = "temp_pose__"
ps_with_offset.pose.position.x = offset.x
ps_with_offset.pose.position.y = offset.y
ps_with_offset.pose.position.z = offset.z
ps_with_offset.pose.orientation.w = 1.0
ps_new = self.listener.transformPose(ps.header.frame_id, ps_with_offset)
rospy.loginfo("New pose:")
rospy.loginfo(str(ps_new.pose.position.x) + ", " + str(ps_new.pose.position.y) + ", " + str(ps_new.pose.position.z))
rospy.loginfo(str(ps_new.pose.orientation.x) + ", " + str(ps_new.pose.orientation.y) + ", " + str(ps_new.pose.orientation.z) + ", " + str(ps_new.pose.orientation.w))
return ps_new
# TODO: Implement the above in the function below
def cycle_through_calibration_poses(self, poses, robot_name, speed=0.1, with_approach=False, use_z_for_approach=False, move_lin=False, go_home=True, end_effector_link=""):
home_pose = "home"
if "screw" in end_effector_link:
home_pose = "screw_ready"
if with_approach and not use_z_for_approach:
rospy.logwarn("with_approach only moves in the X direction of the header frame. Be careful.")
for pose in poses:
ps_approach = copy.deepcopy(pose)
if not use_z_for_approach:
ps_approach.pose.position.x -= .05
else:
ps_approach.pose.position.z += .05
rospy.loginfo("============ Press `Enter` to move " + robot_name + " to " + pose.header.frame_id)
helpers.publish_marker(pose, namespace="place_pose")
raw_input()
robot = self.active_robots[robot_name]
if go_home:
robot.go_to_named_pose(home_pose)
if with_approach:
robot.go_to_pose_goal(ps_approach, speed=speed, end_effector_link=end_effector_link, move_lin=move_lin)
if rospy.is_shutdown():
break
if with_approach:
robot.go_to_pose_goal(ps_approach, speed=speed, end_effector_link=end_effector_link, move_lin=move_lin)
robot.go_to_pose_goal(pose, speed=speed, end_effector_link=end_effector_link, move_lin=move_lin)
else:
robot.go_to_pose_goal(pose, speed=speed, end_effector_link=end_effector_link, move_lin=move_lin)
rospy.loginfo("============ Press `Enter` to proceed ")
raw_input()
if with_approach:
robot.go_to_pose_goal(ps_approach, speed=speed, end_effector_link=end_effector_link, move_lin=move_lin)
if go_home:
robot.go_to_named_pose(home_pose, force_ur_script=move_lin)
if go_home:
rospy.loginfo("Moving all robots home again.")
self.a_bot.go_to_named_pose("home")
self.b_bot.go_to_named_pose("home")
self.c_bot.go_to_named_pose("home")
return
def assembly_calibration_base_plate(self, robot_name="b_bot", end_effector_link="", panel_name="", rotation=0):
# if not self.set_assembly("wrs_assembly_2020"):
rospy.loginfo("============ Calibrating base plate for the assembly task. ============")
rospy.loginfo("eef link " + end_effector_link + " should be 5 mm above each corner of the plate.")
self.publish_part_in_assembled_position("base", marker_only=True)
robot = self.active_robots[robot_name]
self.make_space_for_robot(robot_name)
if end_effector_link == "":
robot.go_to_named_pose("home")
elif "screw" in end_effector_link or "suction" in end_effector_link:
robot.go_to_named_pose("screw_ready")
poses = []
pose0 = geometry_msgs.msg.PoseStamped()
pose0.pose.orientation.w = 1.0
pose0.pose.position.x = -.014
zero_rot = -tau/2 if robot_name == "a_bot" else 0
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(zero_rot + rotation, 0, 0))
self.allow_collisions_with_robot_hand("base_fixture_top", robot_name)
if panel_name == "motor_panel":
for i in range(2):
poses.append(copy.deepcopy(pose0))
poses[0].header.frame_id = "assembled_part_01_screw_hole_panel2_1"
poses[1].header.frame_id = "assembled_part_01_screw_hole_panel2_2"
elif panel_name == "bearing_panel":
for i in range(2):
poses.append(copy.deepcopy(pose0))
poses[0].header.frame_id = "assembled_part_01_screw_hole_panel1_1"
poses[1].header.frame_id = "assembled_part_01_screw_hole_panel1_2"
else:
for i in range(4):
poses.append(copy.deepcopy(pose0))
poses[0].header.frame_id = "assembled_part_01_screw_hole_panel2_2"
poses[1].header.frame_id = "assembled_part_01_screw_hole_panel2_1"
poses[2].header.frame_id = "assembled_part_01_screw_hole_panel1_2"
poses[3].header.frame_id = "assembled_part_01_screw_hole_panel1_1"
print("moving to #", len(poses), "poses")
self.cycle_through_calibration_poses(poses, robot_name, go_home=False, end_effector_link=end_effector_link, move_lin=True, with_approach=True)
return
def assembly_calibration_assembled_parts(self):
rospy.loginfo("============ Calibrating full assembled parts for the assembly task. ============")
rospy.loginfo("b_bot gripper tip should go close to some important spots.")
poses = []
pose0 = geometry_msgs.msg.PoseStamped()
pose0.pose.orientation.w = 1.0
pose0.pose.position.x = -.02
for i in range(5):
poses.append(copy.deepcopy(pose0))
poses[1].header.frame_id = "assembled_part_03" # Top of plate 2
poses[1].pose.position.x = .058
poses[1].pose.position.y = -.0025
poses[1].pose.position.z = .095 + .01
poses[1].pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, 0))
poses[2].header.frame_id = "assembled_part_08_front_tip" # Front of rotary shaft
poses[2].pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, 0, -tau/2))
poses[2].pose.position.x = .03
poses[3].header.frame_id = "assembled_part_14_screw_head"
poses[3].pose.position.x = -.03
poses[4].header.frame_id = "assembled_part_04_tip"
poses[4].pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(-tau/2, 0, -tau/2))
poses[4].pose.position.x = .03
self.cycle_through_calibration_poses(poses, "b_bot", go_home=True)
return
def taskboard_calibration_with_tools(self, robot_name="b_bot", end_effector_link="", hole=""):
rospy.loginfo("============ Calibrating taskboard screw holes. ============")
rospy.loginfo("eef link " + end_effector_link + " should be 5 mm above each corner of the plate.")
self.make_space_for_robot(robot_name)
self.active_robots[robot_name].go_to_named_pose("horizontal_screw_ready")
# self.go_to_named_pose("home", robot_name)
poses = []
pose0 = geometry_msgs.msg.PoseStamped()
pose0.pose.orientation.w = 1.0
pose0.pose.position.x = -.002
if robot_name == "a_bot":
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(-tau/12, 0, 0))
if end_effector_link == "a_bot_gripper_tip_link":
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(-tau/4, 0, 0))
elif robot_name == "b_bot":
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(tau/12, 0, 0))
if end_effector_link == "b_bot_gripper_tip_link":
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(tau/6, 0, 0))
if not hole:
for i in range(3):
poses.append(copy.deepcopy(pose0))
poses[0].header.frame_id = "taskboard_set_screw_link"
poses[1].header.frame_id = "taskboard_m3_screw_link"
poses[2].header.frame_id = "taskboard_m4_screw_link"
elif hole == "m4":
poses.append(copy.deepcopy(pose0))
poses[0].header.frame_id = "taskboard_m4_screw_link"
poses[0].pose.position.y += -0.001 # MAGIC NUMBER (points right)
poses[0].pose.position.z += 0.002 # MAGIC NUMBER (points down)
elif hole == "m3":
poses.append(copy.deepcopy(pose0))
poses[0].header.frame_id = "taskboard_m3_screw_link"
poses[0].pose.position.y += 0.001 # MAGIC NUMBER (points right)
poses[0].pose.position.z += -0.001 # MAGIC NUMBER (points down)
elif hole == "setscrew":
poses.append(copy.deepcopy(pose0))
poses[0].header.frame_id = "taskboard_set_screw_link"
poses[0].pose.position.y += -0.002 # MAGIC NUMBER (points right)
poses[0].pose.position.z += 0.003 # MAGIC NUMBER (points down)
self.cycle_through_calibration_poses(poses, robot_name, go_home=False, with_approach=True, end_effector_link=end_effector_link, move_lin=True)
self.active_robots[robot_name].go_to_named_pose("horizontal_screw_ready")
return
def tray_sponge_calibration(self, robot_name="a_bot", end_effector_link="a_bot_gripper_tip_link"):
rospy.loginfo("============ Touching tray sponge. ============")
rospy.loginfo("eef link " + end_effector_link + " should be touching the tray sponge in middle, then left, then right.")
if robot_name == "a_bot":
self.b_bot.go_to_named_pose("home")
elif robot_name == "b_bot":
self.a_bot.go_to_named_pose("home")
poses = []
pose0 = geometry_msgs.msg.PoseStamped()
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, 0))
pose0.header.frame_id = "tray_center"
pose0.pose.position.z = 0.003
for i in range(3):
poses.append(copy.deepcopy(pose0))
poses[0].pose.position.y = 0.0
poses[1].pose.position.y = -0.1
poses[2].pose.position.y = 0.1
self.cycle_through_calibration_poses(poses, robot_name, go_home=False, with_approach=True, end_effector_link=end_effector_link, move_lin=True)
return
def tray_corners_calibration(self, robot_name="a_bot", end_effector_link="a_bot_gripper_tip_link"):
rospy.loginfo("============ Touching tray corners. ============")
rospy.loginfo("eef link " + end_effector_link + " should go to the tray corners.")
if robot_name == "a_bot":
self.b_bot.go_to_named_pose("home")
elif robot_name == "b_bot":
self.a_bot.go_to_named_pose("home")
poses = []
pose0 = geometry_msgs.msg.PoseStamped()
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, 0))
pose0.pose.position.z = 0.01
for i in range(4):
poses.append(copy.deepcopy(pose0))
poses[0].header.frame_id = "traycorner_1_link"
poses[1].header.frame_id = "traycorner_2_link"
poses[2].header.frame_id = "traycorner_3_link"
poses[3].header.frame_id = "traycorner_4_link"
self.cycle_through_calibration_poses(poses, robot_name, go_home=False, with_approach=False, end_effector_link=end_effector_link, move_lin=True)
return
def touch_workspace_center(self):
rospy.loginfo("============ Touching workspace center. ============")
self.a_bot.go_to_named_pose("home")
self.b_bot.go_to_named_pose("home")
poses = []
pose_a = geometry_msgs.msg.PoseStamped()
pose_a.header.frame_id = "workspace_center"
pose_a.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, 0))
pose_a.pose.position.x = .0
pose_a.pose.position.y = -.2
pose_a.pose.position.z = .03
pose_b = copy.deepcopy(pose_a)
pose_b.pose.position.x = .0
pose_b.pose.position.y = .3
pose_b.pose.position.z = .03
pose_c = copy.deepcopy(pose_a)
pose_c.pose.position.x = -.3
pose_c.pose.position.y = .2
pose_c.pose.position.z = .03
rospy.loginfo("============ Going to 2 cm above the table. ============")
self.b_bot.go_to_pose_goal(pose_b, speed=1.0)
self.a_bot.go_to_pose_goal(pose_a, speed=1.0)
rospy.loginfo("============ Press enter to go to .1 cm above the table. ============")
i = raw_input()
if not rospy.is_shutdown():
pose_a.pose.position.z = .001
pose_b.pose.position.z = .001
pose_c.pose.position.z = .001
self.b_bot.go_to_pose_goal(pose_b, speed=0.01)
self.a_bot.go_to_pose_goal(pose_a, speed=0.01)
rospy.loginfo("============ Press enter to go home. ============")
raw_input()
self.a_bot.go_to_named_pose("home")
self.b_bot.go_to_named_pose("home")
return
def workspace_level_calibration(self, robot_name="a_bot", end_effector_link="a_bot_gripper_tip_link"):
rospy.loginfo("============ Touching workspace surface (tray surface). ============")
rospy.loginfo("eef link " + end_effector_link + " should be touching the surface where the tray is placed in middle, then left, then right.")
if robot_name == "a_bot":
self.b_bot.go_to_named_pose("home")
elif robot_name == "b_bot":
self.a_bot.go_to_named_pose("home")
poses = []
pose0 = geometry_msgs.msg.PoseStamped()
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, 0))
pose0.header.frame_id = "workspace_center"
pose0.pose.position.x = 0.2
pose0.pose.position.z = 0.005
for i in range(2):
poses.append(copy.deepcopy(pose0))
# poses[0].pose.position.y = 0.0
# poses[1].pose.position.y = -0.15
# poses[2].pose.position.y = 0.15
poses[0].pose.position.y = 0.15
poses[1].pose.position.y = -0.15
self.cycle_through_calibration_poses(poses, robot_name, go_home=False, with_approach=True, end_effector_link=end_effector_link, move_lin=True)
return
def make_space_for_robot(self, robot_name):
if robot_name == "b_bot":
self.a_bot.go_to_named_pose("home")
elif robot_name == "a_bot":
self.b_bot.go_to_named_pose("home")
def screw_tool_test_assembly(self, robot_name="b_bot", tool_name="_screw_tool_m4_tip_link"):
rospy.loginfo("============ Moving the screw tool m4 to the screw holes on the base plate ============")
rospy.loginfo("============ The screw tool m4 has to be carried by the robot! ============")
self.make_space_for_robot(robot_name)
self.active_robots[robot_name].go_to_named_pose("screw_ready")
poses = []
pose0 = geometry_msgs.msg.PoseStamped()
pose0.header.frame_id = "assembled_part_01_screw_hole_panel1_1"
if robot_name == "b_bot":
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(tau/8, 0, 0))
pose0.pose.position.x -= .01
for i in range(4):
poses.append(copy.deepcopy(pose0))
poses[1].header.frame_id = "assembled_part_01_screw_hole_panel1_2"
poses[2].header.frame_id = "assembled_part_01_screw_hole_panel2_1"
poses[3].header.frame_id = "assembled_part_01_screw_hole_panel2_2"
end_effector_link = robot_name + tool_name
self.cycle_through_calibration_poses(poses, robot_name, go_home=False, move_lin=True, end_effector_link=end_effector_link)
return
def screw_action_test(self, robot_name="b_bot"):
rospy.loginfo("============ Screwing in one of the plate screws with the tool using the action ============")
rospy.loginfo("============ The screw tool m4 and a screw have to be carried by the robot! ============")
self.active_robots[robot_name].go_to_named_pose("screw_ready")
if robot_name == "b_bot":
self.b_bot.go_to_named_pose("screw_plate_ready")
pose0 = geometry_msgs.msg.PoseStamped()
if robot_name == "b_bot":
pose0.header.frame_id = "assembled_part_03_bottom_screw_hole_aligner_1"
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(-tau/8, 0, 0))
pose0.pose.position.x = -.01
self.skill_server.do_screw_action(robot_name, pose0, screw_size=4, screw_height=.02)
self.active_robots[robot_name].go_to_named_pose("screw_plate_ready")
return
def screw_feeder_calibration(self, feeder_size="", robot_name="b_bot"):
rospy.loginfo("============ Moving the screw tool m3 or m4 to its screw feeder ============")
rospy.loginfo("============ The screw tool has to be carried by the robot! ============")
self.active_robots[robot_name].go_to_named_pose("feeder_pick_ready")
pose0 = geometry_msgs.msg.PoseStamped()
if robot_name == "a_bot":
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(radians(80), 0, 0))
pose0.header.frame_id = "m3_feeder_outlet_link"
ee_link = robot_name + "_screw_tool_m3_tip_link"
else:
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(-tau/12, 0, 0))
pose0.header.frame_id = "m4_feeder_outlet_link"
ee_link = robot_name + "_screw_tool_m4_tip_link"
if feeder_size == "m3":
pose0.header.frame_id = "m3_feeder_outlet_link"
ee_link = robot_name + "_screw_tool_m3_tip_link"
if feeder_size == "m4":
pose0.header.frame_id = "m4_feeder_outlet_link"
ee_link = robot_name + "_screw_tool_m4_tip_link"
# MAGIC NUMBERS (needs to be synced with pick_screw_from_feeder_python)
if robot_name == "a_bot" and feeder_size == "m4":
rospy.logerr("APPLYING MAGIC NUMBERS")
pose0.pose.position.y += -.004 # (world negative y-axis)
pose0.pose.position.z += -.0035 # (world x-axis)
poses = []
for i in range(3):
poses.append(copy.deepcopy(pose0))
poses[0].pose.position.x = -.03
poses[1].pose.position.x = 0
poses[2].pose.position.x = -.01
self.cycle_through_calibration_poses(poses, robot_name, go_home=False, move_lin=True, with_approach=False, end_effector_link=ee_link)
# self.skill_server.toggle_collisions(collisions_on=True)
self.active_robots[robot_name].go_to_named_pose("feeder_pick_ready")
return
def screw_feeder_pick_test(self, robot_name="b_bot", screw_size=4):
rospy.loginfo("============ Picking a screw from a feeder ============")
rospy.loginfo("============ The screw tool has to be carried by the robot! ============")
self.pick_screw_from_feeder(robot_name, screw_size=screw_size, realign_tool_upon_failure=False)
return
def vertical_plate_screw_position_test(self, panel, robot_name="b_bot"):
self.set_assembly("wrs_assembly_2021")
"""panel should be motor_plate or bearing_plate"""
rospy.loginfo("============ Move tool to screw position of plates ============")
self.active_robots[robot_name].go_to_named_pose("feeder_pick_ready")
pose0 = geometry_msgs.msg.PoseStamped()
if robot_name == "a_bot":
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(radians(20), 0, 0))
ee_link = robot_name + "_screw_tool_m4_tip_link"
else:
pose0.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(-radians(20), 0, 0))
pose0.header.frame_id = "bottom_screw_hole_2"
ee_link = robot_name + "_screw_tool_m4_tip_link"
if panel == "bearing_panel":
part_name = "assembled_part_03_"
elif panel == "motor_panel":
part_name = "assembled_part_02_"
pose0.header.frame_id = part_name + "bottom_screw_hole_1"
# self.toggle_collisions(collisions_on=False)
poses = []
for i in range(2):
poses.append(copy.deepcopy(pose0))
poses[1].header.frame_id = part_name + "bottom_screw_hole_2"
self.cycle_through_calibration_poses(poses, robot_name, go_home=False, move_lin=True, end_effector_link=ee_link)
# self.toggle_collisions(collisions_on=True)
self.active_robots[robot_name].go_to_named_pose("feeder_pick_ready")
return
def bearing_screw_holes(self, robot_name="b_bot", end_effector_link="b_bot_screw_tool_m4_tip_link"):
rospy.loginfo("============ Move tool to bearing screw holes with tool ============")
self.active_robots[robot_name].go_to_named_pose("horizontal_screw_ready")
poses = []
for i in [1, 2, 3, 4]:
screw_pose = geometry_msgs.msg.PoseStamped()
screw_pose.header.frame_id = "assembled_part_07_screw_hole_" + str(i)
rospy.logwarn("Is this magic number the same as in common.py? Confirm manually!")
screw_pose.pose.position.z += .0025 # MAGIC NUMBER
screw_pose.pose.position.x += .005
if robot_name == "a_bot":
screw_pose.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(-tau/12, 0, 0))
else:
screw_pose.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(tau/12, 0, 0))
screw_pose_approach = copy.deepcopy(screw_pose)
screw_pose_approach.pose.position.x -= 0.07
poses.append(screw_pose_approach)
poses.append(screw_pose)
poses.append(screw_pose_approach)
self.cycle_through_calibration_poses(poses, robot_name, go_home=False, move_lin=True, end_effector_link=end_effector_link)
self.active_robots[robot_name].go_to_named_pose("horizontal_screw_ready")
return
def motor_screw_holes(self, robot_name="a_bot", end_effector_link="b_bot_screw_tool_m4_tip_link"):
rospy.loginfo("============ Move tool to bearing screw holes with tool ============")
self.active_robots[robot_name].go_to_named_pose("horizontal_screw_ready")
poses = []
for i in [1, 2, 3, 4, 5, 6]:
# TODO(felixvd): Do not use the orientation defined in these frames. Get a static orientation.
screw_pose = geometry_msgs.msg.PoseStamped()
screw_pose.header.frame_id = "assembled_part_02_motor_screw_hole_" + str(i)
screw_pose.pose.position.z += -.001 # MAGIC NUMBER
screw_pose.pose.position.x += .005
if robot_name == "a_bot":
screw_pose.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(-tau/12+tau/2, 0, 0))
else:
screw_pose.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(tau/12+tau/2, 0, 0))
screw_pose_approach = copy.deepcopy(screw_pose)
screw_pose_approach.pose.position.x -= 0.07
poses.append(screw_pose_approach)
poses.append(screw_pose)
poses.append(screw_pose_approach)
self.cycle_through_calibration_poses(poses, robot_name, go_home=False, move_lin=True, end_effector_link=end_effector_link)
self.active_robots[robot_name].go_to_named_pose("horizontal_screw_ready")
return
def go_to_tool_pickup_pose(self, robot_name="b_bot", screw_tool_id="screw_tool_m4"):
self.b_bot.go_to_named_pose("tool_pick_ready")
ps_tool_pickup = geometry_msgs.msg.PoseStamped()
ps_tool_pickup.header.frame_id = screw_tool_id + "_pickup_link"
ps_tool_pickup.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, -pi/6, 0))
ps_tool_pickup.pose.position.x = .017
ps_tool_pickup.pose.position.z = -.008
self.b_bot.go_to_pose_goal(ps_tool_pickup, speed=.1, acceleration=.02)
def calibrate_place_panel(self, panel_name):
self.a_bot.gripper.open()
self.a_bot.move_lin_rel([0, 0, 0.1])
self.a_bot.go_to_named_pose("centering_area")
self.place_panel("a_bot", panel_name, pick_again=True, fake_position=True)
def motor_insertion_from_aid(self):
self.b_bot.gripper.open()
self.b_bot.move_lin_rel([0, 0, 0.2])
self.b_bot.go_to_named_pose("centering_area")
self.align_motor_pre_insertion(False)
print("current pose", np.round(conversions.from_pose_to_list(self.listener.transformPose("assembled_part_02_back_hole", self.a_bot.get_current_pose_stamped()).pose), 4))
self.confirm_to_proceed("finetune")
self.insert_motor("assembled_part_02_back_hole")
self.confirm_to_proceed("are we done?")
def bearing_insertion_assembly(self):
self.a_bot.gripper.open()
self.a_bot.move_lin_rel([0, 0, 0.1])
self.a_bot.go_to_named_pose("home")
self.pick_bearing("a_bot")
self.orient_bearing(task="assembly", robot_name="a_bot")
print("current pose", np.round(conversions.from_pose_to_list(self.listener.transformPose("assembled_part_07_inserted", self.a_bot.get_current_pose_stamped()).pose), 4))
self.confirm_to_proceed("finetune")
self.insert_bearing("assembled_part_07_inserted", robot_name="a_bot")
print("current pose", np.round(conversions.from_pose_to_list(self.listener.transformPose("assembled_part_07_inserted", self.a_bot.get_current_pose_stamped()).pose), 4))
self.confirm_to_proceed("we are done?")
def motor_pulley_insertion(self):
self.a_bot.gripper.open()
self.a_bot.move_lin_rel([0, 0, 0.1])
self.a_bot.go_to_named_pose("home")
self.is_motor_pulley_in_storage = False
self.pick_motor_pulley(robot_name="a_bot")
self.orient_motor_pulley("assembled_part_05_center", robot_name="a_bot")
print("current pose", np.round(conversions.from_pose_to_list(self.listener.transformPose("assembled_part_05_center", self.a_bot.get_current_pose_stamped()).pose), 4))
self.confirm_to_proceed("finetune")
self.insert_motor_pulley("assembled_part_05_center", robot_name="a_bot", retry_insertion=True)
print("current pose", conversions.from_pose_to_list(self.listener.transformPose("assembled_part_05_center", self.a_bot.get_current_pose_stamped()).pose))
self.confirm_to_proceed("are we done?")
def motor_pulley_fastening(self):
self.a_bot.gripper.open()
self.fasten_motor_pulley("assembled_part_05_center")
def end_cap_and_shaft_prep(self):
self.pick_end_cap()
self.orient_shaft_end_cap(calibration=True)
self.pick_shaft()
self.orient_shaft(calibration=True)
def end_cap_and_shaft_preinsertion(self):
pre_insertion_shaft = [1.78158, -0.98719, 2.42349, -4.57638, -1.78597, 0.00433]
if not self.b_bot.move_joints(pre_insertion_shaft, speed=0.4):
rospy.logerr("Fail to go to pre_insertion_shaft")
return False
above_pre_insertion_end_cap = conversions.to_pose_stamped("tray_center", [-0.004, 0.010, 0.280]+np.deg2rad([-180, 90, -90]).tolist())
if not self.a_bot.go_to_pose_goal(above_pre_insertion_end_cap, speed=0.6, move_lin=False):
rospy.logerr("Fail to go to pre_insertion_end_cap")
return False
pre_insertion_end_cap = conversions.to_pose_stamped("tray_center", [-0.0045, 0.010, 0.245]+np.deg2rad([-180, 90, -90]).tolist())
if not self.a_bot.go_to_pose_goal(pre_insertion_end_cap, speed=0.3, move_lin=True):
rospy.logerr("Fail to go to pre_insertion_end_cap")
return False
def simple_end_cap_pick(self):
self.a_bot.go_to_named_pose("centering_area")
self.orient_shaft_end_cap(ignore_orientation=True)
def end_cap_insertion(self):
self.insert_end_cap()
self.a_bot.gripper.send_command(0.06, velocity=0.01)
self.a_bot.move_lin_rel([0, 0, 0.05], speed=0.3)
def bearing_spacer(self):
self.pick_bearing_spacer("a_bot")
self.orient_bearing_spacer("a_bot")
self.align_bearing_spacer_pre_insertion(robot_name="a_bot")
self.confirm_to_proceed("finetune")
self.insert_bearing_spacer("assembled_part_07_inserted", "a_bot")
self.confirm_to_proceed("okay?")
def output_pulley(self):
self.pick_output_pulley("a_bot")
self.orient_output_pulley("a_bot")
self.align_output_pulley_pre_insertion("a_bot")
self.confirm_to_proceed("finetune")
self.insert_output_pulley("assembled_part_07_inserted", "a_bot")
self.confirm_to_proceed("okay?")
if __name__ == '__main__':
try:
rospy.init_node('o2ac_routines', anonymous=False)
c = CalibrationClass()
# c.set_assembly("wrs_assembly_2021")
while not rospy.is_shutdown():
rospy.loginfo("============ Calibration procedures ============ ")
rospy.loginfo("Enter a number to check calibrations for the following things: ")
rospy.loginfo("1: home (b_bot), 100/101: home/back (both robots)")
rospy.loginfo("11: b_bot_outside_camera, 12: b_bot_inside_camera (activate)")
rospy.loginfo("13, 14: Equip/unequip m3 screw tool with a_bot")
rospy.loginfo("15, 16: Equip/unequip m4 screw tool with b_bot")
rospy.loginfo("17, 18: Equip/unequip set screw tool with b_bot")
rospy.loginfo("===== GENERAL")
rospy.loginfo("291, 292: Touch tray sponge with a_bot, b_bot")
rospy.loginfo("293, 294: Touch tray corners with a_bot, b_bot")
rospy.loginfo("21, 22: Calibrate screw feeders (a_bot, b_bot)")
rospy.loginfo("23, 24: Pick m3/m4 screw from feeder")
rospy.loginfo("===== TASKBOARD TASK")
rospy.loginfo("31, 32: Go to screw holes with a_bot m3, b_bot m4")
rospy.loginfo("===== ASSEMBLY TASK (no parts may be mounted!)")
rospy.loginfo("501-502: Base plate screw holes (a_bot, b_bot)")
rospy.loginfo("503-504: Base plate screw holes (a_bot m3, b_bot m4)")
rospy.loginfo("511-512: Motor plate holes (b_bot, b_bot m4)")
rospy.loginfo("55: Bearing screw holes (b_bot m4)")
rospy.loginfo("60: L-plates")
rospy.loginfo("===== TOOLS ")
# rospy.loginfo("65 (651/652): Go to belt tool pickup position (and equip/unequip it)")
# rospy.loginfo("66 (661/662): Go to plunger tool pickup position (and equip/unequip it)")
rospy.loginfo("70: Do screw action with b_bot on rightmost hole")
rospy.loginfo("81: Realign M4 tool")
rospy.loginfo("x: Exit ")
rospy.loginfo("reset: reset the scene")
rospy.loginfo(" ")
r = raw_input()
if r == '1':
c.a_bot.go_to_named_pose("home")
c.b_bot.go_to_named_pose("home")
if r == '1000': # Speed test
ps = geometry_msgs.msg.PoseStamped()
ps.header.frame_id = "workspace_center"
ps.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, tau/4, tau/2))
ps.pose.position.z = .3
# c.b_bot.go_to_named_pose("home")
# c.b_bot.move_lin(ps, speed=.2)
# c.b_bot.go_to_named_pose("home", speed=0.3)
# c.b_bot.move_lin(ps, speed=.5)
# c.b_bot.go_to_named_pose("home", speed=0.6)
c.b_bot.move_lin(ps, speed=.5, acceleration=0.8)
c.b_bot.go_to_named_pose("home", speed=0.5, acceleration=0.8)
if r == '100':
c.a_bot.go_to_named_pose("home")
c.b_bot.go_to_named_pose("home")
if r == '101':
c.a_bot.go_to_named_pose("back")
c.b_bot.go_to_named_pose("back")
if r == '102':
c.b_bot.go_to_named_pose("back", speed=1.0, acceleration=0.7)
c.b_bot.go_to_named_pose("home", speed=1.0, acceleration=0.7)
if r == '11':
c.vision.activate_camera("b_bot_outside_camera")
if r == '12':
c.vision.activate_camera("b_bot_inside_camera")
if r == '11a':
c.vision.activate_camera("a_bot_outside_camera")
if r == '12a':
c.vision.activate_camera("a_bot_inside_camera")
if r == "13":
c.make_space_for_robot("a_bot")
c.equip_tool("a_bot", "screw_tool_m3")
if r == "13b":
c.make_space_for_robot("b_bot")
c.equip_tool("b_bot", "screw_tool_m3")
if r == "14b":
c.make_space_for_robot("b_bot")
c.unequip_tool("b_bot", "screw_tool_m3")
if r == "14":
c.make_space_for_robot("a_bot")
c.unequip_tool("a_bot", "screw_tool_m3")
if r == "15":
c.make_space_for_robot("b_bot")
c.equip_tool("b_bot", "screw_tool_m4")
if r == "16":
c.make_space_for_robot("b_bot")
c.unequip_tool("b_bot", "screw_tool_m4")
if r == "15a":
c.make_space_for_robot("a_bot")
c.equip_tool("a_bot", "screw_tool_m4")
if r == "16a":
c.make_space_for_robot("a_bot")
c.unequip_tool("a_bot", "screw_tool_m4")
if r == "17":
c.make_space_for_robot("b_bot")
c.equip_tool("b_bot", "set_screw_tool")
if r == "18":
c.make_space_for_robot("b_bot")
c.unequip_tool("b_bot", "set_screw_tool")
if r == "191":
c.equip_tool("b_bot", "padless_tool_m4")
if r == "192":
c.unequip_tool("b_bot", "padless_tool_m4")
if r == '21':
c.screw_feeder_calibration(robot_name="a_bot")
if r == 'am3':
c.equip_unequip_realign_tool("a_bot", "screw_tool_m3", "equip", calibration_mode=True)
if r == 'am4':
c.equip_unequip_realign_tool("a_bot", "screw_tool_m4", "equip", calibration_mode=True)
if r == 'bm4':
c.equip_unequip_realign_tool("b_bot", "screw_tool_m4", "equip", calibration_mode=True)
if r == 'bm3':
c.equip_unequip_realign_tool("b_bot", "screw_tool_m3", "equip", calibration_mode=True)
if r == '210':
c.calibration_mode = True
c.pick_screw_from_feeder_python(robot_name="a_bot", screw_size=3, realign_tool_upon_failure=False, skip_retreat=False)
c.calibration_mode = False
if r == '22':
c.screw_feeder_calibration(robot_name="b_bot")
if r == '220':
c.calibration_mode = True
c.pick_screw_from_feeder_python(robot_name="b_bot", screw_size=4, realign_tool_upon_failure=False, skip_retreat=False)
c.calibration_mode = False
if r == '22a':
c.screw_feeder_calibration(robot_name="a_bot", feeder_size="m4")
if r == '220a':
c.calibration_mode = True
c.pick_screw_from_feeder_python(robot_name="a_bot", screw_size=4, realign_tool_upon_failure=False, skip_retreat=False)
c.calibration_mode = False
if r == '23':
c.screw_feeder_pick_test(robot_name="a_bot", screw_size=3)
if r == '24':
c.screw_feeder_pick_test(robot_name="b_bot", screw_size=4)
if r == '24a':
c.screw_feeder_pick_test(robot_name="a_bot", screw_size=4)
if r == '281':
c.planning_scene_interface.allow_collisions("tray")
c.planning_scene_interface.allow_collisions("tray_center")
c.workspace_level_calibration(robot_name="a_bot", end_effector_link="a_bot_gripper_tip_link")
if r == '282':
c.planning_scene_interface.allow_collisions("tray")
c.planning_scene_interface.allow_collisions("tray_center")
c.workspace_level_calibration(robot_name="b_bot", end_effector_link="b_bot_gripper_tip_link")
if r == '291':
c.tray_sponge_calibration(robot_name="a_bot", end_effector_link="a_bot_gripper_tip_link")
if r == '292':
c.tray_sponge_calibration(robot_name="b_bot", end_effector_link="b_bot_gripper_tip_link")
if r == '293':
c.tray_corners_calibration(robot_name="a_bot", end_effector_link="a_bot_gripper_tip_link")
if r == '294':
c.tray_corners_calibration(robot_name="b_bot", end_effector_link="b_bot_gripper_tip_link")
if r == '31':
c.taskboard_calibration_with_tools(robot_name="a_bot", end_effector_link="a_bot_screw_tool_m3_tip_link", hole="m3")
if r == '311':
c.taskboard_calibration_with_tools(robot_name="a_bot", end_effector_link="a_bot_gripper_tip_link")
if r == '32':
c.taskboard_calibration_with_tools(robot_name="b_bot", end_effector_link="b_bot_screw_tool_m4_tip_link", hole="m4")
if r == '321':
c.taskboard_calibration_with_tools(robot_name="b_bot", end_effector_link="b_bot_gripper_tip_link")
if r == '33':
c.taskboard_calibration_with_tools(robot_name="b_bot", end_effector_link="b_bot_set_screw_tool_tip_link", hole="setscrew")
if r == '501':
c.assembly_calibration_base_plate("a_bot", panel_name="motor_panel")
if r == '5011':
c.assembly_calibration_base_plate("a_bot", panel_name="bearing_panel")
if r == '5012':
c.assembly_calibration_base_plate("a_bot", panel_name="motor_panel", rotation=tau/4)
if r == '502':
c.assembly_calibration_base_plate("b_bot", panel_name="motor_panel")
if r == '5021':
c.assembly_calibration_base_plate("b_bot", panel_name="bearing_panel")
if r == '5022':
c.assembly_calibration_base_plate("b_bot", panel_name="motor_panel", rotation=tau/4)
if r == '5023':
c.assembly_calibration_base_plate("b_bot", panel_name="both")
if r == '503':
c.assembly_calibration_base_plate("a_bot", end_effector_link="a_bot_screw_tool_m3_tip_link", panel_name="motor_panel")
if r == '5031':
c.assembly_calibration_base_plate("a_bot", end_effector_link="a_bot_screw_tool_m3_tip_link", panel_name="bearing_panel")
if r == '5032':
c.assembly_calibration_base_plate("a_bot", end_effector_link="a_bot_screw_tool_m3_tip_link", panel_name="motor_panel", rotation=radians(25))
if r == '5033':
c.assembly_calibration_base_plate("a_bot", end_effector_link="a_bot_screw_tool_m3_tip_link", panel_name="motor_panel", rotation=radians(45))
if r == '504':
c.assembly_calibration_base_plate("b_bot", end_effector_link="b_bot_screw_tool_m4_tip_link", panel_name="both")
if r == '5041':
c.assembly_calibration_base_plate("b_bot", end_effector_link="b_bot_screw_tool_m4_tip_link", panel_name="both", rotation=radians(25))
if r == '5042':
c.assembly_calibration_base_plate("b_bot", end_effector_link="b_bot_screw_tool_m4_tip_link", panel_name="both", rotation=radians(45))
if r == '5043':
c.assembly_calibration_base_plate("b_bot", end_effector_link="b_bot_screw_tool_m4_tip_link", panel_name="both", rotation=radians(-45))
if r == '504a':
c.assembly_calibration_base_plate("a_bot", end_effector_link="a_bot_screw_tool_m4_tip_link", panel_name="both")
if r == '5042a':
c.assembly_calibration_base_plate("a_bot", end_effector_link="a_bot_screw_tool_m4_tip_link", panel_name="both", rotation=radians(25))
if r == '5043a':
c.assembly_calibration_base_plate("a_bot", end_effector_link="a_bot_screw_tool_m4_tip_link", panel_name="both", rotation=radians(-45))
if r == '504a':
c.assembly_calibration_base_plate("a_bot", end_effector_link="a_bot_screw_tool_m4_tip_link")
if r == '503b':
c.assembly_calibration_base_plate("b_bot", end_effector_link="b_bot_screw_tool_m3_tip_link")
if r == '511':
c.assembly_calibration_base_plate("b_bot", context="motor_plate")
if r == '52':
c.vertical_plate_screw_position_test(panel="motor_panel")
if r == '522':
c.a_bot.move_lin_rel([-0.05, 0, 0])
c.a_bot.move_lin_rel([0.05, 0, 0])
if r == '53': # Bearing rotation
ps = geometry_msgs.msg.PoseStamped()
ps.header.frame_id = "assembled_part_07_inserted"
ps.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, radians(0), 0))
ps.pose.position = geometry_msgs.msg.Point(-0.0, 0.0, 0.0)
c.b_bot.go_to_pose_goal(ps, speed=.1, acceleration=.04, end_effector_link="b_bot_bearing_rotate_helper_link")
c.b_bot.gripper.close()
ps.pose.orientation = helpers.rotateQuaternionByRPYInUnrotatedFrame(radians(45), 0, 0, ps.pose.orientation)
c.b_bot.go_to_pose_goal(ps, speed=.1, acceleration=.04, end_effector_link="b_bot_bearing_rotate_helper_link")
c.b_bot.gripper.open()
ps.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, 0, 0))
c.b_bot.go_to_pose_goal(ps, speed=.1, acceleration=.04, end_effector_link="b_bot_bearing_rotate_helper_link")
ps.pose.orientation = helpers.rotateQuaternionByRPYInUnrotatedFrame(radians(-45), 0, 0, ps.pose.orientation)
c.b_bot.gripper.close()
c.b_bot.go_to_pose_goal(ps, speed=.1, acceleration=.04, end_effector_link="b_bot_bearing_rotate_helper_link")
ps.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, 0, 0))
c.b_bot.gripper.open()
c.b_bot.go_to_pose_goal(ps, speed=.1, acceleration=.04, end_effector_link="b_bot_bearing_rotate_helper_link")
if r == '531': # Bearing rotation
c.align_bearing_holes(max_adjustments=10, task="assembly")
if r == '54': # Motor angle
c.vision.activate_camera("b_bot_outside_camera")
camera_look_pose = geometry_msgs.msg.PoseStamped()
camera_look_pose.header.frame_id = "vgroove_aid_link"
camera_look_pose.pose.orientation = geometry_msgs.msg.Quaternion(*(0.84, 0.0043246, 0.0024908, 0.54257))
camera_look_pose.pose.position = geometry_msgs.msg.Point(-0.0118, 0.133, 0.0851)
camera_look_pose.pose.position.z += 0.2
c.b_bot.go_to_pose_goal(camera_look_pose, end_effector_link="b_bot_outside_camera_color_optical_frame", speed=.1, acceleration=.04)
camera_look_pose.pose.position.z -= 0.2
c.b_bot.go_to_pose_goal(camera_look_pose, end_effector_link="b_bot_outside_camera_color_optical_frame", speed=.1, acceleration=.04)
if r == '55': # Bearing screw holes
c.bearing_screw_holes()
if r == '551': # Bearing screw holes
c.motor_screw_holes(robot_name="b_bot", end_effector_link="b_bot_screw_tool_m4_tip_link")
if r == '544':
c.vision.activate_camera("b_bot_outside_camera")
angle = c.get_motor_angle()
if r == '600':
c.a_bot.gripper.open()
c.a_bot.move_lin_rel([0, 0, 0.1])
if r == '600b':
c.b_bot.gripper.open()
c.b_bot.move_lin_rel([0, 0, 0.1])
if r == '601':
c.calibrate_place_panel("panel_bearing")
if r == '601f':
c.fasten_panel('panel_bearing')
if r == '601fc':
c.calibration_mode = True
c.fasten_panel('panel_bearing')
c.calibration_mode = False
if r == '601b': # Fallback to reposition
c.center_panel_on_base_plate("panel_bearing", calibration=True)
if r == '602':
c.calibrate_place_panel("panel_motor")
if r == '602f':
c.fasten_panel('panel_motor')
if r == '602fc':
c.calibration_mode = True
c.fasten_panel('panel_motor')
c.calibration_mode = False
if r == '602b': # Fallback to reposition
c.center_panel_on_base_plate("panel_motor", calibration=True)
if r == '603p':
c.pick_and_orient_motor()
if r == '603o':
c.orient_motor()
if r == '603':
c.motor_insertion_from_aid()
if r == '603f':
c.fasten_motor()
if r == '603f2':
c.fasten_motor(part1=False, part2=True)
if r == '603f1c':
c.calibration_mode = True
c.fasten_motor(part1=True, part2=False)
c.calibration_mode = False
if r == '603f2c':
c.calibration_mode = True
c.fasten_motor(part1=False, part2=True)
c.calibration_mode = False
if r == '604':
c.bearing_insertion_assembly()
if r == '604i':
c.orient_bearing(task="assembly", robot_name="a_bot", part1=False)
print("current pose", conversions.from_pose_to_list(c.listener.transformPose("assembled_part_07_inserted", c.a_bot.get_current_pose_stamped()).pose))
c.confirm_to_proceed("finetune")
c.insert_bearing("assembled_part_07_inserted", robot_name="a_bot")
print("current pose", conversions.from_pose_to_list(c.listener.transformPose("assembled_part_07_inserted", c.a_bot.get_current_pose_stamped()).pose))
c.confirm_to_proceed("we are done?")
if r == '604f':
c.fasten_bearing(task="assembly", robot_name="a_bot")
if r == '604fb':
c.fasten_bearing(task="assembly", robot_name="b_bot")
if r == '605':
c.motor_pulley_insertion()
if r == '606':
c.motor_pulley_fastening()
if r == '607':
c.end_cap_and_shaft_prep()
if r == '607sp':
c.pick_shaft()
if r == '607so':
c.orient_shaft(calibration=True, ignore_orientation=False)
if r == '607so2':
c.orient_shaft(calibration=True, ignore_orientation=True)
if r == '607so3':
pre_insertion_shaft = [1.78158, -0.98719, 2.42349, -4.57638, -1.78597, 0.00433]
c.b_bot.move_joints(pre_insertion_shaft, speed=0.4)
if r == '607so4':
c.check_screw_hole_visible_on_shaft_in_v_groove()
if r == '608':
c.end_cap_and_shaft_preinsertion()
if r == '609':
c.simple_end_cap_pick()
if r == '610':
c.end_cap_insertion()
if r == '611':
c.fasten_end_cap()
if r == '612':
c.align_shaft("assembled_part_07_inserted", pre_insert_offset=0.065)
c.insert_shaft("assembled_part_07_inserted", target=0.043)
if r == '613':
c.bearing_spacer()
if r == '614':
c.output_pulley()
if r == '614f':
c.fasten_output_pulley()
if r == '614c':
c.check_output_pulley_angle()
if r == '615r':
c.a_bot.gripper.open(opening_width=0.03)
c.a_bot.move_lin_rel([-0.15,0,0], relative_to_tcp=True, speed=0.2)
c.b_bot.gripper.open(opening_width=0.03)
c.b_bot.move_lin_rel([-0.15,0,0], relative_to_tcp=True, speed=0.2)
if r == '615':
c.publish_part_in_assembled_position("base")
c.publish_part_in_assembled_position("panel_motor")
c.publish_part_in_assembled_position("motor")
c.insert_motor_cables_without_tools_normal("black")
if r == '615t':
c.publish_part_in_assembled_position("base")
c.publish_part_in_assembled_position("panel_motor")
c.publish_part_in_assembled_position("motor")
c.insert_motor_cables_with_tool("black")
if r == '616':
c.publish_part_in_assembled_position("base")
c.publish_part_in_assembled_position("panel_motor")
c.publish_part_in_assembled_position("motor")
c.insert_motor_cables_without_tools_normal("red")
if r == '616t':
c.publish_part_in_assembled_position("base")
c.publish_part_in_assembled_position("panel_motor")
c.publish_part_in_assembled_position("motor")
c.insert_motor_cables_with_tool("red")
if r == '617':
c.calibration_mode = True
c.equip_cable_tool()
c.calibration_mode = False
if r == '618':
c.calibration_mode = True
c.unequip_cable_tool()
c.calibration_mode = False
if r == '6':
c.a_bot.go_to_named_pose("back")
c.b_bot.go_to_named_pose("screw_ready")
if r == '65':
c.b_bot.go_to_named_pose("home")
ps = geometry_msgs.msg.PoseStamped()
ps.header.frame_id = "belt_tool_pickup_link"
ps.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, 0, 0))
ps.pose.position.x = -.05
c.b_bot.go_to_pose_goal(ps, speed=.2, acceleration=.04)
if r == '651':
c.do_change_tool_action("b_bot", equip=True, screw_size=100)
if r == '66':
c.b_bot.go_to_named_pose("home")
ps = geometry_msgs.msg.PoseStamped()
ps.header.frame_id = "plunger_tool_pickup_link"
ps.pose.orientation = geometry_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(0, 0, 0))
ps.pose.position.x = -.05
c.b_bot.go_to_pose_goal(ps, speed=.2, acceleration=.04)
if r == '661':
c.do_change_tool_action("b_bot", equip=True, screw_size=200)
if r == '63':
c.screw_tool_test_assembly(robot_name="b_bot")
if r == '70':
c.screw_action_test(robot_name="b_bot")
if r == '81':
c.realign_tool(robot_name="b_bot", screw_tool_id="screw_tool_m4")
if r == "reset":
c.reset_scene_and_robots()
c.reset_assembly_visualization()
if r == "activate":
c.a_bot.activate_ros_control_on_ur()
c.b_bot.activate_ros_control_on_ur()
if r == "load2020":
c.assembly_status.tray_placed_on_table = True
c.set_assembly("wrs_assembly_2020")
if r == "load2021":
c.assembly_status.tray_placed_on_table = True
c.set_assembly("wrs_assembly_2021")
if r == "load2021s":
c.assembly_status.tray_placed_on_table = True
c.set_assembly("wrs_assembly_2021_surprise")
if r == 'x':
break
rospy.loginfo("============ Exiting!")
except rospy.ROSInterruptException:
print "Something went wrong."
|
function f() {
return 9;
}
|
module.exports = {"default": require("core-js/library/fn/symbol/for"), __esModule: true};
|
import expect from 'expect'
import expectJsx from 'expect-jsx'
import noop from 'lodash.noop'
import Checkbox from '@material-ui/core/Checkbox'
import React from 'react'
import ReduxFormMaterialUICheckbox from '../Checkbox'
expect.extend(expectJsx)
describe('Checkbox', () => {
it('has a display name', () => {
expect(ReduxFormMaterialUICheckbox.displayName).toBe(
'ReduxFormMaterialUIWithStyles'
)
})
it('renders an unchecked Checkbox', () => {
expect(
new ReduxFormMaterialUICheckbox({
input: {
name: 'myCheckbox',
onChange: noop
}
}).render()
).toEqualJSX(
<Checkbox
name="myCheckbox"
checked={false}
onChange={noop}
ref={() => {}}
/>
)
})
it('renders a checked Checkbox', () => {
expect(
new ReduxFormMaterialUICheckbox({
input: {
name: 'myCheckbox',
onChange: noop,
value: true
}
}).render()
).toEqualJSX(
<Checkbox
name="myCheckbox"
checked={true}
onChange={noop}
ref={() => {}}
/>
)
})
it('should ignore defaultChecked', () => {
expect(
new ReduxFormMaterialUICheckbox({
input: {
name: 'myCheckbox',
onChange: noop
},
defaultChecked: true
}).render()
).toEqualJSX(<Checkbox name="myCheckbox" onChange={noop} ref={() => {}} />)
})
})
|
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License
from AlgorithmImports import *
class BasicTemplateIndexAlgorithm(QCAlgorithm):
def Initialize(self) -> None:
self.SetStartDate(2021, 1, 4)
self.SetEndDate(2021, 1, 18)
self.SetCash(1000000)
# Use indicator for signal; but it cannot be traded
self.spx = self.AddIndex("SPX", Resolution.Minute).Symbol
# Trade on SPX ITM calls
self.spxOption = Symbol.CreateOption(
self.spx,
Market.USA,
OptionStyle.European,
OptionRight.Call,
3200,
datetime(2021, 1, 15)
)
self.AddIndexOptionContract(self.spxOption, Resolution.Minute)
self.emaSlow = self.EMA(self.spx, 80)
self.emaFast = self.EMA(self.spx, 200)
def OnData(self, data: Slice):
if self.spx not in data.Bars or self.spxOption not in data.Bars:
return
if not self.emaSlow.IsReady:
return
if self.emaFast > self.emaSlow:
self.SetHoldings(self.spxOption, 1)
else:
self.Liquidate()
def OnEndOfAlgorithm(self) -> None:
if self.Portfolio[self.spx].TotalSaleVolume > 0:
raise Exception("Index is not tradable.")
|
from flask_restful import reqparse
from flask_wtf import FlaskForm
from wtforms import BooleanField, PasswordField, StringField, SubmitField, TextAreaField, validators
from wtforms.validators import DataRequired, Length
class LoginForm(FlaskForm):
username = StringField('Username',
validators=[DataRequired(),
Length(1, 20)])
password = PasswordField('Password',
validators=[DataRequired(),
Length(1, 128)])
remember = BooleanField('Remember me')
submit = SubmitField('Log in')
class SettingForm(FlaskForm):
name = StringField('Name', validators=[DataRequired(), Length(1, 30)])
blog_title = StringField('Blog Title',
validators=[DataRequired(),
Length(1, 60)])
blog_sub_title = StringField('Blog Sub Title',
validators=[DataRequired(),
Length(1, 100)])
about = TextAreaField('About')
submit = SubmitField()
class SignInForm(FlaskForm):
password = PasswordField('Password', [
validators.Required(),
validators.EqualTo('confirm', message='Passwords must match'),
validators.Length(1, 128)
])
confirm = PasswordField('Repeat Password')
submit = SubmitField()
put_article_parser = reqparse.RequestParser()
put_article_parser.add_argument('title', type=str)
put_article_parser.add_argument('body', type=str)
put_article_parser.add_argument('category', type=str)
put_article_parser.add_argument('show', type=bool)
list_article_id_parser = reqparse.RequestParser()
list_article_id_parser.add_argument('id', type=int)
|
/*
* Copyright (c) 2015-2017, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CORPORA_H
#define CORPORA_H
#include <set>
#include <string>
#include <vector>
#include <boost/core/noncopyable.hpp>
struct Corpus {
Corpus() : hasMatches(false) {}
explicit Corpus(const std::string &s) : data(s), hasMatches(false) {}
std::string data; // Corpus itself
bool hasMatches; // Have the matches been pre-calculated?
std::set<unsigned int> matches; // end-offsets of matches
};
struct CorpusFailure {
explicit CorpusFailure(const std::string &s) : message(s) {}
std::string message;
};
// Abstract class for a corpora source: new ways to load or generate corpora
// can be written by subclassing this class and providing its generate
// method.
class CorporaSource : boost::noncopyable {
public:
// destructor
virtual ~CorporaSource();
// Make a copy of this corpora source.
virtual CorporaSource *clone() const = 0;
// Generate corpora for the given signature ID, adding them to the
// vector of strings provided.
virtual void generate(unsigned id, std::vector<Corpus> &data) = 0;
};
#endif // CORPORA_H
|
class FunctionHelper {
constructor() {
this.regex = /^_exp:(.*)/;
}
/**
* Returns whether or not the given string is a text expression
* @param textExpression
*/
isTextExpression(textExpression) {
return typeof textExpression === 'string' && this.regex.test(textExpression);
}
/**]
* Returns whether or not the given variable is a function
* @param func
* @returns {boolean}
*/
isFunction(func) {
return typeof func === 'function';
}
/**
* Generates a function based on a text expression
* @param textExpression
*/
generateFromTextExpression(textExpression) {
let match = this.regex.exec(textExpression);
if(!match.length) {
throw Error('string is not a valid text expression. String: ' + textExpression);
}
try {
// creates a function with two arguments, 'm' and 'e'
return Function("m", "e", `return ${match[1]}`);
}
catch(e) {
// in case the function is not valid it should just return null;
return null;
}
}
/**
* If the object passed in is a function, returns the function. If it's a text expression, returns the converted
* function. Otherwise, throws an exception
* @param func
*/
getFunction(func) {
if(this.isFunction(func)) {
return func;
}
else if (this.isTextExpression(func)) {
return this.generateFromTextExpression(func);
}
throw Error('func should be either a function or a text expression');
}
}
export default new FunctionHelper();
|
(self.webpackChunkreact_template=self.webpackChunkreact_template||[]).push([[143],{61635:(t,r,o)=>{"use strict";o.d(r,{Z:()=>m});var a=o(67294),c=o(74865),i=o.n(c),u=o(68356),l=o.n(u);i().configure({showSpinner:!1});var p=function LazyLoad(){return a.useEffect((function(){return i().start(),function(){i().done()}})),a.createElement(a.Fragment,null)};const m=function LoadComponent(t){return l()({loader:t,loading:function loading(){return a.createElement(p,null)}})}},30251:(t,r,o)=>{"use strict";o.d(r,{wm:()=>a,dh:()=>c});var a="/login",c="__account_info__"},3140:(t,r,o)=>{"use strict";o.d(r,{Z:()=>a});const a=o(67294).createContext(null)},98126:(t,r,o)=>{"use strict";var a=o(67294),c=o(73935),i=o(63038),u=o.n(i),l=o(68519),p=o(65117),m=o.n(p),d=o(30251),h=o(26702);const y=(0,o(61635).Z)((function(){return Promise.all([o.e(423),o.e(650),o.e(438)]).then(o.bind(o,51613))}));var b,v=o(91386),g=o(60306),j=o(7842),O=(o(87757),o(59713)),w=o.n(O),E=(o(48926),o(75314),o(11187)),S=o(9669),_=o.n(S),A=o(44276);function ownKeys(t,r){var o=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);r&&(a=a.filter((function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable}))),o.push.apply(o,a)}return o}E.default.config({maxCount:1});var x=null===(b={SERVER_URL:"www.baidu2.com"})||void 0===b?void 0:b.SERVER_URL,C=_().create({baseURL:x}),P=["/admin/login"];C.interceptors.request.use((function(t){if(t.params){var r=function _objectSpread(t){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(o),!0).forEach((function(r){w()(t,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(o)):ownKeys(Object(o)).forEach((function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(o,r))}))}return t}({},t.params);Object.keys(r).forEach((function(t){"undefined"!==typeof r[t]&&""!==r[t]&&null!==r[t]||delete r[t]})),t.params=r}var o=t.url||"";if(!P.includes(o)){var a,c=null===(a=k())||void 0===a?void 0:a.token;if(!c)return h.Z.push("/login"),t;t.headers.authorization=function _encode(t){return"Basic "+A.DS.encode(t+":")}(c)}return t}),(function(t){return Promise.reject(t)})),C.interceptors.response.use((function(t){if(t.config.url===x+"admin/login"){var r,o=null===(r=t.data)||void 0===r?void 0:r.token;o||h.Z.push("/login"),D({token:o})}return t.data}),(function(t){var r=t.response;if(r){var o,a,c=Array.isArray(null===(o=r.data)||void 0===o?void 0:o.msg)?r.data.msg.join(""):null===(a=r.data)||void 0===a?void 0:a.msg;E.default.error(c),403===r.status&&h.Z.push("/login")}return Promise.reject(t)}));var Z=o(61729);var k=function getUserData(){return(0,Z.rV)(d.dh)},D=function setUserData(t){return(0,Z.LS)(d.dh,t)},I=o(3140),K=o(97499),R=j.Ar.Tabs,L={dropByCacheKey:p.dropByCacheKey,clearCache:p.clearCache,refreshByCacheKey:p.refreshByCacheKey,getCachingKeys:p.getCachingKeys};const T=function Routes(){var t=(0,a.useState)(null),r=u()(t,2),o=r[0],c=r[1];(0,a.useEffect)((function(){h.Z.location.pathname!==d.wm&&((0,K.xb)((0,Z.rV)(d.dh))&&h.Z.push(d.wm),c((0,Z.rV)(d.dh)))}),[]);var i=(0,K.tQ)(v.Z).path;return a.createElement(I.Z.Provider,{value:{userData:o,setUserData:c}},a.createElement(l.F0,{history:h.Z},a.createElement(p.CacheSwitch,null,a.createElement(l.AW,{exact:!0,path:"/"},a.createElement(l.l_,{to:(0,K.xb)((0,Z.rV)(d.dh))?d.wm:i})),a.createElement(l.AW,{exact:!0,path:d.wm,component:y}),a.createElement(j.Ar,{proName:g.u2,routeItems:v.Z,username:(null===o||void 0===o?void 0:o.username)||"",history:h.Z,aliveControl:L,onClickDrop:function handleClickDrop(){R.clearTabsCache(),function removeUserData(){(0,Z.cl)(d.dh)}()}},function renderRoutes(){var t=[];return function routeMap(r){r.forEach((function(r){r.meta.hidden||t.push(a.createElement(m(),{when:function when(){return!!r.meta.isCache},cacheKey:r.path,key:r.path,exact:r.exact,path:r.path,component:r.component})),r.routes&&r.routes.length&&routeMap(r.routes)}))}(v.Z),t}()))))};const U=function App(){return a.createElement(T,null)};c.render(a.createElement(U,null),document.getElementById("root"))},61729:(t,r,o)=>{"use strict";o.d(r,{LS:()=>a,rV:()=>c,cl:()=>i});var a=function setItem(t,r){return window.localStorage.setItem(t,JSON.stringify(r))},c=function getItem(t){return JSON.parse(window.localStorage.getItem(t)||"{}")},i=function removeItem(t){return window.localStorage.removeItem(t)}},97499:(t,r,o)=>{"use strict";o.d(r,{xb:()=>l,TU:()=>p,$k:()=>m,tQ:()=>d,NA:()=>h});var a=o(59713),c=o.n(a),i=o(50008),u=o.n(i);o(319);function _createForOfIteratorHelper(t,r){var o;if("undefined"===typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(o=function _unsupportedIterableToArray(t,r){if(!t)return;if("string"===typeof t)return _arrayLikeToArray(t,r);var o=Object.prototype.toString.call(t).slice(8,-1);"Object"===o&&t.constructor&&(o=t.constructor.name);if("Map"===o||"Set"===o)return Array.from(t);if("Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o))return _arrayLikeToArray(t,r)}(t))||r&&t&&"number"===typeof t.length){o&&(t=o);var a=0,c=function F(){};return{s:c,n:function n(){return a>=t.length?{done:!0}:{done:!1,value:t[a++]}},e:function e(t){throw t},f:c}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,u=!0,l=!1;return{s:function s(){o=t[Symbol.iterator]()},n:function n(){var t=o.next();return u=t.done,t},e:function e(t){l=!0,i=t},f:function f(){try{u||null==o.return||o.return()}finally{if(l)throw i}}}}function _arrayLikeToArray(t,r){(null==r||r>t.length)&&(r=t.length);for(var o=0,a=new Array(r);o<r;o++)a[o]=t[o];return a}function ownKeys(t,r){var o=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);r&&(a=a.filter((function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable}))),o.push.apply(o,a)}return o}function _objectSpread(t){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(o),!0).forEach((function(r){c()(t,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(o)):ownKeys(Object(o)).forEach((function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(o,r))}))}return t}var l=function isEmpty(t){var isEmpty=!1;return(void 0===t||null===t||""===t||Array.isArray(t)&&0===t.length||t.constructor===Object&&0===Object.keys(t).length)&&(isEmpty=!0),isEmpty};var p=function treeDeepForeach(t,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"children",a=0,c=function each(t){a++,r(t,a),t[o]&&t[o].length&&t[o].forEach((function(t){each(t)})),a--};Array.isArray(t)?t.forEach((function(t){c(t)})):"object"===u()(t)&&c(t)},m=function findTreeNode(t,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"children",a=0,c=function find(t){if(a++,r(t))return _objectSpread(_objectSpread({},t),{},{deep:a});if(t[o]&&t[o].length){var c,i=_createForOfIteratorHelper(t[o]);try{for(i.s();!(c=i.n()).done;){var u=find(c.value);if(u)return _objectSpread(_objectSpread({},u),{},{deep:a})}}catch(l){i.e(l)}finally{i.f()}}return a--,null};if(Array.isArray(t)){var i,l=_createForOfIteratorHelper(t);try{for(l.s();!(i=l.n()).done;){var p=i.value,m=c(p);if(m)return m}}catch(d){l.e(d)}finally{l.f()}}else if("object"===u()(t))return c(t)};var d=function getFirstRoute(t){for(var r=0;r<t.length;r++){var o=t[r];if(!o.routes)return o;if(o.routes&&o.routes.length)return getFirstRoute(o.routes)}},h=function getValue(t,r){for(var o=r.replace(/\["?([0-9a-zA-Z_-]+)"?\]/g,".$1").split("."),a=_objectSpread({},t),c=0;c<o.length;c++){var i=o[c];if(!a)return a;a=a[/\d+/.test(i)?Number(i):i]}return a}},26702:(t,r,o)=>{"use strict";o.d(r,{Z:()=>a});const a=(0,o(59731).q_)()},91386:(t,r,o)=>{"use strict";o.d(r,{Z:()=>l});var a=o(67294);const c=function EmptyRoute(){return a.createElement(a.Fragment,null)};var i=o(61635);const u=(0,i.Z)((function(){return Promise.all([o.e(423),o.e(942),o.e(388)]).then(o.bind(o,60963))}));const l=[{path:"/home",exact:!0,meta:{tabFixed:!0,isCache:!0,icon:"iconuser",name:"\u9996\u9875"},component:(0,i.Z)((function(){return Promise.all([o.e(40),o.e(873)]).then(o.bind(o,58284))}))},{path:"/test",exact:!0,meta:{icon:"iconyijibaogao",isCache:!0,name:"\u6d4b\u8bd5\u7ba1\u7406",hidden:!0},component:c,routes:[{path:"/test/table",exact:!0,meta:{icon:"iconuser",name:"\u5217\u8868",isCache:!0},component:u}]},{path:"/tesafst2",exact:!0,meta:{icon:"iconyijibaogao",name:"\u6d4b\u8bd5\u7ba1\u7406\u6d4b\u8bd5\u6d4b\u8bd5\u6d4b\u8bd5\u6d4b\u8bd5"},component:c},{path:"/tegst3",exact:!0,meta:{icon:"iconyijibaogao",name:"\u6d4b\u8bd5\u7ba1\u74063"},component:c},{path:"/tegst10",exact:!0,meta:{icon:"iconyijibaogao",name:"\u6d4b\u8bd5\u7ba1\u74064"},component:c},{path:"/tefsfst9",exact:!0,meta:{icon:"iconyijibaogao",name:"\u6d4b\u8bd5\u7ba1\u74064",hidden:!0},component:c},{path:"/te43st8",exact:!0,meta:{icon:"iconyijibaogao",name:"\u6d4b\u8bd5\u7ba1\u74064",hidden:!0},component:c},{path:"/te23st5",exact:!0,meta:{icon:"iconyijibaogao",name:"\u6d4b\u8bd5\u7ba1\u74064",hidden:!0},component:c},{path:"/test236",exact:!0,meta:{icon:"iconyijibaogao",name:"\u6d4b\u8bd5\u7ba1\u74064",hidden:!0},component:c},{path:"/tes2t7",exact:!0,meta:{icon:"iconyijibaogao",name:"\u6d4b\u8bd5\u7ba1\u74064",hidden:!0},component:c}]},60306:t=>{"use strict";t.exports=JSON.parse('{"u2":"react-template"}')}},0,[[98126,838,787]]]);
|
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.contentfulManagement=t():e.contentfulManagement=t()}(window,(function(){var e=String.prototype,t=Math.floor;return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:r})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var o in e)t.d(r,o,function(t){return e[t]}.bind(null,o));return r},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=20)}([function(e,t,n){(function(t){!function(t,n){e.exports=n()}(0,(function(){"use strict";function e(e,t){var n=!(!t||!t.isStrict),r=t&&t.realm||O,o=n?m:h,i=function(e,t){if(!e||"object"!=typeof e)return e;if(t.has(e))return t.get(e);var a,c=e.constructor;if(c===r.Object)return o(e,r,i,t);if(g(e)){if(n)return m(e,r,i,t);var u=e.length;a=new c,t.set(e,a);for(var s=0;s<u;s++)a[s]=i(e[s],t);return a}if(e instanceof r.Date)return new c(e.getTime());if(e instanceof r.RegExp)return(a=new c(e.source,e.flags||v(e))).lastIndex=e.lastIndex,a;if(r.Map&&e instanceof r.Map)return a=new c,t.set(e,a),e.forEach((function(e,n){a.set(n,i(e,t))})),a;if(r.Set&&e instanceof r.Set)return a=new c,t.set(e,a),e.forEach((function(e){a.add(i(e,t))})),a;if(r.Blob&&e instanceof r.Blob)return e.slice(0,e.size,e.type);if(r.Buffer&&r.Buffer.isBuffer(e))return a=r.Buffer.allocUnsafe?r.Buffer.allocUnsafe(e.length):new c(e.length),t.set(e,a),e.copy(a),a;if(r.ArrayBuffer){if(r.ArrayBuffer.isView(e))return a=new c(e.buffer.slice(0)),t.set(e,a),a;if(e instanceof r.ArrayBuffer)return a=e.slice(0),t.set(e,a),a}return"function"==typeof e.then||e instanceof Error||r.WeakMap&&e instanceof r.WeakMap||r.WeakSet&&e instanceof r.WeakSet?e:o(e,r,i,t)};return i(e,y())}var n=Function.prototype.toString,r=Object.create,o=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,c=Object.getOwnPropertySymbols,u=Object.getPrototypeOf,s=Object.prototype,p=s.hasOwnProperty,f=s.propertyIsEnumerable,l="function"==typeof c,d="function"==typeof WeakMap,y=function(){if(d)return new WeakMap;var e=r({has:function(t){return!!~e._keys.indexOf(t)},set:function(t,n){e._keys.push(t),e._values.push(n)},get:function(t){return e._values[e._keys.indexOf(t)]}});return e._keys=[],e._values=[],e},b=function(e,t){if(!e.constructor)return r(null);var o=e.constructor,i=e.__proto__||u(e);if(o===t.Object)return i===t.Object.prototype?{}:r(i);if(~n.call(o).indexOf("[native code]"))try{return new o}catch(e){}return r(i)},h=function(e,t,n,r){var o=b(e,t);for(var i in r.set(e,o),e)p.call(e,i)&&(o[i]=n(e[i],r));if(l){var a=c(e),u=a.length;if(u)for(var s=0,d=void 0;s<u;s++)d=a[s],f.call(e,d)&&(o[d]=n(e[d],r))}return o},m=function(e,t,n,r){var u=b(e,t);r.set(e,u);var s=l?a(e).concat(c(e)):a(e),p=s.length;if(p)for(var f=0,d=void 0,y=void 0;f<p;f++)if("callee"!==(d=s[f])&&"caller"!==d)if(y=i(e,d)){y.get||y.set||(y.value=n(e[d],r));try{o(u,d,y)}catch(e){u[d]=y.value}}else u[d]=n(e[d],r);return u},v=function(e){var t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.unicode&&(t+="u"),e.sticky&&(t+="y"),t},g=Array.isArray,O="undefined"==typeof self?"undefined"==typeof window?void 0===t?void(console&&console.error&&console.error('Unable to locate global object, returning "this".')):t:window:self;return e.default=e,e.strict=function(t,n){return e(t,{isStrict:!0,realm:n?n.realm:void 0})},e}))}).call(this,n(21))},function(e,n,r){"use strict";(function(e){function o(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function i(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?o(Object(t),!0).forEach((function(n){c(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):o(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function a(e){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function c(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=e&&("undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"]);if(null!=n){var r,o,i=[],a=!0,c=!1;try{for(n=n.call(e);!(a=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);a=!0);}catch(e){c=!0,o=e}finally{try{a||null==n.return||n.return()}finally{if(c)throw o}}return i}}(e,t)||s(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(e,t){if(e){if("string"==typeof e)return p(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p(e,t):void 0}}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function f(){}function l(e){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:5,r=e.defaults,o=r.responseLogger,i=void 0===o?f:o,a=r.requestLogger,c=void 0===a?f:a;e.interceptors.request.use((function(e){return c(e),e}),(function(e){return c(e),Promise.reject(e)})),e.interceptors.response.use((function(e){return i(e),e}),(function(r){var o=Math.pow,a=r.response,c=r.config;if(i(r),!c||!e.defaults.retryOnError)return Promise.reject(r);var u=null,s=0;if(a)E=0;else{if(u="Connection",++E>n)return r.attempts=E,Promise.reject(r);s=o(Math.SQRT2,E),a={}}if(500<=a.status&&600>a.status){u="Server ".concat(a.status);var p=(a.headers||{})["x-contentful-request-id"]||null;if(A[p]=A[p]||0,A[p]++,A[p]>n||!p)return r.attempts=A[p],Promise.reject(r);s=o(Math.SQRT2,A[p])}else 429===a.status&&(u="Rate limit",a.headers&&r.response.headers["x-contentful-ratelimit-reset"]&&(s=a.headers["x-contentful-ratelimit-reset"]));return u?(s=t(1e3*s+200*Math.random()+500),e.defaults.logHandler("warning","".concat(u," error occurred. Waiting for ").concat(s," ms before retrying...")),delete c.httpAgent,delete c.httpsAgent,M(s).then((function(){return e(c)}))):Promise.reject(r)}))}function d(){return void 0!==e&&!e.browser}function y(){return e.versions&&e.versions.node?"v".concat(e.versions.node):e.version}function b(e,t){var n=i(i({},{insecure:!1,retryOnError:!0,logHandler:function(e,t){if("error"===e&&t){var n=[t.name,t.message].filter((function(e){return e})).join(" - ");return console.error("[error] ".concat(n)),void console.error(t)}console.log("[".concat(e,"] ").concat(t))},headers:{},httpAgent:!1,httpsAgent:!1,timeout:3e4,proxy:!1,basePath:"",adapter:void 0,maxContentLength:1073741824,maxBodyLength:1073741824}),t);if(!n.accessToken){var r=new TypeError("Expected parameter accessToken");throw n.logHandler("error",r),r}var o=n.insecure?"http":"https",a=n.space?"".concat(n.space,"/"):"",c=n.defaultHostname,s=n.insecure?80:443;if(n.host&&k.test(n.host)){var p=n.host.split(":");if(2===p.length){var f=u(p,2);c=f[0],s=f[1]}else c=p[0]}n.basePath&&(n.basePath="/".concat(n.basePath.split("/").filter(Boolean).join("/")));var h=t.baseURL||"".concat(o,"://").concat(c,":").concat(s).concat(n.basePath,"/spaces/").concat(a);n.headers.Authorization||"function"==typeof n.accessToken||(n.headers.Authorization="Bearer "+n.accessToken),d()&&(n.headers["user-agent"]="node.js/"+y(),n.headers["Accept-Encoding"]="gzip");var m={baseURL:h,headers:n.headers,httpAgent:n.httpAgent,httpsAgent:n.httpsAgent,paramsSerializer:T.a.stringify,proxy:n.proxy,timeout:n.timeout,adapter:n.adapter,maxContentLength:n.maxContentLength,maxBodyLength:n.maxBodyLength,logHandler:n.logHandler,responseLogger:n.responseLogger,requestLogger:n.requestLogger,retryOnError:n.retryOnError},v=e.create(m);return v.httpClientParams=t,v.cloneWithNewParams=function(n){return b(e,i(i({},P()(t)),n))},n.onBeforeRequest&&v.interceptors.request.use(n.onBeforeRequest),"function"==typeof n.accessToken&&function(e,t){e.interceptors.request.use((function(e){return t().then((function(t){return e.headers=i(i({},e.headers),{},{Authorization:"Bearer ".concat(t)}),e}))}))}(v,n.accessToken),l(v,n.retryLimit),n.onError&&v.interceptors.response.use((function(e){return e}),n.onError),v}function h(e){var t=e.query,n={};return delete t.resolveLinks,n.params=P()(t),n}function m(e){var t,n=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=s(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw i}}}}(Object.getOwnPropertyNames(e));try{for(n.s();!(t=n.n()).done;){var r=e[t.value];r&&"object"===a(r)&&m(r)}}catch(e){n.e(e)}finally{n.f()}return Object.freeze(e)}function v(e){return m(e.sys||{}),e}function g(){var e=window;if(!e)return null;var t=e.navigator.userAgent,n=e.navigator.platform,r=null;return-1===["Macintosh","MacIntel","MacPPC","Mac68K"].indexOf(n)?-1===["iPhone","iPad","iPod"].indexOf(n)?-1===["Win32","Win64","Windows","WinCE"].indexOf(n)?/Android/.test(t)?r="Android":/Linux/.test(n)&&(r="Linux"):r="Windows":r="iOS":r="macOS",r}function O(e,t,n,r){var o=[];t&&o.push("app ".concat(t)),n&&o.push("integration ".concat(n)),r&&o.push("feature "+r),o.push("sdk ".concat(e));var i=null;try{"undefined"!=typeof window&&"navigator"in window&&"product"in window.navigator&&"ReactNative"===window.navigator.product?(i=g(),o.push("platform ReactNative")):d()?(i=function(){var e=Object(S.platform)()||"linux",t=Object(S.release)()||"0.0.0",n={android:"Android",aix:"Linux",darwin:"macOS",freebsd:"Linux",linux:"Linux",openbsd:"Linux",sunos:"Linux",win32:"Windows"};return e in n?"".concat(n[e]||"Linux","/").concat(t):null}(),o.push("platform node.js/".concat(y()))):(i=g(),o.push("platform browser"))}catch(t){i=null}return i&&o.push("os ".concat(i)),"".concat(o.filter((function(e){return""!==e})).join("; "),";")}function j(e){return Object.defineProperty(e,"toPlainObject",{enumerable:!1,configurable:!1,writable:!1,value:function(){return P()(this)}})}r.d(n,"a",(function(){return b})),r.d(n,"b",(function(){return h})),r.d(n,"c",(function(){return v})),r.d(n,"d",(function(){return O})),r.d(n,"e",(function(){return j}));var w=r(0),P=r.n(w),I=r(18),T=r.n(I),S=r(7),A=(r.n(S),{}),E=0,M=function(e){return new Promise((function(t){setTimeout(t,e)}))},k=/^(?!\w+:\/\/)([^\s:]+\.?[^\s:]+)(?::(\d+))?(?!:)$/}).call(this,r(8))},function(e,t,n){"use strict";function r(e){return"[object Array]"===p.call(e)}function o(e){return void 0===e}function i(e){return null!==e&&"object"==typeof e}function a(e){if("[object Object]"!==p.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function c(e){return"[object Function]"===p.call(e)}function u(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),r(e))for(var n=0,o=e.length;n<o;n++)t.call(null,e[n],n,e);else for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.call(null,e[i],i,e)}var s=n(10),p=Object.prototype.toString;e.exports={isArray:r,isArrayBuffer:function(e){return"[object ArrayBuffer]"===p.call(e)},isBuffer:function(e){return null!==e&&!o(e)&&null!==e.constructor&&!o(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:i,isPlainObject:a,isUndefined:o,isDate:function(e){return"[object Date]"===p.call(e)},isFile:function(e){return"[object File]"===p.call(e)},isBlob:function(e){return"[object Blob]"===p.call(e)},isFunction:c,isStream:function(e){return i(e)&&c(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:u,merge:function e(){function t(t,o){n[o]=a(n[o])&&a(t)?e(n[o],t):a(t)?e({},t):r(t)?t.slice():t}for(var n={},o=0,i=arguments.length;o<i;o++)u(arguments[o],t);return n},extend:function(e,t,n){return u(t,(function(t,r){e[r]=n&&"function"==typeof t?s(t,n):t})),e},trim:function(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e}}},function(e){var t=Function.prototype,n=Object.prototype,r=t.toString,o=n.hasOwnProperty,i=r.call(Object),a=n.toString,c=function(e,t){return function(n){return e(t(n))}}(Object.getPrototypeOf,Object);e.exports=function(e){if(!function(e){return!!e&&"object"==typeof e}(e)||"[object Object]"!=a.call(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(t){}return t}(e))return!1;var t=c(e);if(null===t)return!0;var n=o.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&r.call(n)==i}},function(t,n,r){"use strict";var o=SyntaxError,i=Function,a=TypeError,c=function(e){try{return i('"use strict"; return ('+e+").constructor;")()}catch(e){}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch(t){u=null}var s=function(){throw new a},p=u?function(){try{return s}catch(e){try{return u(arguments,"callee").get}catch(e){return s}}}():s,f=r(24)(),l=Object.getPrototypeOf||function(e){return e.__proto__},d={},y="undefined"==typeof Uint8Array?void 0:l(Uint8Array),b={"%AggregateError%":"undefined"==typeof AggregateError?void 0:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?void 0:ArrayBuffer,"%ArrayIteratorPrototype%":f?l([][Symbol.iterator]()):void 0,"%AsyncFromSyncIteratorPrototype%":void 0,"%AsyncFunction%":d,"%AsyncGenerator%":d,"%AsyncGeneratorFunction%":d,"%AsyncIteratorPrototype%":d,"%Atomics%":"undefined"==typeof Atomics?void 0:Atomics,"%BigInt%":"undefined"==typeof BigInt?void 0:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?void 0:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?void 0:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?void 0:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry,"%Function%":i,"%GeneratorFunction%":d,"%Int8Array%":"undefined"==typeof Int8Array?void 0:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?void 0:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?void 0:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":f?l(l([][Symbol.iterator]())):void 0,"%JSON%":"object"==typeof JSON?JSON:void 0,"%Map%":"undefined"==typeof Map?void 0:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&f?l((new Map)[Symbol.iterator]()):void 0,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?void 0:Promise,"%Proxy%":"undefined"==typeof Proxy?void 0:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?void 0:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?void 0:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&f?l((new Set)[Symbol.iterator]()):void 0,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?void 0:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":f?l(""[Symbol.iterator]()):void 0,"%Symbol%":f?Symbol:void 0,"%SyntaxError%":o,"%ThrowTypeError%":p,"%TypedArray%":y,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?void 0:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?void 0:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?void 0:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?void 0:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?void 0:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?void 0:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?void 0:WeakSet},h={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},m=r(5),v=r(27),g=m.call(Function.call,Array.prototype.concat),O=m.call(Function.apply,Array.prototype.splice),j=m.call(Function.call,e.replace),w=m.call(Function.call,e.slice),P=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,I=/\\(\\)?/g,T=function(e){var t=w(e,0,1),n=w(e,-1);if("%"===t&&"%"!==n)throw new o("invalid intrinsic syntax, expected closing `%`");if("%"===n&&"%"!==t)throw new o("invalid intrinsic syntax, expected opening `%`");var r=[];return j(e,P,(function(e,t,n,o){r[r.length]=n?j(o,I,"$1"):t||e})),r},S=function(e,t){var n,r=e;if(v(h,r)&&(r="%"+(n=h[r])[0]+"%"),v(b,r)){var i=b[r];if(i===d&&(i=function e(t){var n;if("%AsyncFunction%"===t)n=c("async function () {}");else if("%GeneratorFunction%"===t)n=c("function* () {}");else if("%AsyncGeneratorFunction%"===t)n=c("async function* () {}");else if("%AsyncGenerator%"===t){var r=e("%AsyncGeneratorFunction%");r&&(n=r.prototype)}else if("%AsyncIteratorPrototype%"===t){var o=e("%AsyncGenerator%");o&&(n=l(o.prototype))}return b[t]=n,n}(r)),void 0===i&&!t)throw new a("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:n,name:r,value:i}}throw new o("intrinsic "+e+" does not exist!")};t.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new a("intrinsic name must be a non-empty string");if(1<arguments.length&&"boolean"!=typeof t)throw new a('"allowMissing" argument must be a boolean');var n=T(e),r=0<n.length?n[0]:"",i=S("%"+r+"%",t),c=i.name,s=i.value,p=!1,f=i.alias;f&&(r=f[0],O(n,g([0,1],f)));for(var l=1,d=!0;l<n.length;l+=1){var y=n[l],h=w(y,0,1),m=w(y,-1);if(('"'===h||"'"===h||"`"===h||'"'===m||"'"===m||"`"===m)&&h!==m)throw new o("property names with quotes must have matching quotes");if("constructor"!==y&&d||(p=!0),v(b,c="%"+(r+="."+y)+"%"))s=b[c];else if(null!=s){if(!(y in s)){if(!t)throw new a("base intrinsic for "+e+" exists, but the property is not available.");return}if(u&&l+1>=n.length){var j=u(s,y);s=(d=!!j)&&"get"in j&&!("originalValue"in j.get)?j.get:s[y]}else d=v(s,y),s=s[y];d&&!p&&(b[c]=s)}}return s}},function(e,t,n){"use strict";var r=n(26);e.exports=Function.prototype.bind||r},function(t){"use strict";var n=e.replace,r=/%20/g,o="RFC1738",i="RFC3986";t.exports={default:i,formatters:{RFC1738:function(e){return n.call(e,r,"+")},RFC3986:function(e){return e+""}},RFC1738:o,RFC3986:i}},function(){},function(e){function t(){throw new Error("setTimeout has not been defined")}function n(){throw new Error("clearTimeout has not been defined")}function r(e){if(u===setTimeout)return setTimeout(e,0);if((u===t||!u)&&setTimeout)return u=setTimeout,setTimeout(e,0);try{return u(e,0)}catch(t){try{return u.call(null,e,0)}catch(t){return u.call(this,e,0)}}}function o(){d&&f&&(d=!1,f.length?l=f.concat(l):y=-1,l.length&&i())}function i(){if(!d){var e=r(o);d=!0;for(var t=l.length;t;){for(f=l,l=[];++y<t;)f&&f[y].run();y=-1,t=l.length}f=null,d=!1,function(e){if(s===clearTimeout)return clearTimeout(e);if((s===n||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(e);try{s(e)}catch(t){try{return s.call(null,e)}catch(t){return s.call(this,e)}}}(e)}}function a(e,t){this.fun=e,this.array=t}function c(){}var u,s,p=e.exports={};!function(){try{u="function"==typeof setTimeout?setTimeout:t}catch(e){u=t}try{s="function"==typeof clearTimeout?clearTimeout:n}catch(e){s=n}}();var f,l=[],d=!1,y=-1;p.nextTick=function(e){var t=Array(arguments.length-1);if(1<arguments.length)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];l.push(new a(e,t)),1!==l.length||d||r(i)},a.prototype.run=function(){this.fun.apply(null,this.array)},p.title="browser",p.browser=!0,p.env={},p.argv=[],p.version="",p.versions={},p.on=c,p.addListener=c,p.once=c,p.off=c,p.removeListener=c,p.removeAllListeners=c,p.emit=c,p.prependListener=c,p.prependOnceListener=c,p.listeners=function(){return[]},p.binding=function(){throw new Error("process.binding is not supported")},p.cwd=function(){return"/"},p.chdir=function(){throw new Error("process.chdir is not supported")},p.umask=function(){return 0}},function(e,t,n){"use strict";var r=n(6),o=Object.prototype.hasOwnProperty,i=Array.isArray,a=function(){for(var e=[],t=0;256>t;++t)e.push("%"+((16>t?"0":"")+t.toString(16)).toUpperCase());return e}(),c=function(e){for(;1<e.length;){var t=e.pop(),n=t.obj[t.prop];if(i(n)){for(var r=[],o=0;o<n.length;++o)void 0!==n[o]&&r.push(n[o]);t.obj[t.prop]=r}}},u=function(e,t){for(var n=t&&t.plainObjects?Object.create(null):{},r=0;r<e.length;++r)void 0!==e[r]&&(n[r]=e[r]);return n};e.exports={arrayToObject:u,assign:function(e,t){return Object.keys(t).reduce((function(e,n){return e[n]=t[n],e}),e)},combine:function(e,t){return[].concat(e,t)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],n=[],r=0;r<t.length;++r)for(var o=t[r],i=o.obj[o.prop],a=Object.keys(i),u=0;u<a.length;++u){var s=a[u],p=i[s];"object"==typeof p&&null!==p&&-1===n.indexOf(p)&&(t.push({obj:i,prop:s}),n.push(p))}return c(t),e},decode:function(e,t,n){var r=e.replace(/\+/g," ");if("iso-8859-1"===n)return r.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(r)}catch(t){return r}},encode:function(e,t,n,o,i){if(0===e.length)return e;var c=e;if("symbol"==typeof e?c=Symbol.prototype.toString.call(e):"string"!=typeof e&&(c=e+""),"iso-8859-1"===n)return escape(c).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var u,s="",p=0;p<c.length;++p)45===(u=c.charCodeAt(p))||46===u||95===u||126===u||48<=u&&57>=u||65<=u&&90>=u||97<=u&&122>=u||i===r.RFC1738&&(40===u||41===u)?s+=c.charAt(p):128>u?s+=a[u]:2048>u?s+=a[192|u>>6]+a[128|63&u]:55296>u||57344<=u?s+=a[224|u>>12]+a[128|63&u>>6]+a[128|63&u]:(p+=1,u=65536+((1023&u)<<10|1023&c.charCodeAt(p)),s+=a[240|u>>18]+a[128|63&u>>12]+a[128|63&u>>6]+a[128|63&u]);return s},isBuffer:function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(i(e)){for(var n=[],r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)},merge:function e(t,n,r){if(!n)return t;if("object"!=typeof n){if(i(t))t.push(n);else{if(!t||"object"!=typeof t)return[t,n];(r&&(r.plainObjects||r.allowPrototypes)||!o.call(Object.prototype,n))&&(t[n]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(n);var a=t;return i(t)&&!i(n)&&(a=u(t,r)),i(t)&&i(n)?(n.forEach((function(n,i){if(o.call(t,i)){var a=t[i];a&&"object"==typeof a&&n&&"object"==typeof n?t[i]=e(a,n,r):t.push(n)}else t[i]=n})),t):Object.keys(n).reduce((function(t,i){var a=n[i];return t[i]=o.call(t,i)?e(t[i],a,r):a,t}),a)}}},function(e){"use strict";e.exports=function(e,t){return function(){for(var n=Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return e.apply(t,n)}}},function(e,t,n){"use strict";function r(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var o=n(2);e.exports=function(e,t,n){if(!t)return e;var i;if(n)i=n(t);else if(o.isURLSearchParams(t))i=t.toString();else{var a=[];o.forEach(t,(function(e,t){null==e||(o.isArray(e)?t+="[]":e=[e],o.forEach(e,(function(e){o.isDate(e)?e=e.toISOString():o.isObject(e)&&(e=JSON.stringify(e)),a.push(r(t)+"="+r(e))})))})),i=a.join("&")}if(i){var c=e.indexOf("#");-1!==c&&(e=e.slice(0,c)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}},function(e){"use strict";e.exports=function(e){return!(!e||!e.__CANCEL__)}},function(e,t,n){"use strict";(function(t){function r(e,t){!o.isUndefined(e)&&o.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var o=n(2),i=n(38),a={"Content-Type":"application/x-www-form-urlencoded"},c={adapter:function(){var e;return"undefined"==typeof XMLHttpRequest?void 0!==t&&"[object process]"===Object.prototype.toString.call(t)&&(e=n(14)):e=n(14),e}(),transformRequest:[function(e,t){return i(t,"Accept"),i(t,"Content-Type"),o.isFormData(e)||o.isArrayBuffer(e)||o.isBuffer(e)||o.isStream(e)||o.isFile(e)||o.isBlob(e)?e:o.isArrayBufferView(e)?e.buffer:o.isURLSearchParams(e)?(r(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):o.isObject(e)?(r(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return 200<=e&&300>e},headers:{common:{Accept:"application/json, text/plain, */*"}}};o.forEach(["delete","get","head"],(function(e){c.headers[e]={}})),o.forEach(["post","put","patch"],(function(e){c.headers[e]=o.merge(a)})),e.exports=c}).call(this,n(8))},function(e,t,n){"use strict";var r=n(2),o=n(39),i=n(41),a=n(11),c=n(42),u=n(45),s=n(46),p=n(15);e.exports=function(e){return new Promise((function(t,n){var f=e.data,l=e.headers;r.isFormData(f)&&delete l["Content-Type"];var d=new XMLHttpRequest;if(e.auth){var y=e.auth.username||"",b=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";l.Authorization="Basic "+btoa(y+":"+b)}var h=c(e.baseURL,e.url);if(d.open(e.method.toUpperCase(),a(h,e.params,e.paramsSerializer),!0),d.timeout=e.timeout,d.onreadystatechange=function(){if(d&&4===d.readyState&&(0!==d.status||d.responseURL&&0===d.responseURL.indexOf("file:"))){var r="getAllResponseHeaders"in d?u(d.getAllResponseHeaders()):null,i={data:e.responseType&&"text"!==e.responseType?d.response:d.responseText,status:d.status,statusText:d.statusText,headers:r,config:e,request:d};o(t,n,i),d=null}},d.onabort=function(){d&&(n(p("Request aborted",e,"ECONNABORTED",d)),d=null)},d.onerror=function(){n(p("Network Error",e,null,d)),d=null},d.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),n(p(t,e,"ECONNABORTED",d)),d=null},r.isStandardBrowserEnv()){var m=(e.withCredentials||s(h))&&e.xsrfCookieName?i.read(e.xsrfCookieName):void 0;m&&(l[e.xsrfHeaderName]=m)}if("setRequestHeader"in d&&r.forEach(l,(function(e,t){void 0===f&&"content-type"===t.toLowerCase()?delete l[t]:d.setRequestHeader(t,e)})),r.isUndefined(e.withCredentials)||(d.withCredentials=!!e.withCredentials),e.responseType)try{d.responseType=e.responseType}catch(n){if("json"!==e.responseType)throw n}"function"==typeof e.onDownloadProgress&&d.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&d.upload&&d.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){d&&(d.abort(),n(e),d=null)})),f||(f=null),d.send(f)}))}},function(e,t,n){"use strict";var r=n(40);e.exports=function(e,t,n,o,i){var a=new Error(e);return r(a,t,n,o,i)}},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t){function n(e,t){return r.isPlainObject(e)&&r.isPlainObject(t)?r.merge(e,t):r.isPlainObject(t)?r.merge({},t):r.isArray(t)?t.slice():t}function o(o){r.isUndefined(t[o])?!r.isUndefined(e[o])&&(i[o]=n(void 0,e[o])):i[o]=n(e[o],t[o])}t=t||{};var i={},a=["url","method","data"],c=["headers","auth","proxy","params"],u=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],s=["validateStatus"];r.forEach(a,(function(e){r.isUndefined(t[e])||(i[e]=n(void 0,t[e]))})),r.forEach(c,o),r.forEach(u,(function(o){r.isUndefined(t[o])?!r.isUndefined(e[o])&&(i[o]=n(void 0,e[o])):i[o]=n(void 0,t[o])})),r.forEach(s,(function(r){r in t?i[r]=n(e[r],t[r]):r in e&&(i[r]=n(void 0,e[r]))}));var p=a.concat(c).concat(u).concat(s),f=Object.keys(e).concat(Object.keys(t)).filter((function(e){return-1===p.indexOf(e)}));return r.forEach(f,o),i}},function(e){"use strict";function t(e){this.message=e}t.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},t.prototype.__CANCEL__=!0,e.exports=t},function(e,t,n){"use strict";var r=n(22),o=n(32),i=n(6);e.exports={formats:i,parse:o,stringify:r}},function(e,t,n){e.exports=n(33)},function(e,t,n){e.exports=n(50)},function(e){var t=function(){return this}();try{t=t||new Function("return this")()}catch(e){"object"==typeof window&&(t=window)}e.exports=t},function(e,t,n){"use strict";var r=n(23),o=n(9),i=n(6),a=Object.prototype.hasOwnProperty,c={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},u=Array.isArray,s=Array.prototype.push,p=function(e,t){s.apply(e,u(t)?t:[t])},f=Date.prototype.toISOString,l=i.default,d={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:o.encode,encodeValuesOnly:!1,format:l,formatter:i.formatters[l],indices:!1,serializeDate:function(e){return f.call(e)},skipNulls:!1,strictNullHandling:!1},y=function e(t,n,i,a,c,s,f,l,y,b,h,m,v,g,O){var j=t;if(O.has(t))throw new RangeError("Cyclic object value");if("function"==typeof f?j=f(n,j):j instanceof Date?j=b(j):"comma"===i&&u(j)&&(j=o.maybeMap(j,(function(e){return e instanceof Date?b(e):e}))),null===j){if(a)return s&&!v?s(n,d.encoder,g,"key",h):n;j=""}if(function(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}(j)||o.isBuffer(j))return s?[m(v?n:s(n,d.encoder,g,"key",h))+"="+m(s(j,d.encoder,g,"value",h))]:[m(n)+"="+m(j+"")];var w,P=[];if(void 0===j)return P;if("comma"===i&&u(j))w=[{value:0<j.length?j.join(",")||null:void 0}];else if(u(f))w=f;else{var I=Object.keys(j);w=l?I.sort(l):I}for(var T=0;T<w.length;++T){var S=w[T],A="object"==typeof S&&void 0!==S.value?S.value:j[S];if(!c||null!==A){var E=u(j)?"function"==typeof i?i(n,S):n:n+(y?"."+S:"["+S+"]");O.set(t,!0);var M=r();p(P,e(A,E,i,a,c,s,f,l,y,b,h,m,v,g,M))}}return P},b=function(e){if(!e)return d;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||d.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var n=i.default;if(void 0!==e.format){if(!a.call(i.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=i.formatters[n],o=d.filter;return("function"==typeof e.filter||u(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:d.addQueryPrefix,allowDots:void 0===e.allowDots?d.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:d.charsetSentinel,delimiter:void 0===e.delimiter?d.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:d.encode,encoder:"function"==typeof e.encoder?e.encoder:d.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:d.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:d.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:d.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:d.strictNullHandling}};e.exports=function(e,t){var n,o=e,i=b(t);"function"==typeof i.filter?o=(0,i.filter)("",o):u(i.filter)&&(n=i.filter);var a=[];if("object"!=typeof o||null===o)return"";var s=t&&t.arrayFormat in c?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices",f=c[s];n||(n=Object.keys(o)),i.sort&&n.sort(i.sort);for(var l,d=r(),h=0;h<n.length;++h)l=n[h],(!i.skipNulls||null!==o[l])&&p(a,y(o[l],l,f,i.strictNullHandling,i.skipNulls,i.encode?i.encoder:null,i.filter,i.sort,i.allowDots,i.serializeDate,i.format,i.formatter,i.encodeValuesOnly,i.charset,d));var m=a.join(i.delimiter),v=!0===i.addQueryPrefix?"?":"";return i.charsetSentinel&&("iso-8859-1"===i.charset?v+="utf8=%26%2310003%3B&":v+="utf8=%E2%9C%93&"),0<m.length?v+m:""}},function(e,t,n){"use strict";var r=n(4),o=n(28),i=n(30),a=r("%TypeError%"),c=r("%WeakMap%",!0),u=r("%Map%",!0),s=o("WeakMap.prototype.get",!0),p=o("WeakMap.prototype.set",!0),f=o("WeakMap.prototype.has",!0),l=o("Map.prototype.get",!0),d=o("Map.prototype.set",!0),y=o("Map.prototype.has",!0),b=function(e,t){for(var n,r=e;null!==(n=r.next);r=n)if(n.key===t)return r.next=n.next,n.next=e.next,e.next=n,n};e.exports=function(){var e,t,n,r={assert:function(e){if(!r.has(e))throw new a("Side channel does not contain "+i(e))},get:function(r){if(c&&r&&("object"==typeof r||"function"==typeof r)){if(e)return s(e,r)}else if(u){if(t)return l(t,r)}else if(n)return function(e,t){var n=b(e,t);return n&&n.value}(n,r)},has:function(r){if(c&&r&&("object"==typeof r||"function"==typeof r)){if(e)return f(e,r)}else if(u){if(t)return y(t,r)}else if(n)return function(e,t){return!!b(e,t)}(n,r);return!1},set:function(r,o){c&&r&&("object"==typeof r||"function"==typeof r)?(!e&&(e=new c),p(e,r,o)):u?(!t&&(t=new u),d(t,r,o)):(!n&&(n={key:{},next:null}),function(e,t,n){var r=b(e,t);r?r.value=n:e.next={key:t,next:e.next,value:n}}(n,r,o))}};return r}},function(e,t,n){"use strict";var r="undefined"!=typeof Symbol&&Symbol,o=n(25);e.exports=function(){return!("function"!=typeof r)&&!("function"!=typeof Symbol)&&!("symbol"!=typeof r("foo"))&&!("symbol"!=typeof Symbol("bar"))&&o()}},function(e){"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),n=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(n))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var r=Object.getOwnPropertySymbols(e);if(1!==r.length||r[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var o=Object.getOwnPropertyDescriptor(e,t);if(42!==o.value||!0!==o.enumerable)return!1}return!0}},function(e){"use strict";var t=Array.prototype.slice,n=Object.prototype.toString;e.exports=function(e){var r=this;if("function"!=typeof r||"[object Function]"!==n.call(r))throw new TypeError("Function.prototype.bind called on incompatible "+r);for(var o,i=t.call(arguments,1),a=function(){if(this instanceof o){var n=r.apply(this,i.concat(t.call(arguments)));return Object(n)===n?n:this}return r.apply(e,i.concat(t.call(arguments)))},c=Math.max(0,r.length-i.length),u=[],s=0;s<c;s++)u.push("$"+s);if(o=Function("binder","return function ("+u.join(",")+"){ return binder.apply(this,arguments); }")(a),r.prototype){var p=function(){};p.prototype=r.prototype,o.prototype=new p,p.prototype=null}return o}},function(e,t,n){"use strict";var r=n(5);e.exports=r.call(Function.call,Object.prototype.hasOwnProperty)},function(e,t,n){"use strict";var r=n(4),o=n(29),i=o(r("String.prototype.indexOf"));e.exports=function(e,t){var n=r(e,!!t);return"function"==typeof n&&-1<i(e,".prototype.")?o(n):n}},function(e,t,n){"use strict";var r=n(5),o=n(4),i=o("%Function.prototype.apply%"),a=o("%Function.prototype.call%"),c=o("%Reflect.apply%",!0)||r.call(a,i),u=o("%Object.getOwnPropertyDescriptor%",!0),s=o("%Object.defineProperty%",!0),p=o("%Math.max%");if(s)try{s({},"a",{value:1})}catch(t){s=null}e.exports=function(e){var t=c(r,a,arguments);if(u&&s){var n=u(t,"length");n.configurable&&s(t,"length",{value:1+p(0,e.length-(arguments.length-1))})}return t};var f=function(){return c(r,i,arguments)};s?s(e.exports,"apply",{value:f}):e.exports.apply=f},function(t,n,r){function o(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function i(e){return(e+"").replace(/"/g,""")}function a(e){return!("[object Array]"!==s(e)||K&&"object"==typeof e&&K in e)}function c(e){if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!W)return!1;try{return W.call(e),!0}catch(e){}return!1}function u(e,t){return V.call(e,t)}function s(e){return z.call(e)}function p(e){if(e.name)return e.name;var t=R.call(F.call(e),/^function\s*([\w$]+)/);return t?t[1]:null}function f(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}function l(e){if(!k||!e||"object"!=typeof e)return!1;try{k.call(e,k);try{x.call(e,x)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}function d(e){if(!D||!e||"object"!=typeof e)return!1;try{return D.call(e),!0}catch(e){}return!1}function y(e){if(!x||!e||"object"!=typeof e)return!1;try{x.call(e,x);try{k.call(e,k)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}function b(e,t){if(e.length>t.maxStringLength){var n=e.length-t.maxStringLength,r="... "+n+" more character"+(1<n?"s":"");return b(e.slice(0,t.maxStringLength),t)+r}return o(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,h),"single",t)}function h(e){var t=e.charCodeAt(0),n={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return n?"\\"+n:"\\x"+(16>t?"0":"")+t.toString(16).toUpperCase()}function m(e){return"Object("+e+")"}function v(e){return e+" { ? }"}function g(e,t,n,r){return e+" ("+t+") {"+(r?O(n,r):n.join(", "))+"}"}function O(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+e.join(","+n)+"\n"+t.prev}function j(e,t){var n=a(e),r=[];if(n){r.length=e.length;for(var o=0;o<e.length;o++)r[o]=u(e,o)?t(e[o],e):""}for(var i in e)u(e,i)&&(n&&+i+""===i&&i<e.length||(/[^\w$]/.test(i)?r.push(t(i,e)+": "+t(e[i],e)):r.push(i+": "+t(e[i],e))));if("function"==typeof q)for(var c=q(e),s=0;s<c.length;s++)_.call(e,c[s])&&r.push("["+t(c[s])+"]: "+t(e[c[s]],e));return r}var w="function"==typeof Map&&Map.prototype,P=Object.getOwnPropertyDescriptor&&w?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,I=w&&P&&"function"==typeof P.get?P.get:null,T=w&&Map.prototype.forEach,S="function"==typeof Set&&Set.prototype,A=Object.getOwnPropertyDescriptor&&S?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,E=S&&A&&"function"==typeof A.get?A.get:null,M=S&&Set.prototype.forEach,k="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,x="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,D="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,C=Boolean.prototype.valueOf,z=Object.prototype.toString,F=Function.prototype.toString,R=e.match,U="function"==typeof BigInt?BigInt.prototype.valueOf:null,q=Object.getOwnPropertySymbols,W="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,_=Object.prototype.propertyIsEnumerable,B=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),L=r(31).custom,N=L&&c(L)?L:null,K="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag?Symbol.toStringTag:null;t.exports=function e(t,n,r,h){function w(t,n,o){if(n&&(h=h.slice()).push(n),o){var i={depth:P.depth};return u(P,"quoteStyle")&&(i.quoteStyle=P.quoteStyle),e(t,i,r+1,h)}return e(t,P,r+1,h)}var P=n||{};if(u(P,"quoteStyle")&&"single"!==P.quoteStyle&&"double"!==P.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(u(P,"maxStringLength")&&("number"==typeof P.maxStringLength?0>P.maxStringLength&&P.maxStringLength!==1/0:null!==P.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var S=!u(P,"customInspect")||P.customInspect;if("boolean"!=typeof S)throw new TypeError('option "customInspect", if provided, must be `true` or `false`');if(u(P,"indent")&&null!==P.indent&&"\t"!==P.indent&&!(parseInt(P.indent,10)===P.indent&&0<P.indent))throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return b(t,P);if("number"==typeof t)return 0===t?0<1/0/t?"0":"-0":t+"";if("bigint"==typeof t)return t+"n";var A=void 0===P.depth?5:P.depth;if(void 0===r&&(r=0),r>=A&&0<A&&"object"==typeof t)return a(t)?"[Array]":"[Object]";var k=function(e,t){var n;if("\t"===e.indent)n="\t";else{if(!("number"==typeof e.indent&&0<e.indent))return null;n=Array(e.indent+1).join(" ")}return{base:n,prev:Array(t+1).join(n)}}(P,r);if(void 0===h)h=[];else if(0<=f(h,t))return"[Circular]";if("function"==typeof t){var x=p(t),D=j(t,w);return"[Function"+(x?": "+x:" (anonymous)")+"]"+(0<D.length?" { "+D.join(", ")+" }":"")}if(c(t)){var z=W.call(t);return"object"==typeof t?m(z):z}if(function(e){return!!(e&&"object"==typeof e&&("undefined"!=typeof HTMLElement&&e instanceof HTMLElement||"string"==typeof e.nodeName&&"function"==typeof e.getAttribute))}(t)){for(var F="<"+(t.nodeName+"").toLowerCase(),R=t.attributes||[],q=0;q<R.length;q++)F+=" "+R[q].name+"="+o(i(R[q].value),"double",P);return F+=">",t.childNodes&&t.childNodes.length&&(F+="..."),F+="</"+(t.nodeName+"").toLowerCase()+">"}if(a(t)){if(0===t.length)return"[]";var _=j(t,w);return k&&!function(e){for(var t=0;t<e.length;t++)if(0<=f(e[t],"\n"))return!1;return!0}(_)?"["+O(_,k)+"]":"[ "+_.join(", ")+" ]"}if(function(e){return!("[object Error]"!==s(e)||K&&"object"==typeof e&&K in e)}(t)){var L=j(t,w);return 0===L.length?"["+t+"]":"{ ["+t+"] "+L.join(", ")+" }"}if("object"==typeof t&&S){if(N&&"function"==typeof t[N])return t[N]();if("function"==typeof t.inspect)return t.inspect()}if(function(e){if(!I||!e||"object"!=typeof e)return!1;try{I.call(e);try{E.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var V=[];return T.call(t,(function(e,n){V.push(w(n,t,!0)+" => "+w(e,t))})),g("Map",I.call(t),V,k)}if(function(e){if(!E||!e||"object"!=typeof e)return!1;try{E.call(e);try{I.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var H=[];return M.call(t,(function(e){H.push(w(e,t))})),g("Set",E.call(t),H,k)}if(l(t))return v("WeakMap");if(y(t))return v("WeakSet");if(d(t))return v("WeakRef");if(function(e){return!("[object Number]"!==s(e)||K&&"object"==typeof e&&K in e)}(t))return m(w(+t));if(function(e){if(!e||"object"!=typeof e||!U)return!1;try{return U.call(e),!0}catch(e){}return!1}(t))return m(w(U.call(t)));if(function(e){return!("[object Boolean]"!==s(e)||K&&"object"==typeof e&&K in e)}(t))return m(C.call(t));if(function(e){return!("[object String]"!==s(e)||K&&"object"==typeof e&&K in e)}(t))return m(w(t+""));if(!function(e){return!("[object Date]"!==s(e)||K&&"object"==typeof e&&K in e)}(t)&&!function(e){return!("[object RegExp]"!==s(e)||K&&"object"==typeof e&&K in e)}(t)){var X=j(t,w),G=B?B(t)===Object.prototype:t instanceof Object||t.constructor===Object,J=t instanceof Object?"":"null prototype",$=!G&&K&&Object(t)===t&&K in t?s(t).slice(8,-1):J?"Object":"",Q=(G||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+($||J?"["+[].concat($||[],J||[]).join(": ")+"] ":"");return 0===X.length?Q+"{}":k?Q+"{"+O(X,k)+"}":Q+"{ "+X.join(", ")+" }"}return t+""};var V=Object.prototype.hasOwnProperty||function(e){return e in this}},function(){},function(e,t,n){"use strict";var r=n(9),o=Object.prototype.hasOwnProperty,i=Array.isArray,a={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:r.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},c=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},u=function(e,t){return e&&"string"==typeof e&&t.comma&&-1<e.indexOf(",")?e.split(","):e},s=function(e,t){var n,s={},p=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,f=t.parameterLimit===1/0?void 0:t.parameterLimit,l=p.split(t.delimiter,f),d=-1,y=t.charset;if(t.charsetSentinel)for(n=0;n<l.length;++n)0===l[n].indexOf("utf8=")&&("utf8=%E2%9C%93"===l[n]?y="utf-8":"utf8=%26%2310003%3B"===l[n]&&(y="iso-8859-1"),d=n,n=l.length);for(n=0;n<l.length;++n)if(n!==d){var b,h,m=l[n],v=m.indexOf("]="),g=-1===v?m.indexOf("="):v+1;-1===g?(b=t.decoder(m,a.decoder,y,"key"),h=t.strictNullHandling?null:""):(b=t.decoder(m.slice(0,g),a.decoder,y,"key"),h=r.maybeMap(u(m.slice(g+1),t),(function(e){return t.decoder(e,a.decoder,y,"value")}))),h&&t.interpretNumericEntities&&"iso-8859-1"===y&&(h=c(h)),-1<m.indexOf("[]=")&&(h=i(h)?[h]:h),s[b]=o.call(s,b)?r.combine(s[b],h):h}return s},p=function(e,t,n,r){for(var o=r?t:u(t,n),i=e.length-1;0<=i;--i){var a,c=e[i];if("[]"===c&&n.parseArrays)a=[].concat(o);else{a=n.plainObjects?Object.create(null):{};var s="["===c.charAt(0)&&"]"===c.charAt(c.length-1)?c.slice(1,-1):c,p=parseInt(s,10);n.parseArrays||""!==s?!isNaN(p)&&c!==s&&p+""===s&&0<=p&&n.parseArrays&&p<=n.arrayLimit?(a=[])[p]=o:a[s]=o:a={0:o}}o=a}return o},f=function(e,t,n,r){if(e){var i=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,a=/(\[[^[\]]*])/g,c=0<n.depth&&/(\[[^[\]]*])/.exec(i),u=c?i.slice(0,c.index):i,s=[];if(u){if(!n.plainObjects&&o.call(Object.prototype,u)&&!n.allowPrototypes)return;s.push(u)}for(var f=0;0<n.depth&&null!==(c=a.exec(i))&&f<n.depth;){if(f+=1,!n.plainObjects&&o.call(Object.prototype,c[1].slice(1,-1))&&!n.allowPrototypes)return;s.push(c[1])}return c&&s.push("["+i.slice(c.index)+"]"),p(s,t,n,r)}},l=function(e){if(!e)return a;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?a.charset:e.charset;return{allowDots:void 0===e.allowDots?a.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:a.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:a.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:a.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:a.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:a.comma,decoder:"function"==typeof e.decoder?e.decoder:a.decoder,delimiter:"string"==typeof e.delimiter||r.isRegExp(e.delimiter)?e.delimiter:a.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:a.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:a.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:a.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:a.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:a.strictNullHandling}};e.exports=function(e,t){var n=l(t);if(""===e||null==e)return n.plainObjects?Object.create(null):{};for(var o="string"==typeof e?s(e,n):e,i=n.plainObjects?Object.create(null):{},a=Object.keys(o),c=0;c<a.length;++c){var u=a[c],p=f(u,o[u],n,"string"==typeof e);i=r.merge(i,p,n)}return!0===n.allowSparse?i:r.compact(i)}},function(e,t,n){"use strict";function r(e){var t=new a(e),n=i(a.prototype.request,t);return o.extend(n,a.prototype,t),o.extend(n,t),n}var o=n(2),i=n(10),a=n(34),c=n(16),u=r(n(13));u.Axios=a,u.create=function(e){return r(c(u.defaults,e))},u.Cancel=n(17),u.CancelToken=n(47),u.isCancel=n(12),u.all=function(e){return Promise.all(e)},u.spread=n(48),u.isAxiosError=n(49),e.exports=u,e.exports.default=u},function(e,t,n){"use strict";function r(e){this.defaults=e,this.interceptors={request:new a,response:new a}}var o=n(2),i=n(11),a=n(35),c=n(36),u=n(16);r.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=u(this.defaults,e)).method=e.method?e.method.toLowerCase():this.defaults.method?this.defaults.method.toLowerCase():"get";var t=[c,void 0],n=Promise.resolve(e);for(this.interceptors.request.forEach((function(e){t.unshift(e.fulfilled,e.rejected)})),this.interceptors.response.forEach((function(e){t.push(e.fulfilled,e.rejected)}));t.length;)n=n.then(t.shift(),t.shift());return n},r.prototype.getUri=function(e){return e=u(this.defaults,e),i(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},o.forEach(["delete","get","head","options"],(function(e){r.prototype[e]=function(t,n){return this.request(u(n||{},{method:e,url:t,data:(n||{}).data}))}})),o.forEach(["post","put","patch"],(function(e){r.prototype[e]=function(t,n,r){return this.request(u(r||{},{method:e,url:t,data:n}))}})),e.exports=r},function(e,t,n){"use strict";function r(){this.handlers=[]}var o=n(2);r.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},r.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},r.prototype.forEach=function(e){o.forEach(this.handlers,(function(t){null!==t&&e(t)}))},e.exports=r},function(e,t,n){"use strict";function r(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var o=n(2),i=n(37),a=n(12),c=n(13);e.exports=function(e){return r(e),e.headers=e.headers||{},e.data=i(e.data,e.headers,e.transformRequest),e.headers=o.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),o.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||c.adapter)(e).then((function(t){return r(e),t.data=i(t.data,t.headers,e.transformResponse),t}),(function(t){return a(t)||(r(e),t&&t.response&&(t.response.data=i(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))}},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t,n){return r.forEach(n,(function(n){e=n(e,t)})),e}},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t){r.forEach(e,(function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])}))}},function(e,t,n){"use strict";var r=n(15);e.exports=function(e,t,n){var o=n.config.validateStatus;n.status&&o&&!o(n.status)?t(r("Request failed with status code "+n.status,n.config,null,n.request,n)):e(n)}},function(e){"use strict";e.exports=function(e,t,n,r,o){return e.config=t,n&&(e.code=n),e.request=r,e.response=o,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},e}},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?{write:function(e,t,n,o,i,a){var c=[];c.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&c.push("expires="+new Date(n).toGMTString()),r.isString(o)&&c.push("path="+o),r.isString(i)&&c.push("domain="+i),!0===a&&c.push("secure"),document.cookie=c.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}},function(e,t,n){"use strict";var r=n(43),o=n(44);e.exports=function(e,t){return e&&!r(t)?o(e,t):t}},function(e){"use strict";e.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}},function(e){"use strict";e.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}},function(e,t,n){"use strict";var r=n(2),o=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];e.exports=function(e){var t,n,i,a={};return e?(r.forEach(e.split("\n"),(function(e){if(i=e.indexOf(":"),t=r.trim(e.substr(0,i)).toLowerCase(),n=r.trim(e.substr(i+1)),t){if(a[t]&&0<=o.indexOf(t))return;a[t]="set-cookie"===t?(a[t]?a[t]:[]).concat([n]):a[t]?a[t]+", "+n:n}})),a):a}},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){function e(e){var t=e;return n&&(o.setAttribute("href",t),t=o.href),o.setAttribute("href",t),{href:o.href,protocol:o.protocol?o.protocol.replace(/:$/,""):"",host:o.host,search:o.search?o.search.replace(/^\?/,""):"",hash:o.hash?o.hash.replace(/^#/,""):"",hostname:o.hostname,port:o.port,pathname:"/"===o.pathname.charAt(0)?o.pathname:"/"+o.pathname}}var t,n=/(msie|trident)/i.test(navigator.userAgent),o=document.createElement("a");return t=e(window.location.href),function(n){var o=r.isString(n)?e(n):n;return o.protocol===t.protocol&&o.host===t.host}}():function(){return!0}},function(e,t,n){"use strict";function r(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var n=this;e((function(e){n.reason||(n.reason=new o(e),t(n.reason))}))}var o=n(17);r.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},r.source=function(){var e;return{token:new r((function(t){e=t})),cancel:e}},e.exports=r},function(e){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}},function(e){"use strict";e.exports=function(e){return"object"==typeof e&&!0===e.isAxiosError}},function(e,n,r){"use strict";function o(e){var t,n=e.config,r=e.response;if(n&&n.headers&&n.headers.Authorization){var o="...".concat(n.headers.Authorization.substr(-5));n.headers.Authorization="Bearer ".concat(o)}if(!io()(r)||!io()(n))throw e;var i=null==r?void 0:r.data,a={status:null==r?void 0:r.status,statusText:null==r?void 0:r.statusText,message:"",details:{}};io()(n)&&(a.request={url:n.url,headers:n.headers,method:n.method,payloadData:n.data}),i&&io()(i)&&("requestId"in i&&(a.requestId=i.requestId||"UNKNOWN"),"message"in i&&(a.message=i.message||""),"details"in i&&(a.details=i.details||{}),"sys"in i&&"id"in i.sys&&(t=i.sys.id));var c=new Error;c.name=t&&"Unknown"!==t?t:"".concat(null==r?void 0:r.status," ").concat(null==r?void 0:r.statusText);try{c.message=JSON.stringify(a,null," ")}catch(e){var u;c.message=null!==(u=null==a?void 0:a.message)&&void 0!==u?u:""}throw c}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function a(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?i(Object(t),!0).forEach((function(n){c(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):i(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function c(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(e){var t;return null===(t=e.defaults.baseURL)||void 0===t?void 0:t.split("/spaces")[0]}function s(e,t,n){return e.get(t,a({baseURL:u(e)},n)).then((function(e){return e.data}),o)}function p(e,t,n,r){return e.post(t,n,a({baseURL:u(e)},r)).then((function(e){return e.data}),o)}function f(e,t,n,r){return e.put(t,n,a({baseURL:u(e)},r)).then((function(e){return e.data}),o)}function l(e,t,n){return e.delete(t,a({baseURL:u(e)},n)).then((function(e){return e.data}),o)}function d(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function y(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?d(Object(t),!0).forEach((function(n){b(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):d(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function b(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function h(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function m(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?h(Object(t),!0).forEach((function(n){v(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):h(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function v(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function g(e){return e&&e.select&&!/sys/i.test(e.select)?m(m({},e),{},{select:e.select+",sys"}):e}function O(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function j(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?O(Object(t),!0).forEach((function(n){w(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):O(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function w(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function P(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function I(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function T(e){var t=e.httpClientParams,n=t.hostUpload,r=t.defaultHostnameUpload;return e.cloneWithNewParams({host:n||r})}function S(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],0<=t.indexOf(n)||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],!(0<=t.indexOf(n))&&Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function A(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function E(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?A(Object(t),!0).forEach((function(n){M(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):A(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function M(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function k(e){return(k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function x(e,t){return!t||"object"!==k(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function D(e){var t="function"==typeof Map?new Map:void 0;return(D=function(e){function n(){return C(e,arguments,R(this).constructor)}if(null===e||!function(e){return-1!==Function.toString.call(e).indexOf("[native code]")}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),F(n,e)})(e)}function C(){return(C=z()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&F(o,n.prototype),o}).apply(null,arguments)}function z(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function F(e,t){return(F=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function R(e){return(R=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function U(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function q(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?U(Object(t),!0).forEach((function(n){W(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):U(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function W(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function B(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?_(Object(t),!0).forEach((function(n){L(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):_(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function L(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function N(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function K(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?N(Object(t),!0).forEach((function(n){V(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):N(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function V(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function H(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function X(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?H(Object(t),!0).forEach((function(n){G(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):H(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function G(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function J(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function $(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?J(Object(t),!0).forEach((function(n){Q(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):J(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Q(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Y(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Z(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?Y(Object(t),!0).forEach((function(n){ee(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):Y(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function ee(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function te(e,t,n,r,o,i,a){try{var c=e[i](a),u=c.value}catch(e){return void n(e)}c.done?t(u):Promise.resolve(u).then(r,o)}function ne(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function re(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?ne(Object(t),!0).forEach((function(n){oe(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ne(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function oe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function ae(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?ie(Object(t),!0).forEach((function(n){ce(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ie(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function ce(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ue(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function se(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?ue(Object(t),!0).forEach((function(n){pe(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ue(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function pe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function le(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?fe(Object(t),!0).forEach((function(n){de(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):fe(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function de(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ye(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function be(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?ye(Object(t),!0).forEach((function(n){he(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ye(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function he(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function me(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function ve(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?me(Object(t),!0).forEach((function(n){ge(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):me(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function ge(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Oe(){console.warn("The user attribute in the space membership root is deprecated. The attribute has been moved inside the sys object (i.e. sys.user)")}function je(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],0<=t.indexOf(n)||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],!(0<=t.indexOf(n))&&Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function we(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Pe(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?we(Object(t),!0).forEach((function(n){Ie(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):we(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Ie(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Te(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],0<=t.indexOf(n)||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],!(0<=t.indexOf(n))&&Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function Se(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Ae(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?Se(Object(t),!0).forEach((function(n){Ee(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):Se(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Ee(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Me(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function ke(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?Me(Object(t),!0).forEach((function(n){xe(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):Me(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function xe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function De(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Ce(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?De(Object(t),!0).forEach((function(n){ze(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):De(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function ze(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Fe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Re(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?Fe(Object(t),!0).forEach((function(n){Ue(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):Fe(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Ue(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function qe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function We(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?qe(Object(t),!0).forEach((function(n){_e(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):qe(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function _e(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Be(e,t,n,r,o,i,a){try{var c=e[i](a),u=c.value}catch(e){return void n(e)}c.done?t(u):Promise.resolve(u).then(r,o)}function Le(e,t,n,r,o,i,a){try{var c=e[i](a),u=c.value}catch(e){return void n(e)}c.done?t(u):Promise.resolve(u).then(r,o)}function Ne(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Ke(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?Ne(Object(t),!0).forEach((function(n){Ve(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):Ne(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Ve(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function He(e,t){for(var n,r=0;r<t.length;r++)(n=t[r]).enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}function Xe(e){return"apiAdapter"in e?e.apiAdapter:new fu(e)}function Ge(e,t){return Object.keys(t).reduce((function(e,n){return Object.defineProperty(e,n,{enumerable:!1,configurable:!0,writable:!1,value:t[n]}),e}),e)}function Je(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){var t,n;return{spaceId:null!==(t=null===(n=e.sys.space)||void 0===n?void 0:n.sys.id)&&void 0!==t?t:"",apiKeyId:e.sys.id}};return{update:function(){return e({entityType:"ApiKey",action:"update",params:t(this),payload:this,headers:{}}).then((function(t){return Je(e,t)}))},delete:function(){return e({entityType:"ApiKey",action:"delete",params:t(this)})}}}(e));return Object(Zr.c)(n)}function $e(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{organizationId:e.sys.organization.sys.id,appDefinitionId:e.sys.appDefinition.sys.id,appBundleId:e.sys.id}};return{delete:function(){var n=this.toPlainObject();return e({entityType:"AppBundle",action:"delete",params:t(n)})}}}(e));return Object(Zr.c)(n)}function Qe(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=ns.appBundle,n=t.wrapAppBundle,r=t.wrapAppBundleCollection,o=function(e){return{appDefinitionId:e.sys.id,organizationId:e.sys.organization.sys.id}};return{update:function(){var t=this.toPlainObject();return e({entityType:"AppDefinition",action:"update",params:o(t),headers:{},payload:t}).then((function(t){return Qe(e,t)}))},delete:function(){var t=this.toPlainObject();return e({entityType:"AppDefinition",action:"delete",params:o(t)})},getAppBundle:function(t){var r=this.toPlainObject();return e({entityType:"AppBundle",action:"get",params:{appBundleId:t,appDefinitionId:r.sys.id,organizationId:r.sys.organization.sys.id}}).then((function(t){return n(e,t)}))},getAppBundles:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"AppBundle",action:"getMany",params:{organizationId:n.sys.organization.sys.id,appDefinitionId:n.sys.id,query:t}}).then((function(t){return r(e,t)}))},createAppBundle:function(t){var r=this.toPlainObject();return e({entityType:"AppBundle",action:"create",params:{appDefinitionId:r.sys.id,organizationId:r.sys.organization.sys.id},payload:t}).then((function(t){return n(e,t)}))}}}(e));return Object(Zr.c)(n)}function Ye(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{spaceId:e.sys.space.sys.id,environmentId:e.sys.environment.sys.id,appDefinitionId:e.sys.appDefinition.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"AppInstallation",action:"upsert",params:t(n),headers:{},payload:n}).then((function(t){return Ye(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"AppInstallation",action:"delete",params:t(n)})}}}(e));return Object(Zr.c)(n)}function Ze(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{organizationId:e.sys.organization.sys.id,appUploadId:e.sys.id}};return{delete:function(){var n=this.toPlainObject();return e({entityType:"AppUpload",action:"delete",params:t(n)})}}}(e));return Object(Zr.c)(n)}function et(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function tt(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?et(Object(t),!0).forEach((function(n){nt(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):et(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function nt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function rt(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{spaceId:e.sys.space.sys.id,environmentId:e.sys.environment.sys.id,assetId:e.sys.id}};return{processForLocale:function(n,r){var o=this.toPlainObject();return e({entityType:"Asset",action:"processForLocale",params:tt(tt({},t(o)),{},{locale:n,options:r,asset:o})}).then((function(t){return rt(e,t)}))},processForAllLocales:function(n){var r=this.toPlainObject();return e({entityType:"Asset",action:"processForAllLocales",params:tt(tt({},t(r)),{},{asset:r,options:n})}).then((function(t){return rt(e,t)}))},update:function(){var n=this.toPlainObject();return e({entityType:"Asset",action:"update",params:t(n),payload:n,headers:{}}).then((function(t){return rt(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"Asset",action:"delete",params:t(n)})},publish:function(){var n=this.toPlainObject();return e({entityType:"Asset",action:"publish",params:t(n),payload:n}).then((function(t){return rt(e,t)}))},unpublish:function(){var n=this.toPlainObject();return e({entityType:"Asset",action:"unpublish",params:t(n)}).then((function(t){return rt(e,t)}))},archive:function(){var n=this.toPlainObject();return e({entityType:"Asset",action:"archive",params:t(n)}).then((function(t){return rt(e,t)}))},unarchive:function(){var n=this.toPlainObject();return e({entityType:"Asset",action:"unarchive",params:t(n)}).then((function(t){return rt(e,t)}))},isPublished:function(){var e=this.toPlainObject();return vu(e)},isUpdated:function(){var e=this.toPlainObject();return gu(e)},isDraft:function(){var e=this.toPlainObject();return Ou(e)},isArchived:function(){var e=this.toPlainObject();return ju(e)}}}(e));return Object(Zr.c)(n)}function ot(e,t){return Object(Zr.e)(ro()(t))}function it(e){return new Promise((function(t){return setTimeout(t,e)}))}function at(e){return(at="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function ct(e,t,n,r,o,i,a){try{var c=e[i](a),u=c.value}catch(e){return void n(e)}c.done?t(u):Promise.resolve(u).then(r,o)}function ut(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){function i(e){ct(c,r,o,i,a,"next",e)}function a(e){ct(c,r,o,i,a,"throw",e)}var c=e.apply(t,n);i(void 0)}))}}function st(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function pt(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&ht(e,t)}function ft(e){var t=bt();return function(){var n,r=mt(e);if(t){var o=mt(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return lt(this,n)}}function lt(e,t){return!t||"object"!==at(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function dt(e){var t="function"==typeof Map?new Map:void 0;return(dt=function(e){function n(){return yt(e,arguments,mt(this).constructor)}if(null===e||!function(e){return-1!==Function.toString.call(e).indexOf("[native code]")}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),ht(n,e)})(e)}function yt(){return(yt=bt()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&ht(o,n.prototype),o}).apply(null,arguments)}function bt(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function ht(e,t){return(ht=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function mt(e){return(mt=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function vt(){return gt.apply(this,arguments)}function gt(){return(gt=ut(regeneratorRuntime.mark((function e(t,n){var r,o,i,a,c,u,s,p,f,l,d;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return c=0,u=!1,p=null!==(r=null==n?void 0:n.retryCount)&&void 0!==r?r:Pu,f=null!==(o=null==n?void 0:n.retryIntervalMs)&&void 0!==o?o:Tu,l=null!==(i=null==n?void 0:n.initialDelayMs)&&void 0!==i?i:Iu,d=null===(a=null==n?void 0:n.throwOnFailedExecution)||void 0===a||a,e.next=8,it(l);case 8:if(!(c<p)||u){e.next=22;break}return e.next=11,t();case 11:if(!(s=e.sent)||![Yr.succeeded,Yr.failed].includes(s.sys.status)){e.next=17;break}if(u=!0,s.sys.status!==Yr.failed||!d){e.next=16;break}throw new Au("BulkAction failed to execute.",s);case 16:return e.abrupt("return",s);case 17:return e.next=19,it(f);case 19:c+=1,e.next=8;break;case 22:throw new Su("BulkAction didn't finish processing within the expected timeframe.",s);case 23:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Ot(e,t,n,r,o,i,a){try{var c=e[i](a),u=c.value}catch(e){return void n(e)}c.done?t(u):Promise.resolve(u).then(r,o)}function jt(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){function i(e){Ot(c,r,o,i,a,"next",e)}function a(e){Ot(c,r,o,i,a,"throw",e)}var c=e.apply(t,n);i(void 0)}))}}function wt(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){var t=e.toPlainObject();return{spaceId:t.sys.space.sys.id,environmentId:t.sys.environment.sys.id,bulkActionId:t.sys.id}};return{get:function(){var n=this;return jt(regeneratorRuntime.mark((function r(){var o;return regeneratorRuntime.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return o=t(n),r.abrupt("return",e({entityType:"BulkAction",action:"get",params:o}).then((function(t){return wt(e,t)})));case 2:case"end":return r.stop()}}),r)})))()},waitProcessing:function(e){var t=this;return jt(regeneratorRuntime.mark((function n(){return regeneratorRuntime.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.abrupt("return",vt(jt(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.get());case 1:case"end":return e.stop()}}),e)}))),e));case 1:case"end":return n.stop()}}),n)})))()}}}(e));return Object(Zr.c)(n)}function Pt(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){return{update:function(){var t=this,n=t.toPlainObject();return e({entityType:"EditorInterface",action:"update",params:{spaceId:t.sys.space.sys.id,environmentId:t.sys.environment.sys.id,contentTypeId:t.sys.contentType.sys.id},payload:n}).then((function(t){return Pt(e,t)}))},getControlForField:function(e){var t=(this.controls||[]).filter((function(t){return t.fieldId===e}));return t&&0<t.length?t[0]:null}}}(e));return Object(Zr.c)(n)}function It(e,t){var n=Ge(Object(Zr.e)(ro()(t)),{});return Object(Zr.c)(n)}function Tt(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],0<=t.indexOf(n)||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],!(0<=t.indexOf(n))&&Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function St(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function At(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?St(Object(t),!0).forEach((function(n){Et(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):St(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Et(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Mt(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){var t=e.toPlainObject();return{raw:t,params:{spaceId:t.sys.space.sys.id,environmentId:t.sys.environment.sys.id,contentTypeId:t.sys.id}}};return{update:function(){var n=t(this),r=n.raw,o=n.params;return e({entityType:"ContentType",action:"update",params:o,payload:r}).then((function(t){return Mt(e,t)}))},delete:function(){var n=t(this).params;return e({entityType:"ContentType",action:"delete",params:n}).then((function(){}))},publish:function(){var n=t(this),r=n.raw,o=n.params;return e({entityType:"ContentType",action:"publish",params:o,payload:r}).then((function(t){return Mt(e,t)}))},unpublish:function(){var n=t(this).params;return e({entityType:"ContentType",action:"unpublish",params:n}).then((function(t){return Mt(e,t)}))},getEditorInterface:function(){var n=t(this).params;return e({entityType:"EditorInterface",action:"get",params:n}).then((function(t){return Pt(e,t)}))},getSnapshots:function(){var n=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},r=t(this),o=r.params;return e({entityType:"Snapshot",action:"getManyForContentType",params:At(At({},o),{},{query:n})}).then((function(t){return ku(e,t)}))},getSnapshot:function(n){var r=t(this).params;return e({entityType:"Snapshot",action:"getForContentType",params:At(At({},r),{},{snapshotId:n})}).then((function(e){return It(0,e)}))},isPublished:function(){return vu(this)},isUpdated:function(){return gu(this)},isDraft:function(){return Ou(this)},omitAndDeleteField:function(n){var r=t(this),o=r.raw,i=r.params;return Du(e,At(At({},i),{},{fieldId:n}),o).then((function(t){return Mt(e,t)}))}}}(e));return Object(Zr.c)(n)}function kt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function xt(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?kt(Object(t),!0).forEach((function(n){Dt(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):kt(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Dt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ct(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=ns.entry,n=t.wrapEntry,r=t.wrapEntryCollection,o=ns.snapshot,i=o.wrapSnapshot,a=o.wrapSnapshotCollection,c=ns.task,u=c.wrapTask,s=c.wrapTaskCollection,p=function(e){var t=e.toPlainObject();return{params:{spaceId:t.sys.space.sys.id,environmentId:t.sys.environment.sys.id,entryId:t.sys.id},raw:t}};return{update:function(){var t=p(this),r=t.raw,o=t.params;return e({entityType:"Entry",action:"update",params:o,payload:r}).then((function(t){return n(e,t)}))},patch:function(t){var r=p(this),o=r.raw,i=r.params;return e({entityType:"Entry",action:"patch",params:xt(xt({},i),{},{version:o.sys.version}),payload:t}).then((function(t){return n(e,t)}))},delete:function(){var t=p(this).params;return e({entityType:"Entry",action:"delete",params:t})},publish:function(){var t=p(this),r=t.raw,o=t.params;return e({entityType:"Entry",action:"publish",params:o,payload:r}).then((function(t){return n(e,t)}))},unpublish:function(){var t=p(this).params;return e({entityType:"Entry",action:"unpublish",params:t}).then((function(t){return n(e,t)}))},archive:function(){var t=p(this).params;return e({entityType:"Entry",action:"archive",params:t}).then((function(t){return n(e,t)}))},unarchive:function(){var t=p(this).params;return e({entityType:"Entry",action:"unarchive",params:t}).then((function(t){return n(e,t)}))},getSnapshots:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=p(this),r=n.params;return e({entityType:"Snapshot",action:"getManyForEntry",params:xt(xt({},r),{},{query:t})}).then((function(t){return a(e,t)}))},getSnapshot:function(t){var n=p(this).params;return e({entityType:"Snapshot",action:"getForEntry",params:xt(xt({},n),{},{snapshotId:t})}).then((function(t){return i(e,t)}))},createTask:function(t){var n=p(this).params;return e({entityType:"Task",action:"create",params:n,payload:t}).then((function(t){return u(e,t)}))},getTasks:function(){var t=p(this).params;return e({entityType:"Task",action:"getAll",params:t}).then((function(t){return s(e,t)}))},getTask:function(t){var n=p(this).params;return e({entityType:"Task",action:"get",params:xt(xt({},n),{},{taskId:t})}).then((function(t){return u(e,t)}))},isPublished:function(){var e=this.toPlainObject();return vu(e)},isUpdated:function(){var e=this.toPlainObject();return gu(e)},isDraft:function(){var e=this.toPlainObject();return Ou(e)},isArchived:function(){var e=this.toPlainObject();return ju(e)},references:function(t){var n=this.toPlainObject();return e({entityType:"Entry",action:"references",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.environment.sys.id,entryId:n.sys.id,maxDepth:null==t?void 0:t.maxDepth}}).then((function(t){return r(e,t)}))}}}(e));return Object(Zr.c)(n)}function zt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Ft(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?zt(Object(t),!0).forEach((function(n){Rt(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):zt(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Rt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ut(e){var t=function(e){return{spaceId:e.sys.space.sys.id,environmentId:e.sys.environment.sys.id,tagId:e.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"Tag",action:"update",params:t(n),payload:n}).then((function(t){return qt(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"Tag",action:"delete",params:Ft(Ft({},t(n)),{},{version:n.sys.version})}).then((function(){}))}}}function qt(e,t){var n=Ge(Object(Zr.e)(ro()(t)),Ut(e));return Object(Zr.c)(n)}function Wt(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=ns.environment.wrapEnvironment,n=ns.contentType,r=n.wrapContentType,o=n.wrapContentTypeCollection,i=ns.entry,a=i.wrapEntry,c=i.wrapEntryCollection,u=ns.asset,s=u.wrapAsset,p=u.wrapAssetCollection,f=ns.assetKey.wrapAssetKey,l=ns.locale,d=l.wrapLocale,y=l.wrapLocaleCollection,b=ns.snapshot.wrapSnapshotCollection,h=ns.editorInterface,m=h.wrapEditorInterface,v=h.wrapEditorInterfaceCollection,g=ns.upload.wrapUpload,O=ns.extension,j=O.wrapExtension,w=O.wrapExtensionCollection,P=ns.appInstallation,I=P.wrapAppInstallation,T=P.wrapAppInstallationCollection,S=ns.bulkAction.wrapBulkAction;return{delete:function(){var t=this.toPlainObject();return e({entityType:"Environment",action:"delete",params:{spaceId:t.sys.space.sys.id,environmentId:t.sys.id}}).then((function(){}))},update:function(){var n=this.toPlainObject();return e({entityType:"Environment",action:"update",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id},payload:n}).then((function(n){return t(e,n)}))},getEntryFromData:function(t){return a(e,t)},getAssetFromData:function(t){return s(e,t)},getBulkAction:function(t){var n=this.toPlainObject();return e({entityType:"BulkAction",action:"get",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,bulkActionId:t}}).then((function(t){return S(e,t)}))},createPublishBulkAction:function(t){var n=this.toPlainObject();return e({entityType:"BulkAction",action:"publish",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id},payload:t}).then((function(t){return S(e,t)}))},createValidateBulkAction:function(t){var n=this.toPlainObject();return e({entityType:"BulkAction",action:"validate",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id},payload:t}).then((function(t){return S(e,t)}))},createUnpublishBulkAction:function(t){var n=this.toPlainObject();return e({entityType:"BulkAction",action:"unpublish",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id},payload:t}).then((function(t){return S(e,t)}))},getContentType:function(t){var n=this.toPlainObject();return e({entityType:"ContentType",action:"get",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,contentTypeId:t}}).then((function(t){return r(e,t)}))},getContentTypes:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"ContentType",action:"getMany",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return o(e,t)}))},createContentType:function(t){var n=this.toPlainObject();return e({entityType:"ContentType",action:"create",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id},payload:t}).then((function(t){return r(e,t)}))},createContentTypeWithId:function(t,n){var o=this.toPlainObject();return e({entityType:"ContentType",action:"createWithId",params:{spaceId:o.sys.space.sys.id,environmentId:o.sys.id,contentTypeId:t},payload:n}).then((function(t){return r(e,t)}))},getEditorInterfaceForContentType:function(t){var n=this.toPlainObject();return e({entityType:"EditorInterface",action:"get",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,contentTypeId:t}}).then((function(t){return m(e,t)}))},getEditorInterfaces:function(){var t=this.toPlainObject();return e({entityType:"EditorInterface",action:"getMany",params:{spaceId:t.sys.space.sys.id,environmentId:t.sys.id}}).then((function(t){return v(e,t)}))},getEntry:function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r=this.toPlainObject();return e({entityType:"Entry",action:"get",params:{spaceId:r.sys.space.sys.id,environmentId:r.sys.id,entryId:t,query:Object(Zr.b)({query:n}).params}}).then((function(t){return a(e,t)}))},deleteEntry:function(t){var n=this.toPlainObject();return e({entityType:"Entry",action:"delete",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,entryId:t}}).then((function(){}))},getEntries:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"Entry",action:"getMany",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return c(e,t)}))},createEntry:function(t,n){var r=this.toPlainObject();return e({entityType:"Entry",action:"create",params:{spaceId:r.sys.space.sys.id,environmentId:r.sys.id,contentTypeId:t},payload:n}).then((function(t){return a(e,t)}))},createEntryWithId:function(t,n,r){var o=this.toPlainObject();return e({entityType:"Entry",action:"createWithId",params:{spaceId:o.sys.space.sys.id,environmentId:o.sys.id,entryId:n,contentTypeId:t},payload:r}).then((function(t){return a(e,t)}))},getEntryReferences:function(t,n){var r=this.toPlainObject();return e({entityType:"Entry",action:"references",params:{spaceId:r.sys.space.sys.id,environmentId:r.sys.id,entryId:t,maxDepth:null==n?void 0:n.maxDepth}}).then((function(t){return c(e,t)}))},getAsset:function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r=this.toPlainObject();return e({entityType:"Asset",action:"get",params:{spaceId:r.sys.space.sys.id,environmentId:r.sys.id,assetId:t,query:Object(Zr.b)({query:n}).params}}).then((function(t){return s(e,t)}))},getAssets:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"Asset",action:"getMany",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return p(e,t)}))},createAsset:function(t){var n=this.toPlainObject();return e({entityType:"Asset",action:"create",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id},payload:t}).then((function(t){return s(e,t)}))},createAssetWithId:function(t,n){var r=this.toPlainObject();return e({entityType:"Asset",action:"createWithId",params:{spaceId:r.sys.space.sys.id,environmentId:r.sys.id,assetId:t},payload:n}).then((function(t){return s(e,t)}))},createAssetFromFiles:function(t){var n=this.toPlainObject();return e({entityType:"Asset",action:"createFromFiles",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id},payload:t}).then((function(t){return s(e,t)}))},createAssetKey:function(t){var n=this.toPlainObject();return e({entityType:"AssetKey",action:"create",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id},payload:t}).then((function(t){return f(e,t)}))},getUpload:function(t){var n=this.toPlainObject();return e({entityType:"Upload",action:"get",params:{spaceId:n.sys.space.sys.id,uploadId:t}}).then((function(t){return g(e,t)}))},createUpload:function(t){var n=this.toPlainObject();return e({entityType:"Upload",action:"create",params:{spaceId:n.sys.space.sys.id},payload:t}).then((function(t){return g(e,t)}))},getLocale:function(t){var n=this.toPlainObject();return e({entityType:"Locale",action:"get",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,localeId:t}}).then((function(t){return d(e,t)}))},getLocales:function(){var t=this.toPlainObject();return e({entityType:"Locale",action:"getMany",params:{spaceId:t.sys.space.sys.id,environmentId:t.sys.id}}).then((function(t){return y(e,t)}))},createLocale:function(t){var n=this.toPlainObject();return e({entityType:"Locale",action:"create",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id},payload:t}).then((function(t){return d(e,t)}))},getUiExtension:function(t){var n=this.toPlainObject();return e({entityType:"Extension",action:"get",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,extensionId:t}}).then((function(t){return j(e,t)}))},getUiExtensions:function(){var t=this.toPlainObject();return e({entityType:"Extension",action:"getMany",params:{spaceId:t.sys.space.sys.id,environmentId:t.sys.id}}).then((function(t){return w(e,t)}))},createUiExtension:function(t){var n=this.toPlainObject();return e({entityType:"Extension",action:"create",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id},payload:t}).then((function(t){return j(e,t)}))},createUiExtensionWithId:function(t,n){var r=this.toPlainObject();return e({entityType:"Extension",action:"createWithId",params:{spaceId:r.sys.space.sys.id,environmentId:r.sys.id,extensionId:t},payload:n}).then((function(t){return j(e,t)}))},createAppInstallation:function(t,n){var r=this.toPlainObject();return e({entityType:"AppInstallation",action:"upsert",params:{spaceId:r.sys.space.sys.id,environmentId:r.sys.id,appDefinitionId:t},payload:n}).then((function(t){return I(e,t)}))},getAppInstallation:function(t){var n=this.toPlainObject();return e({entityType:"AppInstallation",action:"get",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,appDefinitionId:t}}).then((function(t){return I(e,t)}))},getAppInstallations:function(){var t=this.toPlainObject();return e({entityType:"AppInstallation",action:"getMany",params:{spaceId:t.sys.space.sys.id,environmentId:t.sys.id}}).then((function(t){return T(e,t)}))},getEntrySnapshots:function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r=this.toPlainObject();return e({entityType:"Snapshot",action:"getManyForEntry",params:{spaceId:r.sys.space.sys.id,environmentId:r.sys.id,entryId:t,query:n}}).then((function(t){return b(e,t)}))},getContentTypeSnapshots:function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r=this.toPlainObject();return e({entityType:"Snapshot",action:"getManyForContentType",params:{spaceId:r.sys.space.sys.id,environmentId:r.sys.id,contentTypeId:t,query:n}}).then((function(t){return b(e,t)}))},createTag:function(t,n,r){var o=this.toPlainObject();return e({entityType:"Tag",action:"createWithId",params:{spaceId:o.sys.space.sys.id,environmentId:o.sys.id,tagId:t},payload:{name:n,sys:{visibility:null!=r?r:"private"}}}).then((function(t){return qt(e,t)}))},getTags:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"Tag",action:"getMany",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return Fu(e,t)}))},getTag:function(t){var n=this.toPlainObject();return e({entityType:"Tag",action:"get",params:{spaceId:n.sys.space.sys.id,environmentId:n.sys.id,tagId:t}}).then((function(t){return qt(e,t)}))}}}(e));return Object(Zr.c)(n)}function _t(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{spaceId:e.sys.space.sys.id,environmentAliasId:e.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"EnvironmentAlias",action:"update",params:t(n),payload:n}).then((function(t){return _t(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"EnvironmentAlias",action:"delete",params:t(n)}).then((function(){}))}}}(e));return Object(Zr.c)(n)}function Bt(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{spaceId:e.sys.space.sys.id,environmentId:e.sys.environment.sys.id,extensionId:e.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"Extension",action:"update",params:t(n),payload:n}).then((function(t){return Bt(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"Extension",action:"delete",params:t(n)})}}}(e));return Object(Zr.c)(n)}function Lt(e,t){delete t.internal_code;var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{spaceId:e.sys.space.sys.id,environmentId:e.sys.environment.sys.id,localeId:e.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"Locale",action:"update",params:t(n),payload:n}).then((function(t){return Lt(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"Locale",action:"delete",params:t(n)}).then((function(){}))}}}(e));return Object(Zr.c)(n)}function Nt(e,t){var n=Object(Zr.e)(ro()(t)),r=function(e){var t=ns.appDefinition,n=t.wrapAppDefinition,r=t.wrapAppDefinitionCollection,o=ns.user,i=o.wrapUser,a=o.wrapUserCollection,c=ns.organizationMembership,u=c.wrapOrganizationMembership,s=c.wrapOrganizationMembershipCollection,p=ns.teamMembership,f=p.wrapTeamMembership,l=p.wrapTeamMembershipCollection,d=ns.teamSpaceMembership,y=d.wrapTeamSpaceMembership,b=d.wrapTeamSpaceMembershipCollection,h=ns.team,m=h.wrapTeam,v=h.wrapTeamCollection,g=ns.spaceMembership,O=g.wrapSpaceMembership,j=g.wrapSpaceMembershipCollection,w=ns.organizationInvitation.wrapOrganizationInvitation,P=ns.appUpload.wrapAppUpload;return{getUser:function(t){var n=this.toPlainObject();return e({entityType:"User",action:"getForOrganization",params:{organizationId:n.sys.id,userId:t}}).then((function(t){return i(e,t)}))},getUsers:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"User",action:"getManyForOrganization",params:{organizationId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return a(e,t)}))},getOrganizationMembership:function(t){var n=this.toPlainObject().sys.id;return e({entityType:"OrganizationMembership",action:"get",params:{organizationId:n,organizationMembershipId:t}}).then((function(t){return u(e,t,n)}))},getOrganizationMemberships:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject(),r=n.sys.id;return e({entityType:"OrganizationMembership",action:"getMany",params:{organizationId:r,query:Object(Zr.b)({query:t}).params}}).then((function(t){return s(e,t,r)}))},createTeam:function(t){var n=this.toPlainObject();return e({entityType:"Team",action:"create",params:{organizationId:n.sys.id},payload:t}).then((function(t){return m(e,t)}))},getTeam:function(t){var n=this.toPlainObject();return e({entityType:"Team",action:"get",params:{organizationId:n.sys.id,teamId:t}}).then((function(t){return m(e,t)}))},getTeams:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"Team",action:"getMany",params:{organizationId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return v(e,t)}))},createTeamMembership:function(t,n){var r=this.toPlainObject();return e({entityType:"TeamMembership",action:"create",params:{organizationId:r.sys.id,teamId:t},payload:n}).then((function(t){return f(e,t)}))},getTeamMembership:function(t,n){var r=this.toPlainObject();return e({entityType:"TeamMembership",action:"get",params:{organizationId:r.sys.id,teamId:t,teamMembershipId:n}}).then((function(t){return f(e,t)}))},getTeamMemberships:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=t.teamId,r=t.query,o=void 0===r?{}:r,i=this.toPlainObject();return n?e({entityType:"TeamMembership",action:"getManyForTeam",params:{organizationId:i.sys.id,teamId:n,query:Object(Zr.b)({query:o}).params}}).then((function(t){return l(e,t)})):e({entityType:"TeamMembership",action:"getManyForOrganization",params:{organizationId:i.sys.id,query:Object(Zr.b)({query:o}).params}}).then((function(t){return l(e,t)}))},getTeamSpaceMemberships:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"TeamSpaceMembership",action:"getManyForOrganization",params:{organizationId:n.sys.id,query:Object(Zr.b)({query:t.query||{}}).params,teamId:t.teamId}}).then((function(t){return b(e,t)}))},getTeamSpaceMembership:function(t){var n=this.toPlainObject();return e({entityType:"TeamSpaceMembership",action:"getForOrganization",params:{organizationId:n.sys.id,teamSpaceMembershipId:t}}).then((function(t){return y(e,t)}))},getOrganizationSpaceMembership:function(t){var n=this.toPlainObject();return e({entityType:"SpaceMembership",action:"getForOrganization",params:{organizationId:n.sys.id,spaceMembershipId:t}}).then((function(t){return O(e,t)}))},getOrganizationSpaceMemberships:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"SpaceMembership",action:"getManyForOrganization",params:{organizationId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return j(e,t)}))},getOrganizationInvitation:function(t){var n=this.toPlainObject();return e({entityType:"OrganizationInvitation",action:"get",params:{organizationId:n.sys.id,invitationId:t}}).then((function(t){return w(e,t)}))},createOrganizationInvitation:function(t){var n=this.toPlainObject();return e({entityType:"OrganizationInvitation",action:"create",params:{organizationId:n.sys.id},payload:t}).then((function(t){return w(e,t)}))},createAppDefinition:function(t){var r=this.toPlainObject();return e({entityType:"AppDefinition",action:"create",params:{organizationId:r.sys.id},payload:t}).then((function(t){return n(e,t)}))},getAppDefinitions:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"AppDefinition",action:"getMany",params:{organizationId:n.sys.id,query:t}}).then((function(t){return r(e,t)}))},getAppDefinition:function(t){var r=this.toPlainObject();return e({entityType:"AppDefinition",action:"get",params:{organizationId:r.sys.id,appDefinitionId:t}}).then((function(t){return n(e,t)}))},getAppUpload:function(t){var n=this.toPlainObject();return e({entityType:"AppUpload",action:"get",params:{organizationId:n.sys.id,appUploadId:t}}).then((function(t){return P(e,t)}))},createAppUpload:function(t){var n=this.toPlainObject();return e({entityType:"AppUpload",action:"create",params:{organizationId:n.sys.id},payload:{file:t}}).then((function(t){return P(e,t)}))}}}(e),o=Ge(n,r);return Object(Zr.c)(o)}function Kt(e,t){var n=Object(Zr.e)(ro()(t));return Object(Zr.c)(n)}function Vt(e,t,n){var r=Ge(Object(Zr.e)(ro()(t)),function(e,t){var n=function(e){return{organizationMembershipId:e.sys.id,organizationId:t}};return{update:function(){var r=this.toPlainObject();return e({entityType:"OrganizationMembership",action:"update",params:n(r),payload:r}).then((function(n){return Vt(e,n,t)}))},delete:function(){var t=this.toPlainObject();return e({entityType:"OrganizationMembership",action:"delete",params:n(t)})}}}(e,n));return Object(Zr.c)(r)}function Ht(e,t){var n=Ge(Object(Zr.e)(ro()(t)),{revoke:function(){return e({entityType:"PersonalAccessToken",action:"revoke",params:{tokenId:t.sys.id}}).then((function(t){return Ht(e,t)}))}});return Object(Zr.c)(n)}function Xt(e,t){var n=Ge(Object(Zr.e)(ro()(t)),{});return Object(Zr.c)(n)}function Gt(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{spaceId:e.sys.space.sys.id,roleId:e.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"Role",action:"update",params:t(n),payload:n}).then((function(t){return Gt(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"Role",action:"delete",params:t(n)})}}}(e));return Object(Zr.c)(n)}function Jt(e){return function(){var t=this.toPlainObject();return e({entityType:"ScheduledAction",action:"delete",params:{spaceId:t.sys.space.sys.id,scheduledActionId:t.sys.id}}).then((function(t){return Qt(e,t)}))}}function $t(e){return{delete:Jt(e)}}function Qt(e,t){var n=Ge(Object(Zr.e)(ro()(t)),$t(e));return Object(Zr.c)(n)}function Yt(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=ns.space.wrapSpace,n=ns.environment,r=n.wrapEnvironment,o=n.wrapEnvironmentCollection,i=ns.webhook,a=i.wrapWebhook,c=i.wrapWebhookCollection,u=ns.role,s=u.wrapRole,p=u.wrapRoleCollection,f=ns.user,l=f.wrapUser,d=f.wrapUserCollection,y=ns.spaceMember,b=y.wrapSpaceMember,h=y.wrapSpaceMemberCollection,m=ns.spaceMembership,v=m.wrapSpaceMembership,g=m.wrapSpaceMembershipCollection,O=ns.teamSpaceMembership,j=O.wrapTeamSpaceMembership,w=O.wrapTeamSpaceMembershipCollection,P=ns.apiKey,I=P.wrapApiKey,T=P.wrapApiKeyCollection,S=ns.environmentAlias,A=S.wrapEnvironmentAlias,E=S.wrapEnvironmentAliasCollection,M=ns.previewApiKey,k=M.wrapPreviewApiKey,x=M.wrapPreviewApiKeyCollection,D=ns.scheduledAction,C=D.wrapScheduledAction,z=D.wrapScheduledActionCollection;return{delete:function(){var t=this.toPlainObject();return e({entityType:"Space",action:"delete",params:{spaceId:t.sys.id}})},update:function(){var n=this.toPlainObject();return e({entityType:"Space",action:"update",params:{spaceId:n.sys.id},payload:n,headers:{}}).then((function(n){return t(e,n)}))},getEnvironment:function(t){var n=this.toPlainObject();return e({entityType:"Environment",action:"get",params:{spaceId:n.sys.id,environmentId:t}}).then((function(t){return r(e,t)}))},getEnvironments:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"Environment",action:"getMany",params:{spaceId:n.sys.id,query:t}}).then((function(t){return o(e,t)}))},createEnvironment:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"Environment",action:"create",params:{spaceId:n.sys.id},payload:t}).then((function(t){return r(e,t)}))},createEnvironmentWithId:function(t,n,o){var i=this.toPlainObject();return e({entityType:"Environment",action:"createWithId",params:{spaceId:i.sys.id,environmentId:t,sourceEnvironmentId:o},payload:n}).then((function(t){return r(e,t)}))},getWebhook:function(t){var n=this.toPlainObject();return e({entityType:"Webhook",action:"get",params:{spaceId:n.sys.id,webhookDefinitionId:t}}).then((function(t){return a(e,t)}))},getWebhooks:function(){var t=this.toPlainObject();return e({entityType:"Webhook",action:"getMany",params:{spaceId:t.sys.id}}).then((function(t){return c(e,t)}))},createWebhook:function(t){var n=this.toPlainObject();return e({entityType:"Webhook",action:"create",params:{spaceId:n.sys.id},payload:t}).then((function(t){return a(e,t)}))},createWebhookWithId:function(t,n){var r=this.toPlainObject();return e({entityType:"Webhook",action:"createWithId",params:{spaceId:r.sys.id,webhookDefinitionId:t},payload:n}).then((function(t){return a(e,t)}))},getRole:function(t){var n=this.toPlainObject();return e({entityType:"Role",action:"get",params:{spaceId:n.sys.id,roleId:t}}).then((function(t){return s(e,t)}))},getRoles:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"Role",action:"getMany",params:{spaceId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return p(e,t)}))},createRole:function(t){var n=this.toPlainObject();return e({entityType:"Role",action:"create",params:{spaceId:n.sys.id},payload:t}).then((function(t){return s(e,t)}))},createRoleWithId:function(t,n){var r=this.toPlainObject();return e({entityType:"Role",action:"createWithId",params:{spaceId:r.sys.id,roleId:t},payload:n}).then((function(t){return s(e,t)}))},getSpaceUser:function(t){var n=this.toPlainObject();return e({entityType:"User",action:"getForSpace",params:{spaceId:n.sys.id,userId:t}}).then((function(t){return l(e,t)}))},getSpaceUsers:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"User",action:"getManyForSpace",params:{spaceId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return d(e,t)}))},getSpaceMember:function(t){var n=this.toPlainObject();return e({entityType:"SpaceMember",action:"get",params:{spaceId:n.sys.id,spaceMemberId:t}}).then((function(t){return b(e,t)}))},getSpaceMembers:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"SpaceMember",action:"getMany",params:{spaceId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return h(e,t)}))},getSpaceMembership:function(t){var n=this.toPlainObject();return e({entityType:"SpaceMembership",action:"get",params:{spaceId:n.sys.id,spaceMembershipId:t}}).then((function(t){return v(e,t)}))},getSpaceMemberships:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"SpaceMembership",action:"getMany",params:{spaceId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return g(e,t)}))},createSpaceMembership:function(t){var n=this.toPlainObject();return e({entityType:"SpaceMembership",action:"create",params:{spaceId:n.sys.id},payload:t}).then((function(t){return v(e,t)}))},createSpaceMembershipWithId:function(t,n){var r=this.toPlainObject();return e({entityType:"SpaceMembership",action:"createWithId",params:{spaceId:r.sys.id,spaceMembershipId:t},payload:n}).then((function(t){return v(e,t)}))},getTeamSpaceMembership:function(t){var n=this.toPlainObject();return e({entityType:"TeamSpaceMembership",action:"get",params:{spaceId:n.sys.id,teamSpaceMembershipId:t}}).then((function(t){return j(e,t)}))},getTeamSpaceMemberships:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=this.toPlainObject();return e({entityType:"TeamSpaceMembership",action:"getMany",params:{spaceId:n.sys.id,query:Object(Zr.b)({query:t}).params}}).then((function(t){return w(e,t)}))},createTeamSpaceMembership:function(t,n){var r=this.toPlainObject();return e({entityType:"TeamSpaceMembership",action:"create",params:{spaceId:r.sys.id,teamId:t},payload:n}).then((function(t){return j(e,t)}))},getApiKey:function(t){var n=this.toPlainObject();return e({entityType:"ApiKey",action:"get",params:{spaceId:n.sys.id,apiKeyId:t}}).then((function(t){return I(e,t)}))},getApiKeys:function(){var t=this.toPlainObject();return e({entityType:"ApiKey",action:"getMany",params:{spaceId:t.sys.id}}).then((function(t){return T(e,t)}))},getPreviewApiKeys:function(){var t=this.toPlainObject();return e({entityType:"PreviewApiKey",action:"getMany",params:{spaceId:t.sys.id}}).then((function(t){return x(e,t)}))},getPreviewApiKey:function(t){var n=this.toPlainObject();return e({entityType:"PreviewApiKey",action:"get",params:{spaceId:n.sys.id,previewApiKeyId:t}}).then((function(t){return k(e,t)}))},createApiKey:function(t){var n=this.toPlainObject();return e({entityType:"ApiKey",action:"create",params:{spaceId:n.sys.id},payload:t}).then((function(t){return I(e,t)}))},createApiKeyWithId:function(t,n){var r=this.toPlainObject();return e({entityType:"ApiKey",action:"createWithId",params:{spaceId:r.sys.id,apiKeyId:t},payload:n}).then((function(t){return I(e,t)}))},createEnvironmentAliasWithId:function(t,n){var r=this.toPlainObject();return e({entityType:"EnvironmentAlias",action:"createWithId",params:{spaceId:r.sys.id,environmentAliasId:t},payload:n}).then((function(t){return A(e,t)}))},getEnvironmentAlias:function(t){var n=this.toPlainObject();return e({entityType:"EnvironmentAlias",action:"get",params:{spaceId:n.sys.id,environmentAliasId:t}}).then((function(t){return A(e,t)}))},getEnvironmentAliases:function(){var t=this.toPlainObject();return e({entityType:"EnvironmentAlias",action:"getMany",params:{spaceId:t.sys.id}}).then((function(t){return E(e,t)}))},getScheduledActions:function(t){var n=this.toPlainObject();return e({entityType:"ScheduledAction",action:"getMany",params:{spaceId:n.sys.id,query:t}}).then((function(t){return z(e,t)}))},createScheduledAction:function(t){var n=this.toPlainObject();return e({entityType:"ScheduledAction",action:"create",params:{spaceId:n.sys.id},payload:t}).then((function(t){return C(e,t)}))}}}(e));return Object(Zr.c)(n)}function Zt(e,t){var n=Object(Zr.e)(ro()(t));return Object(Zr.c)(n)}function en(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{spaceId:e.sys.space.sys.id,spaceMembershipId:e.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"SpaceMembership",action:"update",params:t(n),payload:n}).then((function(t){return en(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"SpaceMembership",action:"delete",params:t(n)})}}}(e));return Object(Zr.c)(n)}function tn(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{teamId:e.sys.id,organizationId:e.sys.organization.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"Team",action:"update",params:t(n),payload:n}).then((function(t){return tn(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"Team",action:"delete",params:t(n)})}}}(e));return Object(Zr.c)(n)}function nn(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{teamMembershipId:e.sys.id,teamId:e.sys.team.sys.id,organizationId:e.sys.organization.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"TeamMembership",action:"update",params:t(n),payload:n}).then((function(t){return nn(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"TeamMembership",action:"delete",params:t(n)})}}}(e));return Object(Zr.c)(n)}function rn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function on(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?rn(Object(t),!0).forEach((function(n){an(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):rn(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function an(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cn(e){var t=function(e){return{spaceId:e.sys.space.sys.id,environmentId:e.sys.environment.sys.id,entryId:e.sys.parentEntity.sys.id,taskId:e.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"Task",action:"update",params:t(n),payload:n}).then((function(t){return un(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"Task",action:"delete",params:on(on({},t(n)),{},{version:n.sys.version})}).then((function(){}))}}}function un(e,t){var n=Ge(Object(Zr.e)(ro()(t)),cn(e));return Object(Zr.c)(n)}function sn(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{teamSpaceMembershipId:e.sys.id,spaceId:e.sys.space.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"TeamSpaceMembership",action:"update",params:t(n),payload:n}).then((function(t){return sn(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"TeamSpaceMembership",action:"delete",params:t(n)})}}}(e));return Object(Zr.c)(n)}function pn(e,t,n,r,o,i,a){try{var c=e[i](a),u=c.value}catch(e){return void n(e)}c.done?t(u):Promise.resolve(u).then(r,o)}function fn(e){return{delete:function(){var t=function(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){function i(e){pn(c,r,o,i,a,"next",e)}function a(e){pn(c,r,o,i,a,"throw",e)}var c=e.apply(t,n);i(void 0)}))}}(regeneratorRuntime.mark((function t(){var n;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=this.toPlainObject(),t.next=3,e({entityType:"Upload",action:"delete",params:{spaceId:n.sys.space.sys.id,uploadId:n.sys.id}});case 3:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}()}}function ln(e,t){var n=Ge(Object(Zr.e)(ro()(t)),fn(e));return Object(Zr.c)(n)}function dn(e,t){var n=Ge(Object(Zr.e)(ro()(t)),{});return Object(Zr.c)(n)}function yn(e,t){var n=Ge(Object(Zr.e)(ro()(t)),{});return Object(Zr.c)(n)}function bn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function hn(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?bn(Object(t),!0).forEach((function(n){mn(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):bn(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function mn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function vn(e,t){var n=Ge(Object(Zr.e)(ro()(t)),function(e){var t=function(e){return{spaceId:e.sys.space.sys.id,webhookDefinitionId:e.sys.id}};return{update:function(){var n=this.toPlainObject();return e({entityType:"Webhook",action:"update",params:t(n),payload:n}).then((function(t){return vn(e,t)}))},delete:function(){var n=this.toPlainObject();return e({entityType:"Webhook",action:"delete",params:t(n)})},getCalls:function(){var n=this.toPlainObject();return e({entityType:"Webhook",action:"getManyCallDetails",params:t(n)})},getCall:function(n){var r=this.toPlainObject();return e({entityType:"Webhook",action:"getCallDetails",params:hn(hn({},t(r)),{},{callId:n})})},getHealth:function(){var n=this.toPlainObject();return e({entityType:"Webhook",action:"getHealthStatus",params:t(n)})}}}(e));return Object(Zr.c)(n)}function gn(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],0<=t.indexOf(n)||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],!(0<=t.indexOf(n))&&Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function On(e){var t=ns.space,n=t.wrapSpace,r=t.wrapSpaceCollection,o=ns.user.wrapUser,i=ns.personalAccessToken,a=i.wrapPersonalAccessToken,c=i.wrapPersonalAccessTokenCollection,u=ns.organization,s=u.wrapOrganization,p=u.wrapOrganizationCollection,f=ns.usage.wrapUsageCollection;return{getSpaces:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};return e({entityType:"Space",action:"getMany",params:{query:Object(Zr.b)({query:t}).params}}).then((function(t){return r(e,t)}))},getSpace:function(t){return e({entityType:"Space",action:"get",params:{spaceId:t}}).then((function(t){return n(e,t)}))},createSpace:function(t,r){return e({entityType:"Space",action:"create",params:{organizationId:r},payload:t}).then((function(t){return n(e,t)}))},getOrganization:function(t){return e({entityType:"Organization",action:"get",params:{organizationId:t}}).then((function(t){return s(e,t)}))},getOrganizations:function(){return e({entityType:"Organization",action:"getMany"}).then((function(t){return p(e,t)}))},getCurrentUser:function(t){return e({entityType:"User",action:"getCurrent",params:t}).then((function(t){return o(e,t)}))},createPersonalAccessToken:function(t){return e({entityType:"PersonalAccessToken",action:"create",params:{},payload:t}).then((function(t){return a(e,t)}))},getPersonalAccessToken:function(t){return e({entityType:"PersonalAccessToken",action:"get",params:{tokenId:t}}).then((function(t){return a(e,t)}))},getPersonalAccessTokens:function(){return e({entityType:"PersonalAccessToken",action:"getMany",params:{}}).then((function(t){return c(e,t)}))},getOrganizationUsage:function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};return e({entityType:"Usage",action:"getManyForOrganization",params:{organizationId:t,query:n}}).then((function(t){return f(e,t)}))},getSpaceUsage:function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};return e({entityType:"Usage",action:"getManyForSpace",params:{organizationId:t,query:n}}).then((function(t){return f(e,t)}))},rawRequest:function(t){var n=t.url,r=gn(t,["url"]);return e({entityType:"Http",action:"request",params:{url:n,config:r}})}}}function jn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function wn(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?jn(Object(t),!0).forEach((function(n){Pn(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):jn(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Pn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function In(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Tn(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?In(Object(t),!0).forEach((function(n){Sn(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):In(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Sn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function An(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function En(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?An(Object(t),!0).forEach((function(n){Mn(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):An(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Mn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kn(e,t,n,r,o,i,a){try{var c=e[i](a),u=c.value}catch(e){return void n(e)}c.done?t(u):Promise.resolve(u).then(r,o)}function xn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Dn(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?xn(Object(t),!0).forEach((function(n){Cn(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):xn(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}function Cn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function zn(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},n="plain"===t.type?"contentful-management-plain.js":"contentful-management.js",r=Object(Zr.d)("".concat(n,"/").concat("7.19.1"),e.application,e.integration,e.feature),o=Xe(e),i=function(e){return o.makeRequest(Dn(Dn({},e),{},{userAgent:r}))};return"plain"===t.type?os(i,t.defaults):On(i)}r.r(n),r.d(n,"asIterator",(function(){return is})),r.d(n,"isDraft",(function(){return Ou})),r.d(n,"isPublished",(function(){return vu})),r.d(n,"isUpdated",(function(){return gu})),r.d(n,"createClient",(function(){return zn}));var Fn={};r.r(Fn),r.d(Fn,"get",(function(){return ao})),r.d(Fn,"getMany",(function(){return co})),r.d(Fn,"create",(function(){return uo})),r.d(Fn,"createWithId",(function(){return so})),r.d(Fn,"update",(function(){return po})),r.d(Fn,"del",(function(){return fo}));var Rn={};r.r(Rn),r.d(Rn,"get",(function(){return bo})),r.d(Rn,"getMany",(function(){return ho})),r.d(Rn,"del",(function(){return mo})),r.d(Rn,"create",(function(){return vo}));var Un={};r.r(Un),r.d(Un,"getAppDefinitionUrl",(function(){return Oo})),r.d(Un,"get",(function(){return jo})),r.d(Un,"getMany",(function(){return wo})),r.d(Un,"create",(function(){return Po})),r.d(Un,"update",(function(){return Io})),r.d(Un,"del",(function(){return To}));var qn={};r.r(qn),r.d(qn,"getAppInstallationUrl",(function(){return Ao})),r.d(qn,"get",(function(){return Eo})),r.d(qn,"getMany",(function(){return Mo})),r.d(qn,"upsert",(function(){return ko})),r.d(qn,"del",(function(){return xo}));var Wn={};r.r(Wn),r.d(Wn,"get",(function(){return zo})),r.d(Wn,"del",(function(){return Fo})),r.d(Wn,"create",(function(){return Ro}));var _n={};r.r(_n),r.d(_n,"create",(function(){return Uo})),r.d(_n,"del",(function(){return qo})),r.d(_n,"get",(function(){return Wo}));var Bn={};r.r(Bn),r.d(Bn,"get",(function(){return _o})),r.d(Bn,"getMany",(function(){return Bo})),r.d(Bn,"update",(function(){return Lo})),r.d(Bn,"del",(function(){return No})),r.d(Bn,"publish",(function(){return Ko})),r.d(Bn,"unpublish",(function(){return Vo})),r.d(Bn,"archive",(function(){return Ho})),r.d(Bn,"unarchive",(function(){return Xo})),r.d(Bn,"create",(function(){return Go})),r.d(Bn,"createWithId",(function(){return Jo})),r.d(Bn,"createFromFiles",(function(){return $o})),r.d(Bn,"processForLocale",(function(){return Zo})),r.d(Bn,"processForAllLocales",(function(){return ei}));var Ln={};r.r(Ln),r.d(Ln,"ValidationError",(function(){return ti})),r.d(Ln,"create",(function(){return ni}));var Nn={};r.r(Nn),r.d(Nn,"get",(function(){return ri})),r.d(Nn,"publish",(function(){return oi})),r.d(Nn,"unpublish",(function(){return ii})),r.d(Nn,"validate",(function(){return ai}));var Kn={};r.r(Kn),r.d(Kn,"get",(function(){return si})),r.d(Kn,"getMany",(function(){return pi})),r.d(Kn,"create",(function(){return fi})),r.d(Kn,"createWithId",(function(){return li})),r.d(Kn,"update",(function(){return di})),r.d(Kn,"del",(function(){return yi})),r.d(Kn,"publish",(function(){return bi})),r.d(Kn,"unpublish",(function(){return hi}));var Vn={};r.r(Vn),r.d(Vn,"get",(function(){return vi})),r.d(Vn,"getMany",(function(){return gi})),r.d(Vn,"update",(function(){return Oi}));var Hn={};r.r(Hn),r.d(Hn,"get",(function(){return ji})),r.d(Hn,"getMany",(function(){return wi})),r.d(Hn,"patch",(function(){return Pi})),r.d(Hn,"update",(function(){return Ii})),r.d(Hn,"del",(function(){return Ti})),r.d(Hn,"publish",(function(){return Si})),r.d(Hn,"unpublish",(function(){return Ai})),r.d(Hn,"archive",(function(){return Ei})),r.d(Hn,"unarchive",(function(){return Mi})),r.d(Hn,"create",(function(){return ki})),r.d(Hn,"createWithId",(function(){return xi})),r.d(Hn,"references",(function(){return Di}));var Xn={};r.r(Xn),r.d(Xn,"get",(function(){return Ci})),r.d(Xn,"getMany",(function(){return zi})),r.d(Xn,"update",(function(){return Fi})),r.d(Xn,"del",(function(){return Ri})),r.d(Xn,"create",(function(){return Ui})),r.d(Xn,"createWithId",(function(){return qi}));var Gn={};r.r(Gn),r.d(Gn,"get",(function(){return Bi})),r.d(Gn,"getMany",(function(){return Li})),r.d(Gn,"createWithId",(function(){return Ni})),r.d(Gn,"update",(function(){return Ki})),r.d(Gn,"del",(function(){return Vi}));var Jn={};r.r(Jn),r.d(Jn,"getExtensionUrl",(function(){return Xi})),r.d(Jn,"get",(function(){return Gi})),r.d(Jn,"getMany",(function(){return Ji})),r.d(Jn,"create",(function(){return $i})),r.d(Jn,"createWithId",(function(){return Qi})),r.d(Jn,"update",(function(){return Yi})),r.d(Jn,"del",(function(){return Zi}));var $n={};r.r($n),r.d($n,"get",(function(){return ea})),r.d($n,"post",(function(){return ta})),r.d($n,"put",(function(){return na})),r.d($n,"del",(function(){return ra})),r.d($n,"request",(function(){return oa}));var Qn={};r.r(Qn),r.d(Qn,"get",(function(){return ia})),r.d(Qn,"getMany",(function(){return aa})),r.d(Qn,"create",(function(){return ca})),r.d(Qn,"update",(function(){return ua})),r.d(Qn,"del",(function(){return sa}));var Yn={};r.r(Yn),r.d(Yn,"getMany",(function(){return pa})),r.d(Yn,"get",(function(){return fa}));var Zn={};r.r(Zn),r.d(Zn,"create",(function(){return ya})),r.d(Zn,"get",(function(){return ba}));var er={};r.r(er),r.d(er,"get",(function(){return va})),r.d(er,"getMany",(function(){return ga})),r.d(er,"update",(function(){return Oa})),r.d(er,"del",(function(){return ja}));var tr={};r.r(tr),r.d(tr,"get",(function(){return wa})),r.d(tr,"getMany",(function(){return Pa})),r.d(tr,"create",(function(){return Ia})),r.d(tr,"revoke",(function(){return Ta}));var nr={};r.r(nr),r.d(nr,"get",(function(){return Sa})),r.d(nr,"getMany",(function(){return Aa}));var rr={};r.r(rr),r.d(rr,"get",(function(){return Ea})),r.d(rr,"getMany",(function(){return Ma})),r.d(rr,"create",(function(){return ka})),r.d(rr,"createWithId",(function(){return xa})),r.d(rr,"update",(function(){return Da})),r.d(rr,"del",(function(){return Ca}));var or={};r.r(or),r.d(or,"getMany",(function(){return za})),r.d(or,"create",(function(){return Fa})),r.d(or,"del",(function(){return Ra}));var ir={};r.r(ir),r.d(ir,"getManyForEntry",(function(){return qa})),r.d(ir,"getForEntry",(function(){return Wa})),r.d(ir,"getManyForContentType",(function(){return Ba})),r.d(ir,"getForContentType",(function(){return La}));var ar={};r.r(ar),r.d(ar,"get",(function(){return Na})),r.d(ar,"getMany",(function(){return Ka})),r.d(ar,"create",(function(){return Va})),r.d(ar,"update",(function(){return Ha})),r.d(ar,"del",(function(){return Xa}));var cr={};r.r(cr),r.d(cr,"get",(function(){return Ga})),r.d(cr,"getMany",(function(){return Ja}));var ur={};r.r(ur),r.d(ur,"get",(function(){return Ya})),r.d(ur,"getMany",(function(){return Za})),r.d(ur,"getForOrganization",(function(){return ec})),r.d(ur,"getManyForOrganization",(function(){return tc})),r.d(ur,"create",(function(){return nc})),r.d(ur,"createWithId",(function(){return rc})),r.d(ur,"update",(function(){return oc})),r.d(ur,"del",(function(){return ic}));var sr={};r.r(sr),r.d(sr,"get",(function(){return uc})),r.d(sr,"getMany",(function(){return sc})),r.d(sr,"createWithId",(function(){return pc})),r.d(sr,"update",(function(){return fc})),r.d(sr,"del",(function(){return lc}));var pr={};r.r(pr),r.d(pr,"get",(function(){return bc})),r.d(pr,"getAll",(function(){return hc})),r.d(pr,"create",(function(){return mc})),r.d(pr,"update",(function(){return vc})),r.d(pr,"del",(function(){return gc}));var fr={};r.r(fr),r.d(fr,"get",(function(){return wc})),r.d(fr,"getMany",(function(){return Pc})),r.d(fr,"create",(function(){return Ic})),r.d(fr,"update",(function(){return Tc})),r.d(fr,"del",(function(){return Sc}));var lr={};r.r(lr),r.d(lr,"get",(function(){return Mc})),r.d(lr,"getManyForOrganization",(function(){return kc})),r.d(lr,"getManyForTeam",(function(){return xc})),r.d(lr,"create",(function(){return Dc})),r.d(lr,"update",(function(){return Cc})),r.d(lr,"del",(function(){return zc}));var dr={};r.r(dr),r.d(dr,"get",(function(){return Uc})),r.d(dr,"getMany",(function(){return qc})),r.d(dr,"getForOrganization",(function(){return Wc})),r.d(dr,"getManyForOrganization",(function(){return _c})),r.d(dr,"create",(function(){return Bc})),r.d(dr,"update",(function(){return Lc})),r.d(dr,"del",(function(){return Nc}));var yr={};r.r(yr),r.d(yr,"getManyForSpace",(function(){return Kc})),r.d(yr,"getManyForOrganization",(function(){return Vc}));var br={};r.r(br),r.d(br,"getForSpace",(function(){return Hc})),r.d(br,"getCurrent",(function(){return Xc})),r.d(br,"getManyForSpace",(function(){return Gc})),r.d(br,"getForOrganization",(function(){return Jc})),r.d(br,"getManyForOrganization",(function(){return $c}));var hr={};r.r(hr),r.d(hr,"get",(function(){return eu})),r.d(hr,"getManyCallDetails",(function(){return tu})),r.d(hr,"getCallDetails",(function(){return nu})),r.d(hr,"getHealthStatus",(function(){return ru})),r.d(hr,"getMany",(function(){return ou})),r.d(hr,"create",(function(){return iu})),r.d(hr,"createWithId",(function(){return au})),r.d(hr,"update",(function(){return cu})),r.d(hr,"del",(function(){return uu}));var mr={};r.r(mr),r.d(mr,"wrapApiKey",(function(){return Je})),r.d(mr,"wrapApiKeyCollection",(function(){return du}));var vr={};r.r(vr),r.d(vr,"wrapAppBundle",(function(){return $e})),r.d(vr,"wrapAppBundleCollection",(function(){return yu}));var gr={};r.r(gr),r.d(gr,"wrapAppDefinition",(function(){return Qe})),r.d(gr,"wrapAppDefinitionCollection",(function(){return bu}));var Or={};r.r(Or),r.d(Or,"wrapAppInstallation",(function(){return Ye})),r.d(Or,"wrapAppInstallationCollection",(function(){return hu}));var jr={};r.r(jr),r.d(jr,"wrapAppUpload",(function(){return Ze})),r.d(jr,"wrapAppUploadCollection",(function(){return mu}));var wr={};r.r(wr),r.d(wr,"wrapAsset",(function(){return rt})),r.d(wr,"wrapAssetCollection",(function(){return wu}));var Pr={};r.r(Pr),r.d(Pr,"wrapAssetKey",(function(){return ot}));var Ir={};r.r(Ir),r.d(Ir,"BulkActionStatus",(function(){return Yr})),r.d(Ir,"wrapBulkAction",(function(){return wt}));var Tr={};r.r(Tr),r.d(Tr,"wrapEditorInterface",(function(){return Pt})),r.d(Tr,"wrapEditorInterfaceCollection",(function(){return Mu}));var Sr={};r.r(Sr),r.d(Sr,"wrapSnapshot",(function(){return It})),r.d(Sr,"wrapSnapshotCollection",(function(){return ku}));var Ar={};r.r(Ar),r.d(Ar,"wrapContentType",(function(){return Mt})),r.d(Ar,"wrapContentTypeCollection",(function(){return Cu}));var Er={};r.r(Er),r.d(Er,"wrapEntry",(function(){return Ct})),r.d(Er,"wrapEntryCollection",(function(){return zu}));var Mr={};r.r(Mr),r.d(Mr,"default",(function(){return Ut})),r.d(Mr,"wrapTag",(function(){return qt})),r.d(Mr,"wrapTagCollection",(function(){return Fu}));var kr={};r.r(kr),r.d(kr,"wrapEnvironment",(function(){return Wt})),r.d(kr,"wrapEnvironmentCollection",(function(){return Ru}));var xr={};r.r(xr),r.d(xr,"wrapEnvironmentAlias",(function(){return _t})),r.d(xr,"wrapEnvironmentAliasCollection",(function(){return Uu}));var Dr={};r.r(Dr),r.d(Dr,"wrapExtension",(function(){return Bt})),r.d(Dr,"wrapExtensionCollection",(function(){return qu}));var Cr={};r.r(Cr),r.d(Cr,"wrapLocale",(function(){return Lt})),r.d(Cr,"wrapLocaleCollection",(function(){return Wu}));var zr={};r.r(zr),r.d(zr,"wrapOrganization",(function(){return Nt})),r.d(zr,"wrapOrganizationCollection",(function(){return _u}));var Fr={};r.r(Fr),r.d(Fr,"wrapOrganizationInvitation",(function(){return Kt}));var Rr={};r.r(Rr),r.d(Rr,"wrapOrganizationMembership",(function(){return Vt})),r.d(Rr,"wrapOrganizationMembershipCollection",(function(){return Bu}));var Ur={};r.r(Ur),r.d(Ur,"wrapPersonalAccessToken",(function(){return Ht})),r.d(Ur,"wrapPersonalAccessTokenCollection",(function(){return Lu}));var qr={};r.r(qr),r.d(qr,"wrapPreviewApiKey",(function(){return Xt})),r.d(qr,"wrapPreviewApiKeyCollection",(function(){return Nu}));var Wr={};r.r(Wr),r.d(Wr,"wrapRole",(function(){return Gt})),r.d(Wr,"wrapRoleCollection",(function(){return Ku}));var _r={};r.r(_r),r.d(_r,"createDeleteScheduledAction",(function(){return Jt})),r.d(_r,"default",(function(){return $t})),r.d(_r,"wrapScheduledAction",(function(){return Qt})),r.d(_r,"wrapScheduledActionCollection",(function(){return Vu}));var Br={};r.r(Br),r.d(Br,"wrapSpace",(function(){return Yt})),r.d(Br,"wrapSpaceCollection",(function(){return Hu}));var Lr={};r.r(Lr),r.d(Lr,"wrapSpaceMember",(function(){return Zt})),r.d(Lr,"wrapSpaceMemberCollection",(function(){return Xu}));var Nr={};r.r(Nr),r.d(Nr,"wrapSpaceMembership",(function(){return en})),r.d(Nr,"wrapSpaceMembershipCollection",(function(){return Gu}));var Kr={};r.r(Kr),r.d(Kr,"wrapTeam",(function(){return tn})),r.d(Kr,"wrapTeamCollection",(function(){return Ju}));var Vr={};r.r(Vr),r.d(Vr,"wrapTeamMembership",(function(){return nn})),r.d(Vr,"wrapTeamMembershipCollection",(function(){return $u}));var Hr={};r.r(Hr),r.d(Hr,"default",(function(){return cn})),r.d(Hr,"wrapTask",(function(){return un})),r.d(Hr,"wrapTaskCollection",(function(){return Qu}));var Xr={};r.r(Xr),r.d(Xr,"wrapTeamSpaceMembership",(function(){return sn})),r.d(Xr,"wrapTeamSpaceMembershipCollection",(function(){return Yu}));var Gr={};r.r(Gr),r.d(Gr,"wrapUpload",(function(){return ln}));var Jr={};r.r(Jr),r.d(Jr,"wrapUsage",(function(){return dn})),r.d(Jr,"wrapUsageCollection",(function(){return Zu}));var $r={};r.r($r),r.d($r,"wrapUser",(function(){return yn})),r.d($r,"wrapUserCollection",(function(){return es}));var Qr={};r.r(Qr),r.d(Qr,"wrapWebhook",(function(){return vn})),r.d(Qr,"wrapWebhookCollection",(function(){return ts}));var Yr,Zr=r(1),eo=r(19),to=r.n(eo),no=r(0),ro=r.n(no),oo=r(3),io=r.n(oo),ao=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/api_keys/").concat(t.apiKeyId))},co=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/api_keys"),{params:t.query})},uo=function(e,t,n,r){return p(e,"/spaces/".concat(t.spaceId,"/api_keys"),n,{headers:r})},so=function(e,t,n,r){return f(e,"/spaces/".concat(t.spaceId,"/api_keys/").concat(t.apiKeyId),n,{headers:r})},po=function(e,t,n,r){var o,i=ro()(n);return"accessToken"in i&&delete i.accessToken,"preview_api_key"in i&&delete i.preview_api_key,"policies"in i&&delete i.policies,delete i.sys,f(e,"/spaces/".concat(t.spaceId,"/api_keys/").concat(t.apiKeyId),i,{headers:y({"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0},r)})},fo=function(e,t){return l(e,"/spaces/".concat(t.spaceId,"/api_keys/").concat(t.apiKeyId))},lo=function(e){return"/organizations/".concat(e.organizationId,"/app_definitions/").concat(e.appDefinitionId,"/app_bundles")},yo=function(e){return"".concat(lo(e),"/").concat(e.appBundleId)},bo=function(e,t){return s(e,yo(t))},ho=function(e,t){return s(e,lo(t),{params:g(t.query)})},mo=function(e,t){return l(e,yo(t))},vo=function(e,t,n){var r=n.appUploadId,o=n.comment;return p(e,lo(t),{upload:{sys:{type:"Link",linkType:"AppUpload",id:r}},comment:o})},go=function(e){return"/organizations/".concat(e.organizationId,"/app_definitions")},Oo=function(e){return go(e)+"/".concat(e.appDefinitionId)},jo=function(e,t){return s(e,Oo(t),{params:g(t.query)})},wo=function(e,t){return s(e,go(t),{params:t.query})},Po=function(e,t,n){var r=ro()(n);return p(e,go(t),r)},Io=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,Oo(t),i,{headers:j({"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0},r)})},To=function(e,t){return l(e,Oo(t))},So=function(e){return"/spaces/".concat(e.spaceId,"/environments/").concat(e.environmentId,"/app_installations")},Ao=function(e){return So(e)+"/".concat(e.appDefinitionId)},Eo=function(e,t){return s(e,Ao(t),{params:g(t.query)})},Mo=function(e,t){return s(e,So(t),{params:g(t.query)})},ko=function(e,t,n,r){var o=ro()(n);return f(e,Ao(t),o,function(e){for(var t,n=1;n<arguments.length;n++)t=null==arguments[n]?{}:arguments[n],n%2?P(Object(t),!0).forEach((function(n){I(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):P(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}));return e}({},r))},xo=function(e,t){return l(e,Ao(t))},Do=function(e){return"/organizations/".concat(e.organizationId,"/app_uploads")},Co=function(e){return"".concat(Do(e),"/").concat(e.appUploadId)},zo=function(e,t){return s(T(e),Co(t))},Fo=function(e,t){return l(T(e),Co(t))},Ro=function(e,t,n){var r=T(e),o=n.file;return p(r,Do(t),o,{headers:{"Content-Type":"application/octet-stream"}})},Uo=function(e,t,n){var r=T(e),o=n.file;return o?p(r,"/spaces/".concat(t.spaceId,"/uploads"),o,{headers:{"Content-Type":"application/octet-stream"}}):Promise.reject(new Error("Unable to locate a file to upload."))},qo=function(e,t){return l(T(e),"/spaces/".concat(t.spaceId,"/uploads/").concat(t.uploadId))},Wo=function(e,t){return s(T(e),"/spaces/".concat(t.spaceId,"/uploads/").concat(t.uploadId))},_o=function(e,t,n,r){return s(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/assets/").concat(t.assetId),{params:g(t.query),headers:E({},r)})},Bo=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/assets"),{params:g(t.query)})},Lo=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/assets/").concat(t.assetId),i,{headers:E({"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0},r)})},No=function(e,t){return l(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/assets/").concat(t.assetId))},Ko=function(e,t,n){var r;return f(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/assets/").concat(t.assetId,"/published"),null,{headers:{"X-Contentful-Version":null!==(r=n.sys.version)&&void 0!==r?r:0}})},Vo=function(e,t){return l(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/assets/").concat(t.assetId,"/published"))},Ho=function(e,t){return f(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/assets/").concat(t.assetId,"/archived"))},Xo=function(e,t){return l(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/assets/").concat(t.assetId,"/archived"))},Go=function(e,t,n){var r=ro()(n);return p(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/assets"),r)},Jo=function(e,t,n){var r=ro()(n);return f(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/assets/").concat(t.assetId),r)},$o=function(e,t,n){var r=T(e),i=n.fields.file;return Promise.all(Object.keys(i).map((function(e){var n=i[e],o=n.contentType,a=n.fileName;return Uo(r,t,i[e]).then((function(t){return M({},e,{contentType:o,fileName:a,uploadFrom:{sys:{type:"Link",linkType:"Upload",id:t.sys.id}}})}))}))).then((function(r){var o=r.reduce((function(e,t){return E(E({},e),t)}),{}),i=E(E({},n),{},{fields:E(E({},n.fields),{},{file:o})});return Go(e,t,i)})).catch(o)},Qo=3e3,Yo=10,Zo=function(e,t){var n=t.asset,r=t.locale,o=t.options,i=(o=void 0===o?{}:o).processingCheckRetries,a=o.processingCheckWait,c=S(t,["asset","locale","options"]);return f(e,"/spaces/".concat(c.spaceId,"/environments/").concat(c.environmentId,"/assets/").concat(n.sys.id,"/files/").concat(r,"/process"),null,{headers:{"X-Contentful-Version":n.sys.version}}).then((function(){return new Promise((function(t,o){return function e(t,n,r){var o=r.resolve,i=r.reject,a=r.locale,c=r.processingCheckWait,u=void 0===c?Qo:c,s=r.processingCheckRetries,p=void 0===s?Yo:s,f=r.checkCount,l=void 0===f?0:f;return _o(t,n).then((function(r){if(r.fields.file[a].url)o(r);else if(l===p){var c=new Error;c.name="AssetProcessingTimeout",c.message="Asset is taking longer then expected to process.",i(c)}else l++,setTimeout((function(){return e(t,n,{resolve:o,reject:i,locale:a,checkCount:l,processingCheckWait:u,processingCheckRetries:p})}),u)}))}(e,{spaceId:c.spaceId,environmentId:c.environmentId,assetId:n.sys.id},{resolve:t,reject:o,locale:r,processingCheckWait:a,processingCheckRetries:i})}))}))},ei=function(e,t){var n=t.asset,r=t.options,o=void 0===r?{}:r,i=S(t,["asset","options"]),a=Object.keys(n.fields.file||{}),c=n,u=a.map((function(t){return Zo(e,E(E({},i),{},{asset:n,locale:t,options:o})).then((function(e){c=e}))}));return Promise.all(u).then((function(){return c}))},ti=function(e){function t(e,r){var o;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(o=n.call(this,'Invalid "'.concat(e,'" provided, ')+r)).name="ValidationError",o}!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&F(e,t)}(t,e);var n=function(e){var t=z();return function(){var n,r=R(e);if(t){var o=R(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return x(this,n)}}(t);return t}(D(Error)),ni=function(e,n,r){var o=r.expiresAt,i=t(Date.now()/1e3);return function(e,t,n){if(n=n||{},"number"!=typeof t)throw new ti(e,'only numeric values are allowed for timestamps, provided type was "'.concat(k(t),'"'));if(n.maximum&&t>n.maximum)throw new ti(e,"value (".concat(t,") cannot be further in the future than expected maximum (").concat(n.maximum,")"));if(n.now&&t<n.now)throw new ti(e,"value (".concat(t,") cannot be in the past, current time was ").concat(n.now))}("expiresAt",o,{maximum:i+172800,now:i}),p(e,"/spaces/".concat(n.spaceId,"/environments/").concat(n.environmentId,"/asset_keys"),{expiresAt:o})},ri=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/bulk_actions/actions/").concat(t.bulkActionId))},oi=function(e,t,n){return p(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/bulk_actions/publish"),n)},ii=function(e,t,n){return p(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/bulk_actions/unpublish"),n)},ai=function(e,t,n){return p(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/bulk_actions/validate"),n)},ci=function(e){return"/spaces/".concat(e.spaceId,"/environments/").concat(e.environmentId,"/content_types")},ui=function(e){return ci(e)+"/".concat(e.contentTypeId)},si=function(e,t){return s(e,ui(t),{params:g(t.query)})},pi=function(e,t){return s(e,ci(t),{params:t.query})},fi=function(e,t,n){var r=ro()(n);return p(e,ci(t),r)},li=function(e,t,n){var r=ro()(n);return f(e,ui(t),r)},di=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,ui(t),i,{headers:q({"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0},r)})},yi=function(e,t){return l(e,ui(t))},bi=function(e,t,n){return f(e,ui(t)+"/published",null,{headers:{"X-Contentful-Version":n.sys.version}})},hi=function(e,t){return l(e,ui(t)+"/published")},mi=function(e){return"/spaces/".concat(e.spaceId,"/environments/").concat(e.environmentId,"/content_types/").concat(e.contentTypeId,"/editor_interface")},vi=function(e,t){return s(e,mi(t))},gi=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/editor_interfaces"))},Oi=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,mi(t),i,{headers:B({"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0},r)})},ji=function(e,t,n,r){return s(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/entries/").concat(t.entryId),{params:g(t.query),headers:K({},r)})},wi=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/entries"),{params:g(t.query)})},Pi=function(e,t,n,r){return function(e,t,n,r){return e.patch(t,n,a({baseURL:u(e)},r)).then((function(e){return e.data}),o)}(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/entries/").concat(t.entryId),n,{headers:K({"X-Contentful-Version":t.version,"Content-Type":"application/json-patch+json"},r)})},Ii=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/entries/").concat(t.entryId),i,{headers:K({"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0},r)})},Ti=function(e,t){return l(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/entries/").concat(t.entryId))},Si=function(e,t,n){return f(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/entries/").concat(t.entryId,"/published"),null,{headers:{"X-Contentful-Version":n.sys.version}})},Ai=function(e,t){return l(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/entries/").concat(t.entryId,"/published"))},Ei=function(e,t){return f(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/entries/").concat(t.entryId,"/archived"))},Mi=function(e,t){return l(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/entries/").concat(t.entryId,"/archived"))},ki=function(e,t,n){var r=ro()(n);return p(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/entries"),r,{headers:{"X-Contentful-Content-Type":t.contentTypeId}})},xi=function(e,t,n){var r=ro()(n);return f(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/entries/").concat(t.entryId),r,{headers:{"X-Contentful-Content-Type":t.contentTypeId}})},Di=function(e,t){var n=t.spaceId,r=t.environmentId,o=t.entryId,i=t.maxDepth,a=void 0===i?2:i;return s(e,"/spaces/".concat(n,"/environments/").concat(r,"/entries/").concat(o,"/references?include=").concat(a))},Ci=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId))},zi=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/environments"),{params:t.query})},Fi=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId),i,{headers:X(X({},r),{},{"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0})})},Ri=function(e,t){return l(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId))},Ui=function(e,t,n,r){var o=ro()(n);return p(e,"/spaces/".concat(t.spaceId,"/environments"),o,{headers:r})},qi=function(e,t,n,r){var o=ro()(n);return f(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId),o,{headers:X(X({},r),t.sourceEnvironmentId?{"X-Contentful-Source-Environment":t.sourceEnvironmentId}:{})})},Wi=function(e){return"/spaces/".concat(e.spaceId,"/environment_aliases")},_i=function(e){return Wi(e)+"/".concat(e.environmentAliasId)},Bi=function(e,t){return s(e,_i(t))},Li=function(e,t){return s(e,Wi(t),{params:t.query})},Ni=function(e,t,n,r){var o=ro()(n);return f(e,_i(t),o,{headers:r})},Ki=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,_i(t),i,{headers:$($({},r),{},{"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0})})},Vi=function(e,t){return l(e,_i(t))},Hi=function(e){return"/spaces/".concat(e.spaceId,"/environments/").concat(e.environmentId,"/extensions")},Xi=function(e){return Hi(e)+"/".concat(e.extensionId)},Gi=function(e,t){return s(e,Xi(t),{params:g(t.query)})},Ji=function(e,t){return s(e,Hi(t),{params:g(t.query)})},$i=function(e,t,n,r){return p(e,Hi(t),n,{headers:r})},Qi=function(e,t,n,r){var o=ro()(n);return f(e,Xi(t),o,{headers:r})},Yi=function(){var e=function(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){function i(e){te(c,r,o,i,a,"next",e)}function a(e){te(c,r,o,i,a,"throw",e)}var c=e.apply(t,n);i(void 0)}))}}(regeneratorRuntime.mark((function e(t,n,r,o){var i,a;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return delete(a=ro()(r)).sys,e.abrupt("return",f(t,Xi(n),a,{headers:Z({"X-Contentful-Version":null!==(i=r.sys.version)&&void 0!==i?i:0},o)}));case 3:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}(),Zi=function(e,t){return l(e,Xi(t))},ea=function(e,t){return s(e,t.url,t.config)},ta=function(e,t,n){return p(e,t.url,n,t.config)},na=function(e,t,n){return f(e,t.url,n,t.config)},ra=function(e,t){return l(e,t.url,t.config)},oa=function(e,t){return function(e,t,n){return e(t,a({baseURL:u(e)},n)).then((function(e){return e.data}),o)}(e,t.url,t.config)},ia=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/locales/").concat(t.localeId))},aa=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/locales"),{params:g(t.query)})},ca=function(e,t,n,r){return p(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/locales"),n,{headers:r})},ua=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,delete i.default,f(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/locales/").concat(t.localeId),i,{headers:re(re({},r),{},{"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0})})},sa=function(e,t){return l(e,"/spaces/".concat(t.spaceId,"/environments/").concat(t.environmentId,"/locales/").concat(t.localeId))},pa=function(e){return s(e,"/organizations")},fa=function(e,t){return pa(e).then((function(e){var n=e.items.find((function(e){return e.sys.id===t.organizationId}));if(!n){var r=new Error("No organization was found with the ID ".concat(t.organizationId," instead got ").concat(JSON.stringify(e)));return r.status=404,r.statusText="Not Found",Promise.reject(r)}return n}))},la={"x-contentful-enable-alpha-feature":"organization-user-management-api"},da={"x-contentful-enable-alpha-feature":"pending-org-membership"},ya=function(e,t,n,r){return p(e,"/organizations/".concat(t.organizationId,"/invitations"),n,{headers:ae(ae({},da),r)})},ba=function(e,t,n){return s(e,"/organizations/".concat(t.organizationId,"/invitations/").concat(t.invitationId),{headers:ae(ae({},la),n)})},ha=function(e){return"/organizations/".concat(e.organizationId,"/organization_memberships")},ma=function(e){return"".concat(ha(e),"/").concat(e.organizationMembershipId)},va=function(e,t){return s(e,ma(t))},ga=function(e,t){return s(e,ha(t))},Oa=function(e,t,n,r){var o,i=ro()(n);delete i.sys;var a=i.role;return f(e,ma(t),{role:a},{headers:se(se({},r),{},{"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0})})},ja=function(e,t){return l(e,ma(t))},wa=function(e,t){return s(e,"/users/me/access_tokens/".concat(t.tokenId))},Pa=function(e,t){return s(e,"/users/me/access_tokens",{params:t.query})},Ia=function(e,t,n,r){return p(e,"/users/me/access_tokens",n,{headers:r})},Ta=function(e,t){return f(e,"/users/me/access_tokens/".concat(t.tokenId,"/revoked"),null)},Sa=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/preview_api_keys/").concat(t.previewApiKeyId))},Aa=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/preview_api_keys"),{params:t.query})},Ea=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/roles/").concat(t.roleId))},Ma=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/roles"),{params:g(t.query)})},ka=function(e,t,n,r){return p(e,"/spaces/".concat(t.spaceId,"/roles"),n,{headers:r})},xa=function(e,t,n,r){return f(e,"/spaces/".concat(t.spaceId,"/roles/").concat(t.roleId),n,{headers:r})},Da=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,"/spaces/".concat(t.spaceId,"/roles/").concat(t.roleId),i,{headers:le(le({},r),{},{"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0})})},Ca=function(e,t){return l(e,"/spaces/".concat(t.spaceId,"/roles/").concat(t.roleId))},za=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/scheduled_actions"),{params:g(t.query)})},Fa=function(e,t,n){return p(e,"/spaces/".concat(t.spaceId,"/scheduled_actions"),n)},Ra=function(e,t){return l(e,"/spaces/".concat(t.spaceId,"/scheduled_actions/").concat(t.scheduledActionId))},Ua=function(e){return"/spaces/".concat(e.spaceId,"/environments/").concat(e.environmentId,"/entries/").concat(e.entryId,"/snapshots")},qa=function(e,t){return s(e,Ua(t),{params:g(t.query)})},Wa=function(e,t){return s(e,function(e){return Ua(e)+"/".concat(e.snapshotId)}(t))},_a=function(e){return"/spaces/".concat(e.spaceId,"/environments/").concat(e.environmentId,"/content_types/").concat(e.contentTypeId,"/snapshots")},Ba=function(e,t){return s(e,_a(t),{params:g(t.query)})},La=function(e,t){return s(e,function(e){return _a(e)+"/".concat(e.snapshotId)}(t))},Na=function(e,t){return s(e,"/spaces/".concat(t.spaceId))},Ka=function(e,t){return s(e,"/spaces",{params:t.query})},Va=function(e,t,n,r){return p(e,"/spaces",n,{headers:t.organizationId?be(be({},r),{},{"X-Contentful-Organization":t.organizationId}):r})},Ha=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,"/spaces/".concat(t.spaceId),i,{headers:be({"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0},r)})},Xa=function(e,t){return l(e,"/spaces/".concat(t.spaceId))},Ga=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/space_members/").concat(t.spaceMemberId))},Ja=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/space_members"),{params:t.query})},$a=function(e){return"/spaces/".concat(e.spaceId,"/space_memberships")},Qa=function(e){return"".concat($a(e),"/").concat(e.spaceMembershipId)},Ya=function(e,t){return Oe(),s(e,Qa(t))},Za=function(e,t){return Oe(),s(e,$a(t),{params:t.query})},ec=function(e,t){return s(e,"/organizations/".concat(t.organizationId,"/space_memberships/").concat(t.spaceMembershipId))},tc=function(e,t){return s(e,"/organizations/".concat(t.organizationId,"/space_memberships"),{params:t.query})},nc=function(e,t,n,r){return Oe(),p(e,$a(t),n,{headers:r})},rc=function(e,t,n,r){return Oe(),f(e,Qa(t),n,{headers:r})},oc=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,Qa(t),i,{headers:ve(ve({},r),{},{"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0})})},ic=function(e,t){return l(e,Qa(t))},ac=function(e){return"/spaces/".concat(e.spaceId,"/environments/").concat(e.environmentId,"/tags")},cc=function(e){return ac(e)+"/".concat(e.tagId)},uc=function(e,t){return s(e,cc(t))},sc=function(e,t){return s(e,ac(t),{params:t.query})},pc=function(e,t,n){var r,o=ro()(n);return f(e,cc(t),o,{headers:{"X-Contentful-Tag-Visibility":null!==(r=n.sys.visibility)&&void 0!==r?r:"private"}})},fc=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,cc(t),i,{headers:Pe({"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0},r)})},lc=function(e,t){var n=t.version,r=je(t,["version"]);return l(e,cc(r),{headers:{"X-Contentful-Version":n}})},dc=function(e){return"/spaces/".concat(e.spaceId,"/environments/").concat(e.environmentId,"/entries/").concat(e.entryId,"/tasks")},yc=function(e){return"".concat(dc(e),"/").concat(e.taskId)},bc=function(e,t){return s(e,yc(t))},hc=function(e,t){return s(e,dc(t))},mc=function(e,t,n){var r=ro()(n);return p(e,dc(t),r)},vc=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,yc(t),i,{headers:Ae({"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0},r)})},gc=function(e,t){var n=t.version,r=Te(t,["version"]);return l(e,yc(r),{headers:{"X-Contentful-Version":n}})},Oc=function(e){return"/organizations/".concat(e.organizationId,"/teams")},jc=function(e){return"".concat(Oc(e),"/").concat(e.teamId)},wc=function(e,t){return s(e,jc(t))},Pc=function(e,t){return s(e,Oc(t),{params:g(t.query)})},Ic=function(e,t,n,r){return p(e,Oc(t),n,{headers:r})},Tc=function(e,t,n,r){var o,i=ro()(n);return delete i.sys,f(e,jc(t),i,{headers:ke({"X-Contentful-Version":null!==(o=n.sys.version)&&void 0!==o?o:0},r)})},Sc=function(e,t){return l(e,jc(t))},Ac=function(e){return"/organizations/".concat(e.organizationId,"/teams/").concat(e.teamId,"/team_memberships")},Ec=function(e){return"/organizations/".concat(e.organizationId,"/teams/").concat(e.teamId,"/team_memberships/").concat(e.teamMembershipId)},Mc=function(e,t){return s(e,Ec(t))},kc=function(e,t){return s(e,"/organizations/".concat(t.organizationId,"/team_memberships"),{params:g(t.query)})},xc=function(e,t){return s(e,Ac(t),{params:g(t.query)})},Dc=function(e,t,n,r){return p(e,Ac(t),n,{headers:r})},Cc=function(e,t,n,r){var o=ro()(n);return delete o.sys,f(e,Ec(t),o,{headers:Ce({"X-Contentful-Version":n.sys.version||0},r)})},zc=function(e,t){return l(e,Ec(t))},Fc=function(e){return"/spaces/".concat(e.spaceId,"/team_space_memberships")},Rc=function(e){return"".concat(Fc(e),"/").concat(e.teamSpaceMembershipId)},Uc=function(e,t){return s(e,Rc(t))},qc=function(e,t){return s(e,Fc(t),{params:t.query})},Wc=function(e,t){return s(e,"/organizations/".concat(t.organizationId,"/team_space_memberships/").concat(t.teamSpaceMembershipId))},_c=function(e,t){var n=t.query||{};return t.teamId&&(n["sys.team.sys.id"]=t.teamId),s(e,"/organizations/".concat(t.organizationId,"/team_space_memberships"),{params:t.query})},Bc=function(e,t,n,r){return p(e,Fc(t),n,{headers:Re({"x-contentful-team":t.teamId},r)})},Lc=function(e,t,n,r){var o=ro()(n);return delete o.sys,f(e,Rc(t),o,{headers:Re({"X-Contentful-Version":n.sys.version||0,"x-contentful-team":n.sys.team.sys.id},r)})},Nc=function(e,t){return l(e,Rc(t))},Kc=function(e,t){return s(e,"/organizations/".concat(t.organizationId,"/space_periodic_usages"),{params:t.query})},Vc=function(e,t){return s(e,"/organizations/".concat(t.organizationId,"/organization_periodic_usages"),{params:t.query})},Hc=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/users/").concat(t.userId))},Xc=function(e,t){return s(e,"/users/me",{params:null==t?void 0:t.query})},Gc=function(e,t){return s(e,"/spaces/".concat(t.spaceId,"/users"),{params:t.query})},Jc=function(e,t){return s(e,"/organizations/".concat(t.organizationId,"/users/").concat(t.userId))},$c=function(e,t){return s(e,"/organizations/".concat(t.organizationId,"/users"),{params:t.query})},Qc=function(e){return"/spaces/".concat(e.spaceId,"/webhook_definitions")},Yc=function(e){return"/spaces/".concat(e.spaceId,"/webhooks")},Zc=function(e){return"".concat(Qc(e),"/").concat(e.webhookDefinitionId)},eu=function(e,t){return s(e,Zc(t))},tu=function(e,t){return s(e,function(e){return"".concat(Yc(e),"/").concat(e.webhookDefinitionId,"/calls")}(t),{params:g(t.query)})},nu=function(e,t){return s(e,function(e){return"".concat(Yc(e),"/").concat(e.webhookDefinitionId,"/calls/").concat(e.callId)}(t))},ru=function(e,t){return s(e,function(e){return"".concat(Yc(e),"/").concat(e.webhookDefinitionId,"/health")}(t))},ou=function(e,t){return s(e,Qc(t),{params:g(t.query)})},iu=function(e,t,n,r){var o=ro()(n);return p(e,Qc(t),o,{headers:r})},au=function(e,t,n,r){var o=ro()(n);return f(e,Zc(t),o,{headers:r})},cu=function(){var e=function(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){function i(e){Be(c,r,o,i,a,"next",e)}function a(e){Be(c,r,o,i,a,"throw",e)}var c=e.apply(t,n);i(void 0)}))}}(regeneratorRuntime.mark((function e(t,n,r,o){var i,a;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return delete(a=ro()(r)).sys,e.abrupt("return",f(t,Zc(n),a,{headers:We({"X-Contentful-Version":null!==(i=r.sys.version)&&void 0!==i?i:0},o)}));case 3:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}(),uu=function(e,t){return l(e,Zc(t))},su={ApiKey:Fn,AppBundle:Rn,AppDefinition:Un,AppInstallation:qn,AppUpload:Wn,Asset:Bn,AssetKey:Ln,BulkAction:Nn,ContentType:Kn,EditorInterface:Vn,Entry:Hn,Environment:Xn,EnvironmentAlias:Gn,Extension:Jn,Http:$n,Locale:Qn,Organization:Yn,OrganizationInvitation:Zn,OrganizationMembership:er,PersonalAccessToken:tr,PreviewApiKey:nr,Role:rr,ScheduledAction:or,Snapshot:ir,Space:ar,SpaceMember:cr,SpaceMembership:ur,Tag:sr,Task:pr,Team:fr,TeamMembership:lr,TeamSpaceMembership:dr,Upload:_n,Usage:yr,User:br,Webhook:hr},pu={defaultHostname:"api.contentful.com",defaultHostnameUpload:"upload.contentful.com"},fu=function(){function e(t){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t.accessToken)throw new TypeError("Expected parameter accessToken");this.params=Ke(Ke({},pu),ro()(t))}return function(e,t,n){t&&He(e.prototype,t),n&&He(e,n)}(e,[{key:"makeRequest",value:function(){var e=function(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){function i(e){Le(c,r,o,i,a,"next",e)}function a(e){Le(c,r,o,i,a,"throw",e)}var c=e.apply(t,n);i(void 0)}))}}(regeneratorRuntime.mark((function e(t){var n,r,o,i,a,c,u,s,p,f,l;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t.entityType,o=t.action,i=t.params,a=t.payload,c=t.headers,u=t.userAgent,s="delete"===o?"del":o,void 0!==(p=null===(n=su[r])||void 0===n?void 0:n[s])){e.next=5;break}throw new Error("Unknown endpoint");case 5:return f={"Content-Type":"application/vnd.contentful.management.v1+json","X-Contentful-User-Agent":u},l=Object(Zr.a)(to.a,Ke(Ke({},this.params),{},{headers:Ke(Ke({},f),this.params.headers)})),e.next=9,p(l,i,a,c);case 9:return e.abrupt("return",e.sent);case 10:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()}]),e}(),lu=function(e){return function(t,n){for(var r=arguments.length,o=Array(2<r?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];var a=Object(Zr.e)(ro()(n));return a.items=a.items.map((function(n){return e.apply(void 0,[t,n].concat(o))})),a}},du=lu(Je),yu=lu($e),bu=lu(Qe),hu=lu(Ye),mu=lu(Ze),vu=function(e){return!!e.sys.publishedVersion},gu=function(e){return!!(e.sys.publishedVersion&&e.sys.version>e.sys.publishedVersion+1)},Ou=function(e){return!e.sys.publishedVersion},ju=function(e){return!!e.sys.archivedVersion},wu=lu(rt),Pu=30,Iu=1e3,Tu=2e3,Su=function(e){function t(e,r){var o;return st(this,t),(o=n.call(this,e)).bulkAction=r,o.name=o.constructor.name,o}pt(t,e);var n=ft(t);return t}(dt(Error)),Au=function(e){function t(){return st(this,t),n.apply(this,arguments)}pt(t,e);var n=ft(t);return t}(Su);!function(e){e.created="created",e.inProgress="inProgress",e.succeeded="succeeded",e.failed="failed"}(Yr||(Yr={}));Object.values(Yr);var Eu,Mu=lu(Pt),ku=lu(It),xu=function(e,t,n){var r=e.fields.find((function(e){return e.id===t}));return r?(r[n]=!0,Promise.resolve(e)):Promise.reject(new Error("Tried to omitAndDeleteField on a nonexistent field, ".concat(t,", on the content type ").concat(e.name,".")))},Du=function(e,t,n){var r=t.fieldId,o=Tt(t,["fieldId"]);return xu(n,r,"omitted").then((function(t){return e({entityType:"ContentType",action:"update",params:o,payload:t})})).then((function(e){return xu(e,r,"deleted")})).then((function(t){return e({entityType:"ContentType",action:"update",params:o,payload:t})}))},Cu=lu(Mt),zu=lu(Ct),Fu=lu(qt),Ru=lu(Wt),Uu=lu(_t),qu=lu(Bt),Wu=lu(Lt),_u=lu(Nt),Bu=lu(Vt),Lu=lu(Ht),Nu=lu(Xt),Ku=lu(Gt);!function(e){e.scheduled="scheduled",e.inProgress="inProgress",e.succeeded="succeeded",e.failed="failed",e.canceled="canceled"}(Eu||(Eu={}));var Vu=lu(Qt),Hu=lu(Yt),Xu=lu(Zt),Gu=lu(en),Ju=lu(tn),$u=lu(nn),Qu=lu(un),Yu=lu(sn),Zu=lu(dn),es=lu(yn),ts=lu(vn),ns={appBundle:vr,apiKey:mr,appDefinition:gr,appInstallation:Or,appUpload:jr,asset:wr,assetKey:Pr,bulkAction:Ir,contentType:Ar,editorInterface:Tr,entry:Er,environment:kr,environmentAlias:xr,extension:Dr,locale:Cr,organization:zr,organizationInvitation:Fr,organizationMembership:Rr,personalAccessToken:Ur,previewApiKey:qr,role:Wr,scheduledAction:_r,snapshot:Sr,space:Br,spaceMember:Lr,spaceMembership:Nr,tag:Mr,task:Hr,team:Kr,teamMembership:Vr,teamSpaceMembership:Xr,upload:Gr,usage:Jr,user:$r,webhook:Qr},rs=function(e,t,n){var r=e.makeRequest,o=e.defaults;return function(e,i,a){return r({entityType:t,action:n,params:wn(wn({},o),e),payload:i,headers:a})}},os=function(e,t){var n={makeRequest:e,defaults:t};return{raw:{getDefaultParams:function(){return t},get:function(t,n){return e({entityType:"Http",action:"get",params:{url:t,config:n}})},patch:function(t,n,r){return e({entityType:"Http",action:"patch",params:{url:t,config:r},payload:n})},post:function(t,n,r){return e({entityType:"Http",action:"post",params:{url:t,config:r},payload:n})},put:function(t,n,r){return e({entityType:"Http",action:"put",params:{url:t,config:r},payload:n})},delete:function(t,n){return e({entityType:"Http",action:"delete",params:{url:t,config:n}})},http:function(t,n){return e({entityType:"Http",action:"request",params:{url:t,config:n}})}},appBundle:{get:rs(n,"AppBundle","get"),getMany:rs(n,"AppBundle","getMany"),delete:rs(n,"AppBundle","delete"),create:rs(n,"AppBundle","create")},editorInterface:{get:rs(n,"EditorInterface","get"),getMany:rs(n,"EditorInterface","getMany"),update:rs(n,"EditorInterface","update")},space:{get:rs(n,"Space","get"),getMany:rs(n,"Space","getMany"),update:rs(n,"Space","update"),delete:rs(n,"Space","delete"),create:rs(n,"Space","create")},environment:{get:rs(n,"Environment","get"),getMany:rs(n,"Environment","getMany"),create:rs(n,"Environment","create"),createWithId:rs(n,"Environment","createWithId"),update:rs(n,"Environment","update"),delete:rs(n,"Environment","delete")},environmentAlias:{get:rs(n,"EnvironmentAlias","get"),getMany:rs(n,"EnvironmentAlias","getMany"),createWithId:rs(n,"EnvironmentAlias","createWithId"),update:rs(n,"EnvironmentAlias","update"),delete:rs(n,"EnvironmentAlias","delete")},bulkAction:{get:rs(n,"BulkAction","get"),publish:rs(n,"BulkAction","publish"),unpublish:rs(n,"BulkAction","unpublish"),validate:rs(n,"BulkAction","validate")},contentType:{get:rs(n,"ContentType","get"),getMany:rs(n,"ContentType","getMany"),update:rs(n,"ContentType","update"),delete:rs(n,"ContentType","delete"),publish:rs(n,"ContentType","publish"),unpublish:rs(n,"ContentType","unpublish"),omitAndDeleteField:function(n,r,o){return Du(e,Tn(Tn({},Tn(Tn({},t),n)),{},{fieldId:o}),r)}},user:{getManyForSpace:rs(n,"User","getManyForSpace"),getForSpace:rs(n,"User","getForSpace"),getCurrent:rs(n,"User","getCurrent"),getForOrganization:rs(n,"User","getForOrganization"),getManyForOrganization:rs(n,"User","getManyForOrganization")},task:{get:rs(n,"Task","get"),getAll:rs(n,"Task","getAll"),create:rs(n,"Task","create"),update:rs(n,"Task","update"),delete:rs(n,"Task","delete")},entry:{getMany:rs(n,"Entry","getMany"),get:rs(n,"Entry","get"),update:rs(n,"Entry","update"),patch:rs(n,"Entry","patch"),delete:rs(n,"Entry","delete"),publish:rs(n,"Entry","publish"),unpublish:rs(n,"Entry","unpublish"),archive:rs(n,"Entry","archive"),unarchive:rs(n,"Entry","unarchive"),create:rs(n,"Entry","create"),createWithId:rs(n,"Entry","createWithId"),references:rs(n,"Entry","references")},asset:{getMany:rs(n,"Asset","getMany"),get:rs(n,"Asset","get"),update:rs(n,"Asset","update"),delete:rs(n,"Asset","delete"),publish:rs(n,"Asset","publish"),unpublish:rs(n,"Asset","unpublish"),archive:rs(n,"Asset","archive"),unarchive:rs(n,"Asset","unarchive"),create:rs(n,"Asset","create"),createWithId:rs(n,"Asset","createWithId"),createFromFiles:rs(n,"Asset","createFromFiles"),processForAllLocales:function(n,r,o){return e({entityType:"Asset",action:"processForAllLocales",params:Tn(Tn({},Tn(Tn({},t),n)),{},{options:o,asset:r})})},processForLocale:function(n,r,o,i){return e({entityType:"Asset",action:"processForLocale",params:Tn(Tn({},Tn(Tn({},t),n)),{},{locale:o,asset:r,options:i})})}},appUpload:{get:rs(n,"AppUpload","get"),delete:rs(n,"AppUpload","delete"),create:rs(n,"AppUpload","create")},assetKey:{create:rs(n,"AssetKey","create")},upload:{get:rs(n,"Upload","get"),create:rs(n,"Upload","create"),delete:rs(n,"Upload","delete")},locale:{get:rs(n,"Locale","get"),getMany:rs(n,"Locale","getMany"),delete:rs(n,"Locale","delete"),update:rs(n,"Locale","update"),create:rs(n,"Locale","create")},personalAccessToken:{get:rs(n,"PersonalAccessToken","get"),getMany:rs(n,"PersonalAccessToken","getMany"),create:function(t,n){return e({entityType:"PersonalAccessToken",action:"create",params:{},headers:n,payload:t})},revoke:rs(n,"PersonalAccessToken","revoke")},usage:{getManyForSpace:rs(n,"Usage","getManyForSpace"),getManyForOrganization:rs(n,"Usage","getManyForOrganization")},role:{get:rs(n,"Role","get"),getMany:rs(n,"Role","getMany"),create:rs(n,"Role","create"),createWithId:rs(n,"Role","createWithId"),update:rs(n,"Role","update"),delete:rs(n,"Role","delete")},scheduledActions:{getMany:rs(n,"ScheduledAction","getMany"),create:rs(n,"ScheduledAction","create"),delete:rs(n,"ScheduledAction","delete")},previewApiKey:{get:rs(n,"PreviewApiKey","get"),getMany:rs(n,"PreviewApiKey","getMany")},apiKey:{get:rs(n,"ApiKey","get"),getMany:rs(n,"ApiKey","getMany"),create:rs(n,"ApiKey","create"),createWithId:rs(n,"ApiKey","createWithId"),update:rs(n,"ApiKey","update"),delete:rs(n,"ApiKey","delete")},appDefinition:{get:rs(n,"AppDefinition","get"),getMany:rs(n,"AppDefinition","getMany"),create:rs(n,"AppDefinition","create"),update:rs(n,"AppDefinition","update"),delete:rs(n,"AppDefinition","delete")},appInstallation:{get:rs(n,"AppInstallation","get"),getMany:rs(n,"AppInstallation","getMany"),upsert:rs(n,"AppInstallation","upsert"),delete:rs(n,"AppInstallation","delete")},extension:{get:rs(n,"Extension","get"),getMany:rs(n,"Extension","getMany"),create:rs(n,"Extension","create"),createWithId:rs(n,"Extension","createWithId"),update:rs(n,"Extension","update"),delete:rs(n,"Extension","delete")},webhook:{get:rs(n,"Webhook","get"),getMany:rs(n,"Webhook","getMany"),getHealthStatus:rs(n,"Webhook","getHealthStatus"),getCallDetails:rs(n,"Webhook","getCallDetails"),getManyCallDetails:rs(n,"Webhook","getManyCallDetails"),create:rs(n,"Webhook","create"),update:rs(n,"Webhook","update"),delete:rs(n,"Webhook","delete")},snapshot:{getManyForEntry:rs(n,"Snapshot","getManyForEntry"),getForEntry:rs(n,"Snapshot","getForEntry"),getManyForContentType:rs(n,"Snapshot","getManyForContentType"),getForContentType:rs(n,"Snapshot","getForContentType")},tag:{get:rs(n,"Tag","get"),getMany:rs(n,"Tag","getMany"),createWithId:rs(n,"Tag","createWithId"),update:rs(n,"Tag","update"),delete:rs(n,"Tag","delete")},organization:{getAll:rs(n,"Organization","getMany"),get:rs(n,"Organization","get")},organizationInvitation:{get:rs(n,"OrganizationInvitation","get"),create:rs(n,"OrganizationInvitation","create")},organizationMembership:{get:rs(n,"OrganizationMembership","get"),getMany:rs(n,"OrganizationMembership","getMany"),update:rs(n,"OrganizationMembership","update"),delete:rs(n,"OrganizationMembership","delete")},spaceMember:{get:rs(n,"SpaceMember","get"),getMany:rs(n,"SpaceMember","getMany")},spaceMembership:{get:rs(n,"SpaceMembership","get"),getMany:rs(n,"SpaceMembership","getMany"),getForOrganization:rs(n,"SpaceMembership","getForOrganization"),getManyForOrganization:rs(n,"SpaceMembership","getManyForOrganization"),create:rs(n,"SpaceMembership","create"),createWithId:rs(n,"SpaceMembership","createWithId"),update:rs(n,"SpaceMembership","update"),delete:rs(n,"SpaceMembership","delete")},team:{get:rs(n,"Team","get"),getMany:rs(n,"Team","getMany"),create:rs(n,"Team","create"),update:rs(n,"Team","update"),delete:rs(n,"Team","delete")},teamMembership:{get:rs(n,"TeamMembership","get"),getManyForOrganization:rs(n,"TeamMembership","getManyForOrganization"),getManyForTeam:rs(n,"TeamMembership","getManyForTeam"),create:rs(n,"TeamMembership","create"),update:rs(n,"TeamMembership","update"),delete:rs(n,"TeamMembership","delete")},teamSpaceMembership:{get:rs(n,"TeamSpaceMembership","get"),getMany:rs(n,"TeamSpaceMembership","getMany"),getForOrganization:rs(n,"TeamSpaceMembership","getForOrganization"),getManyForOrganization:rs(n,"TeamSpaceMembership","getManyForOrganization"),create:rs(n,"TeamSpaceMembership","create"),update:rs(n,"TeamSpaceMembership","update"),delete:rs(n,"TeamSpaceMembership","delete")}}},is=function(e,t){return Mn({},Symbol.asyncIterator,(function(){var n=ro()(t),r=function(){return e(ro()(n))},o=r();return{current:0,next:function(){var e=this;return function(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){function i(e){kn(c,r,o,i,a,"next",e)}function a(e){kn(c,r,o,i,a,"throw",e)}var c=e.apply(t,n);i(void 0)}))}}(regeneratorRuntime.mark((function t(){var i,a,c,u,s,p,f,l;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,o;case 2:if(i=t.sent,a=i.total,c=i.items,u=i.skip,s=i.limit,a!==e.current){t.next=9;break}return t.abrupt("return",{done:!0,value:null});case 9:return p=c[e.current++-u],f=0==e.current%s,l=e.current===a,f&&!l&&(n=En(En({},n),{},{query:En(En({},n.query),{},{skip:u+s})}),o=r()),t.abrupt("return",{done:!1,value:p});case 14:case"end":return t.stop()}}),t)})))()}}}))}}])}));
|
"""
This project lets you try out Tkinter/Ttk and practice it!
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Mark Hays, Amanda Stouder, Aaron Wilkin, their colleagues,
and Sam Hedrick.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
import tkinter
from tkinter import ttk
def main():
""" Constructs a GUI with stuff on it. """
# -------------------------------------------------------------------------
# DONE: 2. After reading and understanding the m1e module,
# ** make a window that shows up. **
# -------------------------------------------------------------------------
window = tkinter.Tk()
# -------------------------------------------------------------------------
# DONE: 3. After reading and understanding the m2e module,
# ** put a Frame on the window. **
# -------------------------------------------------------------------------
frame = ttk.Frame(window, padding=20)
frame.grid()
# -------------------------------------------------------------------------
# DONE: 4. After reading and understanding the m2e module,
# ** put a Button on the Frame. **
# -------------------------------------------------------------------------
button = ttk.Button(frame, text=' Press for Message ')
button.grid()
# -------------------------------------------------------------------------
# DONE: 5. After reading and understanding the m3e module,
# ** make your Button respond to a button-press **
# ** by printing "Hello" on the Console. **
# -------------------------------------------------------------------------
button['command'] = (lambda: print('Hello!'))
# -------------------------------------------------------------------------
# DONE: 6. After reading and understanding the m4e module,
# -- Put an Entry box on the Frame.
# -- Put a second Button on the Frame.
# -- Make this new Button, when pressed, print "Hello"
# on the Console if the current string in the Entry box
# is the string 'ok', but print "Goodbye" otherwise.
# -------------------------------------------------------------------------
button2 = ttk.Button(frame, text='Type ok')
button2.grid()
my_entry_box = ttk.Entry(frame)
my_entry_box.grid()
button2['command'] = (lambda: test_6(my_entry_box))
# -------------------------------------------------------------------------
# DONE: 7.
# -- Put a second Entry on the Frame.
# -- Put a third Button on the frame.
# -- Make this new Button respond to a button-press as follows:
#
# Pressing this new Button causes the STRING that the user typed
# in the FIRST Entry box to be printed N times on the Console,
# where N is the INTEGER that the user typed
# in the SECOND Entry box.
#
# If the user fails to enter an integer,
# that is a "user error" -- do NOT deal with that.
#
# -------------------------------------------------------------------------
####################################################################
# HINT:
# You will need to obtain the INTEGER from the STRING
# that the GET method returns.
# Use the int function to do so, as in this example:
# s = entry_box.get()
# n = int(s)
####################################################################
button3 = ttk.Button(frame, text='Type a number')
button3.grid()
entry_box2 = ttk.Entry(frame)
entry_box2.grid()
button3['command'] = (lambda: test_7(entry_box2, my_entry_box))
# -------------------------------------------------------------------------
# DONE: 8. As time permits, do other interesting GUI things!
# -------------------------------------------------------------------------
window.mainloop()
def test_6(entry_box):
if entry_box.get() == 'ok':
print('Hello')
else:
print('Goodbye')
def test_7(n, s):
s_contents = s.get()
if s_contents == 'Ligma':
print('Ligma balls')
else:
n_contents = n.get()
for k in range(int(n_contents)):
print(s.get())
# -----------------------------------------------------------------------------
# Calls main to start the ball rolling.
# -----------------------------------------------------------------------------
main()
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[8],{"7cmm":function(t,e,s){"use strict";s.r(e);var A=s("KHd+"),i={metaInfo:{title:"Europe",meta:[{name:"description",content:"A to Z guide of what plays, that are showing at London theatres. Due to coronavirus London theatres are curently closed, new exciting shows coming soon."},[{src:"https://kit.fontawesome.com/e3c70d4fc5.js"}]]},components:{austria:Object(A.a)({},(function(){var t=this,e=t.$createElement,A=t._self._c||e;return A("div",{staticClass:"m-4 p-4 w-auto rounded-lg shadow-2xl",attrs:{id:"work-card"}},[A("div",{staticClass:"p-6"},[A("h1",{staticClass:"text-2xl text-white text-center"},[t._v("\n Austria")]),A("g-image",{staticClass:"h-32 w-full object-fill",attrs:{src:s("PlK/"),alt:"austria flag"}}),A("br"),A("ul",{},[A("li",[t._v("Capital: Vienna")]),t._m(0),A("li",[t._v("Currency: Euro")]),t._m(1),A("br"),t._m(2),A("br"),A("li",[t._v("Genealogy Resourses:"),A("br"),A("g-link",{staticClass:"text-white hover:text-yellow-500",attrs:{to:"/europe/austriangeneral"}},[t._v("\n General\n ")]),A("br"),A("g-link",{staticClass:"text-white hover:text-yellow-500",attrs:{to:"/Jewish/austria"}},[t._v("\n Jewish\n ")])],1)])],1)])}),[function(){var t=this.$createElement,e=this._self._c||t;return e("li",[this._v("Language: "),e("br"),this._v("German")])},function(){var t=this.$createElement,e=this._self._c||t;return e("li",[this._v("Population: 8.859 million "),e("br"),this._v("in 2019")])},function(){var t=this.$createElement,e=this._self._c||t;return e("li",[this._v("Religion:"),e("br"),this._v(" Catholic 57%"),e("br"),this._v(" Eastern Orthodox 9%"),e("br"),this._v("Protestant 3% "),e("br"),this._v(" Islam 8% "),e("br"),this._v("Buddhism 0.3%")])}],!1,null,null,null).exports,belarus:Object(A.a)({},(function(){var t=this,e=t.$createElement,A=t._self._c||e;return A("div",{staticClass:"m-4 p-4 w-auto rounded-lg shadow-2xl",attrs:{id:"work-card"}},[A("div",{staticClass:"p-6"},[A("h1",{staticClass:"text-2xl text-white text-center"},[t._v("\n Belarus")]),A("g-image",{staticClass:"h-32 w-full object-fill",attrs:{src:s("KgMq"),alt:"austria flag"}}),A("br"),A("ul",{},[A("li",[t._v("Capital: Minsk")]),t._m(0),A("li",[t._v("Currency: Belarusian Ruble")]),t._m(1),A("br"),t._m(2),A("br"),A("br"),A("br"),A("br"),A("li",[t._v("Genealogy Resourses:"),A("br"),A("g-link",{staticClass:"text-white hover:text-yellow-500",attrs:{to:"/europe/belarusgeneral"}},[t._v("\n General\n ")]),A("br"),A("g-link",{staticClass:"text-white hover:text-yellow-500",attrs:{to:"/Jewish/belarus"}},[t._v("\n Jewish\n ")])],1)])],1)])}),[function(){var t=this.$createElement,e=this._self._c||t;return e("li",[this._v("Language: "),e("br"),this._v("Byelorussia & Russian")])},function(){var t=this.$createElement,e=this._self._c||t;return e("li",[this._v("Population: 9.475 million "),e("br"),this._v("in 2019")])},function(){var t=this.$createElement,e=this._self._c||t;return e("li",[this._v("Religion:"),e("br"),this._v("Eastern Orthodoxy 48.3%"),e("br"),this._v("Christians 7%")])}],!1,null,null,null).exports,belgium:Object(A.a)({},(function(){var t=this,e=t.$createElement,A=t._self._c||e;return A("div",{staticClass:"m-4 p-4 w-auto rounded-lg shadow-2xl",attrs:{id:"work-card"}},[A("div",{staticClass:"p-6"},[A("h1",{staticClass:"text-2xl text-white text-center"},[t._v("\n Belgium")]),A("g-image",{staticClass:"h-32 w-full object-fill",attrs:{src:s("elzD"),alt:"austria flag"}}),A("br"),A("ul",{},[A("li",[t._v("Capital: Brussels")]),t._m(0),A("li",[t._v("Currency: Euro")]),t._m(1),A("br"),t._m(2),A("br"),A("br"),A("li",[t._v("Genealogy Resourses:"),A("br"),A("g-link",{staticClass:"text-white hover:text-yellow-500",attrs:{to:"/europe/belgiumgeneral"}},[t._v("\n General\n ")]),A("br"),A("g-link",{staticClass:"text-white hover:text-yellow-500",attrs:{to:"/Jewish/belarus"}},[t._v("\n Jewish\n ")])],1)])],1)])}),[function(){var t=this.$createElement,e=this._self._c||t;return e("li",[this._v("Language: "),e("br"),this._v("Dutch, French & German")])},function(){var t=this.$createElement,e=this._self._c||t;return e("li",[this._v("Population: 11.46 million "),e("br"),this._v("in 2019")])},function(){var t=this.$createElement,e=this._self._c||t;return e("li",[this._v("Religion:"),e("br"),this._v("Catholic 54%"),e("br"),this._v(" Protestant 3%"),e("br"),this._v("Eastern Orthodoxy 1%"),e("br"),this._v("Islam 5%")])}],!1,null,null,null).exports}},a=Object(A.a)(i,(function(){var t=this.$createElement,e=this._self._c||t;return e("Layout",[e("div",{staticClass:"container m-auto",attrs:{id:"background"}},[e("h1",{staticClass:"ml-8 mt-3 text-4xl text-teal-900"},[e("span",{staticClass:"text-teal-900"},[e("i",{staticClass:"fas fa-theater-masks"})]),this._v("\n Family History Resourses For Europe\n ")]),e("br"),e("div",{staticClass:"grid sm:flex"},[e("austria"),e("belarus"),e("belgium")],1)]),e("br")])}),[],!1,null,null,null);e.default=a.exports},KgMq:function(t,e){t.exports={type:"image",mimeType:"image/jpeg",src:"/assets/static/belarus-flag.6b65613.7426bc61ecd8d593313c40fdf4fbf32d.jpg",size:{width:300,height:200},sizes:"(max-width: 300px) 100vw, 300px",srcset:["/assets/static/belarus-flag.6b65613.7426bc61ecd8d593313c40fdf4fbf32d.jpg 300w"],dataUri:"data:image/svg+xml,%3csvg fill='none' viewBox='0 0 300 200' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3cdefs%3e%3cfilter id='__svg-blur-592e6aa79017ce25aa228fd443fbdf14'%3e%3cfeGaussianBlur in='SourceGraphic' stdDeviation='40'/%3e%3c/filter%3e%3c/defs%3e%3cimage x='0' y='0' filter='url(%23__svg-blur-592e6aa79017ce25aa228fd443fbdf14)' width='300' height='200' xlink:href='data:image/jpeg%3bbase64%2c/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAArAEADASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAcBBgT/xAAsEAABAwEGBQIHAAAAAAAAAAABAAIDBAUGERIhgRMUIzFRImIzNEFCUmGC/8QAGgEBAAIDAQAAAAAAAAAAAAAAAAMFAQYHBP/EACoRAAIAAggEBwAAAAAAAAAAAAABAgUDBBESFjFTkSFB0fAGI1FScYHC/9oADAMBAAIRAxEAPwD1XpgLLvVDuZgaBC7oiUEwDOeiPObR3kZNPtU0Pdd9eKotUWLNFX2bCxscRp6iZrW4vmcOKx40xwDCP36jtwJ7qmpczrEuhao3b68u%2b/kIiKIsAiIgCIiAr18al4uvaT%2bbGa0YuLUHh/MODg8OH4et748O%2bmHhSEqi3hvFWVtj2q1lnGCK1xzRe/D4TCc2mJynikuw9w17KdKelV52o1WjnVRlPk12kUET42WN8MuSeTTX0EWbpuo7kRJjGS662i6Gos3TdLkQxjJddbRdDUWbpulyIYxkuutouhUL21EbrAqmc1ViQMyvhcW5YH5jhCcPo4Au/keRhLz3VcvZSQMudHM1nUNA95cSSS7iQ6nyeo/X3FSM916Wcs8ZNOuQWe39MxERYNQCIiAIiID/2Q==' /%3e%3c/svg%3e"}},"PlK/":function(t,e){t.exports={type:"image",mimeType:"image/jpeg",src:"/assets/static/austria-flag.6b65613.87dd28c19927bdda9a9142c6b6691db3.jpg",size:{width:300,height:200},sizes:"(max-width: 300px) 100vw, 300px",srcset:["/assets/static/austria-flag.6b65613.87dd28c19927bdda9a9142c6b6691db3.jpg 300w"],dataUri:"data:image/svg+xml,%3csvg fill='none' viewBox='0 0 300 200' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3cdefs%3e%3cfilter id='__svg-blur-24c75ff18f1c12fcc7e2626f00db3a9e'%3e%3cfeGaussianBlur in='SourceGraphic' stdDeviation='40'/%3e%3c/filter%3e%3c/defs%3e%3cimage x='0' y='0' filter='url(%23__svg-blur-24c75ff18f1c12fcc7e2626f00db3a9e)' width='300' height='200' xlink:href='data:image/jpeg%3bbase64%2c/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAArAEADASIAAhEBAxEB/8QAGgAAAgMBAQAAAAAAAAAAAAAAAAEDBgcIAv/EACkQAAECAwcDBQEAAAAAAAAAAAEAAgUR0gQGFyExVZIDB6MSM0FhcdH/xAAYAQACAwAAAAAAAAAAAAAAAAAAAQIGB//EACYRAAEBBAsBAQAAAAAAAAAAAAABAwVS0QIEERMUFkNTkZKhFQb/2gAMAwEAAhEDEQA/AM4TaC4gDUq44Y3x2G08mVJ4Y3y2G08mVKqXDWFeDf8A6tR36HZJlQcWtb6WyJ%2bXfxRq5YY3x2G08mVIwxvlsNp5MqTuGsK8CR6VFNeh2SZTkNBcQBqVccMb47DaeTKk8Mb47DaeTKkrhrCvA/q1HfodkmVBxaxpa3N3y7%2bKNXLDG%2bOw2nkypPDG%2bWw2nkypFw1hXgSPSopr0OyTOuw2Weq9ZLHseoFtUT8dSMeoD8QqJ%2bOpWHGsIjHctPTYXyZsEpI/FkDu/EDDQTComAdPbqSx6gQ0hUT8dSMYwiDLb0XRXyZr4bLPUp5LH8eoFtUT8dSMeoFtUT8dSMYwiDLT02F8mbBKWckfiyB3fiBhoJhUTAOnt1JDv1AtrifjqTxjCIE/NvRdFfJnOCbT6SDIH6Kk6TQWdUkTIbMKJVg3G221BuJcSSZkpIQgkCbT6SDIH6Kk6TQWdQkTIbkokEbbbUG5xcSXGZKSEIJH/9k=' /%3e%3c/svg%3e"}},elzD:function(t,e){t.exports={type:"image",mimeType:"image/jpeg",src:"/assets/static/belgium-flag.6b65613.11284c57d13024cc80b4b6e94876f1e2.jpg",size:{width:300,height:200},sizes:"(max-width: 300px) 100vw, 300px",srcset:["/assets/static/belgium-flag.6b65613.11284c57d13024cc80b4b6e94876f1e2.jpg 300w"],dataUri:"data:image/svg+xml,%3csvg fill='none' viewBox='0 0 300 200' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3cdefs%3e%3cfilter id='__svg-blur-5ef9a280a1e09b82bb6948601c0ec8d2'%3e%3cfeGaussianBlur in='SourceGraphic' stdDeviation='40'/%3e%3c/filter%3e%3c/defs%3e%3cimage x='0' y='0' filter='url(%23__svg-blur-5ef9a280a1e09b82bb6948601c0ec8d2)' width='300' height='200' xlink:href='data:image/jpeg%3bbase64%2c/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAArAEADASIAAhEBAxEB/8QAFwABAQEBAAAAAAAAAAAAAAAAAAgHBv/EACAQAQAAAwkAAAAAAAAAAAAAAAACAwUGBwg1NnFzsrP/xAAYAQADAQEAAAAAAAAAAAAAAAAFBgcBAP/EACARAAECBQUAAAAAAAAAAAAAAAABAgQGMzSxBXFygcH/2gAMAwEAAhEDEQA/AJUAccUNhCzG03BI7xqWTThCzG03BI7xqWTqYL9/WECsLTQMMvI1rUt5fnC3Nhl5GtalvL84WaHXdt6gzy7cu4rlDmgDSOZPYA6RAobCFmNpuCR3jUsmnCFmNpuCR3jUsnUwX7%2bsIFYWmgYZeRrWpby/OFubDLyNa1LeX5ws0Ou7b1Bnl25dxXKHNAGkcyewB0iBQ2ELMbTcEjvGpZNOEPMbTcEjvGpZOpgv39YQKwtNAwy8jWtS3l%2bcLc2GXka1qW8vzhZodd23qDPLty7iuUOaANI5n//Z' /%3e%3c/svg%3e"}}}]);
|
import csv
import os
import sys
import pandas as pd
from collections import OrderedDict
from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.models import HoverTool, CDSView, IndexFilter, ColumnDataSource
from bokeh.transform import factor_cmap
def read_csv(path):
with open(path, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
_headers = next(reader, None)
# get column
_columns = {}
for h in _headers:
_columns[h] = []
for row in reader:
for h, v in zip(_headers, row):
_columns[h].append(v)
for item in _headers:
print(item)
return _headers, _columns
if __name__ == '__main__':
tools_list = "pan," \
"box_select," \
"lasso_select," \
"box_zoom, " \
"wheel_zoom," \
"reset," \
"save," \
"help"
# "hover," \
input_id = '6b87d4f577d78de84819962e8bafeea8'
if len(sys.argv) >= 2:
input_id = sys.argv[1]
output_root_path = rf'G:\kidney\slideseq-cell-type-annotated\slideseq-cell-type-annotated\{input_id}'
nuclei_output_name = 'nuclei.csv'
nuclei_file_path = os.path.join(output_root_path, nuclei_output_name)
vessel_output_name = 'vessel.csv'
vessel_file_path = os.path.join(output_root_path, vessel_output_name)
output_file(os.path.join(output_root_path, f'{input_id}.html'))
p = figure(match_aspect=True,
plot_width=int(2000 * 1.075), plot_height=int(2000 * 1.075),
tools=tools_list,
# title='nuclei/vessel distance',
)
p.xgrid.visible = False
p.ygrid.visible = False
p.axis.visible = False
p.background_fill_alpha = 0.0
p.outline_line_color = None
v_headers, v_columns = read_csv(vessel_file_path)
for i in range(0, len(v_headers)):
v_columns[v_headers[i]] = [float(value) for value in v_columns[v_headers[i]]]
data = dict()
for header in v_headers:
data[header] = v_columns[header]
v_df = pd.DataFrame(data)
# p.circle(x='x', y='y', source=v_df, color='#91672c', size=6, alpha=1)
n_headers, n_columns = read_csv(nuclei_file_path)
# for i in range(1, len(n_headers)):
# n_columns[n_headers[i]] = [float(value) for value in n_columns[n_headers[i]]]
n_columns['y'] = [float(value) for value in n_columns['y']]
n_columns['vy'] = [float(value) for value in n_columns['vy']]
n_columns['x'] = [float(value) for value in n_columns['x']]
n_columns['vx'] = [float(value) for value in n_columns['vx']]
n_columns['alpha'] = [(float(value) + 500) / 1500 for value in n_columns['distance']]
n_columns['color'] = ['#%02x%02x%02x' % (0, int(255 * float(value) / 1000), int(255 * (1000 - float(value)) / 1000))
for value in n_columns['distance']]
cell_type_pool = [
'Ascending Thin Limb to Thick Ascending Limb Cell',
'Ascending Thin Limb Cell',
'Proximal Tubule Cell',
'Fibroblast',
'Thick Ascending Limb Cell',
'Macrophage',
'Distal Convoluted Tubule Cell',
'Myofibroblast',
'Connecting Tubule',
'Principal Cell',
'Descending Thin Limb Cell',
'placeholder_0',
'Podocyte',
'placeholder_1',
'Endothelial Cell',
'placeholder_2',
'Vascular Smooth Muscle Cell and Pericyte'
'placeholder_3',
'Intercalated Alpha Cell',
'Intercalated Beta Cell',
]
data = dict()
for header in n_headers:
data[header] = n_columns[header]
data['alpha'] = n_columns['alpha']
data['color'] = n_columns['color']
n_df = pd.DataFrame(data)
cell_types = list(set(n_columns['type']))
cell_types.sort()
n_df = ColumnDataSource(data=n_df)
for label in cell_types:
index_list = []
legend_label = ''
for i in range(len(n_df.data['type'])):
if n_df.data['type'][i] == label:
index_list.append(i)
legend_label = n_df.data['type'][i]
view = CDSView(source=n_df, filters=[IndexFilter(index_list)])
p.scatter(x='x', y='y', source=n_df, fill_alpha=0.8, size=6,
# marker=factor_mark('style_label', markers, roman_label),
marker='circle',
color=factor_cmap('type', 'Category20_20', cell_type_pool),
# muted_color=factor_cmap(label['real_label_list'], 'Category10_8',
# label['standard_label_list']),
muted_alpha=0.1, view=view,
legend_label=legend_label)
p.segment(x0='x', y0='y', x1='vx', source=n_df, y1='vy',
# color="red",
color=factor_cmap('type', 'Category20_20', cell_type_pool),
alpha=0.2, line_width=1,
view=view,
legend_label=legend_label
)
# p.circle(x='x', y='y', source=n_df, color='color', alpha=0.7, size=6)
# g1_hover = HoverTool(renderers=[circle], tooltips=[('X', "@x"), ('Y', "@y"), ('distance', "@distance")])
# p.add_tools(g1_hover)
p.legend.location = "bottom_right"
p.legend.click_policy = "mute"
show(p)
|
from django.apps import AppConfig
class CuentaConfig(AppConfig):
name = 'cuenta'
|
const caniuse = require('caniuse-api')
const db = require('caniuse-db/data.json')
const fs = require('fs')
const browserslist = require('browserslist')
const featuresMap = require('./featuresMap')
const browserPrefixMap = require('./browserPrefixMap')
const generateFile = (scope, output) => {
caniuse.setBrowserScope(scope)
const browsers = browserslist(scope)
const features = db.data
const cssFeatures = []
Object.keys(features).forEach(feature => {
const {categories} = features[feature]
if (
(categories.indexOf('CSS') >= 0
|| categories.indexOf('CSS2') >= 0
|| categories.indexOf('CSS3') >= 0
|| categories.indexOf('CSS4') >= 0)
&& categories.indexOf('HTML5') < 0
&& categories.indexOf('JS API') < 0
&& categories.indexOf('DOM') < 0
) {
cssFeatures.push(feature)
}
})
const haveToPrefix = []
cssFeatures.forEach(feature => {
const supportedFeatures = caniuse.getSupport(feature)
Object.keys(supportedFeatures).forEach(browser => {
if (supportedFeatures[browser].hasOwnProperty('x')
&& browsers.indexOf(`${browser} ${supportedFeatures[browser].x}`) >= 0) {
if (featuresMap[feature]) {
featuresMap[feature].forEach(mapedFeature => {
const i = haveToPrefix.findIndex(t => t.name === mapedFeature)
if (i < 0) {
haveToPrefix.push({
name: mapedFeature,
prefixes: [browserPrefixMap[browser]]
})
} else if (haveToPrefix[i].prefixes.indexOf(browserPrefixMap[browser]) < 0) {
haveToPrefix[i].prefixes.push(browserPrefixMap[browser])
}
})
}
}
})
})
fs.writeFileSync(output, JSON.stringify(haveToPrefix))
}
module.exports = generateFile
|
exports.urlSafe = function(string) {
const url = string.replace(/[^a-z0-9_\-]/gi, '-').replace(/-{2,}/g, '-').replace(/^\-|\-$/, '').toLowerCase();
return url;
};
|
"""Test for old ternary constructs"""
from UNINFERABLE import condition, true_value, false_value, some_callable # pylint: disable=import-error
SOME_VALUE1 = true_value if condition else false_value
SOME_VALUE2 = condition and true_value or false_value # [consider-using-ternary]
SOME_VALUE3 = condition
def func1():
"""Ternary return value correct"""
return true_value if condition else false_value
def func2():
"""Ternary return value incorrect"""
return condition and true_value or false_value # [consider-using-ternary]
SOME_VALUE4 = some_callable(condition) and 'ERROR' or 'SUCCESS' # [consider-using-ternary]
SOME_VALUE5 = SOME_VALUE1 > 3 and 'greater' or 'not greater' # [consider-using-ternary]
SOME_VALUE6 = (SOME_VALUE2 > 4 and SOME_VALUE3) and 'both' or 'not' # [consider-using-ternary]
SOME_VALUE7 = 'both' if (SOME_VALUE2 > 4) and (SOME_VALUE3) else 'not'
SOME_VALUE8 = SOME_VALUE1 and SOME_VALUE2 and SOME_VALUE3 or SOME_VALUE4
SOME_VALUE9 = SOME_VALUE1 and False or SOME_VALUE2 # [simplify-boolean-expression]
YEAR = 1992
# Cannot be simplified with a ternary.
IS_LEAP_YEAR = YEAR % 4 == 0 and YEAR % 100 != 0 or YEAR % 400 == 0
def func4():
""""Using a Name as a condition but still emits"""
truth_value = 42
return condition and truth_value or false_value # [consider-using-ternary]
|
import Vue from 'vue'
import { on } from './dom.js'
const nodeList = []
const ctx = '@@clickoutsideContext'
!Vue.prototype.$isServer && on(document, 'click', e => {
nodeList.forEach(node => node[ctx].documentHandler(e))
})
/**
* v-clickoutside
* @desc 点击元素外面才会触发的事件
* @example
* ```vue
* <div v-element-clickoutside="handleClose">
* ```
*/
export default {
bind (el, binding, vnode) {
const id = nodeList.push(el) - 1
const documentHandler = function (e) {
if (!vnode.context ||
el.contains(e.target) ||
(vnode.context.popperElm &&
vnode.context.popperElm.contains(e.target))) return
if (binding.expression &&
el[ctx].methodName &&
vnode.context[el[ctx].methodName]) {
vnode.context[el[ctx].methodName]()
} else {
el[ctx].bindingFn && el[ctx].bindingFn()
}
}
el[ctx] = {
id,
documentHandler,
methodName: binding.expression,
bindingFn: binding.value
}
},
update (el, binding) {
el[ctx].methodName = binding.expression
el[ctx].bindingFn = binding.value
},
unbind (el) {
const len = nodeList.length
for (let i = 0; i < len; i++) {
if (nodeList[i][ctx].id === el[ctx].id) {
nodeList.splice(i, 1)
break
}
}
}
}
|
from django.apps import AppConfig
class MapsConfig(AppConfig):
name = "fight_covid19.maps"
|
/*******************************************************************************************
*
* raylib [shaders] example - Sieve of Eratosthenes
*
* Sieve of Eratosthenes, the earliest known (ancient Greek) prime number sieve.
*
* "Sift the twos and sift the threes,
* The Sieve of Eratosthenes.
* When the multiples sublime,
* the numbers that are left are prime."
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by ProfJski and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 ProfJski and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
#include "raylib.h"
#if defined(PLATFORM_DESKTOP)
#define GLSL_VERSION 330
#else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB
#define GLSL_VERSION 100
#endif
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - Sieve of Eratosthenes");
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
// Load Eratosthenes shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(0, TextFormat("resources/shaders/glsl%i/eratosthenes.fs", GLSL_VERSION));
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
// Nothing to do here, everything is happening in the shader
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginTextureMode(target); // Enable drawing to texture
ClearBackground(BLACK); // Clear the render texture
// Draw a rectangle in shader mode to be used as shader canvas
// NOTE: Rectangle uses font white character texture coordinates,
// so shader can not be applied here directly because input vertexTexCoord
// do not represent full screen coordinates (space where want to apply shader)
DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), BLACK);
EndTextureMode(); // End drawing to texture (now we have a blank texture available for the shader)
BeginDrawing();
ClearBackground(RAYWHITE); // Clear screen background
BeginShaderMode(shader);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
DrawTextureRec(target.texture, (Rectangle){ 0, 0, (float)target.texture.width, (float)-target.texture.height }, (Vector2){ 0.0f, 0.0f }, WHITE);
EndShaderMode();
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader); // Unload shader
UnloadRenderTexture(target); // Unload render texture
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.5.4.15_A2_T8;
* @section: 15.5.4.15;
* @assertion: String.prototype.substring (start, end) returns a string value(not object);
* @description: start is tested_string.length+1, end is 0;
*/
__string = new String("this is a string object");
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (__string.substring(__string.length+1, 0) !== "this is a string object") {
$ERROR('#1: __string = new String("this is a string object"); __string.substring(__string.length+1, 0) === "this is a string object". Actual: '+__string.substring(__string.length+1, 0) );
}
//
//////////////////////////////////////////////////////////////////////////////
|
from django import forms
from django.forms.widgets import HiddenInput
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator, BaseValidator
from models import Layout
class UnicodeField(forms.CharField):
def __init__(self, blank=True, *args, **kwargs):
super(UnicodeField, self).__init__(min_length=1, max_length=4, *args, **kwargs)
def to_python(self, value):
if not value:
return None
if len(value)<=1:
return super(UnicodeField, self).to_python(value)
# else:
try:
hexa = int(str(value), 16)
return unichr(hexa)
except (TypeError, ValueError):
raise ValidationError(self.error_messages['invalid'])
class KeyForm(forms.Form):
layout = forms.ModelChoiceField(Layout.objects.all(), widget=HiddenInput)
row = forms.IntegerField(min_value=0, max_value=4, widget=HiddenInput)
pos = forms.IntegerField(min_value=0, max_value=15, widget=HiddenInput)
level1 = UnicodeField()
level2 = UnicodeField()
level3 = UnicodeField(blank=True, required=False)
level4 = UnicodeField(blank=True, required=False)
alphanumeric = RegexValidator(r'^\w*$')
class CloneForm(forms.Form):
new_name = forms.CharField(max_length=64, validators=[alphanumeric], required=False)
def __init__(self, user=None, *args, **kw):
super(CloneForm, self).__init__(*args, **kw)
if user is not None: self.user = user
def clean(self):
cleaned = super(CloneForm, self).clean()
given_name = cleaned.get('new_name', None)
if not given_name:
raise ValidationError("You must give your clone a valid name. Use alphanumerics and '_' only.")
if Layout.objects.filter(name=given_name, owner=self.user).exists():
raise ValidationError("You already have a layout named %s." % given_name)
return cleaned
class LayoutDescriptionForm(forms.Form):
description = forms.CharField(required=False,
widget=forms.Textarea(attrs=dict(
cols=70, rows=4,
placeholder="Write a description for your layout here",
width="100%")))
def __init__(self, layout=None, data=None, *args, **kw):
if data is None:
data = {}
else:
data = data.copy()
if layout is not None:
self.layout = layout
data.setdefault('description',layout.description)
super(LayoutDescriptionForm, self).__init__(data, *args, **kw)
def save(self, commit=True):
self.layout.description = self.cleaned_data['description']
if commit: self.layout.save()
return self.layout
|
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from tastypie.api import Api
from .api import ImageResource, ThumbnailResource, PinResource, UserResource
from .feeds import LatestPins, LatestUserPins, LatestTagPins
from .views import CreateImage
from .models import LICENCES
class PinTemplateView(TemplateView):
def get_context_data(self, **kwargs):
context = super(PinTemplateView, self).get_context_data(**kwargs)
context['licences'] = LICENCES
return context
v1_api = Api(api_name='v1')
v1_api.register(ImageResource())
v1_api.register(ThumbnailResource())
v1_api.register(PinResource())
v1_api.register(UserResource())
urlpatterns = patterns('',
url(r'^api/', include(v1_api.urls, namespace='api')),
url(r'feeds/latest-pins/tag/(?P<tag>(\w|-)+)/', LatestTagPins()),
url(r'feeds/latest-pins/user/(?P<user>(\w|-)+)/', LatestUserPins()),
url(r'feeds/latest-pins/', LatestPins()),
url(r'^pins/pin-form/$', PinTemplateView.as_view(template_name='core/pin_form.html'),
name='pin-form'),
url(r'^pins/create-image/$', CreateImage.as_view(), name='create-image'),
url(r'^pins/tag/(?P<tag>(\w|-)+)/$', PinTemplateView.as_view(template_name='core/pins.html'),
name='tag-pins'),
url(r'^pins/user/(?P<user>(\w|-)+)/$', PinTemplateView.as_view(template_name='core/pins.html'),
name='user-pins'),
url(r'^(?P<pin>[0-9]+)/$', PinTemplateView.as_view(template_name='core/pins.html'),
name='recent-pins'),
url(r'^$', PinTemplateView.as_view(template_name='core/pins.html'),
name='recent-pins'),
)
|
# -*- coding: utf-8 -*-
###
# (C) Copyright [2019] Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
from pprint import pprint
from config_loader import try_load_from_file
from hpOneView.oneview_client import OneViewClient
config = {
"ip": "<oneview_ip>",
"credentials": {
"userName": "<user>",
"password": "<password>"
}
}
# Try load config from a file (if there is a config file)
config = try_load_from_file(config)
oneview_client = OneViewClient(config)
os_deployment_plans = oneview_client.os_deployment_plans
print("\nGet OS Deployment Plans by Filter:")
plans = os_deployment_plans.get_by('deploymentType', 'I3S')
pprint(plans)
print("\nGet the OS Deployment Plan by Name:")
os_deployment_plan = os_deployment_plans.get_by('name', 'Deployment Plan')
pprint(os_deployment_plan)
print("\nGet all OS Deployment Plans:")
os_deployment_plans_all = os_deployment_plans.get_all()
pprint(os_deployment_plans_all)
|
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 10
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class SettingsAclsAclPolicySettings(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'access': 'str',
'calcmode': 'str',
'calcmode_group': 'str',
'calcmode_owner': 'str',
'calcmode_traverse': 'str',
'chmod': 'str',
'chmod_007': 'str',
'chmod_inheritable': 'str',
'chown': 'str',
'create_over_smb': 'str',
'dos_attr': 'str',
'group_owner_inheritance': 'str',
'rwx': 'str',
'synthetic_denies': 'str',
'utimes': 'str'
}
attribute_map = {
'access': 'access',
'calcmode': 'calcmode',
'calcmode_group': 'calcmode_group',
'calcmode_owner': 'calcmode_owner',
'calcmode_traverse': 'calcmode_traverse',
'chmod': 'chmod',
'chmod_007': 'chmod_007',
'chmod_inheritable': 'chmod_inheritable',
'chown': 'chown',
'create_over_smb': 'create_over_smb',
'dos_attr': 'dos_attr',
'group_owner_inheritance': 'group_owner_inheritance',
'rwx': 'rwx',
'synthetic_denies': 'synthetic_denies',
'utimes': 'utimes'
}
def __init__(self, access=None, calcmode=None, calcmode_group=None, calcmode_owner=None, calcmode_traverse=None, chmod=None, chmod_007=None, chmod_inheritable=None, chown=None, create_over_smb=None, dos_attr=None, group_owner_inheritance=None, rwx=None, synthetic_denies=None, utimes=None): # noqa: E501
"""SettingsAclsAclPolicySettings - a model defined in Swagger""" # noqa: E501
self._access = None
self._calcmode = None
self._calcmode_group = None
self._calcmode_owner = None
self._calcmode_traverse = None
self._chmod = None
self._chmod_007 = None
self._chmod_inheritable = None
self._chown = None
self._create_over_smb = None
self._dos_attr = None
self._group_owner_inheritance = None
self._rwx = None
self._synthetic_denies = None
self._utimes = None
self.discriminator = None
if access is not None:
self.access = access
if calcmode is not None:
self.calcmode = calcmode
if calcmode_group is not None:
self.calcmode_group = calcmode_group
if calcmode_owner is not None:
self.calcmode_owner = calcmode_owner
if calcmode_traverse is not None:
self.calcmode_traverse = calcmode_traverse
if chmod is not None:
self.chmod = chmod
if chmod_007 is not None:
self.chmod_007 = chmod_007
if chmod_inheritable is not None:
self.chmod_inheritable = chmod_inheritable
if chown is not None:
self.chown = chown
if create_over_smb is not None:
self.create_over_smb = create_over_smb
if dos_attr is not None:
self.dos_attr = dos_attr
if group_owner_inheritance is not None:
self.group_owner_inheritance = group_owner_inheritance
if rwx is not None:
self.rwx = rwx
if synthetic_denies is not None:
self.synthetic_denies = synthetic_denies
if utimes is not None:
self.utimes = utimes
@property
def access(self):
"""Gets the access of this SettingsAclsAclPolicySettings. # noqa: E501
Access checks (chmod, chown). # noqa: E501
:return: The access of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._access
@access.setter
def access(self, access):
"""Sets the access of this SettingsAclsAclPolicySettings.
Access checks (chmod, chown). # noqa: E501
:param access: The access of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._access = access
@property
def calcmode(self):
"""Gets the calcmode of this SettingsAclsAclPolicySettings. # noqa: E501
Displayed mode bits. # noqa: E501
:return: The calcmode of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._calcmode
@calcmode.setter
def calcmode(self, calcmode):
"""Sets the calcmode of this SettingsAclsAclPolicySettings.
Displayed mode bits. # noqa: E501
:param calcmode: The calcmode of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._calcmode = calcmode
@property
def calcmode_group(self):
"""Gets the calcmode_group of this SettingsAclsAclPolicySettings. # noqa: E501
Approximate group mode bits when ACL exists. # noqa: E501
:return: The calcmode_group of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._calcmode_group
@calcmode_group.setter
def calcmode_group(self, calcmode_group):
"""Sets the calcmode_group of this SettingsAclsAclPolicySettings.
Approximate group mode bits when ACL exists. # noqa: E501
:param calcmode_group: The calcmode_group of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._calcmode_group = calcmode_group
@property
def calcmode_owner(self):
"""Gets the calcmode_owner of this SettingsAclsAclPolicySettings. # noqa: E501
Approximate owner mode bits when ACL exists. # noqa: E501
:return: The calcmode_owner of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._calcmode_owner
@calcmode_owner.setter
def calcmode_owner(self, calcmode_owner):
"""Sets the calcmode_owner of this SettingsAclsAclPolicySettings.
Approximate owner mode bits when ACL exists. # noqa: E501
:param calcmode_owner: The calcmode_owner of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._calcmode_owner = calcmode_owner
@property
def calcmode_traverse(self):
"""Gets the calcmode_traverse of this SettingsAclsAclPolicySettings. # noqa: E501
Require traverse rights in order to traverse directories with existing ACLs. # noqa: E501
:return: The calcmode_traverse of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._calcmode_traverse
@calcmode_traverse.setter
def calcmode_traverse(self, calcmode_traverse):
"""Sets the calcmode_traverse of this SettingsAclsAclPolicySettings.
Require traverse rights in order to traverse directories with existing ACLs. # noqa: E501
:param calcmode_traverse: The calcmode_traverse of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._calcmode_traverse = calcmode_traverse
@property
def chmod(self):
"""Gets the chmod of this SettingsAclsAclPolicySettings. # noqa: E501
chmod on files with existing ACLs. # noqa: E501
:return: The chmod of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._chmod
@chmod.setter
def chmod(self, chmod):
"""Sets the chmod of this SettingsAclsAclPolicySettings.
chmod on files with existing ACLs. # noqa: E501
:param chmod: The chmod of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._chmod = chmod
@property
def chmod_007(self):
"""Gets the chmod_007 of this SettingsAclsAclPolicySettings. # noqa: E501
chmod (007) on files with existing ACLs. # noqa: E501
:return: The chmod_007 of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._chmod_007
@chmod_007.setter
def chmod_007(self, chmod_007):
"""Sets the chmod_007 of this SettingsAclsAclPolicySettings.
chmod (007) on files with existing ACLs. # noqa: E501
:param chmod_007: The chmod_007 of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._chmod_007 = chmod_007
@property
def chmod_inheritable(self):
"""Gets the chmod_inheritable of this SettingsAclsAclPolicySettings. # noqa: E501
ACLs created on directories by UNIX chmod. # noqa: E501
:return: The chmod_inheritable of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._chmod_inheritable
@chmod_inheritable.setter
def chmod_inheritable(self, chmod_inheritable):
"""Sets the chmod_inheritable of this SettingsAclsAclPolicySettings.
ACLs created on directories by UNIX chmod. # noqa: E501
:param chmod_inheritable: The chmod_inheritable of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._chmod_inheritable = chmod_inheritable
@property
def chown(self):
"""Gets the chown of this SettingsAclsAclPolicySettings. # noqa: E501
chown/chgrp on files with existing ACLs. # noqa: E501
:return: The chown of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._chown
@chown.setter
def chown(self, chown):
"""Sets the chown of this SettingsAclsAclPolicySettings.
chown/chgrp on files with existing ACLs. # noqa: E501
:param chown: The chown of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._chown = chown
@property
def create_over_smb(self):
"""Gets the create_over_smb of this SettingsAclsAclPolicySettings. # noqa: E501
ACL creation over SMB. # noqa: E501
:return: The create_over_smb of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._create_over_smb
@create_over_smb.setter
def create_over_smb(self, create_over_smb):
"""Sets the create_over_smb of this SettingsAclsAclPolicySettings.
ACL creation over SMB. # noqa: E501
:param create_over_smb: The create_over_smb of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._create_over_smb = create_over_smb
@property
def dos_attr(self):
"""Gets the dos_attr of this SettingsAclsAclPolicySettings. # noqa: E501
Read only DOS attribute. # noqa: E501
:return: The dos_attr of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._dos_attr
@dos_attr.setter
def dos_attr(self, dos_attr):
"""Sets the dos_attr of this SettingsAclsAclPolicySettings.
Read only DOS attribute. # noqa: E501
:param dos_attr: The dos_attr of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._dos_attr = dos_attr
@property
def group_owner_inheritance(self):
"""Gets the group_owner_inheritance of this SettingsAclsAclPolicySettings. # noqa: E501
Group owner inheritance. # noqa: E501
:return: The group_owner_inheritance of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._group_owner_inheritance
@group_owner_inheritance.setter
def group_owner_inheritance(self, group_owner_inheritance):
"""Sets the group_owner_inheritance of this SettingsAclsAclPolicySettings.
Group owner inheritance. # noqa: E501
:param group_owner_inheritance: The group_owner_inheritance of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._group_owner_inheritance = group_owner_inheritance
@property
def rwx(self):
"""Gets the rwx of this SettingsAclsAclPolicySettings. # noqa: E501
Treatment of 'rwx' permissions. # noqa: E501
:return: The rwx of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._rwx
@rwx.setter
def rwx(self, rwx):
"""Sets the rwx of this SettingsAclsAclPolicySettings.
Treatment of 'rwx' permissions. # noqa: E501
:param rwx: The rwx of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._rwx = rwx
@property
def synthetic_denies(self):
"""Gets the synthetic_denies of this SettingsAclsAclPolicySettings. # noqa: E501
Synthetic 'deny' ACEs. # noqa: E501
:return: The synthetic_denies of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._synthetic_denies
@synthetic_denies.setter
def synthetic_denies(self, synthetic_denies):
"""Sets the synthetic_denies of this SettingsAclsAclPolicySettings.
Synthetic 'deny' ACEs. # noqa: E501
:param synthetic_denies: The synthetic_denies of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._synthetic_denies = synthetic_denies
@property
def utimes(self):
"""Gets the utimes of this SettingsAclsAclPolicySettings. # noqa: E501
Access check (utimes) # noqa: E501
:return: The utimes of this SettingsAclsAclPolicySettings. # noqa: E501
:rtype: str
"""
return self._utimes
@utimes.setter
def utimes(self, utimes):
"""Sets the utimes of this SettingsAclsAclPolicySettings.
Access check (utimes) # noqa: E501
:param utimes: The utimes of this SettingsAclsAclPolicySettings. # noqa: E501
:type: str
"""
self._utimes = utimes
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, SettingsAclsAclPolicySettings):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
import { Meteor } from 'meteor/meteor'
import {
Rooms,
Subscriptions,
Messages,
Uploads,
Integrations,
Users,
} from '../../models'
import { streamerJitsiCall, streamName } from '../lib/streamer'
//import {createMeetURL} from './../lib/createMeet'
//import {generateMeetURL} from './methods/jitsiGenerateToken'
streamerJitsiCall.allowRead('logged')
streamerJitsiCall.allowWrite('logged')
export const sendStartCallJitsi = (userId = false, roomId = false) => {
console.log("----------- sendStartCallJitsi-----------", userId, roomId)
if (userId && roomId) {
const subscriptions = Subscriptions.findByRoomId(roomId, {
fields: { 'u._id': 1 },
sort: { 'u.username': 1 },
})
const members = subscriptions.fetch().map((s) => s.u && s.u._id)
//console.log('+++++++++++++++++++ members', members)
const count = members.length
//console.log('+++++++++++++++++++ count', count)
if (members) {
valueToCaller = {
type: "outCall",
roomId: roomId,
initUserId: userId,
count: count,
members: [],
//date: new Date()
}
//Добавляем участников, исключая инициатора
members.map((id) => {
if (id !== userId) {
valueToCaller.members.push(
{
userId: id,
status: false,
}
)
}
})
valueToUser = {
type: "inCall",
roomId: roomId,
initUserId: userId,
count: count
}
members.map((id) => {
if (id == userId) {
streamerJitsiCall.emit(id + '/' + streamName, valueToCaller) //Данные для инициатора вызова
} else {
streamerJitsiCall.emit(id + '/' + streamName, valueToUser) //Запрос о готовности клиента
}
})
}
}
}
streamerJitsiCall.on(streamName, function (value) {
//Обязательные параметры type, roomId, userId
let valueToCaller = {}
let valueToUser = {}
if (value.type && value.userId && value.roomId) {
switch (value.type) {
// case 'start':
// //Отправляем инициатору данные о участиках конференции
// //Опрашиваем юзера о готовности принять вызов. отправляем ему ask
// const subscriptions = Subscriptions.findByRoomId(value.roomId, {
// fields: { 'u._id': 1 },
// sort: { 'u.username': 1 },
// })
// const members = subscriptions.fetch().map((s) => s.u && s.u._id)
// //console.log('+++++++++++++++++++ members', members)
// const count = members.length
// //console.log('+++++++++++++++++++ count', count)
// if (members) {
// valueToCaller = {
// type: "outCall",
// roomId: value.roomId,
// initUserId: value.userId,
// count: count,
// members: [],
// date: new Date()
// }
// //Добавляем участников, исключая инициатора
// members.map((id) => {
// if (id !== value.userId) {
// valueToCaller.members.push(
// {
// userId: id,
// status: false,
// }
// )
// }
// })
// valueToUser = {
// type: "inCall",
// roomId: value.roomId,
// initUserId: value.userId,
// count: count
// }
// members.map((id) => {
// console.log('STREEM to USER_ID', id)
// if (id == value.userId) {
// streamerJitsiCall.emit(id + '/'+ streamName, valueToCaller) //Данные для инициатора вызова
// } else {
// streamerJitsiCall.emit(id + '/'+ streamName, valueToUser) //Запрос о готовности клиента
// }
// })
// }
// break
case 'cancel':
//Если инициатор отменил вызов
// Параметры type, roomId, userId, members
if (value.members) {
valueToUsers = {
type: 'cancel',
roomId: value.roomId,
initUserId: value.userId,
}
value.members.map((m) => {
streamerJitsiCall.emit(m.userId + '/' + streamName, valueToUsers) //Отмена вызова
})
}
break
case 'reject':
// Если юзер отклонил входящий вызов
// Параметры type, roomId, userId, initUserId
if (value.initUserId) {
valueToUsers = {
type: 'reject',
roomId: value.roomId,
initUserId: value.initUserId,
rejectUserId: value.userId, //юзер который отказлся принять вызов
}
//console.log('STREEM to USER_ID')
streamerJitsiCall.emit(value.initUserId + '/' + streamName, valueToUsers) //Отказ от принятия входящего вызова
}
break
case 'answer':
// Если юзер принял входящий вызов, необходимо прекратить звонок на других устройствах
// Параметры type, roomId, userId, initUserId
if (value.initUserId) {
// valueToUsers = {
// type: 'answer',
// roomId: value.roomId,
// initUserId: value.initUserId,
// answerUserId: value.userId, //юзер который принял входящий вызов
// }
//console.log('STREEM to USER_ID')
// streamerJitsiCall.emit(value.initUserId + '/'+ streamName, valueToUsers) //Начать конференцию Вызывающему юзеру
// streamerJitsiCall.emit(value.userId + '/'+ streamName, valueToUsers) //Начать конференцию ответившему юзеру
//Говорим что ответили на другом устройстве
streamerJitsiCall.emit(value.userId + '/' + streamName, { type: 'finishInCall', roomId: value.roomId, status: 'finishInCall' }) //Закончить вызов если ответивший имеет несколько запущенных клиентов
}
break
case 'connect':
// Опоздавший юзер
if (value.userId) {
streamerJitsiCall.emit(value.userId + '/' + streamName, { type: 'connect', roomId: value.roomId })
}
break
}
}
})
// streamerJitsiCall.on('sendJitsiCallToServer', function (value) {
// console.log("------------------- sendJitsiCallToServer-----------------")
// console.log("------value", value)
// console.log("--------------------------------------------------")
// if (value.jitsiUrl && value.userId && value.roomId) {
// console.log('++++++++++++++++++++++++++++++++++++++++++')
// const subscriptions = Subscriptions.findByRoomId(value.roomId, {
// fields: { 'u._id': 1 },
// sort: { 'u.username': 1 },
// //skip: offset,
// //limit: count,
// })
// //const total = subscriptions.count();
// console.log('++++++++++++++++++++++++++++++++++++++++++')
// const members = subscriptions.fetch().map((s) => s.u && s.u._id)
// console.log('++++++++++++++++++++++++++++++++++++++++++members', members)
// // const users = Users.find(
// // { _id: { $in: members } },
// // {
// // fields: {
// // _id: 1,
// // username: 1,
// // name: 1,
// // status: 1,
// // statusText: 1,
// // utcOffset: 1,
// // },
// // sort: { username: sort.username != null ? sort.username : 1 },
// // }
// // ).fetch()
// // console.log('++++++++++++++++++++++++++++++++++++++++++members', users)
// members.map((id) => {
// if (id!==value.userId) {
// console.log('STREEM to USER_ID', id)
// //let steamName = id + '/getJitsiCall'
// streamerJitsiCall.emit(id + '/JitsiCall', value)
// }
// })
// }
// })
// streamerJitsiCall.on('sendClickJitsiCall', function (value) {
// console.log("------------------- sendClickJitsiCall-----------------")
// console.log("------value", value)
// console.log("--------------------------------------------------")
// if (value.userId && value.roomId) {
// console.log('++++++++++++++++++++++++++++++++++++++++++')
// const subscriptions = Subscriptions.findByRoomId(value.roomId, {
// fields: { 'u._id': 1 },
// sort: { 'u.username': 1 },
// })
// const members = subscriptions.fetch().map((s) => s.u && s.u._id)
// console.log('++++++++++++++++++++++++++++++++++++++++++members', members)
// members.map((id) => {
// console.log('STREEM to USER_ID', id)
// value.caller = id==value.userId ? true : false //true - Звонящий. false - Вызываемый
// streamerJitsiCall.emit(id + '/JitsiCall', value)
// })
// }
// })
// streamerJitsiCall.on('sendAnswerJitsiCall', function (value) {
// console.log("------------------- sendAnswerJitsiCall-----------------")
// console.log("------value", value)
// console.log("--------------------------------------------------")
// if (value.userId && value.roomId) {
// console.log('++++++++++++++++++++++++++++++++++++++++++')
// const subscriptions = Subscriptions.findByRoomId(value.roomId, {
// fields: { 'u._id': 1 },
// sort: { 'u.username': 1 },
// })
// const members = subscriptions.fetch().map((s) => s.u && s.u._id)
// console.log('++++++++++++++++++++++++++++++++++++++++++members', members)
// members.map((id) => {
// console.log('STREEM to USER_ID', id)
// value.caller = id==value.userId ? true : false //true - Звонящий. false - Вызываемый
// streamerJitsiCall.emit(id + '/AnswerJitsiCall', value)
// })
// }
// })
// streamerJitsiCall.on('sendRejectJitsiCall', function (value) {
// console.log("------------------- sendRejectJitsiCall-----------------")
// console.log("------value", value)
// console.log("--------------------------------------------------")
// if (value.userId && value.roomId) {
// console.log('++++++++++++++++++++++++++++++++++++++++++')
// const subscriptions = Subscriptions.findByRoomId(value.roomId, {
// fields: { 'u._id': 1 },
// sort: { 'u.username': 1 },
// })
// const members = subscriptions.fetch().map((s) => s.u && s.u._id)
// console.log('++++++++++++++++++++++++++++++++++++++++++members', members)
// members.map((id) => {
// console.log('STREEM to USER_ID', id)
// value.caller = id==value.userId ? true : false //true - Звонящий. false - Вызываемый
// streamerJitsiCall.emit(id + '/RejectJitsiCall', value)
// })
// }
// })
// value = {
// type : ["start", "ask", "accepted", "init", "cancel", "answer","reject", "connect", "stop", "error"],
// initUserId: initUserId,
// userId: userId,
// roomId: roomId,
// count: count
// members: [
// {
// userId: userId,
// answered: true,
// accepted: true
// }
// ],
// }
|
import React, { useState, useEffect, useContext } from "react";
import HomeComapanySearchFilter from "./HomeComapanySearchFilter";
import { getAllKeywords } from "../API/Api";
import UserContext from "Context/UserContext";
import HomePageEmployementJobProjectResultCard from "Components/HomePageEmployementJobProjectResultCard";
import timeSvg from "../Assets/timeSvg.svg";
import Img from "react-cool-img";
import IndustrySvg from "../Assets/IndustrySvg.svg";
import milesSvg from "../Assets/milesSvg.svg";
import employeeSvg from "../Assets/employeeSvg.svg";
import moneySvg from "../Assets/moneySvg.svg";
import { getText } from "Utils/functions";
import NoData from "./NoData";
export default function JobProjectPanel({
descriptionHeading,
responsibilitesHeading,
isFreelancer,
jobsList,
setIsApplyForJob,
searchByFilter,
setIsLoginOpen,
resetFilter,
keyword,
selectedLocation,
selectedRange,
}) {
const [title, setTitle] = useState("");
let [keyWordTitle, setKeyWordTitle] = useState(keyword);
const [id, setId] = useState(0);
const [skills, setSkills] = useState([]);
const [jobType, setJobType] = useState("");
const [description, setDescription] = useState("");
const [requirements, setRequirements] = useState("");
const [jobLocation, setJobLocation] = useState("");
let [location, setLocation] = useState(selectedLocation);
const [projectDeadline, setProjectDeadline] = useState("");
const [isLoading, setIsLoading] = useState(true);
const [searchBy, setSearchBy] = useState("Employment");
const [searchByFreelancer, setSearchByFreelancer] = useState("Freelancer");
const [keywords, setKeywords] = useState([]);
const [jobStatusApiData, setJobStatusApiData] = useState();
const [isInterestedCheck, setIsInterestedCheck] = useState(false);
const [isAppliedCheck, setIsAppliedCheck] = useState(false);
let [range, setRange] = useState(selectedRange);
const [data, setData] = useState(null);
const [noOfEmployees, setNoOfEmployees] = useState(null);
const [industry, setIndustry] = useState(null);
const [budget, setBudget] = useState(null);
const user = useContext(UserContext);
useEffect(() => {
handleShowJobDetail(jobsList[0], isFreelancer);
}, [jobsList]);
const handleShowJobDetail = (selectedJobData, isFreelancer) => {
setData(selectedJobData);
setId(selectedJobData.Id);
if (!isFreelancer) {
setTitle(
selectedJobData.JobTitle ? selectedJobData.JobTitle : "Not specified"
);
setSkills(selectedJobData.JobSkills);
setJobType(
selectedJobData.JobTypes
? selectedJobData.JobTypes.map(
(item) => item.JobTypeDetailTitle
).join(", ")
: "Not specified"
);
setJobLocation(selectedJobData.Location);
setNoOfEmployees(selectedJobData.NoOfEmployees);
setIndustry(selectedJobData.Company_Industry_Title);
setDescription(selectedJobData.Description);
setRequirements(selectedJobData.Requirements);
if (selectedJobData.SalaryTypeLookup == null) setBudget("Salary");
else {
setBudget(
selectedJobData.SalaryTypeLookup == "Negotiable"
? selectedJobData.SalaryTypeLookup
: selectedJobData.SalaryFrom
? selectedJobData.SalaryTo
? "€ " +
selectedJobData.SalaryFrom +
" - € " +
selectedJobData.SalaryTo
: "€ " + selectedJobData.SalaryFrom
: 0
);
}
} else {
setTitle(selectedJobData.Title);
setSkills(selectedJobData.ProjectSkills);
setJobLocation(selectedJobData.Location);
setDescription(selectedJobData.Description);
setProjectDeadline(selectedJobData.Deadline);
if (selectedJobData.SalaryTypeLookup == null) setBudget("Salary");
else {
setBudget(
selectedJobData.SalaryTypeLookup == "Negotiable"
? selectedJobData.SalaryTypeLookup
: selectedJobData.SalaryFrom
? selectedJobData.SalaryTo
? "€ " +
selectedJobData.SalaryFrom +
" - € " +
selectedJobData.SalaryTo
: "€ " + selectedJobData.SalaryFrom
: 0
);
}
}
// jobStatusAPI(!isFreelancer ? "Jobs" : "Projects", selectedJobData.Id);
};
// const jobStatusAPI = (type, Id) => {
// setIsLoading(true);
// jobStatus(type, user.Id, Id)
// .then(({ data }) => {
// setJobStatusApiData(data.result);
// if (data.result) {
// setIsInterestedCheck(data.result.IsInterested);
// setIsAppliedCheck(data.result.IsApplied);
// }
// setIsLoading(false);
// })
// .catch((err) => {
// setIsLoading(false);
// });
// };
const searchDataByTitle = (data) => {
setKeyWordTitle((keyWordTitle = data));
};
const searchByLocation = (data) => {
setLocation(data.formatted_address);
};
const searchByKeyword = (data) => {
setKeyWordTitle((keyWordTitle = data));
};
const searchByUser = (freelancer, employee) => {
setSearchBy(employee ? "Employment" : "");
setSearchByFreelancer(freelancer ? "Freelancer" : "");
};
useEffect(() => {
getAllKeywordsApi();
}, []);
const getAllKeywordsApi = () => {
setIsLoading(true);
getAllKeywords()
.then(({ data }) => {
setKeywords(data.result);
setIsLoading(false);
})
.catch((err) => {
setIsLoading(false);
});
};
const showApplyScreen = () => {
localStorage.setItem("jobId", id);
if (Object.keys(user).length != 0) {
setIsApplyForJob(true);
} else {
setIsLoginOpen(true);
}
};
const searchData = () => {
searchByFilter(keyWordTitle, range, location);
};
const searchByRange = (value) => {
setRange((range = value));
};
const resetFilters = () => {
setKeywords([]);
setKeyWordTitle((keyWordTitle = ""));
setRange((range = 500));
setLocation((location = ""));
getAllKeywordsApi();
resetFilter();
};
return (
<div className="homepage__container__jobs__projects__penel">
{keywords.length > 0 ? (
<HomeComapanySearchFilter
isMainSearch={true}
keywords={keywords}
searchByTitle={searchDataByTitle}
searchByFilter={searchData}
searchByLocation={searchByLocation}
searchByKeyword={(e) => searchByKeyword(e)}
title={keyword}
searchByRange={searchByRange}
searchBy={searchBy}
searchByFreelancer={searchByFreelancer}
searchByUser={searchByUser}
location={location}
resetFilter={() => resetFilters()}
/>
) : null}
<div className="homepage__container__jobs__projects__penel__container">
<div className="homepage__container__jobs__projects__penel__container__sidebar">
{jobsList.length > 0 ? (
<div className="homepage__container__results">
{jobsList.map((item, i) => (
<HomePageEmployementJobProjectResultCard
key={i}
data={item}
showJobDetail={handleShowJobDetail}
isFreelancer={isFreelancer}
checked={i === 0 ? true : false}
/>
))}
</div>
) : (
<NoData />
)}
</div>
{id !== 0 ? (
<div className="homepage__container__jobs__projects__penel__container__details">
<div className="homepage__container__jobs__projects__penel__container__details__heading">
{title}
</div>
<div className="homepage__container__jobs__projects__penel__container__details__feature">
<div className="homepage__container__result__card__content">
<div className="homepage__container__result__card__content">
<div className="homepage__container__result__card__content__entry">
<Img
loading="lazy"
src={timeSvg}
alt="timeSvg"
className="homepage__container__result__card__content__entry__svg"
/>
<div className="homepage__container__result__card__content__entry__text">
{jobType ? jobType : "Not specified"}
{/* Available */}
</div>
</div>
<div className="homepage__container__result__card__content__entry">
<Img
loading="lazy"
src={milesSvg}
alt="milesSvg"
className="homepage__container__result__card__content__entry__svg"
/>
<div className="homepage__container__result__card__content__entry__text">
{jobLocation != "" ? jobLocation : "Not specified"}
</div>
</div>
<div className="homepage__container__result__card__content__entry">
<Img
loading="lazy"
src={IndustrySvg}
alt="IndustrySvg"
className="homepage__container__result__card__content__entry__svg"
/>
<div className="homepage__container__result__card__content__entry__text">
{industry != null ? industry : "Not specified"}
</div>
</div>
<div className="homepage__container__result__card__content__entry">
<Img
loading="lazy"
src={employeeSvg}
alt="employeeSvg"
className="homepage__container__result__card__content__entry__svg"
/>
<div className="homepage__container__result__card__content__entry__text">
{noOfEmployees != null && noOfEmployees != "" ? (
getText(noOfEmployees).length > 10 ? (
<>{`${getText(noOfEmployees).substring(
0,
10
)}... employees`}</>
) : (
<>{getText(noOfEmployees) + " employees"}</>
)
) : (
"employees"
)}
</div>
</div>
<div className="homepage__container__result__card__content__entry">
<Img
loading="lazy"
src={moneySvg}
alt="moneySvg"
className="homepage__container__result__card__content__entry__svg"
/>
<div className="homepage__container__result__card__content__entry__text">
{budget}
</div>
</div>
</div>
</div>
{/* {jobType ? (
<div className="homepage__container__result__card__content__entry">
<svg
xmlns="http://www.w3.org/2000/svg"
width="22.623"
height="23.964"
viewBox="0 0 22.623 23.964"
fill="currentColor"
>
<g
id="Group_990"
data-name="Group 990"
transform="translate(0.25 0.255)"
stroke="currentColor"
opacity="0.55"
>
<path
id="Path_2281"
data-name="Path 2281"
d="M1811.3,2038.608a9.383,9.383,0,1,1-9.361,9.355A9.394,9.394,0,0,1,1811.3,2038.608Zm.423,17.935a8.138,8.138,0,0,0,5.351-2.224l-.456-.5.484-.583.553.505a8.124,8.124,0,0,0,2.215-5.344l-.705-.038v-.747l.705-.034c.153-1.51-1.179-4.666-2.242-5.328l-.472.445-.582-.486.528-.582a8.606,8.606,0,0,0-5.4-2.228v.744h-.755l-.033-.748a8.66,8.66,0,0,0-5.37,2.232l.508.55-.52.553c-.12-.112-.2-.191-.289-.269s-.169-.153-.281-.254a8.657,8.657,0,0,0-2.229,5.366l.75.042v.746l-.7.034c-.16,1.5,1.17,4.652,2.241,5.329l.5-.473.548.525c-.117.125-.2.21-.274.3s-.151.17-.244.275a8.609,8.609,0,0,0,5.4,2.228v-.745h.777Z"
transform="translate(-1800.96 -2033.916)"
stroke="currentColor"
strokeWidth="0.5"
/>
<path
id="Path_2282"
data-name="Path 2282"
d="M2015.993,1984.875a7.729,7.729,0,0,1-.819-.174c-.472-.148-.526-.479-.134-.793a2.692,2.692,0,0,0,1.069-2.006,2.719,2.719,0,0,0-1.01-2.309c-.141-.123-.321-.366-.281-.488a.733.733,0,0,1,.471-.381,3.121,3.121,0,0,1,3.666,4.312A3.116,3.116,0,0,1,2015.993,1984.875Zm.052-.8a2.321,2.321,0,0,0,2.092-1.167,2.212,2.212,0,0,0-.069-2.469,2.274,2.274,0,0,0-2.016-1.051A3.645,3.645,0,0,1,2016.045,1984.077Z"
transform="translate(-1997.16 -1978.602)"
stroke="currentColor"
strokeWidth="0.5"
/>
<path
id="Path_2283"
data-name="Path 2283"
d="M1874.574,1987.85l-.5-.641.374-.435h-7.187v-.794h7.191l-.437-.541.536-.54c.417.426.824.807,1.181,1.232a.537.537,0,0,1-.035.511C1875.366,1987.052,1874.981,1987.423,1874.574,1987.85Z"
transform="translate(-1861.181 -1984.407)"
stroke="currentColor"
strokeWidth="0.5"
/>
<path
id="Path_2284"
data-name="Path 2284"
d="M1792.957,1997.863a1.758,1.758,0,1,1-1.777-1.747A1.759,1.759,0,0,1,1792.957,1997.863Zm-.787.012a.97.97,0,1,0-.969.971A.975.975,0,0,0,1792.171,1997.875Z"
transform="translate(-1789.442 -1994.747)"
stroke="currentColor"
strokeWidth="0.5"
/>
<path
id="Path_2296"
data-name="Path 2296"
d="M1870.046,2076.979c1.536.274,1.823.627,1.821,2.24,0,.6.015,1.2-.01,1.8a.506.506,0,0,0,.332.534c.855.441,1.7.9,2.587,1.376l-.357.689c-.632-.332-1.23-.643-1.824-.959-1.161-.618-2.325-1.231-3.477-1.866a.584.584,0,0,0-.7.02c-1.23.805-2.477,1.585-3.757,2.4l-.436-.651c.364-.232.688-.468,1.039-.653a.619.619,0,0,0,.35-.655c-.019-.807-.005-1.615,0-2.423a1.591,1.591,0,0,1,1.721-1.807,1.111,1.111,0,0,0,.149-.038,2.076,2.076,0,0,1-.681-1.8,1.913,1.913,0,0,1,.663-1.207,1.955,1.955,0,0,1,2.576.019C1870.885,2074.742,1870.888,2075.7,1870.046,2076.979Zm1.035,3.971c0-.8.005-1.539,0-2.275a.788.788,0,0,0-.878-.867q-1.466-.008-2.931,0a.784.784,0,0,0-.876.867c-.007.742,0,1.485,0,2.228a1.682,1.682,0,0,0,.043.246c.654-.415,1.276-.793,1.878-1.2a.688.688,0,0,1,.824-.034C1869.756,2080.267,1870.393,2080.587,1871.081,2080.951Zm-2.335-6.66a1.169,1.169,0,1,0,1.16,1.179A1.184,1.184,0,0,0,1868.746,2074.291Z"
transform="translate(-1858.376 -2066.077)"
stroke="currentColor"
strokeWidth="0.5"
/>
</g>
</svg>
<div className="homepage__container__result__card__content__entry__text">
{jobType ? jobType : "Not specified"}
</div>
</div>
) : (
null
)}
{jobLocation ? (
<div className="homepage__container__result__card__content__entry">
<svg
xmlns="http://www.w3.org/2000/svg"
width="13.824"
height="18.568"
viewBox="0 0 13.824 18.568"
fill="currentColor"
>
<g id="place" opacity="0.55">
<g
id="Group_749"
data-name="Group 749"
transform="translate(0)"
>
<g id="Group_748" data-name="Group 748">
<path
id="Path_2297"
data-name="Path 2297"
d="M61.47,3.228a6.6,6.6,0,0,0-11.344,0,8.049,8.049,0,0,0-.8,6.908,6.023,6.023,0,0,0,1,1.8l5.019,6.406a.567.567,0,0,0,.91,0l5.017-6.4a6.029,6.029,0,0,0,1-1.794A8.051,8.051,0,0,0,61.47,3.228Zm-.317,6.458a4.722,4.722,0,0,1-.788,1.4l0,0L55.8,16.917l-4.567-5.828a4.724,4.724,0,0,1-.789-1.407,6.658,6.658,0,0,1,.667-5.715,5.454,5.454,0,0,1,9.378,0A6.659,6.659,0,0,1,61.153,9.686Z"
transform="translate(-48.886)"
/>
</g>
</g>
<g
id="Group_751"
data-name="Group 751"
transform="translate(3.567 4.05)"
>
<g id="Group_750" data-name="Group 750">
<path
id="Path_2298"
data-name="Path 2298"
d="M159.1,106.219a3.346,3.346,0,1,0,3.346,3.346A3.35,3.35,0,0,0,159.1,106.219Zm0,5.5a2.151,2.151,0,1,1,2.151-2.151A2.153,2.153,0,0,1,159.1,111.716Z"
transform="translate(-155.754 -106.219)"
/>
</g>
</g>
</g>
</svg>
<div className="homepage__container__result__card__content__entry__text">
{jobLocation ? jobLocation : "Not specified"}
</div>
</div>
) : (
null
)}
</div> */}
{isAppliedCheck ? (
<a
className="header__nav__btn btn__secondary"
style={{
width: "150px",
height: "45px",
marginTop: "1em",
marginBottom: "2em",
}}
>
Already Applied
</a>
) : (
<a
className="header__nav__btn btn__secondary"
style={{
width: "150px",
height: "45px",
marginTop: "1em",
marginBottom: "2em",
}}
onClick={() => showApplyScreen()}
>
Apply
</a>
)}
</div>
<div className="homepage__container__result__card__badges">
{skills.map((skill, i) => (
<div
className="homepage__container__result__card__badge"
key={i}
>
{skill.Title}
</div>
))}
</div>
<div className="homepage__container__jobs__projects__penel__container__details__info">
<div className="homepage__container__jobs__projects__penel__container__details__info__heading">
{descriptionHeading}
</div>
<div className="homepage__container__jobs__projects__penel__container__details__content">
{getText(description).length > 1000 ? (
<>{`${getText(description).substring(0, 1000)}...`}</>
) : (
<>{getText(description)}</>
)}
</div>
</div>
<div className="homepage__container__jobs__projects__penel__container__details__info">
<div className="homepage__container__jobs__projects__penel__container__details__info__heading">
{responsibilitesHeading}
</div>
<div className="homepage__container__jobs__projects__penel__container__details__content">
{getText(requirements).length > 1000 ? (
<>{`${getText(requirements).substring(0, 1000)}...`}</>
) : (
<>{getText(requirements)}</>
)}
</div>
</div>
</div>
) : null}
</div>
</div>
);
}
|
'use strict'
const { parseArgs } = require('./utils')
module.exports = ({ ipld, preload }) => {
return async function get (cid, path, options) {
[cid, path, options] = parseArgs(cid, path, options)
if (options.preload !== false) {
preload(cid)
}
if (path == null || path === '/') {
const value = await ipld.get(cid)
return {
value,
remainderPath: ''
}
} else {
let result
for await (const entry of ipld.resolve(cid, path)) {
if (options.localResolve) {
return entry
}
result = entry
}
return result
}
}
}
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef ClientTestLibraryC_h
#define ClientTestLibraryC_h
#include "ClientTestLibraryCExport.h"
#include "itkObject.h"
namespace LibraryC
{
class ClientTestLibraryC_EXPORT ITKObjectProducer
{
public:
ITKObjectProducer();
itk::Object *
EquivalencyTable();
itk::Object *
Image();
private:
itk::Object::Pointer m_EquivalencyTable;
itk::Object::Pointer m_Image;
};
int ClientTestLibraryC_EXPORT
dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, itk::Object const * base);
int ClientTestLibraryC_EXPORT
dynamic_castDownCastImage(const char * type, const char * instanceSource, itk::Object const * base);
} // end namespace LibraryC
#endif
|
'use strict';
const txtLog = () => document.getElementById('txtLog');
/**
* Implementation has been changed to utilize flex-layout to reverse the log direction.
* @param {string} aText
*/
function addLogText(aText) {
let d = document.createElement('div');
d.innerHTML = aText;
txtLog().appendChild(d);
}
function setMousePos(aEvent) {
const bounds = cvs.getBoundingClientRect();
mousePos.x = aEvent.clientX - bounds.left;
mousePos.y = aEvent.clientY - bounds.top;
}
// convenience, so we don't have to type addLogText every time we wish to log.
const log = addLogText;
|
/*
* Implementation of the Microsoft Installer (msi.dll)
*
* Copyright 2002 Mike McCormack for CodeWeavers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdarg.h>
#include "windef.h"
#include "winbase.h"
#include "winerror.h"
#include "wine/debug.h"
#include "msi.h"
#include "msiquery.h"
#include "objbase.h"
#include "objidl.h"
#include "msipriv.h"
#include "winnls.h"
#include "query.h"
WINE_DEFAULT_DEBUG_CHANNEL(msidb);
#define MSI_HASH_TABLE_SIZE 37
typedef struct tagMSIHASHENTRY
{
struct tagMSIHASHENTRY *next;
UINT value;
UINT row;
} MSIHASHENTRY;
/* below is the query interface to a table */
typedef struct tagMSIWHEREVIEW
{
MSIVIEW view;
MSIDATABASE *db;
MSIVIEW *table;
UINT row_count;
MSIHASHENTRY **reorder;
struct expr *cond;
UINT rec_index;
} MSIWHEREVIEW;
static void free_hash_table(MSIHASHENTRY **table)
{
MSIHASHENTRY *new, *old;
int i;
if (!table)
return;
for (i = 0; i < MSI_HASH_TABLE_SIZE; i++)
{
new = table[i];
while (new)
{
old = new;
new = old->next;
msi_free(old);
}
table[i] = NULL;
}
msi_free(table);
}
static UINT find_entry_in_hash(MSIHASHENTRY **table, UINT row, UINT *val)
{
MSIHASHENTRY *entry;
if (!table)
return ERROR_SUCCESS;
if (!(entry = table[row % MSI_HASH_TABLE_SIZE]))
{
WARN("Row not found in hash table!\n");
return ERROR_FUNCTION_FAILED;
}
while (entry && entry->row != row)
entry = entry->next;
if (entry) *val = entry->value;
return ERROR_SUCCESS;
}
static UINT add_entry_to_hash(MSIHASHENTRY **table, UINT row, UINT val)
{
MSIHASHENTRY *new = msi_alloc(sizeof(MSIHASHENTRY));
MSIHASHENTRY *prev;
if (!new)
return ERROR_OUTOFMEMORY;
new->next = NULL;
new->value = val;
new->row = row;
prev = table[row % MSI_HASH_TABLE_SIZE];
if (prev)
new->next = prev;
table[row % MSI_HASH_TABLE_SIZE] = new;
return ERROR_SUCCESS;
}
static UINT WHERE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW*)view;
UINT r;
TRACE("%p %d %d %p\n", wv, row, col, val );
if( !wv->table )
return ERROR_FUNCTION_FAILED;
if( row > wv->row_count )
return ERROR_NO_MORE_ITEMS;
r = find_entry_in_hash(wv->reorder, row, &row);
if (r != ERROR_SUCCESS)
return r;
return wv->table->ops->fetch_int( wv->table, row, col, val );
}
static UINT WHERE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW*)view;
UINT r;
TRACE("%p %d %d %p\n", wv, row, col, stm );
if( !wv->table )
return ERROR_FUNCTION_FAILED;
if( row > wv->row_count )
return ERROR_NO_MORE_ITEMS;
r = find_entry_in_hash(wv->reorder, row, &row);
if (r != ERROR_SUCCESS)
return r;
return wv->table->ops->fetch_stream( wv->table, row, col, stm );
}
static UINT WHERE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW *)view;
UINT r;
TRACE("%p %d %p\n", wv, row, rec );
if (!wv->table)
return ERROR_FUNCTION_FAILED;
if (row > wv->row_count)
return ERROR_NO_MORE_ITEMS;
r = find_entry_in_hash(wv->reorder, row, &row);
if (r != ERROR_SUCCESS)
return r;
return wv->table->ops->get_row(wv->table, row, rec);
}
static UINT WHERE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW*)view;
UINT r;
TRACE("%p %d %p %08x\n", wv, row, rec, mask );
if( !wv->table )
return ERROR_FUNCTION_FAILED;
if( row > wv->row_count )
return ERROR_NO_MORE_ITEMS;
r = find_entry_in_hash(wv->reorder, row, &row);
if (r != ERROR_SUCCESS)
return r;
return wv->table->ops->set_row( wv->table, row, rec, mask );
}
static UINT WHERE_delete_row(struct tagMSIVIEW *view, UINT row)
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW *)view;
UINT r;
TRACE("(%p %d)\n", view, row);
if ( !wv->table )
return ERROR_FUNCTION_FAILED;
if ( row > wv->row_count )
return ERROR_NO_MORE_ITEMS;
r = find_entry_in_hash( wv->reorder, row, &row );
if ( r != ERROR_SUCCESS )
return r;
return wv->table->ops->delete_row( wv->table, row );
}
static INT INT_evaluate_binary( INT lval, UINT op, INT rval )
{
switch( op )
{
case OP_EQ:
return ( lval == rval );
case OP_AND:
return ( lval && rval );
case OP_OR:
return ( lval || rval );
case OP_GT:
return ( lval > rval );
case OP_LT:
return ( lval < rval );
case OP_LE:
return ( lval <= rval );
case OP_GE:
return ( lval >= rval );
case OP_NE:
return ( lval != rval );
default:
ERR("Unknown operator %d\n", op );
}
return 0;
}
static INT INT_evaluate_unary( INT lval, UINT op )
{
switch( op )
{
case OP_ISNULL:
return ( !lval );
case OP_NOTNULL:
return ( lval );
default:
ERR("Unknown operator %d\n", op );
}
return 0;
}
static const WCHAR *STRING_evaluate( MSIWHEREVIEW *wv, UINT row,
const struct expr *expr,
const MSIRECORD *record )
{
UINT val = 0, r;
switch( expr->type )
{
case EXPR_COL_NUMBER_STRING:
r = wv->table->ops->fetch_int( wv->table, row, expr->u.col_number, &val );
if( r != ERROR_SUCCESS )
return NULL;
return msi_string_lookup_id( wv->db->strings, val );
case EXPR_SVAL:
return expr->u.sval;
case EXPR_WILDCARD:
return MSI_RecordGetString( record, ++wv->rec_index );
default:
ERR("Invalid expression type\n");
break;
}
return NULL;
}
static UINT STRCMP_Evaluate( MSIWHEREVIEW *wv, UINT row, const struct expr *cond,
INT *val, const MSIRECORD *record )
{
int sr;
const WCHAR *l_str, *r_str;
l_str = STRING_evaluate( wv, row, cond->u.expr.left, record );
r_str = STRING_evaluate( wv, row, cond->u.expr.right, record );
if( l_str == r_str ||
((!l_str || !*l_str) && (!r_str || !*r_str)) )
sr = 0;
else if( l_str && ! r_str )
sr = 1;
else if( r_str && ! l_str )
sr = -1;
else
sr = lstrcmpW( l_str, r_str );
*val = ( cond->u.expr.op == OP_EQ && ( sr == 0 ) ) ||
( cond->u.expr.op == OP_NE && ( sr != 0 ) ) ||
( cond->u.expr.op == OP_LT && ( sr < 0 ) ) ||
( cond->u.expr.op == OP_GT && ( sr > 0 ) );
return ERROR_SUCCESS;
}
static UINT WHERE_evaluate( MSIWHEREVIEW *wv, UINT row,
struct expr *cond, INT *val, MSIRECORD *record )
{
UINT r, tval;
INT lval, rval;
if( !cond )
return ERROR_SUCCESS;
switch( cond->type )
{
case EXPR_COL_NUMBER:
r = wv->table->ops->fetch_int( wv->table, row, cond->u.col_number, &tval );
*val = tval - 0x8000;
return ERROR_SUCCESS;
case EXPR_COL_NUMBER32:
r = wv->table->ops->fetch_int( wv->table, row, cond->u.col_number, &tval );
*val = tval - 0x80000000;
return r;
case EXPR_UVAL:
*val = cond->u.uval;
return ERROR_SUCCESS;
case EXPR_COMPLEX:
r = WHERE_evaluate( wv, row, cond->u.expr.left, &lval, record );
if( r != ERROR_SUCCESS )
return r;
r = WHERE_evaluate( wv, row, cond->u.expr.right, &rval, record );
if( r != ERROR_SUCCESS )
return r;
*val = INT_evaluate_binary( lval, cond->u.expr.op, rval );
return ERROR_SUCCESS;
case EXPR_UNARY:
r = wv->table->ops->fetch_int( wv->table, row, cond->u.expr.left->u.col_number, &tval );
if( r != ERROR_SUCCESS )
return r;
*val = INT_evaluate_unary( tval, cond->u.expr.op );
return ERROR_SUCCESS;
case EXPR_STRCMP:
return STRCMP_Evaluate( wv, row, cond, val, record );
case EXPR_WILDCARD:
*val = MSI_RecordGetInteger( record, ++wv->rec_index );
return ERROR_SUCCESS;
default:
ERR("Invalid expression type\n");
break;
}
return ERROR_SUCCESS;
}
static UINT WHERE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW*)view;
UINT count = 0, r, i;
INT val;
MSIVIEW *table = wv->table;
TRACE("%p %p\n", wv, record);
if( !table )
return ERROR_FUNCTION_FAILED;
r = table->ops->execute( table, record );
if( r != ERROR_SUCCESS )
return r;
r = table->ops->get_dimensions( table, &count, NULL );
if( r != ERROR_SUCCESS )
return r;
free_hash_table(wv->reorder);
wv->reorder = msi_alloc_zero(MSI_HASH_TABLE_SIZE * sizeof(MSIHASHENTRY *));
if( !wv->reorder )
return ERROR_OUTOFMEMORY;
wv->row_count = 0;
if (wv->cond->type == EXPR_STRCMP)
{
MSIITERHANDLE handle = NULL;
UINT row, value, col;
struct expr *col_cond = wv->cond->u.expr.left;
struct expr *val_cond = wv->cond->u.expr.right;
/* swap conditionals */
if (col_cond->type != EXPR_COL_NUMBER_STRING)
{
val_cond = wv->cond->u.expr.left;
col_cond = wv->cond->u.expr.right;
}
if ((col_cond->type == EXPR_COL_NUMBER_STRING) && (val_cond->type == EXPR_SVAL))
{
col = col_cond->u.col_number;
/* special case for "" - translate it into nil */
if (!val_cond->u.sval[0])
value = 0;
else
{
r = msi_string2idW(wv->db->strings, val_cond->u.sval, &value);
if (r != ERROR_SUCCESS)
{
TRACE("no id for %s, assuming it doesn't exist in the table\n", debugstr_w(wv->cond->u.expr.right->u.sval));
return ERROR_SUCCESS;
}
}
do
{
r = table->ops->find_matching_rows(table, col, value, &row, &handle);
if (r == ERROR_SUCCESS)
add_entry_to_hash(wv->reorder, wv->row_count++, row);
} while (r == ERROR_SUCCESS);
if (r == ERROR_NO_MORE_ITEMS)
return ERROR_SUCCESS;
else
return r;
}
/* else fallback to slow case */
}
for( i=0; i<count; i++ )
{
val = 0;
wv->rec_index = 0;
r = WHERE_evaluate( wv, i, wv->cond, &val, record );
if( r != ERROR_SUCCESS )
return r;
if( val )
add_entry_to_hash( wv->reorder, wv->row_count++, i );
}
return ERROR_SUCCESS;
}
static UINT WHERE_close( struct tagMSIVIEW *view )
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW*)view;
TRACE("%p\n", wv );
if( !wv->table )
return ERROR_FUNCTION_FAILED;
return wv->table->ops->close( wv->table );
}
static UINT WHERE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols )
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW*)view;
TRACE("%p %p %p\n", wv, rows, cols );
if( !wv->table )
return ERROR_FUNCTION_FAILED;
if( rows )
{
if( !wv->reorder )
return ERROR_FUNCTION_FAILED;
*rows = wv->row_count;
}
return wv->table->ops->get_dimensions( wv->table, NULL, cols );
}
static UINT WHERE_get_column_info( struct tagMSIVIEW *view,
UINT n, LPWSTR *name, UINT *type )
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW*)view;
TRACE("%p %d %p %p\n", wv, n, name, type );
if( !wv->table )
return ERROR_FUNCTION_FAILED;
return wv->table->ops->get_column_info( wv->table, n, name, type );
}
static UINT WHERE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
MSIRECORD *rec, UINT row )
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW*)view;
TRACE("%p %d %p\n", wv, eModifyMode, rec);
find_entry_in_hash(wv->reorder, row - 1, &row);
row++;
return wv->table->ops->modify( wv->table, eModifyMode, rec, row );
}
static UINT WHERE_delete( struct tagMSIVIEW *view )
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW*)view;
TRACE("%p\n", wv );
if( wv->table )
wv->table->ops->delete( wv->table );
wv->table = 0;
free_hash_table(wv->reorder);
wv->reorder = NULL;
wv->row_count = 0;
msiobj_release( &wv->db->hdr );
msi_free( wv );
return ERROR_SUCCESS;
}
static UINT WHERE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
UINT val, UINT *row, MSIITERHANDLE *handle )
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW*)view;
UINT r;
TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
if( !wv->table )
return ERROR_FUNCTION_FAILED;
r = wv->table->ops->find_matching_rows( wv->table, col, val, row, handle );
if (r != ERROR_SUCCESS)
return r;
if( *row > wv->row_count )
return ERROR_NO_MORE_ITEMS;
return find_entry_in_hash(wv->reorder, *row, row);
}
static UINT WHERE_sort(struct tagMSIVIEW *view, column_info *columns)
{
MSIWHEREVIEW *wv = (MSIWHEREVIEW *)view;
TRACE("%p %p\n", view, columns);
return wv->table->ops->sort(wv->table, columns);
}
static const MSIVIEWOPS where_ops =
{
WHERE_fetch_int,
WHERE_fetch_stream,
WHERE_get_row,
WHERE_set_row,
NULL,
WHERE_delete_row,
WHERE_execute,
WHERE_close,
WHERE_get_dimensions,
WHERE_get_column_info,
WHERE_modify,
WHERE_delete,
WHERE_find_matching_rows,
NULL,
NULL,
NULL,
NULL,
WHERE_sort,
NULL,
};
static UINT WHERE_VerifyCondition( MSIDATABASE *db, MSIVIEW *table, struct expr *cond,
UINT *valid )
{
UINT r, val = 0;
switch( cond->type )
{
case EXPR_COLUMN:
r = VIEW_find_column( table, cond->u.column, &val );
if( r == ERROR_SUCCESS )
{
UINT type = 0;
r = table->ops->get_column_info( table, val, NULL, &type );
if( r == ERROR_SUCCESS )
{
if (type&MSITYPE_STRING)
cond->type = EXPR_COL_NUMBER_STRING;
else if ((type&0xff) == 4)
cond->type = EXPR_COL_NUMBER32;
else
cond->type = EXPR_COL_NUMBER;
cond->u.col_number = val;
*valid = 1;
}
else
*valid = 0;
}
else
{
*valid = 0;
WARN("Couldn't find column %s\n", debugstr_w( cond->u.column ) );
}
break;
case EXPR_COMPLEX:
r = WHERE_VerifyCondition( db, table, cond->u.expr.left, valid );
if( r != ERROR_SUCCESS )
return r;
if( !*valid )
return ERROR_SUCCESS;
r = WHERE_VerifyCondition( db, table, cond->u.expr.right, valid );
if( r != ERROR_SUCCESS )
return r;
/* check the type of the comparison */
if( ( cond->u.expr.left->type == EXPR_SVAL ) ||
( cond->u.expr.left->type == EXPR_COL_NUMBER_STRING ) ||
( cond->u.expr.right->type == EXPR_SVAL ) ||
( cond->u.expr.right->type == EXPR_COL_NUMBER_STRING ) )
{
switch( cond->u.expr.op )
{
case OP_EQ:
case OP_GT:
case OP_LT:
case OP_NE:
break;
default:
*valid = FALSE;
return ERROR_INVALID_PARAMETER;
}
/* FIXME: check we're comparing a string to a column */
cond->type = EXPR_STRCMP;
}
break;
case EXPR_UNARY:
if ( cond->u.expr.left->type != EXPR_COLUMN )
{
*valid = FALSE;
return ERROR_INVALID_PARAMETER;
}
r = WHERE_VerifyCondition( db, table, cond->u.expr.left, valid );
if( r != ERROR_SUCCESS )
return r;
break;
case EXPR_IVAL:
*valid = 1;
cond->type = EXPR_UVAL;
cond->u.uval = cond->u.ival;
break;
case EXPR_WILDCARD:
*valid = 1;
break;
case EXPR_SVAL:
*valid = 1;
break;
default:
ERR("Invalid expression type\n");
*valid = 0;
break;
}
return ERROR_SUCCESS;
}
UINT WHERE_CreateView( MSIDATABASE *db, MSIVIEW **view, MSIVIEW *table,
struct expr *cond )
{
MSIWHEREVIEW *wv = NULL;
UINT count = 0, r, valid = 0;
TRACE("%p\n", table );
r = table->ops->get_dimensions( table, NULL, &count );
if( r != ERROR_SUCCESS )
{
ERR("can't get table dimensions\n");
return r;
}
if( cond )
{
r = WHERE_VerifyCondition( db, table, cond, &valid );
if( r != ERROR_SUCCESS )
return r;
if( !valid )
return ERROR_FUNCTION_FAILED;
}
wv = msi_alloc_zero( sizeof *wv );
if( !wv )
return ERROR_FUNCTION_FAILED;
/* fill the structure */
wv->view.ops = &where_ops;
msiobj_addref( &db->hdr );
wv->db = db;
wv->table = table;
wv->row_count = 0;
wv->reorder = NULL;
wv->cond = cond;
wv->rec_index = 0;
*view = (MSIVIEW*) wv;
return ERROR_SUCCESS;
}
|
define(
"dojo/cldr/nls/cs/roc", //begin v1.x content
{
"field-second": "Sekunda",
"field-year-relative+-1": "Minulý rok",
"field-week": "Týden",
"field-month-relative+-1": "Minulý měsíc",
"field-day-relative+-1": "Včera",
"field-day-relative+-2": "Předevčírem",
"field-year": "Rok",
"field-week-relative+0": "Tento týden",
"field-week-relative+1": "Příští týden",
"field-minute": "Minuta",
"field-week-relative+-1": "Minulý týden",
"field-day-relative+0": "Dnes",
"field-hour": "Hodina",
"field-day-relative+1": "Zítra",
"field-day-relative+2": "Pozítří",
"field-day": "Den",
"field-month-relative+0": "Tento měsíc",
"field-month-relative+1": "Příští měsíc",
"field-dayperiod": "AM/PM",
"field-month": "Měsíc",
"field-era": "Letopočet",
"field-year-relative+0": "Tento rok",
"field-year-relative+1": "Příští rok",
"eraAbbr": [
"Před R. O. C."
],
"field-weekday": "Den v týdnu",
"field-zone": "Časové pásmo"
}
//end v1.x content
);
|
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Gearmand client and server library.
*
* Copyright (C) 2011-2013 Data Differential, http://datadifferential.com/
* Copyright (C) 2008 Brian Aker, Eric Day
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* @file
* @brief Gearmand Declarations
*/
#pragma once
#include <netinet/in.h>
#include <stdlib.h>
#include <poll.h>
#include <event.h>
#include <libgearman-1.0/visibility.h>
#include <libgearman-1.0/protocol.h>
#include <libgearman-server/error.h>
#include <libgearman-server/constants.h>
#include <libgearman-server/wakeup.h>
#include <libgearman-server/byteorder.h>
#include <libgearman-server/log.h>
#include <libgearman-server/packet.h>
#include <libgearman-server/connection.h>
#ifdef __cplusplus
#include <libgearman-server/connection.hpp>
#endif
#include <libgearman-server/function.h>
#include <libgearman-server/client.h>
#include <libgearman-server/worker.h>
#include <libgearman-server/job.h>
#include <libgearman-server/thread.h>
#include <libgearman-server/server.h>
#include <libgearman-server/gearmand_thread.h>
#include <libgearman-server/gearmand_con.h>
#include <libgearman-server/struct/gearmand.h>
#include <libgearman-server/text.h>
#include <libgearman-server/config.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @addtogroup gearmand Gearmand Declarations
*
* This is a server implementation using the gearman_server interface.
*
* @{
*/
GEARMAN_API
gearmand_st *Gearmand(void);
#define Server (&(Gearmand()->server))
/**
* Create a server instance.
* @param host Host for the server to listen on.
* @param port Port for the server to listen on.
* @return Pointer to an allocated gearmand structure.
*/
GEARMAN_API
gearmand_st *gearmand_create(gearmand_config_st *config,
const char *host,
uint32_t threads,
int backlog,
const uint32_t job_retries,
const char *job_handle_prefix,
uint8_t worker_wakeup,
gearmand_log_fn *function, void *log_context, const gearmand_verbose_t verbose,
bool round_robin,
bool exceptions_,
uint32_t hashtable_buckets);
/**
* Free resources used by a server instace.
* @param gearmand Server instance structure previously initialized with
* gearmand_create.
*/
GEARMAN_API
void gearmand_free(gearmand_st *gearmand);
GEARMAN_API
gearman_server_st *gearmand_server(gearmand_st *gearmand);
/**
* Add a port to listen on when starting server with optional callback.
* @param gearmand Server instance structure previously initialized with
* gearmand_create.
* @param port Port for the server to listen on.
* @param function Optional callback function that is called when a connection
has been accepted on the given port.
* @return Standard gearman return value.
*/
GEARMAN_API
gearmand_error_t gearmand_port_add(gearmand_st *gearmand,
const char *port,
gearmand_connection_add_fn*,
gearmand_connection_remove_fn*);
/**
* Run the server instance.
* @param gearmand Server instance structure previously initialized with
* gearmand_create.
* @return Standard gearman return value.
*/
GEARMAN_API
gearmand_error_t gearmand_run(gearmand_st *gearmand);
bool gearmand_exceptions(gearmand_st *gearmand);
/**
* Interrupt a running gearmand server from another thread. You should only
* call this when another thread is currently running gearmand_run() and you
* want to wakeup the server with the given event.
* @param gearmand Server instance structure previously initialized with
* gearmand_create.
* @param wakeup Wakeup event to send to running gearmand.
*/
GEARMAN_API
void gearmand_wakeup(gearmand_st *gearmand, gearmand_wakeup_t wakeup);
GEARMAN_API
const char *gearmand_version(void);
GEARMAN_API
const char *gearmand_bugreport(void);
GEARMAN_API
const char *gearmand_verbose_name(gearmand_verbose_t verbose);
GEARMAN_API
gearmand_error_t gearmand_set_socket_keepalive(gearmand_st *gearmand, bool arg);
GEARMAN_API
gearmand_error_t gearmand_set_socket_keepalive_idle(gearmand_st *gearmand, int arg);
GEARMAN_API
gearmand_error_t gearmand_set_socket_keepalive_interval(gearmand_st *gearmand, int arg);
GEARMAN_API
gearmand_error_t gearmand_set_socket_keepalive_count(gearmand_st *gearmand, int arg);
/** @} */
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
GEARMAN_API
bool gearmand_verbose_check(const char *name, gearmand_verbose_t& level);
#endif
|
import {createStore, combineReducers, applyMiddleware} from 'redux'
import createLogger from 'redux-logger'
import thunkMiddleware from 'redux-thunk'
import {composeWithDevTools} from 'redux-devtools-extension'
import {food} from './food'
import {recipe} from './recipe'
const reducer = combineReducers({food, recipe})
const middleware = composeWithDevTools(
applyMiddleware(thunkMiddleware, createLogger({collapsed: true}))
)
const store = createStore(reducer, middleware)
export default store
export * from './food'
export * from './recipe'
|
import Vue from 'vue'
import VueGithubActivity from 'vue-github-activity'
Vue.use(VueGithubActivity)
|
/*
* Copyright (C) 2017 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
class Type extends Node {
get typeParameters() { return []; }
get kind() { return Type; }
get isPtr() { return false; }
get isArray() { return false; }
get isArrayRef() { return false; }
get isRef() { return this.isPtr || this.isArrayRef; }
get isNumber() { return false; }
get isInt() { return false; }
get isFloating() { return false; }
get isPrimitive() { return false; }
inherits(protocol)
{
if (!protocol)
return {result: true};
return protocol.hasHeir(this);
}
get instantiatedType() { return this.visit(new InstantiateImmediates()); }
// Have to call these on the unifyNode.
argumentForAndOverload(origin, value)
{
return new MakePtrExpression(origin, value);
}
argumentTypeForAndOverload(origin)
{
return new PtrType(origin, "thread", this);
}
returnTypeFromAndOverload(origin)
{
throw new WTypeError(origin.originString, "By-pointer overload returned non-pointer type: " + this);
}
}
|
/**
* bootbox.js 5.2.0
*
* http://bootboxjs.com/license.txt
*/
!function(t,e){'use strict';'function'==typeof define&&define.amd?define(['jquery'],e):'object'==typeof exports?module.exports=e(require('jquery')):t.bootbox=e(t.jQuery)}(this,function e(p,u){'use strict';var r,n,i,l;Object.keys||(Object.keys=(r=Object.prototype.hasOwnProperty,n=!{toString:null}.propertyIsEnumerable('toString'),l=(i=['toString','toLocaleString','valueOf','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','constructor']).length,function(t){if('function'!=typeof t&&('object'!=typeof t||null===t))throw new TypeError('Object.keys called on non-object');var e,o,a=[];for(e in t)r.call(t,e)&&a.push(e);if(n)for(o=0;o<l;o++)r.call(t,i[o])&&a.push(i[o]);return a}));var d={};d.VERSION='5.0.0';var b={ar:{OK:'موافق',CANCEL:'الغاء',CONFIRM:'تأكيد'},bg_BG:{OK:'Ок',CANCEL:'Отказ',CONFIRM:'Потвърждавам'},br:{OK:'OK',CANCEL:'Cancelar',CONFIRM:'Sim'},cs:{OK:'OK',CANCEL:'Zrušit',CONFIRM:'Potvrdit'},da:{OK:'OK',CANCEL:'Annuller',CONFIRM:'Accepter'},de:{OK:'OK',CANCEL:'Abbrechen',CONFIRM:'Akzeptieren'},el:{OK:'Εντάξει',CANCEL:'Ακύρωση',CONFIRM:'Επιβεβαίωση'},en:{OK:'OK',CANCEL:'Cancel',CONFIRM:'OK'},es:{OK:'OK',CANCEL:'Cancelar',CONFIRM:'Aceptar'},eu:{OK:'OK',CANCEL:'Ezeztatu',CONFIRM:'Onartu'},et:{OK:'OK',CANCEL:'Katkesta',CONFIRM:'OK'},fa:{OK:'قبول',CANCEL:'لغو',CONFIRM:'تایید'},fi:{OK:'OK',CANCEL:'Peruuta',CONFIRM:'OK'},fr:{OK:'OK',CANCEL:'Annuler',CONFIRM:'Confirmer'},he:{OK:'אישור',CANCEL:'ביטול',CONFIRM:'אישור'},hu:{OK:'OK',CANCEL:'Mégsem',CONFIRM:'Megerősít'},hr:{OK:'OK',CANCEL:'Odustani',CONFIRM:'Potvrdi'},id:{OK:'OK',CANCEL:'Batal',CONFIRM:'OK'},it:{OK:'OK',CANCEL:'Annulla',CONFIRM:'Conferma'},ja:{OK:'OK',CANCEL:'キャンセル',CONFIRM:'確認'},lt:{OK:'Gerai',CANCEL:'Atšaukti',CONFIRM:'Patvirtinti'},lv:{OK:'Labi',CANCEL:'Atcelt',CONFIRM:'Apstiprināt'},nl:{OK:'OK',CANCEL:'Annuleren',CONFIRM:'Accepteren'},no:{OK:'OK',CANCEL:'Avbryt',CONFIRM:'OK'},pl:{OK:'OK',CANCEL:'Anuluj',CONFIRM:'Potwierdź'},pt:{OK:'OK',CANCEL:'Cancelar',CONFIRM:'Confirmar'},ru:{OK:'OK',CANCEL:'Отмена',CONFIRM:'Применить'},sk:{OK:'OK',CANCEL:'Zrušiť',CONFIRM:'Potvrdiť'},sl:{OK:'OK',CANCEL:'Prekliči',CONFIRM:'Potrdi'},sq:{OK:'OK',CANCEL:'Anulo',CONFIRM:'Prano'},sv:{OK:'OK',CANCEL:'Avbryt',CONFIRM:'OK'},sw:{OK:'Sawa',CANCEL:'Ghairi',CONFIRM:'Thibitisha'},ta:{OK:'சரி',CANCEL:'ரத்து செய்',CONFIRM:'உறுதி செய்'},th:{OK:'ตกลง',CANCEL:'ยกเลิก',CONFIRM:'ยืนยัน'},tr:{OK:'Tamam',CANCEL:'İptal',CONFIRM:'Onayla'},uk:{OK:'OK',CANCEL:'Відміна',CONFIRM:'Прийняти'},zh_CN:{OK:'OK',CANCEL:'取消',CONFIRM:'确认'},zh_TW:{OK:'OK',CANCEL:'取消',CONFIRM:'確認'}},f={dialog:"<div class=\"bootbox modal\" tabindex=\"-1\" role=\"dialog\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-body\"><div class=\"bootbox-body\"></div></div></div></div></div>",header:"<div class=\"modal-header\"><h5 class=\"modal-title\"></h5></div>",footer:'<div class="modal-footer"></div>',closeButton:'<button type="button" class="bootbox-close-button close" aria-hidden="true">×</button>',form:'<form class="bootbox-form"></form>',button:'<button type="button" class="btn"></button>',option:'<option></option>',promptMessage:'<div class="bootbox-prompt-message"></div>',inputs:{text:'<input class="bootbox-input bootbox-input-text form-control" autocomplete="off" type="text" />',textarea:'<textarea class="bootbox-input bootbox-input-textarea form-control"></textarea>',email:'<input class="bootbox-input bootbox-input-email form-control" autocomplete="off" type="email" />',select:'<select class="bootbox-input bootbox-input-select form-control"></select>',checkbox:'<div class="form-check checkbox"><label class="form-check-label"><input class="form-check-input bootbox-input bootbox-input-checkbox" type="checkbox" /></label></div>',radio:'<div class="form-check radio"><label class="form-check-label"><input class="form-check-input bootbox-input bootbox-input-radio" type="radio" name="bootbox-radio" /></label></div>',date:'<input class="bootbox-input bootbox-input-date form-control" autocomplete="off" type="date" />',time:'<input class="bootbox-input bootbox-input-time form-control" autocomplete="off" type="time" />',number:'<input class="bootbox-input bootbox-input-number form-control" autocomplete="off" type="number" />',password:'<input class="bootbox-input bootbox-input-password form-control" autocomplete="off" type="password" />',range:'<input class="bootbox-input bootbox-input-range form-control-range" autocomplete="off" type="range" />'}},m={locale:'en',backdrop:'static',animate:!0,className:null,closeButton:!0,show:!0,container:'body',value:'',inputType:'text',swapButtonOrder:!1,centerVertical:!1,multiple:!1,scrollable:!1};function c(t,e,o){return p.extend(!0,{},t,function(t,e){var o=t.length,a={};if(o<1||2<o)throw new Error('Invalid argument length');return 2===o||'string'==typeof t[0]?(a[e[0]]=t[0],a[e[1]]=t[1]):a=t[0],a}(e,o))}function h(t,e,o,a){var r;a&&a[0]&&(r=a[0].locale||m.locale,(a[0].swapButtonOrder||m.swapButtonOrder)&&(e=e.reverse()));var n,i,l,s={className:'bootbox-'+t,buttons:function(t,e){for(var o={},a=0,r=t.length;a<r;a++){var n=t[a],i=n.toLowerCase(),l=n.toUpperCase();o[i]={label:(s=l,c=e,void 0,p=b[c],p?p[s]:b.en[s])}}var s,c,p;return o}(e,r)};return n=c(s,a,o),l={},O(i=e,function(t,e){l[e]=!0}),O(n.buttons,function(t){if(l[t]===u)throw new Error('button key "'+t+'" is not allowed (options are '+i.join(' ')+')')}),n}function C(t){return Object.keys(t).length}function O(t,o){var a=0;p.each(t,function(t,e){o(t,e,a++)})}function v(t,e,o){t.stopPropagation(),t.preventDefault(),p.isFunction(o)&&!1===o.call(e,t)||e.modal('hide')}function w(t){return/([01][0-9]|2[0-3]):[0-5][0-9]?:[0-5][0-9]/.test(t)}function g(t){return/(\d{4})-(\d{2})-(\d{2})/.test(t)}return d.locales=function(t){return t?b[t]:b},d.addLocale=function(t,o){return p.each(['OK','CANCEL','CONFIRM'],function(t,e){if(!o[e])throw new Error('Please supply a translation for "'+e+'"')}),b[t]={OK:o.OK,CANCEL:o.CANCEL,CONFIRM:o.CONFIRM},d},d.removeLocale=function(t){if('en'===t)throw new Error('"en" is used as the default and fallback locale and cannot be removed.');return delete b[t],d},d.setLocale=function(t){return d.setDefaults('locale',t)},d.setDefaults=function(){var t={};return 2===arguments.length?t[arguments[0]]=arguments[1]:t=arguments[0],p.extend(m,t),d},d.hideAll=function(){return p('.bootbox').modal('hide'),d},d.init=function(t){return e(t||p)},d.dialog=function(t){if(p.fn.modal===u)throw new Error("\"$.fn.modal\" is not defined; please double check you have included the Bootstrap JavaScript library. See http://getbootstrap.com/javascript/ for more details.");if(t=function(r){var n,i;if('object'!=typeof r)throw new Error('Please supply an object of options');if(!r.message)throw new Error('"message" option must not be null or an empty string.');(r=p.extend({},m,r)).buttons||(r.buttons={});return n=r.buttons,i=C(n),O(n,function(t,e,o){if(p.isFunction(e)&&(e=n[t]={callback:e}),'object'!==p.type(e))throw new Error('button with key "'+t+'" must be an object');if(e.label||(e.label=t),!e.className){var a=!1;a=r.swapButtonOrder?0===o:o===i-1,e.className=i<=2&&a?'btn-primary':'btn-secondary btn-default'}}),r}(t),p.fn.modal.Constructor.VERSION){t.fullBootstrapVersion=p.fn.modal.Constructor.VERSION;var e=t.fullBootstrapVersion.indexOf('.');t.bootstrap=t.fullBootstrapVersion.substring(0,e)}else t.bootstrap='2',t.fullBootstrapVersion='2.3.2',console.warn('Bootbox will *mostly* work with Bootstrap 2, but we do not officially support it. Please upgrade, if possible.');var o=p(f.dialog),a=o.find('.modal-dialog'),r=o.find('.modal-body'),n=p(f.header),i=p(f.footer),l=t.buttons,s={onEscape:t.onEscape};if(r.find('.bootbox-body').html(t.message),0<C(t.buttons)&&(O(l,function(t,e){var o=p(f.button);switch(o.data('bb-handler',t),o.addClass(e.className),t){case'ok':case'confirm':o.addClass('bootbox-accept');break;case'cancel':o.addClass('bootbox-cancel')}o.html(e.label),i.append(o),s[t]=e.callback}),r.after(i)),!0===t.animate&&o.addClass('fade'),t.className&&o.addClass(t.className),t.size)switch(t.fullBootstrapVersion.substring(0,3)<'3.1'&&console.warn('"size" requires Bootstrap 3.1.0 or higher. You appear to be using '+t.fullBootstrapVersion+'. Please upgrade to use this option.'),t.size){case'small':case'sm':a.addClass('modal-sm');break;case'large':case'lg':a.addClass('modal-lg');break;case'xl':case'extra-large':t.fullBootstrapVersion.substring(0,3)<'4.2'&&console.warn('Using size "xl"/"extra-large" requires Bootstrap 4.2.0 or higher. You appear to be using '+t.fullBootstrapVersion+'. Please upgrade to use this option.'),a.addClass('modal-xl')}if(t.scrollable&&(t.fullBootstrapVersion.substring(0,3)<'4.3'&&console.warn('Using "scrollable" requires Bootstrap 4.3.0 or higher. You appear to be using '+t.fullBootstrapVersion+'. Please upgrade to use this option.'),a.addClass('modal-dialog-scrollable')),t.title&&(r.before(n),o.find('.modal-title').html(t.title)),t.closeButton){var c=p(f.closeButton);t.title?3<t.bootstrap?o.find('.modal-header').append(c):o.find('.modal-header').prepend(c):c.prependTo(r)}return t.centerVertical&&(t.fullBootstrapVersion<'4.0.0'&&console.warn('"centerVertical" requires Bootstrap 4.0.0-beta.3 or higher. You appear to be using '+t.fullBootstrapVersion+'. Please upgrade to use this option.'),a.addClass('modal-dialog-centered')),o.one('hide.bs.modal',function(t){t.target===this&&(o.off('escape.close.bb'),o.off('click'))}),o.one('hidden.bs.modal',function(t){t.target===this&&o.remove()}),o.one('shown.bs.modal',function(){o.find('.bootbox-accept:first').trigger('focus')}),'static'!==t.backdrop&&o.on('click.dismiss.bs.modal',function(t){o.children('.modal-backdrop').length&&(t.currentTarget=o.children('.modal-backdrop').get(0)),t.target===t.currentTarget&&o.trigger('escape.close.bb')}),o.on('escape.close.bb',function(t){s.onEscape&&v(t,o,s.onEscape)}),o.on('click','.modal-footer button:not(.disabled)',function(t){var e=p(this).data('bb-handler');e!==u&&v(t,o,s[e])}),o.on('click','.bootbox-close-button',function(t){v(t,o,s.onEscape)}),o.on('keyup',function(t){27===t.which&&o.trigger('escape.close.bb')}),p(t.container).append(o),o.modal({backdrop:!!t.backdrop&&'static',keyboard:!1,show:!1}),t.show&&o.modal('show'),o},d.alert=function(){var t;if((t=h('alert',['ok'],['message','callback'],arguments)).callback&&!p.isFunction(t.callback))throw new Error('alert requires the "callback" property to be a function when provided');return t.buttons.ok.callback=t.onEscape=function(){return!p.isFunction(t.callback)||t.callback.call(this)},d.dialog(t)},d.confirm=function(){var t;if(t=h('confirm',['cancel','confirm'],['message','callback'],arguments),!p.isFunction(t.callback))throw new Error('confirm requires a callback');return t.buttons.cancel.callback=t.onEscape=function(){return t.callback.call(this,!1)},t.buttons.confirm.callback=function(){return t.callback.call(this,!0)},d.dialog(t)},d.prompt=function(){var r,e,t,n,o,a;if(t=p(f.form),(r=h('prompt',['cancel','confirm'],['title','callback'],arguments)).value||(r.value=m.value),r.inputType||(r.inputType=m.inputType),o=r.show===u?m.show:r.show,r.show=!1,r.buttons.cancel.callback=r.onEscape=function(){return r.callback.call(this,null)},r.buttons.confirm.callback=function(){var t;if('checkbox'===r.inputType)t=n.find('input:checked').map(function(){return p(this).val()}).get();else if('radio'===r.inputType)t=n.find('input:checked').val();else{if(n[0].checkValidity&&!n[0].checkValidity())return!1;t='select'===r.inputType&&!0===r.multiple?n.find('option:selected').map(function(){return p(this).val()}).get():n.val()}return r.callback.call(this,t)},!r.title)throw new Error('prompt requires a title');if(!p.isFunction(r.callback))throw new Error('prompt requires a callback');if(!f.inputs[r.inputType])throw new Error('Invalid prompt type');switch(n=p(f.inputs[r.inputType]),r.inputType){case'text':case'textarea':case'email':case'password':n.val(r.value),r.placeholder&&n.attr('placeholder',r.placeholder),r.pattern&&n.attr('pattern',r.pattern),r.maxlength&&n.attr('maxlength',r.maxlength),r.required&&n.prop({required:!0}),r.rows&&!isNaN(parseInt(r.rows))&&'textarea'===r.inputType&&n.attr({rows:r.rows});break;case'date':case'time':case'number':case'range':if(n.val(r.value),r.placeholder&&n.attr('placeholder',r.placeholder),r.pattern&&n.attr('pattern',r.pattern),r.required&&n.prop({required:!0}),'date'!==r.inputType&&r.step){if(!('any'===r.step||!isNaN(r.step)&&0<parseInt(r.step)))throw new Error('"step" must be a valid positive number or the value "any". See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-step for more information.');n.attr('step',r.step)}(function(t,e,o){var a=!1,r=!0,n=!0;if('date'===t)e===u||(r=g(e))?o===u||(n=g(o))||console.warn('Browsers which natively support the "date" input type expect date values to be of the form "YYYY-MM-DD" (see ISO-8601 https://www.iso.org/iso-8601-date-and-time-format.html). Bootbox does not enforce this rule, but your max value may not be enforced by this browser.'):console.warn('Browsers which natively support the "date" input type expect date values to be of the form "YYYY-MM-DD" (see ISO-8601 https://www.iso.org/iso-8601-date-and-time-format.html). Bootbox does not enforce this rule, but your min value may not be enforced by this browser.');else if('time'===t){if(e!==u&&!(r=w(e)))throw new Error('"min" is not a valid time. See https://www.w3.org/TR/2012/WD-html-markup-20120315/datatypes.html#form.data.time for more information.');if(o!==u&&!(n=w(o)))throw new Error('"max" is not a valid time. See https://www.w3.org/TR/2012/WD-html-markup-20120315/datatypes.html#form.data.time for more information.')}else{if(e!==u&&isNaN(e))throw new Error('"min" must be a valid number. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-min for more information.');if(o!==u&&isNaN(o))throw new Error('"max" must be a valid number. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-max for more information.')}if(r&&n){if(o<=e)throw new Error('"max" must be greater than "min". See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-max for more information.');a=!0}return a})(r.inputType,r.min,r.max)&&(r.min!==u&&n.attr('min',r.min),r.max!==u&&n.attr('max',r.max));break;case'select':var i={};if(a=r.inputOptions||[],!p.isArray(a))throw new Error('Please pass an array of input options');if(!a.length)throw new Error('prompt with "inputType" set to "select" requires at least one option');r.placeholder&&n.attr('placeholder',r.placeholder),r.required&&n.prop({required:!0}),r.multiple&&n.prop({multiple:!0}),O(a,function(t,e){var o=n;if(e.value===u||e.text===u)throw new Error('each option needs a "value" property and a "text" property');e.group&&(i[e.group]||(i[e.group]=p('<optgroup />').attr('label',e.group)),o=i[e.group]);var a=p(f.option);a.attr('value',e.value).text(e.text),o.append(a)}),O(i,function(t,e){n.append(e)}),n.val(r.value);break;case'checkbox':var l=p.isArray(r.value)?r.value:[r.value];if(!(a=r.inputOptions||[]).length)throw new Error('prompt with "inputType" set to "checkbox" requires at least one option');n=p('<div class="bootbox-checkbox-list"></div>'),O(a,function(t,o){if(o.value===u||o.text===u)throw new Error('each option needs a "value" property and a "text" property');var a=p(f.inputs[r.inputType]);a.find('input').attr('value',o.value),a.find('label').append('\n'+o.text),O(l,function(t,e){e===o.value&&a.find('input').prop('checked',!0)}),n.append(a)});break;case'radio':if(r.value!==u&&p.isArray(r.value))throw new Error('prompt with "inputType" set to "radio" requires a single, non-array value for "value"');if(!(a=r.inputOptions||[]).length)throw new Error('prompt with "inputType" set to "radio" requires at least one option');n=p('<div class="bootbox-radiobutton-list"></div>');var s=!0;O(a,function(t,e){if(e.value===u||e.text===u)throw new Error('each option needs a "value" property and a "text" property');var o=p(f.inputs[r.inputType]);o.find('input').attr('value',e.value),o.find('label').append('\n'+e.text),r.value!==u&&e.value===r.value&&(o.find('input').prop('checked',!0),s=!1),n.append(o)}),s&&n.find('input[type="radio"]').first().prop('checked',!0)}if(t.append(n),t.on('submit',function(t){t.preventDefault(),t.stopPropagation(),e.find('.bootbox-accept').trigger('click')}),''!==p.trim(r.message)){var c=p(f.promptMessage).html(r.message);t.prepend(c),r.message=t}else r.message=t;return(e=d.dialog(r)).off('shown.bs.modal'),e.on('shown.bs.modal',function(){n.focus()}),!0===o&&e.modal('show'),e},d.addLocale('en',{OK:'OK',CANCEL:'Cancel',CONFIRM:'OK'}),d});
|
"""Module to test metarl.torch._functions."""
import numpy as np
import pytest
import torch
import torch.nn.functional as F
from metarl.torch import compute_advantages, pad_to_last
from metarl.torch import dict_np_to_torch, global_device
from metarl.torch import product_of_gaussians, set_gpu_mode, torch_to_np
import metarl.torch._functions as tu
from tests.fixtures import TfGraphTestCase
def stack(d, arr):
"""Stack 'arr' 'd' times."""
return np.repeat(np.expand_dims(arr, axis=0), repeats=d, axis=0)
ONES = np.ones((6, ))
ZEROS = np.zeros((6, ))
ARRANGE = np.arange(6)
PI_DIGITS = np.array([3, 1, 4, 1, 5, 9])
FIBS = np.array([1, 1, 2, 3, 5, 8])
nums_1d = np.arange(0, 4).astype(float)
nums_2d = np.arange(0, 4).astype(float).reshape(2, 2)
nums_3d = np.arange(0, 8).astype(float).reshape(2, 2, 2)
def test_utils_set_gpu_mode():
"""Test setting gpu mode to False to force CPU."""
if torch.cuda.is_available():
set_gpu_mode(mode=True)
assert global_device() == torch.device('cuda:0')
assert tu._USE_GPU
else:
set_gpu_mode(mode=False)
assert global_device() == torch.device('cpu')
assert not tu._USE_GPU
assert not tu._GPU_ID
def test_torch_to_np():
"""Test whether tuples of tensors can be converted to np arrays."""
tup = (torch.zeros(1), torch.zeros(1))
np_out_1, np_out_2 = torch_to_np(tup)
assert isinstance(np_out_1, np.ndarray)
assert isinstance(np_out_2, np.ndarray)
def test_dict_np_to_torch():
"""Test if dict whose values are tensors can be converted to np arrays."""
dic = {'a': np.zeros(1), 'b': np.ones(1)}
dict_np_to_torch(dic)
for tensor in dic.values():
assert isinstance(tensor, torch.Tensor)
def test_product_of_gaussians():
"""Test computing mu, sigma of product of gaussians."""
size = 5
mu = torch.ones(size)
sigmas_squared = torch.ones(size)
output = product_of_gaussians(mu, sigmas_squared)
assert output[0] == 1
assert output[1] == 1 / size
class TestTorchAlgoUtils(TfGraphTestCase):
"""Test class for torch algo utility functions."""
# yapf: disable
@pytest.mark.parametrize('discount', [1, 0.95])
@pytest.mark.parametrize('num_trajs', [1, 5])
@pytest.mark.parametrize('gae_lambda', [0, 0.5, 1])
@pytest.mark.parametrize('rewards_traj, baselines_traj', [
(ONES, ZEROS),
(PI_DIGITS, ARRANGE),
(ONES, FIBS),
])
# yapf: enable
def test_compute_advantages(self, num_trajs, discount, gae_lambda,
rewards_traj, baselines_traj):
"""Test compute_advantage function."""
def get_advantage(discount, gae_lambda, rewards, baselines):
adv = torch.zeros(rewards.shape)
for i in range(rewards.shape[0]):
acc = 0
for j in range(rewards.shape[1]):
acc = acc * discount * gae_lambda
acc += rewards[i][-j - 1] - baselines[i][-j - 1]
acc += discount * baselines[i][-j] if j else 0
adv[i][-j - 1] = acc
return adv
length = len(rewards_traj)
rewards = torch.Tensor(stack(num_trajs, rewards_traj))
baselines = torch.Tensor(stack(num_trajs, baselines_traj))
expected_adv = get_advantage(discount, gae_lambda, rewards, baselines)
computed_adv = compute_advantages(discount, gae_lambda, length,
baselines, rewards)
assert torch.allclose(expected_adv, computed_adv)
def test_add_padding_last_1d(self):
"""Test pad_to_last function for 1d."""
max_length = 10
expected = F.pad(torch.Tensor(nums_1d),
(0, max_length - nums_1d.shape[-1]))
tensor_padding = pad_to_last(nums_1d, total_length=max_length)
assert expected.eq(tensor_padding).all()
tensor_padding = pad_to_last(nums_1d, total_length=10, axis=0)
assert expected.eq(tensor_padding).all()
def test_add_padding_last_2d(self):
"""Test pad_to_last function for 2d."""
max_length = 10
tensor_padding = pad_to_last(nums_2d, total_length=10)
expected = F.pad(torch.Tensor(nums_2d),
(0, max_length - nums_2d.shape[-1]))
assert expected.eq(tensor_padding).all()
tensor_padding = pad_to_last(nums_2d, total_length=10, axis=0)
expected = F.pad(torch.Tensor(nums_2d),
(0, 0, 0, max_length - nums_2d.shape[0]))
assert expected.eq(tensor_padding).all()
tensor_padding = pad_to_last(nums_2d, total_length=10, axis=1)
expected = F.pad(torch.Tensor(nums_2d),
(0, max_length - nums_2d.shape[-1], 0, 0))
assert expected.eq(tensor_padding).all()
def test_add_padding_last_3d(self):
"""Test pad_to_last function for 3d."""
max_length = 10
tensor_padding = pad_to_last(nums_3d, total_length=10)
expected = F.pad(torch.Tensor(nums_3d),
(0, max_length - nums_3d.shape[-1], 0, 0, 0, 0))
assert expected.eq(tensor_padding).all()
tensor_padding = pad_to_last(nums_3d, total_length=10, axis=0)
expected = F.pad(torch.Tensor(nums_3d),
(0, 0, 0, 0, 0, max_length - nums_3d.shape[0]))
assert expected.eq(tensor_padding).all()
tensor_padding = pad_to_last(nums_3d, total_length=10, axis=1)
expected = F.pad(torch.Tensor(nums_3d),
(0, 0, 0, max_length - nums_3d.shape[-1], 0, 0))
assert expected.eq(tensor_padding).all()
tensor_padding = pad_to_last(nums_3d, total_length=10, axis=2)
expected = F.pad(torch.Tensor(nums_3d),
(0, max_length - nums_3d.shape[-1], 0, 0, 0, 0))
assert expected.eq(tensor_padding).all()
@pytest.mark.parametrize('nums', [nums_1d, nums_2d, nums_3d])
def test_out_of_index_error(self, nums):
"""Test pad_to_last raises IndexError."""
with pytest.raises(IndexError):
pad_to_last(nums, total_length=10, axis=len(nums.shape))
|
# coding: utf-8
#
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Job registries."""
from core.domain import activity_jobs_one_off
from core.domain import collection_jobs_one_off
from core.domain import email_jobs_one_off
from core.domain import exp_jobs_one_off
from core.domain import feedback_jobs_continuous
from core.domain import feedback_jobs_one_off
from core.domain import recommendations_jobs_one_off
from core.domain import stats_jobs_continuous
from core.domain import stats_jobs_one_off
from core.domain import user_jobs_continuous
from core.domain import user_jobs_one_off
# List of all manager classes for one-off batch jobs for which to show controls
# on the admin dashboard.
ONE_OFF_JOB_MANAGERS = [
activity_jobs_one_off.IndexAllActivitiesJobManager,
collection_jobs_one_off.CollectionMigrationJob,
email_jobs_one_off.EmailHashRegenerationOneOffJob,
exp_jobs_one_off.ExpSummariesContributorsOneOffJob,
exp_jobs_one_off.ExpSummariesCreationOneOffJob,
exp_jobs_one_off.ExplorationContributorsSummaryOneOffJob,
exp_jobs_one_off.ExplorationFirstPublishedOneOffJob,
exp_jobs_one_off.ExplorationMigrationJobManager,
exp_jobs_one_off.ExplorationValidityJobManager,
exp_jobs_one_off.ExplorationStateIdMappingJob,
exp_jobs_one_off.HintsAuditOneOffJob,
exp_jobs_one_off.ItemSelectionInteractionOneOffJob,
exp_jobs_one_off.ViewableExplorationsAuditJob,
exp_jobs_one_off.ExplorationContentValidationJobForTextAngular,
exp_jobs_one_off.ExplorationMigrationValidationJobForTextAngular,
exp_jobs_one_off.ExplorationContentValidationJobForCKEditor,
exp_jobs_one_off.ExplorationMigrationValidationJobForCKEditor,
exp_jobs_one_off.ImageDataMigrationJob,
feedback_jobs_one_off.FeedbackThreadMessagesCountOneOffJob,
feedback_jobs_one_off.FeedbackSubjectOneOffJob,
feedback_jobs_one_off.SuggestionMigrationOneOffJob,
feedback_jobs_one_off.SuggestionMigrationValdiationOneOffJob,
recommendations_jobs_one_off.ExplorationRecommendationsOneOffJob,
stats_jobs_one_off.ExplorationIssuesModelCreatorOneOffJob,
stats_jobs_one_off.RecomputeStatisticsOneOffJob,
stats_jobs_one_off.StatisticsAuditV1,
stats_jobs_one_off.StatisticsAudit,
user_jobs_one_off.DashboardSubscriptionsOneOffJob,
user_jobs_one_off.LongUserBiosOneOffJob,
user_jobs_one_off.UserContributionsOneOffJob,
user_jobs_one_off.UserLanguageAuditOneOffJob,
user_jobs_one_off.UserLanguageResetOneOffJob,
user_jobs_one_off.UserDefaultDashboardOneOffJob,
user_jobs_one_off.UserFirstContributionMsecOneOffJob,
user_jobs_one_off.UserLastExplorationActivityOneOffJob,
user_jobs_one_off.UserProfilePictureOneOffJob,
user_jobs_one_off.UsernameLengthDistributionOneOffJob,
]
# List of all ContinuousComputation managers to show controls for on the
# admin dashboard.
# NOTE TO DEVELOPERS: When a new ContinuousComputation manager is defined,
# it should be registered here.
ALL_CONTINUOUS_COMPUTATION_MANAGERS = [
feedback_jobs_continuous.FeedbackAnalyticsAggregator,
stats_jobs_continuous.InteractionAnswerSummariesAggregator,
user_jobs_continuous.DashboardRecentUpdatesAggregator,
user_jobs_continuous.UserStatsAggregator,
]
class ContinuousComputationEventDispatcher(object):
"""Dispatches events to the relevant ContinuousComputation classes."""
@classmethod
def dispatch_event(cls, event_type, *args, **kwargs):
"""Dispatches an incoming event to the ContinuousComputation
classes which listen to events of that type.
"""
for klass in ALL_CONTINUOUS_COMPUTATION_MANAGERS:
if event_type in klass.get_event_types_listened_to():
klass.on_incoming_event(event_type, *args, **kwargs)
|
from collections import Counter
import re,string
def add_text_to_vocab(w,vocab):
list = [words for words in w.split(' ')]
token_list =[]
for i in range(len(list)):
#load file
#tokens = clean_doc(list[i])
#token_list.append(tokens)
vocab.update(list)
return token_list
def save_vocab(vocab,filename):
tokens = [k for k, c in vocab.items()]
# print(len(tokens))
file = open(filename, 'w+')
for token in tokens:
file.write(token)
file.write('\n')
#file.write(data)
file.close()
def preprocess(w):
w = w.lower().strip()
# creating a space between a word and the punctuation following it
# eg: "he is a boy." => "he is a boy ."
# Reference:-
# https://stackoverflow.com/questions/3645931/python-padding-punctuation-with-white-spaces-keeping-punctuation
w= w.replace("<p>", " ")
w = w.replace("</p>", " ")
w = re.sub(r"([?.!,¿])", r" \1 ", w)
w = re.sub(r'[" "]+', " ", w)
re_punc = re.compile('[%s]' % re.escape(string.punctuation))
w = re_punc.sub('', w)
lines_str = w.replace("”", "")
lines_str = lines_str.replace("“", "")
lines_str = lines_str.replace("’", "'")
lines_str = lines_str.replace("«", "")
lines_str = lines_str.replace("»", "")
# #
lines_str = ' '.join([word for word in lines_str.split() if word.isalpha()])
# # replacing everything with space except (a-z, A-Z, ".", "?", "!", ",")
# # w = re.sub(r"[^a-zA-Z?.!,¿]+", " ", w)
#
# w = lines_str
# adding a start and an end token to the sentence
# so that the model know when to start and stop predicting.
w = lines_str
#tokens = [words for words in w.split(' ')]
#add_text_to_vocab(tokens,vocab)
return w
vocab_src = Counter()
with open('C:/Users/USER/Downloads/Compressed/json/igbo_data10000.txt', 'r') as src:
lines = src.readlines()
for line in lines:
add_text_to_vocab(preprocess(line),vocab_src)
save_vocab(vocab_src,'C:/xampp/htdocs/IgboKeyboard/essentials/ig-vocab.txt')
print("All done")
|
from functools import reduce
import copy
import itertools as it
import operator as op
import os
import random
import sys
from colour import Color
import numpy as np
from ..constants import *
from ..config import config
from ..container.container import Container
from ..utils.color import color_gradient
from ..utils.color import interpolate_color
from ..utils.iterables import list_update
from ..utils.iterables import remove_list_redundancies
from ..utils.paths import straight_path
from ..utils.simple_functions import get_parameters
from ..utils.space_ops import angle_of_vector
from ..utils.space_ops import get_norm
from ..utils.space_ops import rotation_matrix
# TODO: Explain array_attrs
class Mobject(Container):
"""
Mathematical Object
"""
CONFIG = {
"color": WHITE,
"name": None,
"dim": 3,
"target": None,
"z_index": 0,
}
def __init__(self, **kwargs):
Container.__init__(self, **kwargs)
self.submobjects = []
self.color = Color(self.color)
if self.name is None:
self.name = self.__class__.__name__
self.updaters = []
self.updating_suspended = False
self.reset_points()
self.generate_points()
self.init_colors()
def __str__(self):
return str(self.name)
def reset_points(self):
self.points = np.zeros((0, self.dim))
def init_colors(self):
# For subclasses
pass
def generate_points(self):
# Typically implemented in subclass, unless purposefully left blank
pass
def add(self, *mobjects):
if self in mobjects:
raise Exception("Mobject cannot contain self")
self.submobjects = list_update(self.submobjects, mobjects)
return self
def add_to_back(self, *mobjects):
self.remove(*mobjects)
self.submobjects = list(mobjects) + self.submobjects
return self
def remove(self, *mobjects):
for mobject in mobjects:
if mobject in self.submobjects:
self.submobjects.remove(mobject)
return self
def get_array_attrs(self):
return ["points"]
def digest_mobject_attrs(self):
"""
Ensures all attributes which are mobjects are included
in the submobjects list.
"""
mobject_attrs = [x for x in list(self.__dict__.values()) if isinstance(x, Mobject)]
self.submobjects = list_update(self.submobjects, mobject_attrs)
return self
def apply_over_attr_arrays(self, func):
for attr in self.get_array_attrs():
setattr(self, attr, func(getattr(self, attr)))
return self
# Displaying
def get_image(self, camera=None):
if camera is None:
from ..camera.camera import Camera
camera = Camera()
camera.capture_mobject(self)
return camera.get_image()
def show(self, camera=None):
self.get_image(camera=camera).show()
def save_image(self, name=None):
self.get_image().save(
os.path.join(config['VIDEO_DIR'], (name or str(self)) + ".png")
)
def copy(self):
# TODO, either justify reason for shallow copy, or
# remove this redundancy everywhere
# return self.deepcopy()
copy_mobject = copy.copy(self)
copy_mobject.points = np.array(self.points)
copy_mobject.submobjects = [
submob.copy() for submob in self.submobjects
]
copy_mobject.updaters = list(self.updaters)
family = self.get_family()
for attr, value in list(self.__dict__.items()):
if isinstance(value, Mobject) and value in family and value is not self:
setattr(copy_mobject, attr, value.copy())
if isinstance(value, np.ndarray):
setattr(copy_mobject, attr, np.array(value))
return copy_mobject
def deepcopy(self):
return copy.deepcopy(self)
def generate_target(self, use_deepcopy=False):
self.target = None # Prevent exponential explosion
if use_deepcopy:
self.target = self.deepcopy()
else:
self.target = self.copy()
return self.target
# Updating
def update(self, dt=0, recursive=True):
if self.updating_suspended:
return self
for updater in self.updaters:
parameters = get_parameters(updater)
if "dt" in parameters:
updater(self, dt)
else:
updater(self)
if recursive:
for submob in self.submobjects:
submob.update(dt, recursive)
return self
def get_time_based_updaters(self):
return [
updater for updater in self.updaters
if "dt" in get_parameters(updater)
]
def has_time_based_updater(self):
for updater in self.updaters:
if "dt" in get_parameters(updater):
return True
return False
def get_updaters(self):
return self.updaters
def get_family_updaters(self):
return list(it.chain(*[
sm.get_updaters()
for sm in self.get_family()
]))
def add_updater(self, update_function, index=None, call_updater=True):
if index is None:
self.updaters.append(update_function)
else:
self.updaters.insert(index, update_function)
if call_updater:
self.update(0)
return self
def remove_updater(self, update_function):
while update_function in self.updaters:
self.updaters.remove(update_function)
return self
def clear_updaters(self, recursive=True):
self.updaters = []
if recursive:
for submob in self.submobjects:
submob.clear_updaters()
return self
def match_updaters(self, mobject):
self.clear_updaters()
for updater in mobject.get_updaters():
self.add_updater(updater)
return self
def suspend_updating(self, recursive=True):
self.updating_suspended = True
if recursive:
for submob in self.submobjects:
submob.suspend_updating(recursive)
return self
def resume_updating(self, recursive=True):
self.updating_suspended = False
if recursive:
for submob in self.submobjects:
submob.resume_updating(recursive)
self.update(dt=0, recursive=recursive)
return self
# Transforming operations
def apply_to_family(self, func):
for mob in self.family_members_with_points():
func(mob)
def shift(self, *vectors):
total_vector = reduce(op.add, vectors)
for mob in self.family_members_with_points():
mob.points = mob.points.astype('float')
mob.points += total_vector
return self
def scale(self, scale_factor, **kwargs):
"""
Default behavior is to scale about the center of the mobject.
The argument about_edge can be a vector, indicating which side of
the mobject to scale about, e.g., mob.scale(about_edge = RIGHT)
scales about mob.get_right().
Otherwise, if about_point is given a value, scaling is done with
respect to that point.
"""
self.apply_points_function_about_point(
lambda points: scale_factor * points, **kwargs
)
return self
def rotate_about_origin(self, angle, axis=OUT, axes=[]):
return self.rotate(angle, axis, about_point=ORIGIN)
def rotate(self, angle, axis=OUT, **kwargs):
rot_matrix = rotation_matrix(angle, axis)
self.apply_points_function_about_point(
lambda points: np.dot(points, rot_matrix.T),
**kwargs
)
return self
def flip(self, axis=UP, **kwargs):
return self.rotate(TAU / 2, axis, **kwargs)
def stretch(self, factor, dim, **kwargs):
def func(points):
points[:, dim] *= factor
return points
self.apply_points_function_about_point(func, **kwargs)
return self
def apply_function(self, function, **kwargs):
# Default to applying matrix about the origin, not mobjects center
if len(kwargs) == 0:
kwargs["about_point"] = ORIGIN
self.apply_points_function_about_point(
lambda points: np.apply_along_axis(function, 1, points),
**kwargs
)
return self
def apply_function_to_position(self, function):
self.move_to(function(self.get_center()))
return self
def apply_function_to_submobject_positions(self, function):
for submob in self.submobjects:
submob.apply_function_to_position(function)
return self
def apply_matrix(self, matrix, **kwargs):
# Default to applying matrix about the origin, not mobjects center
if ("about_point" not in kwargs) and ("about_edge" not in kwargs):
kwargs["about_point"] = ORIGIN
full_matrix = np.identity(self.dim)
matrix = np.array(matrix)
full_matrix[:matrix.shape[0], :matrix.shape[1]] = matrix
self.apply_points_function_about_point(
lambda points: np.dot(points, full_matrix.T),
**kwargs
)
return self
def apply_complex_function(self, function, **kwargs):
def R3_func(point):
x, y, z = point
xy_complex = function(complex(x, y))
return [
xy_complex.real,
xy_complex.imag,
z
]
return self.apply_function(R3_func)
def wag(self, direction=RIGHT, axis=DOWN, wag_factor=1.0):
for mob in self.family_members_with_points():
alphas = np.dot(mob.points, np.transpose(axis))
alphas -= min(alphas)
alphas /= max(alphas)
alphas = alphas**wag_factor
mob.points += np.dot(
alphas.reshape((len(alphas), 1)),
np.array(direction).reshape((1, mob.dim))
)
return self
def reverse_points(self):
for mob in self.family_members_with_points():
mob.apply_over_attr_arrays(
lambda arr: np.array(list(reversed(arr)))
)
return self
def repeat(self, count):
"""
This can make transition animations nicer
"""
def repeat_array(array):
return reduce(
lambda a1, a2: np.append(a1, a2, axis=0),
[array] * count
)
for mob in self.family_members_with_points():
mob.apply_over_attr_arrays(repeat_array)
return self
# In place operations.
# Note, much of these are now redundant with default behavior of
# above methods
def apply_points_function_about_point(self, func, about_point=None, about_edge=None):
if about_point is None:
if about_edge is None:
about_edge = ORIGIN
about_point = self.get_critical_point(about_edge)
for mob in self.family_members_with_points():
mob.points -= about_point
mob.points = func(mob.points)
mob.points += about_point
return self
def rotate_in_place(self, angle, axis=OUT):
# redundant with default behavior of rotate now.
return self.rotate(angle, axis=axis)
def scale_in_place(self, scale_factor, **kwargs):
# Redundant with default behavior of scale now.
return self.scale(scale_factor, **kwargs)
def scale_about_point(self, scale_factor, point):
# Redundant with default behavior of scale now.
return self.scale(scale_factor, about_point=point)
def pose_at_angle(self, **kwargs):
self.rotate(TAU / 14, RIGHT + UP, **kwargs)
return self
# Positioning methods
def center(self):
self.shift(-self.get_center())
return self
def align_on_border(self, direction, buff=DEFAULT_MOBJECT_TO_EDGE_BUFFER):
"""
Direction just needs to be a vector pointing towards side or
corner in the 2d plane.
"""
target_point = np.sign(direction) * (config['frame_x_radius'], config['frame_y_radius'], 0)
point_to_align = self.get_critical_point(direction)
shift_val = target_point - point_to_align - buff * np.array(direction)
shift_val = shift_val * abs(np.sign(direction))
self.shift(shift_val)
return self
def to_corner(self, corner=LEFT + DOWN, buff=DEFAULT_MOBJECT_TO_EDGE_BUFFER):
return self.align_on_border(corner, buff)
def to_edge(self, edge=LEFT, buff=DEFAULT_MOBJECT_TO_EDGE_BUFFER):
return self.align_on_border(edge, buff)
def next_to(self, mobject_or_point,
direction=RIGHT,
buff=DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
aligned_edge=ORIGIN,
submobject_to_align=None,
index_of_submobject_to_align=None,
coor_mask=np.array([1, 1, 1]),
):
if isinstance(mobject_or_point, Mobject):
mob = mobject_or_point
if index_of_submobject_to_align is not None:
target_aligner = mob[index_of_submobject_to_align]
else:
target_aligner = mob
target_point = target_aligner.get_critical_point(
aligned_edge + direction
)
else:
target_point = mobject_or_point
if submobject_to_align is not None:
aligner = submobject_to_align
elif index_of_submobject_to_align is not None:
aligner = self[index_of_submobject_to_align]
else:
aligner = self
point_to_align = aligner.get_critical_point(aligned_edge - direction)
self.shift((target_point - point_to_align +
buff * direction) * coor_mask)
return self
def shift_onto_screen(self, **kwargs):
space_lengths = [config['frame_x_radius'], config['frame_y_radius']]
for vect in UP, DOWN, LEFT, RIGHT:
dim = np.argmax(np.abs(vect))
buff = kwargs.get("buff", DEFAULT_MOBJECT_TO_EDGE_BUFFER)
max_val = space_lengths[dim] - buff
edge_center = self.get_edge_center(vect)
if np.dot(edge_center, vect) > max_val:
self.to_edge(vect, **kwargs)
return self
def is_off_screen(self):
if self.get_left()[0] > config['frame_x_radius']:
return True
if self.get_right()[0] < -config['frame_x_radius']:
return True
if self.get_bottom()[1] > config['frame_y_radius']:
return True
if self.get_top()[1] < -config['frame_y_radius']:
return True
return False
def stretch_about_point(self, factor, dim, point):
return self.stretch(factor, dim, about_point=point)
def stretch_in_place(self, factor, dim):
# Now redundant with stretch
return self.stretch(factor, dim)
def rescale_to_fit(self, length, dim, stretch=False, **kwargs):
old_length = self.length_over_dim(dim)
if old_length == 0:
return self
if stretch:
self.stretch(length / old_length, dim, **kwargs)
else:
self.scale(length / old_length, **kwargs)
return self
def stretch_to_fit_width(self, width, **kwargs):
return self.rescale_to_fit(width, 0, stretch=True, **kwargs)
def stretch_to_fit_height(self, height, **kwargs):
return self.rescale_to_fit(height, 1, stretch=True, **kwargs)
def stretch_to_fit_depth(self, depth, **kwargs):
return self.rescale_to_fit(depth, 1, stretch=True, **kwargs)
def set_width(self, width, stretch=False, **kwargs):
return self.rescale_to_fit(width, 0, stretch=stretch, **kwargs)
def set_height(self, height, stretch=False, **kwargs):
return self.rescale_to_fit(height, 1, stretch=stretch, **kwargs)
def set_depth(self, depth, stretch=False, **kwargs):
return self.rescale_to_fit(depth, 2, stretch=stretch, **kwargs)
def set_coord(self, value, dim, direction=ORIGIN):
curr = self.get_coord(dim, direction)
shift_vect = np.zeros(self.dim)
shift_vect[dim] = value - curr
self.shift(shift_vect)
return self
def set_x(self, x, direction=ORIGIN):
return self.set_coord(x, 0, direction)
def set_y(self, y, direction=ORIGIN):
return self.set_coord(y, 1, direction)
def set_z(self, z, direction=ORIGIN):
return self.set_coord(z, 2, direction)
def space_out_submobjects(self, factor=1.5, **kwargs):
self.scale(factor, **kwargs)
for submob in self.submobjects:
submob.scale(1. / factor)
return self
def move_to(self, point_or_mobject, aligned_edge=ORIGIN,
coor_mask=np.array([1, 1, 1])):
if isinstance(point_or_mobject, Mobject):
target = point_or_mobject.get_critical_point(aligned_edge)
else:
target = point_or_mobject
point_to_align = self.get_critical_point(aligned_edge)
self.shift((target - point_to_align) * coor_mask)
return self
def replace(self, mobject, dim_to_match=0, stretch=False):
if not mobject.get_num_points() and not mobject.submobjects:
raise Warning("Attempting to replace mobject with no points")
return self
if stretch:
self.stretch_to_fit_width(mobject.get_width())
self.stretch_to_fit_height(mobject.get_height())
else:
self.rescale_to_fit(
mobject.length_over_dim(dim_to_match),
dim_to_match,
stretch=False
)
self.shift(mobject.get_center() - self.get_center())
return self
def surround(self, mobject,
dim_to_match=0,
stretch=False,
buff=MED_SMALL_BUFF):
self.replace(mobject, dim_to_match, stretch)
length = mobject.length_over_dim(dim_to_match)
self.scale_in_place((length + buff) / length)
return self
def put_start_and_end_on(self, start, end):
curr_start, curr_end = self.get_start_and_end()
curr_vect = curr_end - curr_start
if np.all(curr_vect == 0):
raise Exception("Cannot position endpoints of closed loop")
target_vect = np.array(end) - np.array(start)
self.scale(
get_norm(target_vect) / get_norm(curr_vect),
about_point=curr_start,
)
self.rotate(
angle_of_vector(target_vect) -
angle_of_vector(curr_vect),
about_point=curr_start
)
self.shift(start - curr_start)
return self
# Background rectangle
def add_background_rectangle(self, color=BLACK, opacity=0.75, **kwargs):
# TODO, this does not behave well when the mobject has points,
# since it gets displayed on top
from ..mobject.shape_matchers import BackgroundRectangle
self.background_rectangle = BackgroundRectangle(
self, color=color,
fill_opacity=opacity,
**kwargs
)
self.add_to_back(self.background_rectangle)
return self
def add_background_rectangle_to_submobjects(self, **kwargs):
for submobject in self.submobjects:
submobject.add_background_rectangle(**kwargs)
return self
def add_background_rectangle_to_family_members_with_points(self, **kwargs):
for mob in self.family_members_with_points():
mob.add_background_rectangle(**kwargs)
return self
# Color functions
def set_color(self, color=YELLOW_C, family=True):
"""
Condition is function which takes in one arguments, (x, y, z).
Here it just recurses to submobjects, but in subclasses this
should be further implemented based on the the inner workings
of color
"""
if family:
for submob in self.submobjects:
submob.set_color(color, family=family)
self.color = color
return self
def set_color_by_gradient(self, *colors):
self.set_submobject_colors_by_gradient(*colors)
return self
def set_colors_by_radial_gradient(self, center=None, radius=1, inner_color=WHITE, outer_color=BLACK):
self.set_submobject_colors_by_radial_gradient(
center, radius, inner_color, outer_color)
return self
def set_submobject_colors_by_gradient(self, *colors):
if len(colors) == 0:
raise Exception("Need at least one color")
elif len(colors) == 1:
return self.set_color(*colors)
mobs = self.family_members_with_points()
new_colors = color_gradient(colors, len(mobs))
for mob, color in zip(mobs, new_colors):
mob.set_color(color, family=False)
return self
def set_submobject_colors_by_radial_gradient(self, center=None, radius=1, inner_color=WHITE, outer_color=BLACK):
if center is None:
center = self.get_center()
for mob in self.family_members_with_points():
t = get_norm(mob.get_center() - center) / radius
t = min(t, 1)
mob_color = interpolate_color(inner_color, outer_color, t)
mob.set_color(mob_color, family=False)
return self
def to_original_color(self):
self.set_color(self.color)
return self
def fade_to(self, color, alpha, family=True):
if self.get_num_points() > 0:
new_color = interpolate_color(
self.get_color(), color, alpha
)
self.set_color(new_color, family=False)
if family:
for submob in self.submobjects:
submob.fade_to(color, alpha)
return self
def fade(self, darkness=0.5, family=True):
if family:
for submob in self.submobjects:
submob.fade(darkness, family)
return self
def get_color(self):
return self.color
##
def save_state(self, use_deepcopy=False):
if hasattr(self, "saved_state"):
# Prevent exponential growth of data
self.saved_state = None
if use_deepcopy:
self.saved_state = self.deepcopy()
else:
self.saved_state = self.copy()
return self
def restore(self):
if not hasattr(self, "saved_state") or self.save_state is None:
raise Exception("Trying to restore without having saved")
self.become(self.saved_state)
return self
##
def reduce_across_dimension(self, points_func, reduce_func, dim):
points = self.get_all_points()
if points is None or len(points) == 0:
# Note, this default means things like empty VGroups
# will appear to have a center at [0, 0, 0]
return 0
values = points_func(points[:, dim])
return reduce_func(values)
def nonempty_submobjects(self):
return [
submob for submob in self.submobjects
if len(submob.submobjects) != 0 or len(submob.points) != 0
]
def get_merged_array(self, array_attr):
result = getattr(self, array_attr)
for submob in self.submobjects:
result = np.append(
result, submob.get_merged_array(array_attr),
axis=0
)
submob.get_merged_array(array_attr)
return result
def get_all_points(self):
return self.get_merged_array("points")
# Getters
def get_points_defining_boundary(self):
return self.get_all_points()
def get_num_points(self):
return len(self.points)
def get_extremum_along_dim(self, points=None, dim=0, key=0):
if points is None:
points = self.get_points_defining_boundary()
values = points[:, dim]
if key < 0:
return np.min(values)
elif key == 0:
return (np.min(values) + np.max(values)) / 2
else:
return np.max(values)
def get_critical_point(self, direction):
"""
Picture a box bounding the mobject. Such a box has
9 'critical points': 4 corners, 4 edge center, the
center. This returns one of them.
"""
result = np.zeros(self.dim)
all_points = self.get_points_defining_boundary()
if len(all_points) == 0:
return result
for dim in range(self.dim):
result[dim] = self.get_extremum_along_dim(
all_points, dim=dim, key=direction[dim]
)
return result
# Pseudonyms for more general get_critical_point method
def get_edge_center(self, direction):
return self.get_critical_point(direction)
def get_corner(self, direction):
return self.get_critical_point(direction)
def get_center(self):
return self.get_critical_point(np.zeros(self.dim))
def get_center_of_mass(self):
return np.apply_along_axis(np.mean, 0, self.get_all_points())
def get_boundary_point(self, direction):
all_points = self.get_points_defining_boundary()
index = np.argmax(np.dot(all_points, np.array(direction).T))
return all_points[index]
def get_top(self):
return self.get_edge_center(UP)
def get_bottom(self):
return self.get_edge_center(DOWN)
def get_right(self):
return self.get_edge_center(RIGHT)
def get_left(self):
return self.get_edge_center(LEFT)
def get_zenith(self):
return self.get_edge_center(OUT)
def get_nadir(self):
return self.get_edge_center(IN)
def length_over_dim(self, dim):
return (
self.reduce_across_dimension(np.max, np.max, dim) -
self.reduce_across_dimension(np.min, np.min, dim)
)
def get_width(self):
return self.length_over_dim(0)
def get_height(self):
return self.length_over_dim(1)
def get_depth(self):
return self.length_over_dim(2)
def get_coord(self, dim, direction=ORIGIN):
"""
Meant to generalize get_x, get_y, get_z
"""
return self.get_extremum_along_dim(
dim=dim, key=direction[dim]
)
def get_x(self, direction=ORIGIN):
return self.get_coord(0, direction)
def get_y(self, direction=ORIGIN):
return self.get_coord(1, direction)
def get_z(self, direction=ORIGIN):
return self.get_coord(2, direction)
def get_start(self):
self.throw_error_if_no_points()
return np.array(self.points[0])
def get_end(self):
self.throw_error_if_no_points()
return np.array(self.points[-1])
def get_start_and_end(self):
return self.get_start(), self.get_end()
def point_from_proportion(self, alpha):
raise NotImplementedError('Please override in a child class.')
def get_pieces(self, n_pieces):
template = self.copy()
template.submobjects = []
alphas = np.linspace(0, 1, n_pieces + 1)
return Group(*[
template.copy().pointwise_become_partial(
self, a1, a2
)
for a1, a2 in zip(alphas[:-1], alphas[1:])
])
def get_z_index_reference_point(self):
# TODO, better place to define default z_index_group?
z_index_group = getattr(self, "z_index_group", self)
return z_index_group.get_center()
def has_points(self):
return len(self.points) > 0
def has_no_points(self):
return not self.has_points()
# Match other mobject properties
def match_color(self, mobject):
return self.set_color(mobject.get_color())
def match_dim_size(self, mobject, dim, **kwargs):
return self.rescale_to_fit(
mobject.length_over_dim(dim), dim,
**kwargs
)
def match_width(self, mobject, **kwargs):
return self.match_dim_size(mobject, 0, **kwargs)
def match_height(self, mobject, **kwargs):
return self.match_dim_size(mobject, 1, **kwargs)
def match_depth(self, mobject, **kwargs):
return self.match_dim_size(mobject, 2, **kwargs)
def match_coord(self, mobject, dim, direction=ORIGIN):
return self.set_coord(
mobject.get_coord(dim, direction),
dim=dim,
direction=direction,
)
def match_x(self, mobject, direction=ORIGIN):
return self.match_coord(mobject, 0, direction)
def match_y(self, mobject, direction=ORIGIN):
return self.match_coord(mobject, 1, direction)
def match_z(self, mobject, direction=ORIGIN):
return self.match_coord(mobject, 2, direction)
def align_to(self, mobject_or_point, direction=ORIGIN, alignment_vect=UP):
"""
Examples:
mob1.align_to(mob2, UP) moves mob1 vertically so that its
top edge lines ups with mob2's top edge.
mob1.align_to(mob2, alignment_vect = RIGHT) moves mob1
horizontally so that it's center is directly above/below
the center of mob2
"""
if isinstance(mobject_or_point, Mobject):
point = mobject_or_point.get_critical_point(direction)
else:
point = mobject_or_point
for dim in range(self.dim):
if direction[dim] != 0:
self.set_coord(point[dim], dim, direction)
return self
# Family matters
def __getitem__(self, value):
self_list = self.split()
if isinstance(value, slice):
GroupClass = self.get_group_class()
return GroupClass(*self_list.__getitem__(value))
return self_list.__getitem__(value)
def __iter__(self):
return iter(self.split())
def __len__(self):
return len(self.split())
def get_group_class(self):
return Group
def split(self):
result = [self] if len(self.points) > 0 else []
return result + self.submobjects
def get_family(self):
sub_families = list(map(Mobject.get_family, self.submobjects))
all_mobjects = [self] + list(it.chain(*sub_families))
return remove_list_redundancies(all_mobjects)
def family_members_with_points(self):
return [m for m in self.get_family() if m.get_num_points() > 0]
def arrange(self, direction=RIGHT, center=True, **kwargs):
for m1, m2 in zip(self.submobjects, self.submobjects[1:]):
m2.next_to(m1, direction, **kwargs)
if center:
self.center()
return self
def arrange_in_grid(self, n_rows=None, n_cols=None, **kwargs):
submobs = self.submobjects
if n_rows is None and n_cols is None:
n_cols = int(np.sqrt(len(submobs)))
if n_rows is not None:
v1 = RIGHT
v2 = DOWN
n = len(submobs) // n_rows
elif n_cols is not None:
v1 = DOWN
v2 = RIGHT
n = len(submobs) // n_cols
Group(*[
Group(*submobs[i:i + n]).arrange(v1, **kwargs)
for i in range(0, len(submobs), n)
]).arrange(v2, **kwargs)
return self
def sort(self, point_to_num_func=lambda p: p[0], submob_func=None):
if submob_func is None:
submob_func = lambda m: point_to_num_func(m.get_center())
self.submobjects.sort(key=submob_func)
return self
def shuffle(self, recursive=False):
if recursive:
for submob in self.submobjects:
submob.shuffle(recursive=True)
random.shuffle(self.submobjects)
# Just here to keep from breaking old scenes.
def arrange_submobjects(self, *args, **kwargs):
return self.arrange(*args, **kwargs)
def sort_submobjects(self, *args, **kwargs):
return self.sort(*args, **kwargs)
def shuffle_submobjects(self, *args, **kwargs):
return self.shuffle(*args, **kwargs)
# Alignment
def align_data(self, mobject):
self.null_point_align(mobject)
self.align_submobjects(mobject)
self.align_points(mobject)
# Recurse
for m1, m2 in zip(self.submobjects, mobject.submobjects):
m1.align_data(m2)
def get_point_mobject(self, center=None):
"""
The simplest mobject to be transformed to or from self.
Should by a point of the appropriate type
"""
msg = f"get_point_mobject not implemented for {self.__class__.__name__}"
raise NotImplementedError(msg)
def align_points(self, mobject):
count1 = self.get_num_points()
count2 = mobject.get_num_points()
if count1 < count2:
self.align_points_with_larger(mobject)
elif count2 < count1:
mobject.align_points_with_larger(self)
return self
def align_points_with_larger(self, larger_mobject):
raise NotImplementedError('Please override in a child class.')
def align_submobjects(self, mobject):
mob1 = self
mob2 = mobject
n1 = len(mob1.submobjects)
n2 = len(mob2.submobjects)
mob1.add_n_more_submobjects(max(0, n2 - n1))
mob2.add_n_more_submobjects(max(0, n1 - n2))
return self
def null_point_align(self, mobject):
"""
If a mobject with points is being aligned to
one without, treat both as groups, and push
the one with points into its own submobjects
list.
"""
for m1, m2 in (self, mobject), (mobject, self):
if m1.has_no_points() and m2.has_points():
m2.push_self_into_submobjects()
return self
def push_self_into_submobjects(self):
copy = self.copy()
copy.submobjects = []
self.reset_points()
self.add(copy)
return self
def add_n_more_submobjects(self, n):
if n == 0:
return
curr = len(self.submobjects)
if curr == 0:
# If empty, simply add n point mobjects
self.submobjects = [
self.get_point_mobject()
for k in range(n)
]
return
target = curr + n
# TODO, factor this out to utils so as to reuse
# with VMobject.insert_n_curves
repeat_indices = (np.arange(target) * curr) // target
split_factors = [
sum(repeat_indices == i)
for i in range(curr)
]
new_submobs = []
for submob, sf in zip(self.submobjects, split_factors):
new_submobs.append(submob)
for k in range(1, sf):
new_submobs.append(
submob.copy().fade(1)
)
self.submobjects = new_submobs
return self
def repeat_submobject(self, submob):
return submob.copy()
def interpolate(self, mobject1, mobject2,
alpha, path_func=straight_path):
"""
Turns self into an interpolation between mobject1
and mobject2.
"""
self.points = path_func(
mobject1.points, mobject2.points, alpha
)
self.interpolate_color(mobject1, mobject2, alpha)
return self
def interpolate_color(self, mobject1, mobject2, alpha):
raise NotImplementedError('Please override in a child class.')
def pointwise_become_partial(self, mobject, a, b):
raise NotImplementedError('Please override in a child class.')
def become(self, mobject, copy_submobjects=True):
"""
Edit points, colors and submobjects to be idential
to another mobject
"""
self.align_data(mobject)
for sm1, sm2 in zip(self.get_family(), mobject.get_family()):
sm1.points = np.array(sm2.points)
sm1.interpolate_color(sm1, sm2, 1)
return self
# Errors
def throw_error_if_no_points(self):
if self.has_no_points():
message = "Cannot call Mobject.{} " +\
"for a Mobject with no points"
caller_name = sys._getframe(1).f_code.co_name
raise Exception(message.format(caller_name))
# About z-index
def set_z_index(self, z_index_value):
"""Sets the mobject's :attr:`z_index` to the value specified in `z_index_value`.
Parameters
----------
z_index_value : Union[:class:`int`, :class:`float`]
The new value of :attr:`z_index` set.
Returns
-------
:class:`Mobject`
The Mobject itself, after :attr:`z_index` is set. (Returns `self`.)
"""
self.z_index = z_index_value
return self
def set_z_index_by_z_coordinate(self):
"""Sets the mobject's z coordinate to the value of :attr:`z_index`.
Returns
-------
:class:`Mobject`
The Mobject itself, after :attr:`z_index` is set. (Returns `self`.)
"""
z_coord = self.get_center()[-1]
self.set_z_index(z_coord)
return self
class Group(Mobject):
def __init__(self, *mobjects, **kwargs):
if not all([isinstance(m, Mobject) for m in mobjects]):
raise Exception("All submobjects must be of type Mobject")
Mobject.__init__(self, **kwargs)
self.add(*mobjects)
|
/* eslint-disable class-methods-use-this, camelcase, no-param-reassign, max-classes-per-file */
import { dedupeMixin, SlotMixin } from '@lion/core';
import { localize } from '@lion/localize';
import { ResultValidator } from './ResultValidator.js';
import { Unparseable } from './Unparseable.js';
import { AsyncQueue } from './utils/AsyncQueue.js';
import { pascalCase } from './utils/pascal-case.js';
import { SyncUpdatableMixin } from './utils/SyncUpdatableMixin.js';
import { Validator } from './Validator.js';
import { Required } from './validators/Required.js';
function arrayDiff(array1 = [], array2 = []) {
return array1.filter(x => !array2.includes(x)).concat(array2.filter(x => !array1.includes(x)));
}
/**
* @desc Handles all validation, based on modelValue changes. It has no knowledge about dom and
* UI. All error visibility, dom interaction and accessibility are handled in FeedbackMixin.
*
* @event error-state-changed fires when FormControl goes from non-error to error state and vice versa
* @event error-changed fires when the Validator(s) leading to the error state, change
*/
export const ValidateMixin = dedupeMixin(
superclass =>
// eslint-disable-next-line no-unused-vars, no-shadow
class ValidateMixin extends SyncUpdatableMixin(SlotMixin(superclass)) {
static get properties() {
return {
/**
* @desc List of all Validator instances applied to FormControl
* @type {Validator[]}
* @example
* FormControl.validators = [new Required(), new MinLength(3, { type: 'warning' })];
*/
validators: Array,
hasFeedbackFor: {
type: Array,
},
shouldShowFeedbackFor: {
type: Array,
},
showsFeedbackFor: {
type: Array,
attribute: 'shows-feedback-for',
reflect: true,
converter: {
fromAttribute: value => value.split(','),
toAttribute: value => value.join(','),
},
},
validationStates: {
type: Object,
// hasChanged: this._hasObjectChanged,
},
/**
* @desc flag that indicates whether async validation is pending
*/
isPending: {
type: Boolean,
attribute: 'is-pending',
reflect: true,
},
/**
* @desc value that al validation revolves around: once changed (usually triggered by
* end user entering input), it will automatically trigger validation.
*/
modelValue: Object,
/**
* @desc specialized fields (think of input-date and input-email) can have preconfigured
* validators.
*/
defaultValidators: Array,
/**
* Subclassers can enable this to show multiple feedback messages at the same time
* By default, just like the platform, only one message (with highest prio) is visible.
*/
_visibleMessagesAmount: Number,
/**
* @type {Promise<string>|string} will be passed as an argument to the `.getMessage`
* method of a Validator. When filled in, this field name can be used to enhance
* error messages.
*/
fieldName: String,
};
}
/**
* @overridable
*/
static get validationTypes() {
return ['error'];
}
/**
* @overridable
* Adds "._feedbackNode" as described below
*/
get slots() {
return {
...super.slots,
feedback: () => document.createElement('lion-validation-feedback'),
};
}
/**
* @overridable
* @type {Element} _feedbackNode:
* Gets a `FeedbackData` object as its input.
* This element can be a custom made (web) component that renders messages in accordance with
* the implemented Design System. For instance, it could add an icon in front of a message.
* The _feedbackNode is only responsible for the visual rendering part, it should NOT contain
* state. All state will be determined by the outcome of `FormControl.filterFeeback()`.
* FormControl delegates to individual sub elements and decides who renders what.
* For instance, FormControl itself is responsible for reflecting error-state and error-show
* to its host element.
* This means filtering out messages should happen in FormControl and NOT in `_feedbackNode`
*
* - gets a FeedbackData object as input
* - should know about the FeedbackMessage types('error', 'success' etc.) that the FormControl
* (having ValidateMixin applied) returns
* - renders result and
*
*/
get _feedbackNode() {
return this.querySelector('[slot=feedback]');
}
get _allValidators() {
return [...this.validators, ...this.defaultValidators];
}
constructor() {
super();
this.hasFeedbackFor = [];
this.shouldShowFeedbackFor = [];
this.showsFeedbackFor = [];
this.validationStates = {};
this._visibleMessagesAmount = 1;
this.isPending = false;
/** @type {Validator[]} */
this.validators = [];
/** @type {Validator[]} */
this.defaultValidators = [];
/** @type {Validator[]} */
this.__syncValidationResult = [];
/** @type {Validator[]} */
this.__asyncValidationResult = [];
/**
* @desc contains results from sync Validators, async Validators and ResultValidators
* @type {Validator[]}
*/
this.__validationResult = [];
this.__onValidatorUpdated = this.__onValidatorUpdated.bind(this);
this._updateFeedbackComponent = this._updateFeedbackComponent.bind(this);
}
connectedCallback() {
super.connectedCallback();
localize.addEventListener('localeChanged', this._updateFeedbackComponent);
}
disconnectedCallback() {
super.disconnectedCallback();
localize.addEventListener('localeChanged', this._updateFeedbackComponent);
}
/**
* Should be overridden by subclasses if a different validation-feedback component is used
*/
async _loadFeedbackComponent() {
await import('../lion-validation-feedback.js');
}
firstUpdated(c) {
super.firstUpdated(c);
this.__validateInitialized = true;
this.validate();
this._loadFeedbackComponent();
}
updateSync(name, oldValue) {
super.updateSync(name, oldValue);
if (name === 'validators') {
// trigger validation (ideally only for the new or changed validator)
this.__setupValidators();
this.validate();
} else if (name === 'modelValue') {
this.validate({ clearCurrentResult: true });
}
if (['touched', 'dirty', 'prefilled', 'submitted', 'hasFeedbackFor'].includes(name)) {
this._updateShouldShowFeedbackFor();
}
if (name === 'showsFeedbackFor') {
// This can't be reflected asynchronously in Safari
// Screen reader output should be in sync with visibility of error messages
if (this._inputNode) {
this._inputNode.setAttribute('aria-invalid', this._hasFeedbackVisibleFor('error'));
// this._inputNode.setCustomValidity(this._validationMessage || '');
}
const diff = arrayDiff(this.showsFeedbackFor, oldValue);
if (diff.length > 0) {
this.dispatchEvent(new Event(`showsFeedbackForChanged`, { bubbles: true }));
}
diff.forEach(type => {
this.dispatchEvent(
new Event(`showsFeedbackFor${pascalCase(type)}Changed`, { bubbles: true }),
);
});
}
if (name === 'shouldShowFeedbackFor') {
const diff = arrayDiff(this.shouldShowFeedbackFor, oldValue);
if (diff.length > 0) {
this.dispatchEvent(new Event(`shouldShowFeedbackForChanged`, { bubbles: true }));
}
}
}
/**
* @desc The main function of this mixin. Triggered by:
* - a modelValue change
* - a change in the 'validators' array
* - a change in the config of an individual Validator
*
* Three situations are handled:
* - A.1 The FormControl is empty: further execution is halted. When the Required Validator
* (being mutually exclusive to the other Validators) is applied, it will end up in the
* validation result (as the only Validator, since further execution was halted).
* - A.2 There are synchronous Validators: this is the most common flow. When modelValue hasn't
* changed since last async results were generated, 'sync results' are merged with the
* 'async results'.
* - A.3 There are asynchronous Validators: for instance when server side evaluation is needed.
* Executions are scheduled and awaited and the 'async results' are merged with the
* 'sync results'.
*
* - B. There are ResultValidators. After steps A.1, A.2, or A.3 are finished, the holistic
* ResultValidators (evaluating the total result of the 'regular' (A.1, A.2 and A.3) validators)
* will be run...
*
* Situations A.2 and A.3 are not mutually exclusive and can be triggered within one validate()
* call. Situation B will occur after every call.
*/
async validate({ clearCurrentResult } = {}) {
if (!this.__validateInitialized) {
return;
}
this.__storePrevResult();
if (clearCurrentResult) {
// Clear ('invalidate') all pending and existing validation results.
// This is needed because we have async (pending) validators whose results
// need to be merged with those of sync validators and vice versa.
this.__clearValidationResults();
}
await this.__executeValidators();
}
__storePrevResult() {
this.__prevValidationResult = this.__validationResult;
}
/**
* @desc step A1-3 + B (as explained in 'validate')
*/
async __executeValidators() {
this.validateComplete = new Promise(resolve => {
this.__validateCompleteResolve = resolve;
});
// When the modelValue can't be created by FormatMixin.parser, still allow all validators
// to give valuable feedback to the user based on the current viewValue.
const value =
this.modelValue instanceof Unparseable ? this.modelValue.viewValue : this.modelValue;
/** @type {Validator} */
const requiredValidator = this._allValidators.find(v => v instanceof Required);
/**
* 1. Handle the 'exceptional' Required validator:
* - the validatity is dependent on the formControl type and therefore determined
* by the formControl.__isEmpty method. Basically, the Required Validator is a means
* to trigger formControl.__isEmpty.
* - when __isEmpty returns false, the input was empty. This means we need to stop
* validation here, because all other Validators' execute functions assume the
* value is not empty (there would be nothing to validate).
*/
const isEmpty = this.__isEmpty(value);
if (isEmpty) {
if (requiredValidator) {
this.__syncValidationResult = [requiredValidator];
}
this.__finishValidation({ source: 'sync' });
return;
}
// Separate Validators in sync and async
const /** @type {Validator[]} */ filteredValidators = this._allValidators.filter(
v => !(v instanceof ResultValidator) && !(v instanceof Required),
);
const /** @type {Validator[]} */ syncValidators = filteredValidators.filter(v => !v.async);
const /** @type {Validator[]} */ asyncValidators = filteredValidators.filter(v => v.async);
/**
* 2. Synchronous validators
*/
this.__executeSyncValidators(syncValidators, value, {
hasAsync: Boolean(asyncValidators.length),
});
/**
* 3. Asynchronous validators
*/
await this.__executeAsyncValidators(asyncValidators, value);
}
/**
* @desc step A2, calls __finishValidation
* @param {Validator[]} syncValidators
*/
__executeSyncValidators(syncValidators, value, { hasAsync }) {
if (syncValidators.length) {
this.__syncValidationResult = syncValidators.filter(v =>
v.execute(value, v.param, { node: this }),
);
}
this.__finishValidation({ source: 'sync', hasAsync });
}
/**
* @desc step A3, calls __finishValidation
* @param {Validator[]} filteredValidators all Validators except required and ResultValidators
*/
async __executeAsyncValidators(asyncValidators, value) {
if (asyncValidators.length) {
this.isPending = true;
const resultPromises = asyncValidators.map(v =>
v.execute(value, v.param, { node: this }),
);
const booleanResults = await Promise.all(resultPromises);
this.__asyncValidationResult = booleanResults
.map((r, i) => asyncValidators[i]) // Create an array of Validators
.filter((v, i) => booleanResults[i]); // Only leave the ones returning true
this.__finishValidation({ source: 'async' });
this.isPending = false;
}
}
/**
* @desc step B, called by __finishValidation
* @param {Validator[]} regularValidationResult result of steps 1-3
*/
__executeResultValidators(regularValidationResult) {
/** @type {ResultValidator[]} */
const resultValidators = this._allValidators.filter(
v => !v.async && v instanceof ResultValidator,
);
return resultValidators.filter(v =>
v.executeOnResults({
regularValidationResult,
prevValidationResult: this.__prevValidationResult,
}),
);
}
/**
* @param {object} options
* @param {'sync'|'async'} options.source
* @param {boolean} [options.hasAsync] whether async validators are configured in this run.
* If not, we have nothing left to wait for.
*/
__finishValidation({ source, hasAsync }) {
const /** @type {Validator[]} */ syncAndAsyncOutcome = [
...this.__syncValidationResult,
...this.__asyncValidationResult,
];
// if we have any ResultValidators left, now is the time to run them...
const resultOutCome = this.__executeResultValidators(syncAndAsyncOutcome);
/** @typedef {Validator[]} TotalValidationResult */
this.__validationResult = [...resultOutCome, ...syncAndAsyncOutcome];
// this._storeResultsOnInstance(this.__validationResult);
const validationStates = this.constructor.validationTypes.reduce(
(acc, type) => ({ ...acc, [type]: {} }),
{},
);
this.__validationResult.forEach(v => {
if (!validationStates[v.type]) {
validationStates[v.type] = {};
}
validationStates[v.type][v.name] = true;
});
this.validationStates = validationStates;
this.hasFeedbackFor = [...new Set(this.__validationResult.map(v => v.type))];
/** private event that should be listened to by LionFieldSet */
this.dispatchEvent(new Event('validate-performed', { bubbles: true }));
if (source === 'async' || !hasAsync) {
this.__validateCompleteResolve();
}
}
__clearValidationResults() {
this.__syncValidationResult = [];
this.__asyncValidationResult = [];
}
__onValidatorUpdated(e) {
if (e.type === 'param-changed' || e.type === 'config-changed') {
this.validate();
}
}
__setupValidators() {
const events = ['param-changed', 'config-changed'];
if (this.__prevValidators) {
this.__prevValidators.forEach(v => {
events.forEach(e => v.removeEventListener(e, this.__onValidatorUpdated));
v.onFormControlDisconnect(this);
});
}
this._allValidators.forEach(v => {
if (!(v instanceof Validator)) {
// throws in constructor are not visible to end user so we do both
const errorType = Array.isArray(v) ? 'array' : typeof v;
const errorMessage = `Validators array only accepts class instances of Validator. Type "${errorType}" found.`;
// eslint-disable-next-line no-console
console.error(errorMessage, this);
throw new Error(errorMessage);
}
if (this.constructor.validationTypes.indexOf(v.type) === -1) {
// throws in constructor are not visible to end user so we do both
const errorMessage = `This component does not support the validator type "${v.type}" used in "${v.name}". You may change your validators type or add it to the components "static get validationTypes() {}".`;
// eslint-disable-next-line no-console
console.error(errorMessage, this);
throw new Error(errorMessage);
}
events.forEach(e => v.addEventListener(e, this.__onValidatorUpdated));
v.onFormControlConnect(this);
});
this.__prevValidators = this._allValidators;
}
static _hasObjectChanged(result, prevResult) {
return JSON.stringify(result) !== JSON.stringify(prevResult);
}
__isEmpty(v) {
if (typeof this._isEmpty === 'function') {
return this._isEmpty(v);
}
// // TODO: move to compat layer. Be sure to keep this, because people use this a lot
// if (typeof this.__isRequired === 'function') {
// return !this.__isRequired(v);
// }
return v === null || typeof v === 'undefined' || v === '';
}
// ------------------------------------------------------------------------------------------
// -- Feedback specifics --------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
/**
* @typedef {object} FeedbackMessage
* @property {string} message this
* @property {string} type will be 'error' for messages from default Validators. Could be
* 'warning', 'info' etc. for Validators with custom types. Needed as a directive for
* feedbackNode how to render a message of a certain type
* @property {Validator} [validator] when the message is directly coupled to a Validator
* (in most cases), this property is filled. When a message is not coupled to a Validator
* (in case of success feedback which is based on a diff or current and previous validation
* results), this property can be left empty.
*/
/**
* @param {Validator[]} validators list of objects having a .getMessage method
* @return {FeedbackMessage[]}
*/
async __getFeedbackMessages(validators) {
let fieldName = await this.fieldName;
return Promise.all(
validators.map(async validator => {
if (validator.config.fieldName) {
fieldName = await validator.config.fieldName;
}
const message = await validator._getMessage({
modelValue: this.modelValue,
formControl: this,
fieldName,
});
return { message, type: validator.type, validator };
}),
);
}
/**
* @desc Responsible for retrieving messages from Validators and
* (delegation of) rendering them.
*
* For `._feedbackNode` (extension of LionValidationFeedback):
* - retrieve messages from highest prio Validators
* - provide the result to custom feedback node and let the
* custom node decide on their renderings
*
* In both cases:
* - we compute the 'show' flag (like 'hasErrorVisible') for all types
* - we set the customValidity message of the highest prio Validator
* - we set aria-invalid="true" in case hasErrorVisible is true
*/
_updateFeedbackComponent() {
if (!this.__feedbackQueue) {
this.__feedbackQueue = new AsyncQueue();
}
if (this.showsFeedbackFor.length > 0) {
this.__feedbackQueue.add(async () => {
/** @type {Validator[]} */
this.__prioritizedResult = this._prioritizeAndFilterFeedback({
validationResult: this.__validationResult,
});
const messageMap = await this.__getFeedbackMessages(this.__prioritizedResult);
this._feedbackNode.feedbackData = messageMap.length ? messageMap : [];
});
} else {
this.__feedbackQueue.add(async () => {
this._feedbackNode.feedbackData = [];
});
}
this.feedbackComplete = this.__feedbackQueue.complete;
}
/**
* Show the validity feedback when one of the following conditions is met:
*
* - submitted
* If the form is submitted, always show the error message.
*
* - prefilled
* the user already filled in something, or the value is prefilled
* when the form is initially rendered.
*
* - touched && dirty
* When a user starts typing for the first time in a field with for instance `required`
* validation, error message should not be shown until a field becomes `touched`
* (a user leaves(blurs) a field).
* When a user enters a field without altering the value(making it `dirty`),
* an error message shouldn't be shown either.
*/
_showFeedbackConditionFor(/* type */) {
return (this.touched && this.dirty) || this.prefilled || this.submitted;
}
_hasFeedbackVisibleFor(type) {
return (
this.hasFeedbackFor &&
this.hasFeedbackFor.includes(type) &&
this.shouldShowFeedbackFor &&
this.shouldShowFeedbackFor.includes(type)
);
}
updated(c) {
super.updated(c);
if (c.has('shouldShowFeedbackFor') || c.has('hasFeedbackFor')) {
this.showsFeedbackFor = this.constructor.validationTypes
.map(type => (this._hasFeedbackVisibleFor(type) ? type : undefined))
.filter(_ => !!_);
this._updateFeedbackComponent();
}
}
_updateShouldShowFeedbackFor() {
this.shouldShowFeedbackFor = this.constructor.validationTypes
.map(type => (this._showFeedbackConditionFor(type) ? type : undefined))
.filter(_ => !!_);
}
/**
* @overridable
* @desc Orders all active validators in this.__validationResult. Can
* also filter out occurrences (based on interaction states)
* @returns {Validator[]} ordered list of Validators with feedback messages visible to the
* end user
*/
_prioritizeAndFilterFeedback({ validationResult }) {
const types = this.constructor.validationTypes;
// Sort all validators based on the type provided.
const res = validationResult.sort((a, b) => types.indexOf(a.type) - types.indexOf(b.type));
return res.slice(0, this._visibleMessagesAmount);
}
},
);
|
import pytest
def user_flows_handler(event, context):
environment = event['environment']
return pytest.main([
"-p", "no:cacheprovider",
"-s", "--verbose",
"--environment", environment,
"./test_retrieve_everything.py"
])
|
// Copyright (c) 2019-2020 The Beans Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BEANS_UTIL_ASMAP_H
#define BEANS_UTIL_ASMAP_H
#include <stdint.h>
#include <vector>
uint32_t Interpret(const std::vector<bool> &asmap, const std::vector<bool> &ip);
bool SanityCheckASMap(const std::vector<bool>& asmap, int bits);
#endif // BEANS_UTIL_ASMAP_H
|
import test from 'ava'
import sinon from 'sinon'
import Analytics from '../src'
test.beforeEach((t) => {
t.context.sandbox = sinon.createSandbox()
})
test.cb('Plugins should have correct config in methods', (t) => {
let valueOne
let valueTwo
const analytics = Analytics({
app: 'appname',
version: 100,
plugins: [
{
name: 'pluginA',
config: {
test: 'A'
},
'page:pluginB': ({ config }) => {
valueOne = config.test // should be A
}
},
{
name: 'pluginB',
config: {test: 'B'},
page: ({ config }) => {
valueTwo = config.test // should be B
}
}
]
})
analytics.page(() => {
t.is(valueOne, 'A')
t.is(valueTwo, 'B')
t.end()
})
})
|
import axios from "axios";
const adminGet = async (id) => {
const token = localStorage.getItem('jwt_token');
const url = "/api/auth/admin/get";
const body = {
id: id,
};
const headers = {
"Authorization": "Bearer " + token
}
const response = await axios({
method: 'post',
url: url,
data: body,
headers: headers
});
return response;
}
export default adminGet;
|
const express = require('express');
const aplicacion = express();
const mysql = require('mysql');
const bodyParser = require('body-parser');
const constantes = require('constants');
var pool = mysql.createPool({
connectionLimit: 20,
host: 'localhost',
user: 'root',
password: '****',
database: 'inventario'
});
//aplicacion.set('view engine', 'ejs');
aplicacion.use(bodyParser.json());
aplicacion.use(bodyParser.urlencoded({ extended: true }));
//aplicacion.use(express.static('public'));
/**
* Find a producto with parametters, use id
* parametters: ruta, internal function
* return: id is used for find product, a product data is getted.
* in other way code 404 is getted and sended a error message on
* json file for be viewed on the browser.
*/
aplicacion.get("/api/inventario/producto/:id", function(peticion, respuesta) {
//GET METHODE
pool.getConnection(function(err, connection) {
let query = `SELECT id, nombre, precio, cantidad FROM producto WHERE id=${connection.escape(peticion.params.id)} ORDER BY precio ASC`
connection.query(query, function(error, filas, campos) {
if (filas.length > 0) {
respuesta.json({
data: filas[0]
});
} else {
respuesta.status(404);
respuesta.send({
errors: ["Error 404 - Producto No Encontrado."]
})
}
});
connection.release();
})
})
/**
* Lista los productos, segun una consulta por campos
* parametros: ruta, funcion interna de busqueda
* retorna: Lista de productos segun orden de campos entregada.
* deprecado: en caso contrario actualiza el estado a 404 y envia un mensaje de error como json file.
*/
aplicacion.get('/api/inventario/productos', function(peticion, respuesta) {
/*
A path valid is this type: /api/[sistema]/[subsistema]/?orden=[id || nombre || cantidad || precio]
For example the path '/api/inventario/productos?orden=precio' the productos list´s is ordered by
precio and file json is showed on the browser.
*/
//API REST - GET Method - parametters are used
pool.getConnection(function(err, connection) {
//parametters used here for order by...
let query = `SELECT * FROM producto ORDER BY nombre ASC;`;
if (peticion.query.orden == "precio") {
query = `SELECT * FROM producto ORDER BY precio ASC;`;
} else if (peticion.query.orden == "cantidad") {
query = `SELECT * FROM producto as p ORDER BY p.cantidad ASC;`;
} else if (peticion.query.orden == "id") {
query = `SELECT * FROM producto ORDER BY id ASC;`;
} else {
query = `SELECT * FROM producto ORDER BY nombre ASC;`;
}
connection.query(query, function(error, filas, campos) {
//I have data in filas(length >0), use:
respuesta.json({ data: filas });
// Connection is Disabled now
connection.release();
})
})
})
/**
* Actualiza el puerto de escucha
* parametros:
* puerto de escucha, funcion interna
*/
aplicacion.listen(8080, function() {
console.log("Servidor Escuchando...");
})
|
/****************************************************************
* AUTHOR: Brett Kettering
* DATE: July 26, 2005
* LAST MODIFIED: July 26, 2005
*
* LOS ALAMOS NATIONAL LABORATORY
* An Affirmative Action/Equal Opportunity Employer
*
* Copyright (c) 2005
* the Regents of the University of California.
*
* Unless otherwise indicated, this information has been authored by an
* employee or employees of the University of California, operator of the Los
* Alamos National Laboratory under Contract No. W-7405-ENG-36 with the U. S.
* Department of Energy. The U. S. Government has rights to use, reproduce, and
* distribute this information. The public may copy and use this information
* without charge, provided that this Notice and any statement of authorship
* are reproduced on all copies. Neither the Government nor the University
* makes any warranty, express or implied, or assumes any liability or
* responsibility for the use of this information.
******************************************************************/
#ifndef __BOOLEAN_H_INCLUDED
#define __BOOLEAN_H_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif
#define TRUE 1
#define FALSE 0
/****************************************************************
*
* This function returns text for a boolean value.
*
******************************************************************/
char *boolean_to_text( unsigned char the_boolean );
#ifdef __cplusplus
}
#endif
#endif /* __BOOLEAN_H_INCLUDED */
|
# -*- coding: UTF-8 -*-
# import pprint
from clarifai.rest import ClarifaiApp
import settings
def is_cat(file_name):
""" Add ClarifaiApp call for image_classification"""
is_cat = False
app = ClarifaiApp(api_key=settings.CLARIFAI_API_KEY)
model = app.public_models.general_model
response = model.predict_by_filename(file_name, max_concepts=5)
# pprint.pprint(response)
if response['status']['code'] == 10000:
for concept in response['outputs'][0]['data']['concepts']:
if concept.get('name') == 'cat':
is_cat = True
break
return is_cat
if __name__ == "__main__":
# is_cat('images/cat1.jpg')
if is_cat('2017-10-14 14-25-04.JPG'):
print('Have cat!')
|
# Copyright (c) 2017-2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# fmt: off
# isort: skip_file
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from . import config_management_service_pb2 as com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2
class ConfigManagementServiceStub(object):
"""Status: experimental interface, will change before it is deemed production
ready
Ledger configuration management service provides methods for the ledger administrator
to change the current ledger configuration. The services provides methods to modify
different aspects of the configuration.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetTimeModel = channel.unary_unary(
'/com.daml.ledger.api.v1.admin.ConfigManagementService/GetTimeModel',
request_serializer=com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.GetTimeModelRequest.SerializeToString,
response_deserializer=com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.GetTimeModelResponse.FromString,
)
self.SetTimeModel = channel.unary_unary(
'/com.daml.ledger.api.v1.admin.ConfigManagementService/SetTimeModel',
request_serializer=com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.SetTimeModelRequest.SerializeToString,
response_deserializer=com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.SetTimeModelResponse.FromString,
)
class ConfigManagementServiceServicer(object):
"""Status: experimental interface, will change before it is deemed production
ready
Ledger configuration management service provides methods for the ledger administrator
to change the current ledger configuration. The services provides methods to modify
different aspects of the configuration.
"""
def GetTimeModel(self, request, context):
"""Return the currently active time model and the current configuration generation.
Errors:
- ``UNAUTHENTICATED``: if the request does not include a valid access token
- ``PERMISSION_DENIED``: if the claims in the token are insufficient to perform a given operation
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def SetTimeModel(self, request, context):
"""Set the ledger time model.
Errors:
- ``UNAUTHENTICATED``: if the request does not include a valid access token
- ``PERMISSION_DENIED``: if the claims in the token are insufficient to perform a given operation
- ``INVALID_ARGUMENT``: if arguments are invalid, or the provided configuration generation
does not match the current active configuration generation. The caller is expected
to retry by again fetching current time model using 'GetTimeModel', applying changes
and resubmitting.
- ``ABORTED``: if the request is rejected or times out. Note that a timed out request may
have still been committed to the ledger. Application should re-query the current
time model before retrying.
- ``UNIMPLEMENTED``: if this method is not supported by the backing ledger.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ConfigManagementServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetTimeModel': grpc.unary_unary_rpc_method_handler(
servicer.GetTimeModel,
request_deserializer=com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.GetTimeModelRequest.FromString,
response_serializer=com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.GetTimeModelResponse.SerializeToString,
),
'SetTimeModel': grpc.unary_unary_rpc_method_handler(
servicer.SetTimeModel,
request_deserializer=com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.SetTimeModelRequest.FromString,
response_serializer=com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.SetTimeModelResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'com.daml.ledger.api.v1.admin.ConfigManagementService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class ConfigManagementService(object):
"""Status: experimental interface, will change before it is deemed production
ready
Ledger configuration management service provides methods for the ledger administrator
to change the current ledger configuration. The services provides methods to modify
different aspects of the configuration.
"""
@staticmethod
def GetTimeModel(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/com.daml.ledger.api.v1.admin.ConfigManagementService/GetTimeModel',
com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.GetTimeModelRequest.SerializeToString,
com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.GetTimeModelResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def SetTimeModel(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/com.daml.ledger.api.v1.admin.ConfigManagementService/SetTimeModel',
com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.SetTimeModelRequest.SerializeToString,
com_dot_daml_dot_ledger_dot_api_dot_v1_dot_admin_dot_config__management__service__pb2.SetTimeModelResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
|
"""Support for monitoring energy usage using the DTE energy bridge."""
import logging
from homeassistant.helpers.entity import Entity
_LOGGER = logging.getLogger(__name__)
ICON = 'mdi:flash'
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the DTE energy bridge sensor."""
ip_address = config.get('ip')
if not ip_address:
_LOGGER.error(
"Configuration Error"
"'ip' of the DTE energy bridge is required")
return None
dev = [DteEnergyBridgeSensor(ip_address)]
add_devices(dev)
# pylint: disable=too-many-instance-attributes
class DteEnergyBridgeSensor(Entity):
"""Implementation of an DTE Energy Bridge sensor."""
def __init__(self, ip_address):
"""Initialize the sensor."""
self._url = "http://{}/instantaneousdemand".format(ip_address)
self._name = "Current Energy Usage"
self._unit_of_measurement = "kW"
self._state = None
@property
def name(self):
"""Return the name of th sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return ICON
def update(self):
"""Get the energy usage data from the DTE energy bridge."""
import requests
try:
response = requests.get(self._url, timeout=5)
except (requests.exceptions.RequestException, ValueError):
_LOGGER.warning(
'Could not update status for DTE Energy Bridge (%s)',
self._name)
return
if response.status_code != 200:
_LOGGER.warning(
'Invalid status_code from DTE Energy Bridge: %s (%s)',
response.status_code, self._name)
return
response_split = response.text.split()
if len(response_split) != 2:
_LOGGER.warning(
'Invalid response from DTE Energy Bridge: "%s" (%s)',
response.text, self._name)
return
self._state = float(response_split[0])
|
/*!
* OpenUI5
* (c) Copyright 2009-2020 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['sap/ui/core/Renderer','sap/m/PlanningCalendarRenderer'],function(R,P){"use strict";var a=R.extend(P);a.addAdditionalClasses=function(r){r.class("sapMPlanCalInCard");};return a;},true);
|
from datetime import datetime
from glob import glob
from argparse import ArgumentParser
import requests
import os
import logging
import subprocess
logging.basicConfig(level=logging.INFO, format='%(message)s', handlers=[logging.FileHandler('synchronize.log'), logging.StreamHandler()])
'''
pc.synchronize.vcfs.py
October 4th, 2018
Dennis Kao, Center for Computational Medicine
Description:
Script to match and upload vcf files on our local file system to users on PhenomeCentral.
Implementation details:
requests:
gets a list of user data from PhenomeCentral in JSON format
matching algorithm:
exact_match: user's external_id is identical to a vcf file's name minus the extension (123_456R matches 123_456R.vcf)
prefix_match: user's external_id is the prefix to a vcf (123_456 matches 123_456_replacement_2017.06.12.vcf)
uploading vcfs:
run a script created by PhenomeCentral team for each match of user id to vcf file
Output:
Stats on vcfs on filesystem, vcf-user matching result, vcfs on PhenomeCentral
System requirements:
Python 3.5
UNIX file system
'''
def get_user_data(pc_credentials):
def parse_auth(pc_credentials):
with open(pc_credentials) as f:
line = f.readline().strip('\n').split(':')
username = line[0]
password = line[1]
return (username, password)
user_data_url = "https://phenomecentral.org/get/PhenomeCentral/patient_list_script?action=list"
with requests.Session() as session:
session.auth = parse_auth(pc_credentials)
user_data = session.get(user_data_url).json()["data"]
return user_data
def scan_filesystem_vcf(results_dir, exhaustive_search=False):
'''
TODO: Use file creation date when deciding between 2 identically named files instead of modification date -- os.path.getmtime()
Note on exhaustive_search:
Our file structure is extremely consistent. 99.9999% of the time, vcfs that you want to find are detected by the regex defined below.
VCF's which fall outside of this condition are mostly vcfs from an older pipeline version, or vcfs uploaded from collaborates and not created from our pipelines.
'''
vcf_paths = []
vcf_dict = {}
duplicates = {}
if not exhaustive_search:
vcf_paths = glob('{}/*/*/*.vcf'.format(results_dir)) # equivalent to: ls results_dir/*/*/*.vcf
else:
for dirpath, dirname, files in os.walk(results_dir):
for filename in files:
if filename.endswith('.vcf'):
vcf_paths.append(os.path.join(dirpath, filename))
# exclude some directories known to contain junk
vcf_paths = [ p for p in vcf_paths if "/misc/" not in p and "/miscx/" not in p and "/calx/" not in p and "/database/" not in p ]
# detect and filter out identically named vcf files
for path in vcf_paths:
filename = os.path.basename(path)
if filename in duplicates.keys():
duplicates[filename].append(path)
elif filename in vcf_dict.keys():
duplicates[filename] = []
duplicates[filename].append(path)
duplicates[filename].append(vcf_dict[filename])
vcf_dict.pop(filename)
else:
vcf_dict[filename] = path
if duplicates:
logging.warning('[DUPLICATES] Identically named vcfs detected. Attempting to resolve based on earliest modification date.')
for filename, paths in duplicates.items():
paths = sorted(paths, key=os.path.getmtime)
if os.path.getmtime(paths[-1]) == os.path.getmtime(paths[-2]):
logging.warning('Could not resolve duplicates of {} based on earliest modification date. Script won\'t upload any of these files: {}'.format(filename, str(paths)))
else:
vcf_dict[filename] = paths[-1]
logging.warning('Using {} out of all files: {}'.format(vcf_dict[filename], str(paths)))
return vcf_dict
def match_vcf2user(vcfs, no_vcf_users):
def print_matched(message, users, matched):
header = '\t'.join(['ID', 'EXTERNAL_ID', 'VCF'])
external_id = { user["id"]:user["external_id"] for user in users if user["id"] in matched.keys() }
logging.info(message)
logging.info(header)
for id, paths in matched.items():
logging.info('\t'.join([id, external_id[id], str(paths)]))
def remove_matched(vcf_dict, users, matched_dict):
return {vcf:path for vcf, path in vcf_dict.items() if path not in matched_dict.values()}, [user for user in users if user["id"] not in matched_dict.keys()]
def match_exact(vcf_dict, users):
def vcf_extension(id):
return u'{}.vcf'.format(id)
return { user["id"]:vcf_dict[vcf_extension(user["external_id"])] for user in users if vcf_extension(user["external_id"]) in vcf_dict.keys() }
def match_prefix(vcf_dict, users):
prefix_match = {}
multiple_prefix_match_hits = {}
for user in users:
external_id = user["external_id"]
pc_id = user["id"]
for vcf, filepath in vcf_dict.items():
if vcf.startswith(external_id) or vcf.startswith(external_id.strip()) or vcf.startswith(external_id.strip('-')) or vcf.startswith(external_id.strip('_')):
if pc_id in multiple_prefix_match_hits.keys():
multiple_prefix_match_hits[pc_id].append(filepath)
elif pc_id not in prefix_match.keys():
prefix_match[pc_id] = filepath
else:
multiple_prefix_match_hits[pc_id] = []
multiple_prefix_match_hits[pc_id].append(filepath)
multiple_prefix_match_hits[pc_id].append(prefix_match[pc_id])
prefix_match.pop(pc_id)
if multiple_prefix_match_hits:
print_matched("{}: These files will not be uploaded. External_id is the prefix to multiple VCFs:".format(match_prefix.__name__), users, multiple_prefix_match_hits)
return prefix_match
matched = {}
has_external_id = [ user for user in no_vcf_users if user["external_id"] is not None and not user["external_id"].isspace() and len(user["external_id"]) != 0 ]
for matching_algo in [ match_exact, match_prefix ]:
newly_matched = matching_algo(vcfs, has_external_id)
if newly_matched:
message = '{}: managed to match {} users'.format(matching_algo.__name__, str(len(newly_matched)))
print_matched(message, has_external_id, newly_matched)
else:
logging.info('{}: did not manage to match any users to vcfs'.format(matching_algo.__name__))
matched.update(newly_matched)
vcfs, has_external_id = remove_matched(vcfs, has_external_id, matched)
unmatched = [ u for u in no_vcf_users if u["id"] not in matched.keys() ] # consented, no vcf, and no matches with vcf on filesystem
return matched, unmatched
def upload_to_pc(pc_credentials, matched):
with open("failed_uploads.txt", "w") as failed:
for id, path in matched.items():
logging.info('Uploading {} to PhenomeCentral user {}'.format(path, id))
cmd = 'python ~/cre/pc.upload_vcf.py {} {} {} phenomecentral.org'.format(id, path, pc_credentials)
try:
p = subprocess.check_output(cmd, shell=True, timeout=10)
logging.info(p)
except Exception as e:
failed.write('{}\t{}\t{}\n'.format(id, path, str(e)))
def synchronize(pc_credentials, results_dir, upload_flag):
logging.info("Scanning filesystem for vcf's at: {}".format(results_dir))
vcfs = scan_filesystem_vcf(results_dir)
total_vcfs = len(vcfs)
logging.info("Getting user data from PhenomeCentral")
user_data = get_user_data(pc_credentials)
granted = [ u for u in user_data if u["genetic_consent"] == "granted" ]
not_granted = [ u for u in user_data if u["genetic_consent"] == "not granted" ]
no_vcf = [ u for u in granted if u["vcf"] == "none" ] # consented, but no vcf
has_vcf = [ u for u in granted if u["vcf"] != "none" ] # consented and has vcf
already_uploaded = [ u for u in has_vcf if u["vcf"] in vcfs.keys() ] # consented, has vcf, and vcf matches with one on filesystem
logging.info("Matching users to vcfs ...")
matched, unmatched = match_vcf2user(vcfs, no_vcf)
logging.info('')
logging.info("Filesystem statistics:")
logging.info("Total vcfs: %d" % total_vcfs)
logging.info("VCFs already uploaded to PhenomeCentral: %d" % len(already_uploaded))
logging.info("Remaining VCFs: %d" % (total_vcfs-len(already_uploaded)))
logging.info('')
logging.info("PhenomeCentral user statistics:")
logging.info("Total users:\t%d" % len(user_data))
logging.info("Granted consent:\t%d" % len(granted))
logging.info("Not granted:\t%d" % len(not_granted))
logging.info("Granted consent and has a vcf uploaded:\t%d" % len(has_vcf))
logging.info("Granted consent and no vcf uploaded:\t%d" % len(no_vcf))
logging.info("Granted consent, no vcf uploaded, and has a matched vcf:\t%d" % len(matched))
logging.info("Granted consent, no vcf uploaded, and no matched vcf:\t%d" % len(unmatched))
logging.info('')
if upload_flag:
upload_to_pc(pc_credentials, matched)
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('-pc_credentials', help='Text file containing PhenomeCentral login credentials in the format: username:password', required=True)
parser.add_argument('-results_dir', help='Path to the results directory containing vcf files. Our typical directory structure: results/10x/1031R/1031R_1234.vcf', required=True)
parser.add_argument('--upload', help='Upload VCF file\'s identified through matching to PhenomeCentral', action='store_true')
args = parser.parse_args()
logging.info('started vcf synchronization on {}'.format(datetime.now().strftime("%Y-%m-%d_%H:%M:%S")))
synchronize(args.pc_credentials, args.results_dir, args.upload)
logging.info('synchronization finished on {}'.format(datetime.now().strftime("%Y-%m-%d_%H:%M:%S")))
|
import re
from collections import namedtuple
from itertools import dropwhile
from .base import BaseVersion
from .exceptions import InvalidVersion
from .utils import Infinity
_Version = namedtuple("_Version", ["epoch", "release", "dev", "pre", "post", "local"])
VERSION_PATTERN = re.compile(
"""
^
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_.]?
(?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
[-_.]?
(?P<pre_n>[0-9]+)?
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+))
|
(?:
[-_.]?
(?P<post_l>post|rev|r)
[-_.]?
(?P<post_n2>[0-9]+)?
)
)?
(?P<dev> # dev release
[-_.]?
(?P<dev_l>dev)
[-_.]?
(?P<dev_n>[0-9]+)?
)?
)
(?:\+(?P<local>[a-z0-9]+(?:[-_.][a-z0-9]+)*))? # local version
$
""",
re.IGNORECASE | re.VERBOSE,
)
class Version(BaseVersion):
def __init__(self, version):
# Validate the version and parse it into pieces
match = VERSION_PATTERN.match(version)
if not match:
raise InvalidVersion("Invalid version: '{0}'".format(version))
# Store the parsed out pieces of the version
self._version = _Version(
epoch=int(match.group("epoch")) if match.group("epoch") else 0,
release=tuple(int(i) for i in match.group("release").split(".")),
pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
post=_parse_letter_version(
match.group("post_l"), match.group("post_n1") or match.group("post_n2")
),
dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
local=_parse_local_version(match.group("local")),
)
# Generate a key which will be used for sorting
self._key = _cmpkey(
self._version.epoch,
self._version.release,
self._version.pre,
self._version.post,
self._version.dev,
self._version.local,
)
def __repr__(self):
return "<Version({0})>".format(repr(str(self)))
def __str__(self):
parts = []
# Epoch
if self._version.epoch != 0:
parts.append("{0}!".format(self._version.epoch))
# Release segment
parts.append(".".join(str(x) for x in self._version.release))
# Pre-release
if self._version.pre is not None:
parts.append("".join(str(x) for x in self._version.pre))
# Post-release
if self._version.post is not None:
parts.append(".post{0}".format(self._version.post[1]))
# Development release
if self._version.dev is not None:
parts.append(".dev{0}".format(self._version.dev[1]))
# Local version segment
if self._version.local is not None:
parts.append("+{0}".format(".".join(str(x) for x in self._version.local)))
return "".join(parts)
@property
def public(self):
return str(self).split("+", 1)[0]
@property
def base_version(self):
parts = []
# Epoch
if self._version.epoch != 0:
parts.append("{0}!".format(self._version.epoch))
# Release segment
parts.append(".".join(str(x) for x in self._version.release))
return "".join(parts)
@property
def local(self):
version_string = str(self)
if "+" in version_string:
return version_string.split("+", 1)[1]
@property
def is_prerelease(self):
return bool(self._version.dev or self._version.pre)
@property
def is_postrelease(self):
return bool(self._version.post)
def _parse_letter_version(letter, number):
if letter:
# We consider there to be an implicit 0 in a pre-release if there is
# not a numeral associated with it.
if number is None:
number = 0
# We normalize any letters to their lower case form
letter = letter.lower()
# We consider some words to be alternate spellings of other words and
# in those cases we want to normalize the spellings to our preferred
# spelling.
if letter == "alpha":
letter = "a"
elif letter == "beta":
letter = "b"
elif letter in ["c", "pre", "preview"]:
letter = "rc"
elif letter in ["rev", "r"]:
letter = "post"
return letter, int(number)
if not letter and number:
# We assume if we are given a number, but we are not given a letter
# then this is using the implicit post release syntax (e.g. 1.0-1)
letter = "post"
return letter, int(number)
_local_version_seperators = re.compile(r"[._-]")
def _parse_local_version(local):
"""
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
"""
if local is not None:
return tuple(
part.lower() if not part.isdigit() else int(part)
for part in _local_version_seperators.split(local)
)
def _cmpkey(epoch, release, pre, post, dev, local):
# When we compare a release version, we want to compare it with all of the
# trailing zeros removed. So we'll use a reverse the list, drop all the now
# leading zeros until we come to something non zero, then take the rest
# re-reverse it back into the correct order and make it a tuple and use
# that for our sorting key.
release = tuple(reversed(list(dropwhile(lambda x: x == 0, reversed(release)))))
# We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
# We'll do this by abusing the pre segment, but we _only_ want to do this
# if there is not a pre or a post segment. If we have one of those then
# the normal sorting rules will handle this case correctly.
if pre is None and post is None and dev is not None:
pre = -Infinity
# Versions without a pre-release (except as noted above) should sort after
# those with one.
elif pre is None:
pre = Infinity
# Versions without a post segment should sort before those with one.
if post is None:
post = -Infinity
# Versions without a development segment should sort after those with one.
if dev is None:
dev = Infinity
if local is None:
# Versions without a local segment should sort before those with one.
local = -Infinity
else:
# Versions with a local segment need that segment parsed to implement
# the sorting rules in PEP440.
# - Alpha numeric segments sort before numeric segments
# - Alpha numeric segments sort lexicographically
# - Numeric segments sort numerically
# - Shorter versions sort before longer versions when the prefixes
# match exactly
local = tuple((i, "") if isinstance(i, int) else (-Infinity, i) for i in local)
return epoch, release, pre, post, dev, local
|
define(['datetime'], function (datetime) {
function getDisplayName(item, displayAsSpecial, includeParentInfo) {
if (!item) {
throw new Error("null item passed into getPosterViewDisplayName");
}
var name = item.EpisodeTitle || item.Name || '';
if (item.Type == "TvChannel") {
if (item.Number) {
return item.Number + ' ' + name;
}
return name;
}
if (displayAsSpecial && item.Type == "Episode" && item.ParentIndexNumber == 0) {
name = Globalize.translate('ValueSpecialEpisodeName', name);
} else if (item.Type == "Episode" && item.IndexNumber != null && item.ParentIndexNumber != null) {
var displayIndexNumber = item.IndexNumber;
var number = "E" + displayIndexNumber;
if (includeParentInfo !== false) {
number = "S" + item.ParentIndexNumber + ", " + number;
}
if (item.IndexNumberEnd) {
displayIndexNumber = item.IndexNumberEnd;
number += "-" + displayIndexNumber;
}
name = number + " - " + name;
}
return name;
}
function setShapeHome(items, options) {
var primaryImageAspectRatio = Emby.ImageLoader.getPrimaryImageAspectRatio(items) || 0;
if (primaryImageAspectRatio && primaryImageAspectRatio < .85) {
options.shape = 'portraitCard';
options.rows = 2;
options.width = DefaultTheme.CardBuilder.homePortraitWidth;
}
else if (primaryImageAspectRatio && primaryImageAspectRatio > 1.34) {
options.shape = 'backdropCard';
options.rows = 3;
options.width = DefaultTheme.CardBuilder.homeThumbWidth;
}
else {
options.shape = 'squareCard';
options.rows = 3;
options.width = DefaultTheme.CardBuilder.homeSquareWidth;
}
}
function setShape(items, options) {
var primaryImageAspectRatio = Emby.ImageLoader.getPrimaryImageAspectRatio(items) || 0;
if (primaryImageAspectRatio && primaryImageAspectRatio < .85) {
options.shape = 'portraitCard';
options.width = 280;
}
else if (primaryImageAspectRatio && primaryImageAspectRatio > 1.34) {
options.shape = 'backdropCard';
options.width = 384;
}
else {
options.shape = 'squareCard';
options.width = 280;
}
}
function buildCardsHtml(items, options) {
return new Promise(function (resolve, reject) {
require(['connectionManager'], function (connectionManager) {
var apiClient = connectionManager.currentApiClient();
var html = buildCardsHtmlInternal(items, apiClient, options);
resolve(html);
});
});
}
function buildCardsHtmlInternal(items, apiClient, options) {
if (options.shape == 'autoHome') {
setShapeHome(items, options);
}
else if (options.shape == 'autoVertical') {
setShape(items, options);
}
else if (options.shape == 'auto') {
setShapeHome(items, options);
}
if (options.indexBy == 'Genres') {
return buildCardsByGenreHtmlInternal(items, apiClient, options);
}
var className = 'card';
if (options.shape) {
className += ' ' + options.shape;
}
var html = '';
var itemsInRow = 0;
var currentIndexValue;
var hasOpenRow;
var hasOpenSection;
for (var i = 0, length = items.length; i < length; i++) {
var item = items[i];
if (options.indexBy) {
var newIndexValue = '';
if (options.indexBy == 'PremiereDate') {
if (item.PremiereDate) {
try {
newIndexValue = getDisplayDateText(datetime.parseISO8601Date(item.PremiereDate));
} catch (err) {
}
}
}
else if (options.indexBy == 'Genres') {
newIndexValue = item.Name;
}
else if (options.indexBy == 'ProductionYear') {
newIndexValue = item.ProductionYear;
}
else if (options.indexBy == 'CommunityRating') {
newIndexValue = item.CommunityRating ? (Math.floor(item.CommunityRating) + (item.CommunityRating % 1 >= .5 ? .5 : 0)) + '+' : null;
}
if (newIndexValue != currentIndexValue) {
if (hasOpenRow) {
html += '</div>';
hasOpenRow = false;
itemsInRow = 0;
}
if (hasOpenSection) {
//html += '<paper-button>...</paper-button>';
html += '</div>';
hasOpenSection = false;
}
html += '<div class="horizontalSection">';
html += '<div class="sectionTitle">' + newIndexValue + '</div>';
currentIndexValue = newIndexValue;
hasOpenSection = true;
}
}
if (options.rows && itemsInRow == 0) {
if (hasOpenRow) {
html += '</div>';
hasOpenRow = false;
}
html += '<div class="cardColumn">';
hasOpenRow = true;
}
var cardClass = className;
html += buildCard(i, item, apiClient, options, cardClass);
itemsInRow++;
if (options.rows && itemsInRow >= options.rows) {
html += '</div>';
hasOpenRow = false;
itemsInRow = 0;
}
}
if (hasOpenRow) {
html += '</div>';
}
if (hasOpenSection) {
html += '</div>';
}
return html;
}
function buildCardsByGenreHtmlInternal(items, apiClient, options) {
var className = 'card';
if (options.shape) {
className += ' ' + options.shape;
}
var html = '';
var loopItems = options.genres;
for (var i = 0, length = loopItems.length; i < length; i++) {
var item = loopItems[i];
var genreLower = item.Name.toLowerCase();
var renderItems = items.filter(function (currentItem) {
return currentItem.Genres.filter(function (g) {
return g.toLowerCase() == genreLower;
}).length > 0;
});
if (!renderItems.length) {
continue;
}
html += '<div class="horizontalSection focuscontainer-down">';
html += '<div class="sectionTitle">' + item.Name + '</div>';
var showMoreButton = false;
if (renderItems.length > options.indexLimit) {
renderItems.length = Math.min(renderItems.length, options.indexLimit);
showMoreButton = true;
}
var itemsInRow = 0;
var hasOpenRow = false;
var hasOpenSection = false;
html += renderItems.map(function (renderItem) {
var currentItemHtml = '';
if (options.rows && itemsInRow == 0) {
if (hasOpenRow) {
currentItemHtml += '</div>';
hasOpenRow = false;
}
currentItemHtml += '<div class="cardColumn">';
hasOpenRow = true;
}
var cardClass = className;
currentItemHtml += buildCard(i, renderItem, apiClient, options, cardClass);
itemsInRow++;
if (options.rows && itemsInRow >= options.rows) {
currentItemHtml += '</div>';
hasOpenRow = false;
itemsInRow = 0;
}
return currentItemHtml;
}).join('');
if (showMoreButton) {
html += '<div class="listItemsMoreButtonContainer">';
html += '<paper-button class="listItemsMoreButton" data-parentid="' + options.parentId + '" data-indextype="Genres" data-indexvalue="' + item.Id + '" raised>MORE</paper-button>';
html += '</div>';
}
html += '</div>';
html += '</div>';
}
return html;
}
function getDisplayDateText(date) {
var weekday = [];
weekday[0] = Globalize.translate('OptionSunday');
weekday[1] = Globalize.translate('OptionMonday');
weekday[2] = Globalize.translate('OptionTuesday');
weekday[3] = Globalize.translate('OptionWednesday');
weekday[4] = Globalize.translate('OptionThursday');
weekday[5] = Globalize.translate('OptionFriday');
weekday[6] = Globalize.translate('OptionSaturday');
var day = weekday[date.getDay()];
date = date.toLocaleDateString();
if (date.toLowerCase().indexOf(day.toLowerCase()) == -1) {
return day + " " + date;
}
return date;
}
function getCardImageUrl(item, apiClient, options) {
var width = options.width;
var height = null;
var primaryImageAspectRatio = Emby.ImageLoader.getPrimaryImageAspectRatio([item]);
var forceName = false;
var imgUrl = null;
var coverImage = false;
if (options.preferThumb && item.ImageTags && item.ImageTags.Thumb) {
imgUrl = apiClient.getScaledImageUrl(item.Id, {
type: "Thumb",
maxWidth: width,
tag: item.ImageTags.Thumb
});
} else if (options.preferBanner && item.ImageTags && item.ImageTags.Banner) {
imgUrl = apiClient.getScaledImageUrl(item.Id, {
type: "Banner",
maxWidth: width,
tag: item.ImageTags.Banner
});
} else if (options.preferThumb && item.SeriesThumbImageTag && options.inheritThumb !== false) {
imgUrl = apiClient.getScaledImageUrl(item.SeriesId, {
type: "Thumb",
maxWidth: width,
tag: item.SeriesThumbImageTag
});
} else if (options.preferThumb && item.ParentThumbItemId && options.inheritThumb !== false) {
imgUrl = apiClient.getThumbImageUrl(item.ParentThumbItemId, {
type: "Thumb",
maxWidth: width,
tag: item.ParentThumbImageTag
});
} else if (options.preferThumb && item.BackdropImageTags && item.BackdropImageTags.length) {
imgUrl = apiClient.getScaledImageUrl(item.Id, {
type: "Backdrop",
maxWidth: width,
tag: item.BackdropImageTags[0]
});
forceName = true;
} else if (item.ImageTags && item.ImageTags.Primary) {
height = width && primaryImageAspectRatio ? Math.round(width / primaryImageAspectRatio) : null;
imgUrl = apiClient.getImageUrl(item.Id, {
type: "Primary",
maxHeight: height,
maxWidth: width,
tag: item.ImageTags.Primary
});
if (options.preferThumb && options.showTitle !== false) {
forceName = true;
}
coverImage = height != null;
} else if (item.PrimaryImageTag) {
height = width && primaryImageAspectRatio ? Math.round(width / primaryImageAspectRatio) : null;
imgUrl = apiClient.getImageUrl(item.Id || item.ItemId, {
type: "Primary",
maxHeight: height,
maxWidth: width,
tag: item.PrimaryImageTag
});
if (options.preferThumb && options.showTitle !== false) {
forceName = true;
}
coverImage = width != null;
}
else if (item.ParentPrimaryImageTag) {
imgUrl = apiClient.getImageUrl(item.ParentPrimaryImageItemId, {
type: "Primary",
maxWidth: width,
tag: item.ParentPrimaryImageTag
});
}
else if (item.AlbumId && item.AlbumPrimaryImageTag) {
width = primaryImageAspectRatio ? Math.round(height * primaryImageAspectRatio) : null;
imgUrl = apiClient.getScaledImageUrl(item.AlbumId, {
type: "Primary",
maxHeight: height,
maxWidth: width,
tag: item.AlbumPrimaryImageTag
});
coverImage = width != null;
}
else if (item.Type == 'Season' && item.ImageTags && item.ImageTags.Thumb) {
imgUrl = apiClient.getScaledImageUrl(item.Id, {
type: "Thumb",
maxWidth: width,
tag: item.ImageTags.Thumb
});
}
else if (item.BackdropImageTags && item.BackdropImageTags.length) {
imgUrl = apiClient.getScaledImageUrl(item.Id, {
type: "Backdrop",
maxWidth: width,
tag: item.BackdropImageTags[0]
});
} else if (item.ImageTags && item.ImageTags.Thumb) {
imgUrl = apiClient.getScaledImageUrl(item.Id, {
type: "Thumb",
maxWidth: width,
tag: item.ImageTags.Thumb
});
} else if (item.SeriesThumbImageTag) {
imgUrl = apiClient.getScaledImageUrl(item.SeriesId, {
type: "Thumb",
maxWidth: width,
tag: item.SeriesThumbImageTag
});
} else if (item.ParentThumbItemId) {
imgUrl = apiClient.getThumbImageUrl(item.ParentThumbItemId, {
type: "Thumb",
maxWidth: width,
tag: item.ParentThumbImageTag
});
}
return {
imgUrl: imgUrl,
forceName: forceName,
coverImage: coverImage
};
}
function enableProgressIndicator(item) {
if (item.MediaType == 'Video') {
if (item.Type != 'TvChannel') {
return true;
}
}
return false;
}
function getProgressBarHtml(item) {
if (enableProgressIndicator(item)) {
if (item.Type == "Recording" && item.CompletionPercentage) {
return '<paper-progress value="' + item.CompletionPercentage + '" class="block transparent"></paper-progress>';
}
var userData = item.UserData;
if (userData) {
var pct = userData.PlayedPercentage;
if (pct && pct < 100) {
return '<paper-progress value="' + pct + '" class="block transparent"></paper-progress>';
}
}
}
return '';
}
function getCountIndicator(count) {
return '<div class="cardCountIndicator">' + count + '</div>';
}
function getPlayedIndicator(item) {
if (item.Type == "Series" || item.Type == "Season" || item.Type == "BoxSet" || item.MediaType == "Video" || item.MediaType == "Game" || item.MediaType == "Book") {
var userData = item.UserData || {};
if (userData.UnplayedItemCount) {
return '<div class="cardCountIndicator">' + userData.UnplayedItemCount + '</div>';
}
if (item.Type != 'TvChannel') {
if (userData.PlayedPercentage && userData.PlayedPercentage >= 100 || (userData.Played)) {
return '<div class="playedIndicator"><iron-icon icon="check"></iron-icon></div>';
}
}
}
return '';
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function buildCard(index, item, apiClient, options, className) {
className += " itemAction";
if (options.scalable) {
className += " scalableCard";
}
var imgInfo = getCardImageUrl(item, apiClient, options);
var imgUrl = imgInfo.imgUrl;
var cardImageContainerClass = 'cardImageContainer';
if (options.coverImage || imgInfo.coverImage) {
cardImageContainerClass += ' coveredImage';
}
if (!imgUrl) {
cardImageContainerClass += ' emptyCardImageContainer defaultCardColor' + getRandomInt(1, 5);
}
var separateCardBox = options.scalable;
if (!separateCardBox) {
cardImageContainerClass += " cardBox";
}
// cardBox can be it's own separate element if an outer footer is ever needed
var cardImageContainerOpen = imgUrl ? ('<div class="' + cardImageContainerClass + ' lazy" data-src="' + imgUrl + '">') : ('<div class="' + cardImageContainerClass + '">');
var cardImageContainerClose = '</div>';
if (separateCardBox) {
cardImageContainerOpen = '<div class="cardBox"><div class="cardScalable"><div class="cardPadder"></div><div class="cardContent">' + cardImageContainerOpen;
cardImageContainerClose += '</div></div></div>';
}
if (options.showGroupCount) {
if (item.ChildCount && item.ChildCount > 1) {
cardImageContainerOpen += getCountIndicator(item.ChildCount);
}
}
else {
cardImageContainerOpen += getPlayedIndicator(item);
}
var showTitle = options.showTitle || imgInfo.forceName;
if (!imgUrl) {
cardImageContainerOpen += '<div class="cardText cardCenteredText">' + getDisplayName(item) + '</div>';
}
var nameHtml = '';
if (options.showParentTitle) {
nameHtml += '<div class="cardText">' + (item.EpisodeTitle ? item.Name : (item.SeriesName || item.Album || item.AlbumArtist || item.GameSystem || "")) + '</div>';
}
if (showTitle) {
var nameClass = 'cardText';
nameHtml += '<div class="' + nameClass + '">' + getDisplayName(item) + '</div>';
}
var innerCardFooterClass = 'innerCardFooter';
var progressHtml = getProgressBarHtml(item);
if (progressHtml) {
nameHtml += progressHtml;
innerCardFooterClass += " fullInnerCardFooter";
}
var innerCardFooter = '';
if (nameHtml && imgUrl) {
innerCardFooter += '<div class="' + innerCardFooterClass + '">';
innerCardFooter += nameHtml;
innerCardFooter += '</div>';
}
var data = '';
if (options.addImageData) {
var primaryImageTag = (item.ImageTags || {}).Primary || item.PrimaryImageTag || '';
data += '<input type="hidden" class="primaryImageTag" value="' + primaryImageTag + '" />';
}
var action = options.action || 'link';
var tagName = 'button';
var prefix = (item.SortName || item.Name || '')[0];
if (prefix) {
prefix = prefix.toUpperCase();
}
return '\
<' + tagName + ' data-index="' + index + '" data-action="' + action + '" data-isfolder="' + (item.IsFolder || false) + '" data-id="' + (item.Id || item.ItemId) + '" data-type="' + item.Type + '" data-prefix="' + prefix + '" raised class="' + className + '"> \
' + cardImageContainerOpen + innerCardFooter + data + cardImageContainerClose + '\
</' + tagName + '>';
}
function buildCards(items, options) {
// Abort if the container has been disposed
if (!Emby.Dom.isInDocument(options.itemsContainer)) {
return;
}
if (options.parentContainer) {
if (items.length) {
options.parentContainer.classList.remove('hide');
} else {
options.parentContainer.classList.add('hide');
return;
}
}
require(['connectionManager'], function (connectionManager) {
var apiClient = connectionManager.currentApiClient();
var html = buildCardsHtmlInternal(items, apiClient, options);
options.itemsContainer.innerHTML = html;
Emby.ImageLoader.lazyChildren(options.itemsContainer);
if (options.autoFocus) {
Emby.FocusManager.autoFocus(options.itemsContainer, true);
}
if (options.indexBy == 'Genres') {
options.itemsContainer.addEventListener('click', onItemsContainerClick);
}
});
}
function onItemsContainerClick(e) {
var listItemsMoreButton = Emby.Dom.parentWithClass(e.target, 'listItemsMoreButton');
if (listItemsMoreButton) {
var value = listItemsMoreButton.getAttribute('data-indexvalue');
var parentid = listItemsMoreButton.getAttribute('data-parentid');
Emby.Page.show(Emby.PluginManager.mapPath('defaulttheme', 'list/list.html') + '?parentid=' + parentid + '&genreId=' + value);
}
}
function getMediaInfoHtml(item, options) {
var html = '';
var miscInfo = [];
options = options || {};
var text, date, minutes;
if (item.Type == "MusicAlbum" || item.MediaType == 'MusicArtist' || item.MediaType == 'Playlist' || item.MediaType == 'MusicGenre') {
var count = item.SongCount || item.ChildCount;
if (count) {
miscInfo.push(Globalize.translate('TrackCount', count));
}
if (item.CumulativeRunTimeTicks) {
miscInfo.push(getDisplayRuntime(item.CumulativeRunTimeTicks));
}
}
if (item.Type == "Episode" || item.MediaType == 'Photo') {
if (item.PremiereDate) {
try {
date = datetime.parseISO8601Date(item.PremiereDate);
text = date.toLocaleDateString();
miscInfo.push(text);
}
catch (e) {
console.log("Error parsing date: " + item.PremiereDate);
}
}
}
if (item.StartDate) {
try {
date = datetime.parseISO8601Date(item.StartDate);
text = date.toLocaleDateString();
miscInfo.push(text);
if (item.Type != "Recording") {
text = getDisplayTime(date);
miscInfo.push(text);
}
}
catch (e) {
console.log("Error parsing date: " + item.PremiereDate);
}
}
if (item.ProductionYear && item.Type == "Series") {
if (item.Status == "Continuing") {
miscInfo.push(Globalize.translate('ValueSeriesYearToPresent', item.ProductionYear));
}
else if (item.ProductionYear) {
text = item.ProductionYear;
if (item.EndDate) {
try {
var endYear = datetime.parseISO8601Date(item.EndDate).getFullYear();
if (endYear != item.ProductionYear) {
text += "-" + datetime.parseISO8601Date(item.EndDate).getFullYear();
}
}
catch (e) {
console.log("Error parsing date: " + item.EndDate);
}
}
miscInfo.push(text);
}
}
if (item.Type != "Series" && item.Type != "Episode" && item.Type != "Person" && item.MediaType != 'Photo') {
if (item.ProductionYear) {
miscInfo.push(item.ProductionYear);
}
else if (item.PremiereDate) {
try {
text = datetime.parseISO8601Date(item.PremiereDate).getFullYear();
miscInfo.push(text);
}
catch (e) {
console.log("Error parsing date: " + item.PremiereDate);
}
}
}
if (item.RunTimeTicks && item.Type != "Series" && options.runtime !== false) {
if (item.Type == "Audio") {
miscInfo.push(getDisplayRuntime(item.RunTimeTicks));
} else {
minutes = item.RunTimeTicks / 600000000;
minutes = minutes || 1;
miscInfo.push(Math.round(minutes) + " mins");
}
}
if (item.OfficialRating && item.Type !== "Season" && item.Type !== "Episode") {
miscInfo.push({
text: item.OfficialRating,
cssClass: 'mediaInfoOfficialRating'
});
}
if (item.HasSubtitles && options.subtitles !== false) {
miscInfo.push({
html: '<iron-icon class="mediaInfoItem closedCaptionIcon" icon="closed-caption"></iron-icon>'
});
}
if (item.Video3DFormat) {
miscInfo.push("3D");
}
if (item.MediaType == 'Photo' && item.Width && item.Height) {
miscInfo.push(item.Width + "x" + item.Height);
}
html += miscInfo.map(function (m) {
var cssClass = "mediaInfoItem";
var mediaInfoText = m;
if (typeof (m) !== 'string' && typeof (m) !== 'number') {
if (m.html) {
return m.html;
}
mediaInfoText = m.text;
cssClass += ' ' + m.cssClass;
}
return '<div class="' + cssClass + '">' + mediaInfoText + '</div>';
}).join('');
html += getStarIconsHtml(item);
if (item.CriticRating && options.criticRating !== false) {
if (item.CriticRating >= 60) {
html += '<div class="mediaInfoItem criticRating criticRatingFresh">' + item.CriticRating + '</div>';
} else {
html += '<div class="mediaInfoItem criticRating criticRatingRotten">' + item.CriticRating + '</div>';
}
}
return html;
}
function getDisplayRuntime(ticks) {
var ticksPerHour = 36000000000;
var ticksPerMinute = 600000000;
var ticksPerSecond = 10000000;
var parts = [];
var hours = ticks / ticksPerHour;
hours = Math.floor(hours);
if (hours) {
parts.push(hours);
}
ticks -= (hours * ticksPerHour);
var minutes = ticks / ticksPerMinute;
minutes = Math.floor(minutes);
ticks -= (minutes * ticksPerMinute);
if (minutes < 10 && hours) {
minutes = '0' + minutes;
}
parts.push(minutes);
var seconds = ticks / ticksPerSecond;
seconds = Math.floor(seconds);
if (seconds < 10) {
seconds = '0' + seconds;
}
parts.push(seconds);
return parts.join(':');
}
function getStarIconsHtml(item) {
var html = '';
var rating = item.CommunityRating;
if (rating) {
html += '<div class="starRatingContainer mediaInfoItem">';
for (var i = 0; i < 5; i++) {
var starValue = (i + 1) * 2;
if (rating < starValue - 2) {
html += '<iron-icon icon="star" class="emptyStar"></iron-icon>';
}
else if (rating < starValue) {
html += '<iron-icon icon="star-half"></iron-icon>';
}
else {
html += '<iron-icon icon="star"></iron-icon>';
}
}
html += '</div>';
}
return html;
}
function getListViewHtml(items, options) {
var outerHtml = "";
var index = 0;
var groupTitle = '';
var action = options.action || 'link';
var isLargeStyle = options.imageSize == 'large';
outerHtml += items.map(function (item) {
var html = '';
var cssClass = "itemAction";
var downloadWidth = 80;
if (isLargeStyle) {
cssClass += " largeImage";
downloadWidth = 500;
}
html += '<paper-icon-item class="' + cssClass + '" data-index="' + index + '" data-action="' + action + '" data-isfolder="' + item.IsFolder + '" data-id="' + item.Id + '" data-type="' + item.Type + '">';
var imgUrl = Emby.Models.imageUrl(item, {
width: downloadWidth,
type: "Primary"
});
if (!imgUrl) {
imgUrl = Emby.Models.thumbImageUrl(item, {
width: downloadWidth,
type: "Thumb"
});
}
if (imgUrl) {
html += '<div class="paperIconItemImage lazy" data-src="' + imgUrl + '" item-icon>';
} else {
html += '<div class="paperIconItemImage" item-icon>';
}
html += getPlayedIndicator(item);
var progressHtml = getProgressBarHtml(item);
if (progressHtml) {
html += progressHtml;
}
html += '</div>';
var textlines = [];
if (options.showParentTitle) {
if (item.Type == 'Episode') {
textlines.push(item.SeriesName || ' ');
} else if (item.Type == 'MusicAlbum') {
textlines.push(item.AlbumArtist || ' ');
}
}
var displayName = getDisplayName(item);
if (options.showIndexNumber && item.IndexNumber != null) {
displayName = item.IndexNumber + ". " + displayName;
}
textlines.push(displayName);
if (item.Type == 'Audio') {
textlines.push(item.ArtistItems.map(function (a) {
return a.Name;
}).join(', ') || ' ');
}
var lineCount = textlines.length;
if (!options.enableSideMediaInfo) {
lineCount++;
}
if (options.enableOverview && item.Overview) {
lineCount++;
}
if (lineCount > 2) {
html += '<paper-item-body three-line>';
} else if (lineCount > 1) {
html += '<paper-item-body two-line>';
} else {
html += '<paper-item-body>';
}
for (var i = 0, textLinesLength = textlines.length; i < textLinesLength; i++) {
if (i == 0 && isLargeStyle) {
html += '<h2 class="listItemTitle">';
}
else if (i == 0) {
html += '<div>';
} else {
html += '<div secondary>';
}
html += textlines[i] || ' ';
if (i == 0 && isLargeStyle) {
html += '</h2>';
} else {
html += '</div>';
}
}
if (!options.enableSideMediaInfo) {
html += '<div class="paperIconItemMediaInfo">' + getMediaInfoHtml(item) + '</div>';
}
if (options.enableOverview && item.Overview) {
html += '<div secondary class="overview">';
html += item.Overview;
html += '</div>';
}
html += '</paper-item-body>';
if (options.enableSideMediaInfo) {
html += '<div class="paperIconItemMediaInfo">' + getMediaInfoHtml(item) + '</div>';
}
html += '</paper-icon-item>';
index++;
return html;
}).join('');
return outerHtml;
}
var cardBuilder = {
buildCardsHtml: buildCardsHtml,
buildCards: buildCards,
homeThumbWidth: 600,
homePortraitWidth: 500,
homeSquareWidth: 330,
getDisplayName: getDisplayName,
getMediaInfoHtml: getMediaInfoHtml,
getListViewHtml: getListViewHtml,
getProgressBarHtml: getProgressBarHtml
};
window.DefaultTheme = window.DefaultTheme || {};
window.DefaultTheme.CardBuilder = cardBuilder;
return cardBuilder;
});
|
from enum import Enum
import numpy as np
class State:
"""状態(位置)を定義するクラス
原点は左上
正の向き
-->
↓
"""
def __init__(self, row=-1, column=-1):
self.row = row
self.column = column
def __repr__(self):
return "<State: [{}, {}]>".format(self.row, self.column)
def clone(self):
"""
(現在の)状態(位置)を返す関数
Returns:
Stateクラス
"""
return State(self.row, self.column)
def __hash__(self):
return hash((self.row, self.column))
def __eq__(self, other):
return self.row == other.row and self.column == other.column
class Action(Enum):
"""行動を定義するクラス"""
UP = 1
DOWN = -1
LEFT = 2
RIGHT = -2
class Environment:
"""環境を定義するクラス"""
def __init__(self, grid, move_prob=0.8):
# grid is 2d-array. Its values are treated as an attribute.
# Kinds of attribute is following.
# 0: ordinary cell
# -1: damage cell (game end)
# 1: reward cell (game end)
# 9: block cell (can't locate agent)
self.grid = grid
self.agent_state = State()
# Default reward is minus. Just like a poison swamp.
# It means the agent has to reach the goal fast!
self.default_reward = -0.04
# Agent can move to a selected direction in move_prob.
# It means the agent will move different direction
# in (1 - move_prob).
self.move_prob = move_prob # 同一方向
self.reset()
@property
def row_length(self):
"""
行数を返す関数
Returns:
int: 行数
"""
return len(self.grid)
@property
def column_length(self):
"""
列数を返す関数
Returns:
int: 列数
"""
return len(self.grid[0])
@property
def actions(self):
"""
一連の行動を返す関数
Returns:
List: 行動のリスト
"""
return [Action.UP, Action.DOWN, Action.LEFT, Action.RIGHT]
@property
def states(self):
"""
グリッド内のすべてのセルの状態(位置)を返す関数
ただし、ブロックセルは除く
Returns:
List: 各セルの状態(位置)のリスト
"""
states = []
for row in range(self.row_length):
for column in range(self.column_length):
# Block cells are not included to the state.
if self.grid[row][column] != 9:
states.append(State(row, column))
return states
def transit_func(self, state, action):
"""遷移関数
次に移動し得る可能性の各グリッドの遷移確率を返す関数
関数transitに呼び出される
Args:
state: 現在の位置
action: 移動を選択する方向
Returns:
dict: 次に移動し得る可能性の各グリッドの遷移確率
- ゴール地点にいるとき -> {}
- ゴール地点にいないとき、{次の位置:遷移確率、...}
"""
transition_probs = {}
if not self.can_action_at(state):
# Already on the terminal cell.
return transition_probs
opposite_direction = Action(action.value * -1)
for a in self.actions:
# 選択した方向の真逆の場合
prob = 0
# 選択した方向の場合
if a == action:
prob = self.move_prob
# 選択した方向の真逆でない場合
# 進行方向に対して、右か左
elif a != opposite_direction:
prob = (1 - self.move_prob) / 2
next_state = self._move(state, a)
if next_state not in transition_probs:
transition_probs[next_state] = prob
else:
transition_probs[next_state] += prob
return transition_probs
def can_action_at(self, state):
"""
セルが0(移動可能なセル)かどうかを確認する関数
Returns:
bool: 0ならTrue, 0以外ならFalse
"""
if self.grid[state.row][state.column] == 0:
return True
else:
return False
def _move(self, state, action):
"""
現在の状態から選択した方向に移動する関数
ただし、範囲外またはブロックセルの場合は現在の位置を返す
Args:
state: 現在の位置
action: 移動を選択する方向
Returns:
Stete: 現在の位置からの移動後の位置
"""
if not self.can_action_at(state):
raise Exception("Can't move from here!")
next_state = state.clone()
# Execute an action (move).
# 正の向きに注意
if action == Action.UP:
next_state.row -= 1
elif action == Action.DOWN:
next_state.row += 1
elif action == Action.LEFT:
next_state.column -= 1
elif action == Action.RIGHT:
next_state.column += 1
# Check whether a state is out of the grid.
# 範囲外の場合は、移動前の状態のままにする
if not (0 <= next_state.row < self.row_length):
print("範囲外に移動しようとしました")
next_state = state
if not (0 <= next_state.column < self.column_length):
print("範囲外に移動しようとしました")
next_state = state
# Check whether the agent bumped a block cell.
# ブロックセルの場合は、移動前の状態のままにする
if self.grid[next_state.row][next_state.column] == 9:
print("ブロックセルに移動しようとしました")
next_state = state
return next_state
def reward_func(self, state):
"""報酬関数
Args:
state(State()): 状態(位置)
Returns:
float: 報酬。緑セル(1)なら+1を与える。赤セル(-1)なら-1を与える
bool:緑または赤セルにいる場合はTrue。それ以外の場合はFalse。
"""
# ゴール(赤or緑セル)以外のセルのときはデフォルトの報酬を与える
reward = self.default_reward
done = False
# Check an attribute of next state.
attribute = self.grid[state.row][state.column]
if attribute == 1:
# Get reward! and the game ends.
reward = 1
done = True
elif attribute == -1:
# Get damage! and the game ends.
reward = -1
done = True
return reward, done
def reset(self):
"""
初期状態(位置)を返す関数
Returns:
State: 初期状態(位置)
"""
# Locate the agent at lower left corner.
self.agent_state = State(self.row_length - 1, 0)
return self.agent_state
def step(self, action):
""" """
next_state, reward, done = self.transit(self.agent_state, action)
if next_state is not None:
self.agent_state = next_state
return next_state, reward, done
def transit(self, state, action):
"""
Args:
State: 現在の位置
action: エージェントがランダムに決定した進行方向(実際の移動方向とは異なる)
Returns:
State: 次の位置
float: 次の位置で得られる報酬
bool: 次の位置がゴールの場合にTrue、それ以外の場合にFalse
"""
transition_probs = self.transit_func(state, action)
if len(transition_probs) == 0:
return None, None, True
next_states = []
probs = []
for s in transition_probs:
next_states.append(s)
probs.append(transition_probs[s])
# 次の移動する可能性のある各セルの遷移確率に基づいて、次の移動先を選択
next_state = np.random.choice(next_states, p=probs)
reward, done = self.reward_func(next_state)
return next_state, reward, done
|
#ifndef _CAMERA5DOF
#define _CAMERA5DOF
#include "Camera.h"
// Camera with 5 degrees of freedom, 3 translational (X, Y, Z) and two rotational (yaw, pitch)
class Camera5DoF : public Camera {
float pitch = 0.0f;
public:
Camera5DoF(SDL_Window *window);
void move(float x, float y, float z) override;
void rotate(float yaw, float pitch = 0, float _ = 0) override;
const Matrix4f getViewMatrix() const override;
const Vec3f getPos() const override;
};
#endif
|