text
stringlengths
3
1.05M
/* * cam_VFW.h * PHD Guiding * * Created by Craig Stark. * Copyright (c) 2006-2010 Craig Stark. * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Craig Stark, Stark Labs 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 HOLDER 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 VFWDEF #define VFWDEF #include "vcapwin.h" #include <wx/splitter.h> class Camera_VFWClass : public GuideCamera { wxVideoCaptureWindow *VFW_Window; wxSplitterWindow *Extra_Window; public: Camera_VFWClass(); bool Capture(int duration, usImage& img, int options, const wxRect& subframe); bool Connect(); bool Disconnect(); void ShowPropertyDialog(); void InitCapture() { return; } }; #endif
const _R = require('../') describe('intersection', function() { it('should return array with intersection elements when two arrays are passed', function() { const array1 = [ 1, 2 ]; const array2 = [ 2, 4 ]; const response = _R.intersection(array1, array2); expect(response).toEqual([ 2 ]); }) it('should return array with intersection elements when three arrays are passed', function() { const array1 = [ 1, 2 ]; const array2 = [ 2, 4 ]; const array3 = [ 2, 5 ]; const response = _R.intersection(array1, array2, array3); expect(response).toEqual([ 2 ]); }) it('should return empty array when no common element is found', function() { const array1 = [ 1, 2 ]; const array2 = [ 2, 3 ]; const array3 = [ 3, 4 ]; const response = _R.intersection(array1, array2, array3); expect(response).toEqual([]); }) })
import React from 'react' import Title from './title' import Subtitle from './subtitle' import SmallTitle from './small-title' import Paragraph from './paragraph' import List from './list' import Code from './code' import {preToCodeBlock} from 'mdx-utils' export default { h1: props => <Title {...props} />, h2: props => <Subtitle {...props} />, h3: props => <SmallTitle {...props} />, p: props => <Paragraph {...props} />, ul: props => <List {...props} />, pre: preProps => { const props = preToCodeBlock(preProps) // if there's a codeString and some props, we passed the test if (props) { return <Code {...props} /> } else { // it's possible to have a pre without a code in it return <pre {...preProps} /> } }, } /* eslint react/display-name:0 */
# generate random integer values from random import seed from random import randint import sys def gen_random_array(input_size_r,seed_val): """ The function helps generate an array of randomly generated integers. :param input_size_r: The size of input array. :return: An array of integers of given input size. """ # generate some integers seed(seed_val) values = [randint(1, sys.maxsize) for _ in range(input_size_r)] #values = [randint(1, 500) for _ in range(input_size_r)] #values = [randint(1, input_size_r) for _ in range(input_size_r)] return values
!function(e,t){"use strict";var n=1,i=3,o=9,r=11,a=1,s="​",d=e.defaultView,l=navigator.userAgent,c=/Android/.test(l),h=/iP(?:ad|hone|od)/.test(l),f=/Mac OS X/.test(l),u=/Windows NT/.test(l),p=/Gecko\//.test(l),g=/Trident\/[456]\./.test(l),m=!!d.opera,v=/Edge\//.test(l),_=!v&&/WebKit\//.test(l),C=/Trident\/[4567]\./.test(l),N=f?"meta-":"ctrl-",S=g||m,y=g||_,T=g,E="undefined"!=typeof MutationObserver,b="undefined"!=typeof WeakMap,k=/[^ \t\r\n]/,x=Array.prototype.indexOf;Object.create||(Object.create=function(e){var t=function(){};return t.prototype=e,new t});var L={1:1,2:2,3:4,8:128,9:256,11:1024},B=function(){return!0};function A(e,t,n){this.root=this.currentNode=e,this.nodeType=t,this.filter=n||B}A.prototype.nextNode=function(){for(var e,t=this.currentNode,n=this.root,i=this.nodeType,o=this.filter;;){for(e=t.firstChild;!e&&t&&t!==n;)(e=t.nextSibling)||(t=t.parentNode);if(!e)return null;if(L[e.nodeType]&i&&o(e))return this.currentNode=e,e;t=e}},A.prototype.previousNode=function(){for(var e,t=this.currentNode,n=this.root,i=this.nodeType,o=this.filter;;){if(t===n)return null;if(e=t.previousSibling)for(;t=e.lastChild;)e=t;else e=t.parentNode;if(!e)return null;if(L[e.nodeType]&i&&o(e))return this.currentNode=e,e;t=e}},A.prototype.previousPONode=function(){for(var e,t=this.currentNode,n=this.root,i=this.nodeType,o=this.filter;;){for(e=t.lastChild;!e&&t&&t!==n;)(e=t.previousSibling)||(t=t.parentNode);if(!e)return null;if(L[e.nodeType]&i&&o(e))return this.currentNode=e,e;t=e}};var O=/^(?:#text|A(?:BBR|CRONYM)?|B(?:R|D[IO])?|C(?:ITE|ODE)|D(?:ATA|EL|FN)|EM|FONT|HR|I(?:FRAME|MG|NPUT|NS)?|KBD|Q|R(?:P|T|UBY)|S(?:AMP|MALL|PAN|TR(?:IKE|ONG)|U[BP])?|TIME|U|VAR|WBR)$/,R={BR:1,HR:1,IFRAME:1,IMG:1,INPUT:1};var D=0,P=1,U=2,I=3,w=b?new WeakMap:null;function F(e){return e.nodeType===n&&!!R[e.nodeName]}function M(e){switch(e.nodeType){case i:return P;case n:case r:if(b&&w.has(e))return w.get(e);break;default:return D}var t;return t=function(e,t){for(var n=e.length;n--;)if(!t(e[n]))return!1;return!0}(e.childNodes,H)?O.test(e.nodeName)?P:U:I,b&&w.set(e,t),t}function H(e){return M(e)===P}function W(e){return M(e)===U}function z(e){return M(e)===I}function q(e,t){var n=new A(t,a,W);return n.currentNode=e,n}function K(e,t){return(e=q(e,t).previousNode())!==t?e:null}function G(e,t){return(e=q(e,t).nextNode())!==t?e:null}function Z(e){return!e.textContent&&!e.querySelector("IMG")}function j(e,t){return!F(e)&&e.nodeType===t.nodeType&&e.nodeName===t.nodeName&&"A"!==e.nodeName&&e.className===t.className&&(!e.style&&!t.style||e.style.cssText===t.style.cssText)}function $(e,t,n){if(e.nodeName!==t)return!1;for(var i in n)if(e.getAttribute(i)!==n[i])return!1;return!0}function Q(e,t,n,i){for(;e&&e!==t;){if($(e,n,i))return e;e=e.parentNode}return null}function V(e,t){for(;t;){if(t===e)return!0;t=t.parentNode}return!1}function Y(e){var t=e.nodeType;return t===n||t===r?e.childNodes.length:e.length||0}function X(e){var t=e.parentNode;return t&&t.removeChild(e),e}function J(e,t){var n=e.parentNode;n&&n.replaceChild(t,e)}function ee(e){for(var t=e.ownerDocument.createDocumentFragment(),n=e.childNodes,i=n?n.length:0;i--;)t.appendChild(e.firstChild);return t}function te(e,n,i,o){var r,a,s,d,l=e.createElement(n);if(i instanceof Array&&(o=i,i=null),i)for(r in i)(a=i[r])!==t&&l.setAttribute(r,a);if(o)for(s=0,d=o.length;s<d;s+=1)l.appendChild(o[s]);return l}function ne(e,t){var n,o,r=t.__squire__,a=e.ownerDocument,d=e;if(e===t&&((o=e.firstChild)&&"BR"!==o.nodeName||(n=r.createDefaultBlock(),o?e.replaceChild(n,o):e.appendChild(n),e=n,n=null)),e.nodeType===i)return d;if(H(e)){for(o=e.firstChild;y&&o&&o.nodeType===i&&!o.data;)e.removeChild(o),o=e.firstChild;o||(y?(n=a.createTextNode(s),r._didAddZWS()):n=a.createTextNode(""))}else if(S){for(;e.nodeType!==i&&!F(e);){if(!(o=e.firstChild)){n=a.createTextNode("");break}e=o}e.nodeType===i?/^ +$/.test(e.data)&&(e.data=""):F(e)&&e.parentNode.insertBefore(a.createTextNode(""),e)}else if(!e.querySelector("BR"))for(n=te(a,"BR");(o=e.lastElementChild)&&!H(o);)e=o;if(n)try{e.appendChild(n)}catch(t){r.didError({name:"Squire: fixCursor – "+t,message:"Parent: "+e.nodeName+"/"+e.innerHTML+" appendChild: "+n.nodeName})}return d}function ie(e,t){var n,i,o,r,a=e.childNodes,s=e.ownerDocument,d=null;t.__squire__._config;for(n=0,i=a.length;n<i;n+=1)!(r="BR"===(o=a[n]).nodeName)&&H(o)?(d||(d=te(s,"div")),d.appendChild(o),n-=1,i-=1):(r||d)&&(d||(d=te(s,"div")),ne(d,t),r?e.replaceChild(d,o):(e.insertBefore(d,o),n+=1,i+=1),d=null),z(o)&&ie(o,t);return d&&e.appendChild(ne(d,t)),e}function oe(e,t,o,r){var a,s,d,l=e.nodeType;if(l===i&&e!==o)return oe(e.parentNode,e.splitText(t),o,r);if(l===n){if("number"==typeof t&&(t=t<e.childNodes.length?e.childNodes[t]:null),e===o)return t;for(a=e.parentNode,s=e.cloneNode(!1);t;)d=t.nextSibling,s.appendChild(t),t=d;return"OL"===e.nodeName&&Q(e,r,"BLOCKQUOTE")&&(s.start=(+e.start||1)+e.childNodes.length-1),ne(e,r),ne(s,r),(d=e.nextSibling)?a.insertBefore(s,d):a.appendChild(s),oe(a,s,o,r)}return t}function re(e,t){if(e.nodeType===i&&(e=e.parentNode),e.nodeType===n){var o={startContainer:t.startContainer,startOffset:t.startOffset,endContainer:t.endContainer,endOffset:t.endOffset};!function e(t,o){for(var r,a,s,d=t.childNodes,l=d.length,c=[];l--;)if(r=d[l],a=l&&d[l-1],l&&H(r)&&j(r,a)&&!R[r.nodeName])o.startContainer===r&&(o.startContainer=a,o.startOffset+=Y(a)),o.endContainer===r&&(o.endContainer=a,o.endOffset+=Y(a)),o.startContainer===t&&(o.startOffset>l?o.startOffset-=1:o.startOffset===l&&(o.startContainer=a,o.startOffset=Y(a))),o.endContainer===t&&(o.endOffset>l?o.endOffset-=1:o.endOffset===l&&(o.endContainer=a,o.endOffset=Y(a))),X(r),r.nodeType===i?a.appendData(r.data):c.push(ee(r));else if(r.nodeType===n){for(s=c.length;s--;)r.appendChild(c.pop());e(r,o)}}(e,o),t.setStart(o.startContainer,o.startOffset),t.setEnd(o.endContainer,o.endOffset)}}function ae(e,t,i,o){for(var r,a,s,d=t;(r=d.parentNode)&&r!==o&&r.nodeType===n&&1===r.childNodes.length;)d=r;X(d),s=e.childNodes.length,(a=e.lastChild)&&"BR"===a.nodeName&&(e.removeChild(a),s-=1),e.appendChild(ee(t)),i.setStart(e,s),i.collapse(!0),re(e,i),m&&(a=e.lastChild)&&"BR"===a.nodeName&&e.removeChild(a)}function se(e,t){var n,i,o=e.previousSibling,r=e.firstChild,a=e.ownerDocument,s="LI"===e.nodeName;if(!s||r&&/^[OU]L$/.test(r.nodeName))if(o&&j(o,e)){if(!z(o)){if(!s)return;(i=te(a,"DIV")).appendChild(ee(o)),o.appendChild(i)}X(e),n=!z(e),o.appendChild(ee(e)),n&&ie(o,t),r&&se(r,t)}else s&&(o=te(a,"DIV"),e.insertBefore(o,r),ne(o,t))}var de=function(e,t){for(var i=e.childNodes;t&&e.nodeType===n;)t=(i=(e=i[t-1]).childNodes).length;return e},le=function(e,t){if(e.nodeType===n){var i=e.childNodes;if(t<i.length)e=i[t];else{for(;e&&!e.nextSibling;)e=e.parentNode;e&&(e=e.nextSibling)}}return e},ce=function(e,t){var n,o,r,a,s=e.startContainer,d=e.startOffset,l=e.endContainer,c=e.endOffset;s.nodeType===i?(o=(n=s.parentNode).childNodes,d===s.length?(d=x.call(o,s)+1,e.collapsed&&(l=n,c=d)):(d&&(a=s.splitText(d),l===s?(c-=d,l=a):l===n&&(c+=1),s=a),d=x.call(o,s)),s=n):o=s.childNodes,d===(r=o.length)?s.appendChild(t):s.insertBefore(t,o[d]),s===l&&(c+=o.length-r),e.setStart(s,d),e.setEnd(l,c)},he=function(e,t,n){var o=e.startContainer,r=e.startOffset,a=e.endContainer,s=e.endOffset;t||(t=e.commonAncestorContainer),t.nodeType===i&&(t=t.parentNode);for(var d,l,c,h,f,u=oe(a,s,t,n),p=oe(o,r,t,n),g=t.ownerDocument.createDocumentFragment();p!==u;)d=p.nextSibling,g.appendChild(p),p=d;return o=t,r=u?x.call(t.childNodes,u):t.childNodes.length,(l=(c=t.childNodes[r])&&c.previousSibling)&&l.nodeType===i&&c.nodeType===i&&(o=l,r=l.length,h=l.data,f=c.data," "===h.charAt(h.length-1)&&" "===f.charAt(0)&&(f=" "+f.slice(1)),l.appendData(f),X(c)),e.setStart(o,r),e.collapse(!0),ne(t,n),g},fe=function(e,t){var n,i,o=ve(e,t),r=_e(e,t),a=o!==r;return ge(e),me(e,o,r,t),n=he(e,null,t),ge(e),a&&(r=_e(e,t),o&&r&&o!==r&&ae(o,r,e,t)),o&&ne(o,t),(i=t.firstChild)&&"BR"!==i.nodeName?e.collapse(!0):(ne(t,t),e.selectNodeContents(t.firstChild)),n},ue=function(e,t,n){var i,o,r,a,s,d,l,c,h,f,u,p=t.firstChild&&H(t.firstChild);for(ie(t,n),i=t;i=G(i,n);)ne(i,n);if(e.collapsed||fe(e,n),ge(e),e.collapse(!1),a=Q(e.endContainer,n,"BLOCKQUOTE")||n,o=ve(e,n),c=G(t,t),l=!p&&!!o&&Z(o),o&&c&&!l&&!Q(c,t,"PRE")&&!Q(c,t,"TABLE")){if(me(e,o,o,n),e.collapse(!0),s=e.endContainer,d=e.endOffset,We(o,n,!1),H(s)&&(s=(h=oe(s,d,K(s,n),n)).parentNode,d=x.call(s.childNodes,h)),d!==Y(s))for(r=n.ownerDocument.createDocumentFragment();i=s.childNodes[d];)r.appendChild(i);ae(s,c,e,n),d=x.call(s.parentNode.childNodes,s)+1,s=s.parentNode,e.setEnd(s,d)}Y(t)&&(l&&(e.setEndBefore(o),e.collapse(!1),X(o)),me(e,a,a,n),f=(h=oe(e.endContainer,e.endOffset,a,n))?h.previousSibling:a.lastChild,a.insertBefore(t,h),h?e.setEndBefore(h):e.setEnd(a,Y(a)),o=_e(e,n),ge(e),s=e.endContainer,d=e.endOffset,h&&z(h)&&se(h,n),(h=f&&f.nextSibling)&&z(h)&&se(h,n),e.setEnd(s,d)),r&&(ae(o,r,u=e.cloneRange(),n),e.setEnd(u.endContainer,u.endOffset)),ge(e)},pe=function(e,t,n){var i=t.ownerDocument.createRange();if(i.selectNode(t),n){var o=e.compareBoundaryPoints(3,i)>-1,r=e.compareBoundaryPoints(1,i)<1;return!o&&!r}var a=e.compareBoundaryPoints(0,i)<1,s=e.compareBoundaryPoints(2,i)>-1;return a&&s},ge=function(e){for(var t,n=e.startContainer,o=e.startOffset,r=e.endContainer,a=e.endOffset,s=!0;n.nodeType!==i&&(t=n.childNodes[o])&&!F(t);)n=t,o=0;if(a)for(;r.nodeType!==i;){if(!(t=r.childNodes[a-1])||F(t)){if(s&&t&&"BR"===t.nodeName){a-=1,s=!1;continue}break}a=Y(r=t)}else for(;r.nodeType!==i&&(t=r.firstChild)&&!F(t);)r=t;e.collapsed?(e.setStart(r,a),e.setEnd(n,o)):(e.setStart(n,o),e.setEnd(r,a))},me=function(e,t,n,o){var r,a=e.startContainer,s=e.startOffset,d=e.endContainer,l=e.endOffset,c=!0;for(t||(t=e.commonAncestorContainer),n||(n=t);!s&&a!==t&&a!==o;)r=a.parentNode,s=x.call(r.childNodes,a),a=r;for(;c&&d.nodeType!==i&&d.childNodes[l]&&"BR"===d.childNodes[l].nodeName&&(l+=1,c=!1),d!==n&&d!==o&&l===Y(d);)r=d.parentNode,l=x.call(r.childNodes,d)+1,d=r;e.setStart(a,s),e.setEnd(d,l)},ve=function(e,t){var n,i=e.startContainer;return(n=H(i)?K(i,t):i!==t&&W(i)?i:G(n=de(i,e.startOffset),t))&&pe(e,n,!0)?n:null},_e=function(e,t){var n,i,o=e.endContainer;if(H(o))n=K(o,t);else if(o!==t&&W(o))n=o;else{if(!(n=le(o,e.endOffset))||!V(t,n))for(n=t;i=n.lastChild;)n=i;n=K(n,t)}return n&&pe(e,n,!0)?n:null},Ce=new A(null,4|a,function(e){return e.nodeType===i?k.test(e.data):"IMG"===e.nodeName}),Ne=function(e,t){var n,o=e.startContainer,r=e.startOffset;if(Ce.root=null,o.nodeType===i){if(r)return!1;n=o}else if((n=le(o,r))&&!V(t,n)&&(n=null),!n&&(n=de(o,r)).nodeType===i&&n.length)return!1;return Ce.currentNode=n,Ce.root=ve(e,t),!Ce.previousNode()},Se=function(e,t){var n,o=e.endContainer,r=e.endOffset;if(Ce.root=null,o.nodeType===i){if((n=o.data.length)&&r<n)return!1;Ce.currentNode=o}else Ce.currentNode=de(o,r);return Ce.root=_e(e,t),!Ce.nextNode()},ye=function(e,t){var n,i=ve(e,t),o=_e(e,t);i&&o&&(n=i.parentNode,e.setStart(n,x.call(n.childNodes,i)),n=o.parentNode,e.setEnd(n,x.call(n.childNodes,o)+1))},Te={8:"backspace",9:"tab",13:"enter",32:"space",33:"pageup",34:"pagedown",37:"left",39:"right",46:"delete",219:"[",221:"]"},Ee=function(e){var t=e.keyCode,n=Te[t],i="",o=this.getSelection();e.defaultPrevented||(n||(n=String.fromCharCode(t).toLowerCase(),/^[A-Za-z0-9]$/.test(n)||(n="")),m&&46===e.which&&(n="."),111<t&&t<124&&(n="f"+(t-111)),"backspace"!==n&&"delete"!==n&&(e.altKey&&(i+="alt-"),e.ctrlKey&&(i+="ctrl-"),e.metaKey&&(i+="meta-")),e.shiftKey&&(i+="shift-"),n=i+n,this._keyHandlers[n]?this._keyHandlers[n](this,e,o):o.collapsed||e.isComposing||e.ctrlKey||e.metaKey||1!==(e.key||n).length||(this.saveUndoState(o),fe(o,this._root),this._ensureBottomLine(),this.setSelection(o),this._updatePath(o,!0)))},be=function(e){return function(t,n){n.preventDefault(),t[e]()}},ke=function(e,t){return t=t||null,function(n,i){i.preventDefault();var o=n.getSelection();n.hasFormat(e,null,o)?n.changeFormat(null,{tag:e},o):n.changeFormat({tag:e},t,o)}},xe=function(e,t){try{t||(t=e.getSelection());var n,o=t.startContainer;for(o.nodeType===i&&(o=o.parentNode),n=o;H(n)&&(!n.textContent||n.textContent===s);)n=(o=n).parentNode;o!==n&&(t.setStart(n,x.call(n.childNodes,o)),t.collapse(!0),n.removeChild(o),W(n)||(n=K(n,e._root)),ne(n,e._root),ge(t)),o===e._root&&(o=o.firstChild)&&"BR"===o.nodeName&&X(o),e._ensureBottomLine(),e.setSelection(t),e._updatePath(t,!0)}catch(t){e.didError(t)}},Le=function(e,t,o){var r,a,d,l,c,h=e._root;if(e._recordUndoState(o),e._config.addLinks&&ht(o.startContainer,h,e),e._removeZWS(),e._getRangeAndRemoveBookmark(o),o.collapsed||fe(o,h),(r=ve(o,h))&&(a=Q(r,h,"PRE")))return ge(o),d=o.startContainer,l=o.startOffset,d.nodeType!==i&&(d=e._doc.createTextNode(""),a.insertBefore(d,a.firstChild)),t||"\n"!==d.data.charAt(l-1)&&!Ne(o,h)||"\n"!==d.data.charAt(l)&&!Se(o,h)?(d.insertData(l,"\n"),ne(a,h),d.length===l+1?o.setStartAfter(d):o.setStart(d,l+1)):(d.deleteData(l&&l-1,l?2:1),(d=(c=oe(d,l&&l-1,h,h)).previousSibling).textContent||X(d),d=e.createDefaultBlock(),c.parentNode.insertBefore(d,c),c.textContent||X(c),o.setStart(d,0)),o.collapse(!0),e.setSelection(o),e._updatePath(o,!0),void e._docWasChanged();if(!r||t||/^T[HD]$/.test(r.nodeName))return(a=Q(o.endContainer,h,"A"))&&(a=a.parentNode,me(o,a,a,h),o.collapse(!1)),ce(o,e.createElement("BR")),o.collapse(!1),e.setSelection(o),void e._updatePath(o,!0);if((a=Q(r,h,"LI"))&&(r=a),Z(r)){if(Q(r,h,"UL")||Q(r,h,"OL"))return e.decreaseListLevel(o);if(Q(r,h,"BLOCKQUOTE"))return e.modifyBlocks(dt,o)}for(c=at(e,r,o.startContainer,o.startOffset),it(r),Fe(r),ne(r,h);c.nodeType===n;){var f,u=c.firstChild;if("A"===c.nodeName&&(!c.textContent||c.textContent===s)){J(c,u=e._doc.createTextNode("")),c=u;break}for(;u&&u.nodeType===i&&!u.data&&(f=u.nextSibling)&&"BR"!==f.nodeName;)X(u),u=f;if(!u||"BR"===u.nodeName||u.nodeType===i&&!m)break;c=u}o=e.createRange(c,0),e.setSelection(o),e._updatePath(o,!0)},Be={enter:h?function(e,t,n){e._saveRangeToBookmark(n);var i=e._getHTML(),o=function(){e.removeEventListener("keyup",o),e._setHTML(i),n=e._getRangeAndRemoveBookmark(),Le(e,!1,n)};e.addEventListener("keyup",o)}:function(e,t,n){t.preventDefault(),Le(e,t.shiftKey,n)},"shift-enter":function(e,t,n){return e._keyHandlers.enter(e,t,n)},backspace:function(e,t,n){var i=e._root;if(e._removeZWS(),e.saveUndoState(n),n.collapsed)if(Ne(n,i)){t.preventDefault();var o,r=ve(n,i);if(!r)return;if(ie(r.parentNode,i),o=K(r,i)){if(!o.isContentEditable)return void X(o);for(ae(o,r,n,i),r=o.parentNode;r!==i&&!r.nextSibling;)r=r.parentNode;r!==i&&(r=r.nextSibling)&&se(r,i),e.setSelection(n)}else if(r){if(Q(r,i,"UL")||Q(r,i,"OL"))return e.decreaseListLevel(n);if(Q(r,i,"BLOCKQUOTE"))return e.modifyBlocks(st,n);e.setSelection(n),e._updatePath(n,!0)}}else e.setSelection(n),setTimeout(function(){xe(e)},0);else t.preventDefault(),fe(n,i),xe(e,n)},delete:function(e,t,i){var o,r,a,s,d,l,c=e._root;if(e._removeZWS(),e.saveUndoState(i),i.collapsed)if(Se(i,c)){if(t.preventDefault(),!(o=ve(i,c)))return;if(ie(o.parentNode,c),r=G(o,c)){if(!r.isContentEditable)return void X(r);for(ae(o,r,i,c),r=o.parentNode;r!==c&&!r.nextSibling;)r=r.parentNode;r!==c&&(r=r.nextSibling)&&se(r,c),e.setSelection(i),e._updatePath(i,!0)}}else{if(a=i.cloneRange(),me(i,c,c,c),s=i.endContainer,d=i.endOffset,s.nodeType===n&&(l=s.childNodes[d])&&"IMG"===l.nodeName)return t.preventDefault(),X(l),ge(i),void xe(e,i);e.setSelection(a),setTimeout(function(){xe(e)},0)}else t.preventDefault(),fe(i,c),xe(e,i)},tab:function(e,t,n){var i,o,r=e._root;if(e._removeZWS(),n.collapsed&&Ne(n,r))for(i=ve(n,r);o=i.parentNode;){if("UL"===o.nodeName||"OL"===o.nodeName){t.preventDefault(),e.increaseListLevel(n);break}i=o}},"shift-tab":function(e,t,n){var i,o=e._root;e._removeZWS(),n.collapsed&&Ne(n,o)&&(Q(i=n.startContainer,o,"UL")||Q(i,o,"OL"))&&(t.preventDefault(),e.decreaseListLevel(n))},space:function(e,t,n){var i,o=e._root;if(e._recordUndoState(n),e._config.addLinks&&ht(n.startContainer,o,e),e._getRangeAndRemoveBookmark(n),i=n.endContainer,n.collapsed&&n.endOffset===Y(i))do{if("A"===i.nodeName){n.setStartAfter(i);break}}while(!i.nextSibling&&(i=i.parentNode)&&i!==o);n.collapsed||(fe(n,o),e._ensureBottomLine(),e.setSelection(n),e._updatePath(n,!0)),e.setSelection(n)},left:function(e){e._removeZWS()},right:function(e){e._removeZWS()}};f&&p&&(Be["meta-left"]=function(e,t){t.preventDefault();var n=Je(e);n&&n.modify&&n.modify("move","backward","lineboundary")},Be["meta-right"]=function(e,t){t.preventDefault();var n=Je(e);n&&n.modify&&n.modify("move","forward","lineboundary")}),f||(Be.pageup=function(e){e.moveCursorToStart()},Be.pagedown=function(e){e.moveCursorToEnd()}),Be[N+"b"]=ke("B"),Be[N+"i"]=ke("I"),Be[N+"u"]=ke("U"),Be[N+"shift-7"]=ke("S"),Be[N+"shift-5"]=ke("SUB",{tag:"SUP"}),Be[N+"shift-6"]=ke("SUP",{tag:"SUB"}),Be[N+"shift-8"]=be("makeUnorderedList"),Be[N+"shift-9"]=be("makeOrderedList"),Be[N+"["]=be("decreaseQuoteLevel"),Be[N+"]"]=be("increaseQuoteLevel"),Be[N+"d"]=be("toggleCode"),Be[N+"y"]=be("redo"),Be[N+"z"]=be("undo"),Be[N+"shift-z"]=be("redo");var Ae={1:10,2:13,3:16,4:18,5:24,6:32,7:48},Oe={fontWeight:{regexp:/^bold|^700/i,replace:function(e){return te(e,"B")}},fontStyle:{regexp:/^italic/i,replace:function(e){return te(e,"I")}},fontFamily:{regexp:k,replace:function(e,t,n){return te(e,"SPAN",{class:t.fontFamily,style:"font-family:"+n})}},fontSize:{regexp:k,replace:function(e,t,n){return te(e,"SPAN",{class:t.fontSize,style:"font-size:"+n})}},textDecoration:{regexp:/^underline/i,replace:function(e){return te(e,"U")}}},Re=function(e){return function(t,n){var i,o,r,a=te(t.ownerDocument,e),s=t.attributes;for(i=0,o=s.length;i<o;i+=1)r=s[i],a.setAttribute(r.name,r.value);return n.replaceChild(a,t),a.appendChild(ee(t)),a}},De={SPAN:function(e,t,n){var i,o,r,a,s,d,l=e.style,c=e.ownerDocument;for(i in Oe)if(o=Oe[i],(r=l[i])&&o.regexp.test(r)){if((d=o.replace(c,n.classNames,r)).nodeName===e.nodeName&&d.className===e.className)continue;s||(s=d),a&&a.appendChild(d),a=d,e.style[i]=""}return s&&(a.appendChild(ee(e)),e.appendChild(s)),a||e},STRONG:Re("B"),EM:Re("I"),INS:Re("U"),STRIKE:Re("S"),FONT:function(e,t,n){var i,o,r,a,s,d=e.face,l=e.size,c=e.color,h=e.ownerDocument,f=n.classNames;return d&&(s=i=te(h,"SPAN",{class:f.fontFamily,style:"font-family:"+d}),a=i),l&&(o=te(h,"SPAN",{class:f.fontSize,style:"font-size:"+Ae[l]+"px"}),s||(s=o),a&&a.appendChild(o),a=o),c&&/^#?([\dA-F]{3}){1,2}$/i.test(c)&&("#"!==c.charAt(0)&&(c="#"+c),r=te(h,"SPAN",{class:f.colour,style:"color:"+c}),s||(s=r),a&&a.appendChild(r),a=r),s||(s=a=te(h,"SPAN")),t.replaceChild(s,e),a.appendChild(ee(e)),a},TT:function(e,t,n){var i=te(e.ownerDocument,"SPAN",{class:n.classNames.fontFamily,style:'font-family:menlo,consolas,"courier new",monospace'});return t.replaceChild(i,e),i.appendChild(ee(e)),i}},Pe=/^(?:A(?:DDRESS|RTICLE|SIDE|UDIO)|BLOCKQUOTE|CAPTION|D(?:[DLT]|IV)|F(?:IGURE|IGCAPTION|OOTER)|H[1-6]|HEADER|L(?:ABEL|EGEND|I)|O(?:L|UTPUT)|P(?:RE)?|SECTION|T(?:ABLE|BODY|D|FOOT|H|HEAD|R)|COL(?:GROUP)?|UL)$/,Ue=/^(?:HEAD|META|STYLE)/,Ie=new A(null,4|a),we=function e(t,o,r){var a,s,d,l,c,h,f,u,p,g,m,v,_=t.childNodes;for(a=t;H(a);)a=a.parentNode;for(Ie.root=a,s=0,d=_.length;s<d;s+=1)if(c=(l=_[s]).nodeName,h=l.nodeType,f=De[c],h===n){if(u=l.childNodes.length,f)l=f(l,t,o);else{if(Ue.test(c)){t.removeChild(l),s-=1,d-=1;continue}if(!Pe.test(c)&&!H(l)){s-=1,d+=u-1,t.replaceChild(ee(l),l);continue}}u&&e(l,o,r||"PRE"===c)}else{if(h===i){if(m=l.data,p=!k.test(m.charAt(0)),g=!k.test(m.charAt(m.length-1)),r||!p&&!g)continue;if(p){for(Ie.currentNode=l;(v=Ie.previousPONode())&&!("IMG"===(c=v.nodeName)||"#text"===c&&k.test(v.data));)if(!H(v)){v=null;break}m=m.replace(/^[ \t\r\n]+/g,v?" ":"")}if(g){for(Ie.currentNode=l;(v=Ie.nextNode())&&!("IMG"===c||"#text"===c&&k.test(v.data));)if(!H(v)){v=null;break}m=m.replace(/[ \t\r\n]+$/g,v?" ":"")}if(m){l.data=m;continue}}t.removeChild(l),s-=1,d-=1}return t},Fe=function e(t){for(var o,r=t.childNodes,a=r.length;a--;)(o=r[a]).nodeType!==n||F(o)?o.nodeType!==i||o.data||t.removeChild(o):(e(o),H(o)&&!o.firstChild&&t.removeChild(o))},Me=function(e){return e.nodeType===n?"BR"===e.nodeName:k.test(e.data)},He=function(e,t){for(var n,i=e.parentNode;H(i);)i=i.parentNode;return(n=new A(i,4|a,Me)).currentNode=e,!!n.nextNode()||t&&!n.previousNode()},We=function(e,t,n){var i,o,r,a=e.querySelectorAll("BR"),s=[],d=a.length;for(i=0;i<d;i+=1)s[i]=He(a[i],n);for(;d--;)(r=(o=a[d]).parentNode)&&(s[d]?H(r)||ie(r,t):X(o))},ze=function(e,t,n,i){var o,r,a=t.ownerDocument.body,s=i.willCutCopy;We(t,n,!0),t.setAttribute("style","position:fixed;overflow:hidden;bottom:100%;right:100%;"),a.appendChild(t),o=t.innerHTML,r=t.innerText||t.textContent,s&&(o=s(o)),u&&(r=r.replace(/\r?\n/g,"\r\n")),e.setData("text/html",o),e.setData("text/plain",r),a.removeChild(t)},qe=function(e){var t,n,o,r,a,s,d=e.clipboardData,l=this.getSelection(),c=this._root,h=this;if(l.collapsed)e.preventDefault();else{if(this.saveUndoState(l),!v&&d){for(n=(t=ve(l,c))===_e(l,c)&&t||c,o=fe(l,c),(r=l.commonAncestorContainer).nodeType===i&&(r=r.parentNode);r&&r!==n;)(a=r.cloneNode(!1)).appendChild(o),o=a,r=r.parentNode;(s=this.createElement("div")).appendChild(o),ze(d,s,c,this._config),e.preventDefault()}else setTimeout(function(){try{h._ensureBottomLine()}catch(e){h.didError(e)}},0);this.setSelection(l)}},Ke=function(e){var t,n,o,r,a,s,d=e.clipboardData,l=this.getSelection(),c=this._root;if(!v&&d){for(n=(t=ve(l,c))===_e(l,c)&&t||c,l=l.cloneRange(),ge(l),me(l,n,n,c),o=l.cloneContents(),(r=l.commonAncestorContainer).nodeType===i&&(r=r.parentNode);r&&r!==n;)(a=r.cloneNode(!1)).appendChild(o),o=a,r=r.parentNode;(s=this.createElement("div")).appendChild(o),ze(d,s,c,this._config),e.preventDefault()}};function Ge(e){this.isShiftDown=e.shiftKey}var Ze=function(e){var t,n,i,o,r,a=e.clipboardData,s=a&&a.items,d=this.isShiftDown,l=!1,c=!1,h=!1,f=null,u=null,g=this;if(s){for(t=s.length;t--;)"text/html"===(i=(n=s[t]).type)?u=n:"text/plain"===i||"text/uri-list"===i?f=n:"text/rtf"===i?c=!0:/^image\/.*/.test(i)&&(h=!0);if(h&&(!c||!u))return e.preventDefault(),this.fireEvent("dragover",{dataTransfer:a,preventDefault:function(){l=!0}}),void(l&&this.fireEvent("drop",{dataTransfer:a}));if(!v)return e.preventDefault(),void(!u||d&&f?f&&f.getAsString(function(e){g.insertPlainText(e,!0)}):u.getAsString(function(e){g.insertHTML(e,!0)}))}if(o=a&&a.types,!v&&o&&(x.call(o,"text/html")>-1||!p&&x.call(o,"text/plain")>-1&&x.call(o,"text/rtf")<0))return e.preventDefault(),void(!d&&(r=a.getData("text/html"))?this.insertHTML(r,!0):((r=a.getData("text/plain"))||(r=a.getData("text/uri-list")))&&this.insertPlainText(r,!0));this._awaitingPaste=!0;var m=this._doc.body,_=this.getSelection(),C=_.startContainer,N=_.startOffset,S=_.endContainer,y=_.endOffset,T=this.createElement("DIV",{contenteditable:"true",style:"position:fixed; overflow:hidden; top:0; right:100%; width:1px; height:1px;"});m.appendChild(T),_.selectNodeContents(T),this.setSelection(_),setTimeout(function(){try{g._awaitingPaste=!1;for(var e,t,n="",i=T;T=i;)i=T.nextSibling,X(T),(e=T.firstChild)&&e===T.lastChild&&"DIV"===e.nodeName&&(T=e),n+=T.innerHTML;t=g.createRange(C,N,S,y),g.setSelection(t),n&&g.insertHTML(n,!0)}catch(e){g.didError(e)}},0)},je=function(e){for(var t=e.dataTransfer.types,n=t.length,i=!1,o=!1;n--;)switch(t[n]){case"text/plain":i=!0;break;case"text/html":o=!0;break;default:return}(o||i)&&this.saveUndoState()};function $e(e,t,n){var i,o;if(e||(e={}),t)for(i in t)!n&&i in e||(o=t[i],e[i]=o&&o.constructor===Object?$e(e[i],o,n):o);return e}function Qe(e,t){e.nodeType===o&&(e=e.body);var n,i=e.ownerDocument,r=i.defaultView;this._win=r,this._doc=i,this._root=e,this._events={},this._isFocused=!1,this._lastSelection=null,T&&this.addEventListener("beforedeactivate",this.getSelection),this._hasZWS=!1,this._lastAnchorNode=null,this._lastFocusNode=null,this._path="",this._willUpdatePath=!1,"onselectionchange"in i?this.addEventListener("selectionchange",this._updatePathOnEvent):(this.addEventListener("keyup",this._updatePathOnEvent),this.addEventListener("mouseup",this._updatePathOnEvent)),this._undoIndex=-1,this._undoStack=[],this._undoStackLength=0,this._isInUndoState=!1,this._ignoreChange=!1,this._ignoreAllChanges=!1,E?((n=new MutationObserver(this._docWasChanged.bind(this))).observe(e,{childList:!0,attributes:!0,characterData:!0,subtree:!0}),this._mutation=n):this.addEventListener("keyup",this._keyUpDetectChange),this._restoreSelection=!1,this.addEventListener("blur",et),this.addEventListener("mousedown",tt),this.addEventListener("touchstart",tt),this.addEventListener("focus",nt),this._awaitingPaste=!1,this.addEventListener(g?"beforecut":"cut",qe),this.addEventListener("copy",Ke),this.addEventListener("keydown",Ge),this.addEventListener("keyup",Ge),this.addEventListener(g?"beforepaste":"paste",Ze),this.addEventListener("drop",je),this.addEventListener(m?"keypress":"keydown",Ee),this._keyHandlers=Object.create(Be),this.setConfig(t),g&&(r.Text.prototype.splitText=function(e){var t=this.ownerDocument.createTextNode(this.data.slice(e)),n=this.nextSibling,i=this.parentNode,o=this.length-e;return n?i.insertBefore(t,n):i.appendChild(t),o&&this.deleteData(e,o),t}),e.setAttribute("contenteditable","true");try{i.execCommand("enableObjectResizing",!1,"false"),i.execCommand("enableInlineTableEditing",!1,"false")}catch(e){}e.__squire__=this,this.setHTML("")}var Ve=Qe.prototype,Ye=function(e,t,n){var i=n._doc,o=e?DOMPurify.sanitize(e,{ALLOW_UNKNOWN_PROTOCOLS:!0,WHOLE_DOCUMENT:!1,RETURN_DOM:!0,RETURN_DOM_FRAGMENT:!0}):null;return o?i.importNode(o,!0):i.createDocumentFragment()};Ve.setConfig=function(e){return(e=$e({blockTag:"DIV",blockAttributes:null,tagAttributes:{blockquote:null,ul:null,ol:null,li:null,a:null},classNames:{colour:"colour",fontFamily:"font",fontSize:"size",highlight:"highlight"},leafNodeNames:R,undo:{documentSizeThreshold:-1,undoLimit:-1},isInsertedHTMLSanitized:!0,isSetHTMLSanitized:!0,sanitizeToDOMFragment:"undefined"!=typeof DOMPurify&&DOMPurify.isSupported?Ye:null,willCutCopy:null,addLinks:!0},e,!0)).blockTag=e.blockTag.toUpperCase(),this._config=e,this},Ve.createElement=function(e,t,n){return te(this._doc,e,t,n)},Ve.createDefaultBlock=function(e){var t=this._config;return ne(this.createElement(t.blockTag,t.blockAttributes,e),this._root)},Ve.didError=function(e){console.log(e)},Ve.getDocument=function(){return this._doc},Ve.getRoot=function(){return this._root},Ve.modifyDocument=function(e){var t=this._mutation;t&&(t.takeRecords().length&&this._docWasChanged(),t.disconnect()),this._ignoreAllChanges=!0,e(),this._ignoreAllChanges=!1,t&&(t.observe(this._root,{childList:!0,attributes:!0,characterData:!0,subtree:!0}),this._ignoreChange=!1)};var Xe={pathChange:1,select:1,input:1,undoStateChange:1};Ve.fireEvent=function(e,t){var n,i,o,r=this._events[e];if(/^(?:focus|blur)/.test(e))if(n=this._root===this._doc.activeElement,"focus"===e){if(!n||this._isFocused)return this;this._isFocused=!0}else{if(n||!this._isFocused)return this;this._isFocused=!1}if(r)for(t||(t={}),t.type!==e&&(t.type=e),i=(r=r.slice()).length;i--;){o=r[i];try{o.handleEvent?o.handleEvent(t):o.call(this,t)}catch(t){t.details="Squire: fireEvent error. Event type: "+e,this.didError(t)}}return this},Ve.destroy=function(){var e,t=this._events;for(e in t)this.removeEventListener(e);this._mutation&&this._mutation.disconnect(),delete this._root.__squire__,this._undoIndex=-1,this._undoStack=[],this._undoStackLength=0},Ve.handleEvent=function(e){this.fireEvent(e.type,e)},Ve.addEventListener=function(e,t){var n=this._events[e],i=this._root;return t?(n||(n=this._events[e]=[],Xe[e]||("selectionchange"===e&&(i=this._doc),i.addEventListener(e,this,!0))),n.push(t),this):(this.didError({name:"Squire: addEventListener with null or undefined fn",message:"Event type: "+e}),this)},Ve.removeEventListener=function(e,t){var n,i=this._events[e],o=this._root;if(i){if(t)for(n=i.length;n--;)i[n]===t&&i.splice(n,1);else i.length=0;i.length||(delete this._events[e],Xe[e]||("selectionchange"===e&&(o=this._doc),o.removeEventListener(e,this,!0)))}return this},Ve.createRange=function(e,t,n,i){if(e instanceof this._win.Range)return e.cloneRange();var o=this._doc.createRange();return o.setStart(e,t),n?o.setEnd(n,i):o.setEnd(e,t),o},Ve.getCursorPosition=function(e){if(!e&&!(e=this.getSelection())||!e.getBoundingClientRect)return null;var t,n,i=e.getBoundingClientRect();return i&&!i.top&&(this._ignoreChange=!0,(t=this._doc.createElement("SPAN")).textContent=s,ce(e,t),i=t.getBoundingClientRect(),(n=t.parentNode).removeChild(t),re(n,e)),i},Ve._moveCursorTo=function(e){var t=this._root,n=this.createRange(t,e?0:t.childNodes.length);return ge(n),this.setSelection(n),this},Ve.moveCursorToStart=function(){return this._moveCursorTo(!0)},Ve.moveCursorToEnd=function(){return this._moveCursorTo(!1)};var Je=function(e){return e._win.getSelection()||null};function et(){this._restoreSelection=!0}function tt(){this._restoreSelection=!1}function nt(){this._restoreSelection&&this.setSelection(this._lastSelection)}Ve.setSelection=function(e){if(e)if(this._lastSelection=e,this._isFocused)if(c&&!this._restoreSelection)et.call(this),this.blur(),this.focus();else{h&&this._win.focus();var t=Je(this);t&&(t.removeAllRanges(),t.addRange(e))}else et.call(this);return this},Ve.getSelection=function(){var e,t,n,i,o=Je(this),r=this._root;return this._isFocused&&o&&o.rangeCount&&(t=(e=o.getRangeAt(0).cloneRange()).startContainer,n=e.endContainer,t&&F(t)&&e.setStartBefore(t),n&&F(n)&&e.setEndBefore(n)),e&&V(r,e.commonAncestorContainer)?this._lastSelection=e:V((i=(e=this._lastSelection).commonAncestorContainer).ownerDocument,i)||(e=null),e||(e=this.createRange(r.firstChild,0)),e},Ve.getSelectedText=function(){var e=this.getSelection();if(!e||e.collapsed)return"";var t,n=new A(e.commonAncestorContainer,4|a,function(t){return pe(e,t,!0)}),o=e.startContainer,r=e.endContainer,s=n.currentNode=o,d="",l=!1;for(n.filter(s)||(s=n.nextNode());s;)s.nodeType===i?(t=s.data)&&/\S/.test(t)&&(s===r&&(t=t.slice(0,e.endOffset)),s===o&&(t=t.slice(e.startOffset)),d+=t,l=!0):("BR"===s.nodeName||l&&!H(s))&&(d+="\n",l=!1),s=n.nextNode();return d},Ve.getPath=function(){return this._path};var it=function(e,t){for(var n,i,o,r=new A(e,4);i=r.nextNode();)for(;(o=i.data.indexOf(s))>-1&&(!t||i.parentNode!==t);){if(1===i.length){do{(n=i.parentNode).removeChild(i),i=n,r.currentNode=n}while(H(i)&&!Y(i));break}i.deleteData(o,1)}};Ve._didAddZWS=function(){this._hasZWS=!0},Ve._removeZWS=function(){this._hasZWS&&(it(this._root),this._hasZWS=!1)},Ve._updatePath=function(e,t){if(e){var i,o=e.startContainer,r=e.endContainer;(t||o!==this._lastAnchorNode||r!==this._lastFocusNode)&&(this._lastAnchorNode=o,this._lastFocusNode=r,i=o&&r?o===r?function e(t,i,o){var r,a,s,d,l,c="";return t&&t!==i&&(c=e(t.parentNode,i,o),t.nodeType===n&&(c+=(c?">":"")+t.nodeName,(r=t.id)&&(c+="#"+r),(a=t.className.trim())&&((s=a.split(/\s\s*/)).sort(),c+=".",c+=s.join(".")),(d=t.dir)&&(c+="[dir="+d+"]"),s&&(l=o.classNames,x.call(s,l.highlight)>-1&&(c+="[backgroundColor="+t.style.backgroundColor.replace(/ /g,"")+"]"),x.call(s,l.colour)>-1&&(c+="[color="+t.style.color.replace(/ /g,"")+"]"),x.call(s,l.fontFamily)>-1&&(c+="[fontFamily="+t.style.fontFamily.replace(/ /g,"")+"]"),x.call(s,l.fontSize)>-1&&(c+="[fontSize="+t.style.fontSize+"]")))),c}(r,this._root,this._config):"(selection)":"",this._path!==i&&(this._path=i,this.fireEvent("pathChange",{path:i}))),this.fireEvent(e.collapsed?"cursor":"select",{range:e})}},Ve._updatePathOnEvent=function(e){var t=this;t._isFocused&&!t._willUpdatePath&&(t._willUpdatePath=!0,setTimeout(function(){t._willUpdatePath=!1,t._updatePath(t.getSelection())},0))},Ve.focus=function(){return this._root.focus({preventScroll:!0}),C&&this.fireEvent("focus"),this},Ve.blur=function(){return this._root.blur(),C&&this.fireEvent("blur"),this};var ot="squire-selection-end";Ve._saveRangeToBookmark=function(e){var t,n=this.createElement("INPUT",{id:"squire-selection-start",type:"hidden"}),i=this.createElement("INPUT",{id:ot,type:"hidden"});ce(e,n),e.collapse(!1),ce(e,i),2&n.compareDocumentPosition(i)&&(n.id=ot,i.id="squire-selection-start",t=n,n=i,i=t),e.setStartAfter(n),e.setEndBefore(i)},Ve._getRangeAndRemoveBookmark=function(e){var t=this._root,n=t.querySelector("#squire-selection-start"),o=t.querySelector("#"+ot);if(n&&o){var r=n.parentNode,a=o.parentNode,s=x.call(r.childNodes,n),d=x.call(a.childNodes,o);r===a&&(d-=1),X(n),X(o),e||(e=this._doc.createRange()),e.setStart(r,s),e.setEnd(a,d),re(r,e),r!==a&&re(a,e),e.collapsed&&(r=e.startContainer).nodeType===i&&((a=r.childNodes[e.startOffset])&&a.nodeType===i||(a=r.childNodes[e.startOffset-1]),a&&a.nodeType===i&&(e.setStart(a,0),e.collapse(!0)))}return e||null},Ve._keyUpDetectChange=function(e){var t=e.keyCode;e.ctrlKey||e.metaKey||e.altKey||!(t<16||t>20)||!(t<33||t>45)||this._docWasChanged()},Ve._docWasChanged=function(){b&&(w=new WeakMap),this._ignoreAllChanges||(E&&this._ignoreChange?this._ignoreChange=!1:(this._isInUndoState&&(this._isInUndoState=!1,this.fireEvent("undoStateChange",{canUndo:!0,canRedo:!1})),this.fireEvent("input")))},Ve._recordUndoState=function(e,t){if(!this._isInUndoState||t){var n,i=this._undoIndex,o=this._undoStack,r=this._config.undo,a=r.documentSizeThreshold,s=r.undoLimit;t||(i+=1),i<this._undoStackLength&&(o.length=this._undoStackLength=i),e&&this._saveRangeToBookmark(e),n=this._getHTML(),a>-1&&2*n.length>a&&s>-1&&i>s&&(o.splice(0,i-s),i=s,this._undoStackLength=s),o[i]=n,this._undoIndex=i,this._undoStackLength+=1,this._isInUndoState=!0}},Ve.saveUndoState=function(e){return e===t&&(e=this.getSelection()),this._recordUndoState(e,this._isInUndoState),this._getRangeAndRemoveBookmark(e),this},Ve.undo=function(){if(0!==this._undoIndex||!this._isInUndoState){this._recordUndoState(this.getSelection(),!1),this._undoIndex-=1,this._setHTML(this._undoStack[this._undoIndex]);var e=this._getRangeAndRemoveBookmark();e&&this.setSelection(e),this._isInUndoState=!0,this.fireEvent("undoStateChange",{canUndo:0!==this._undoIndex,canRedo:!0}),this.fireEvent("input")}return this},Ve.redo=function(){var e=this._undoIndex,t=this._undoStackLength;if(e+1<t&&this._isInUndoState){this._undoIndex+=1,this._setHTML(this._undoStack[this._undoIndex]);var n=this._getRangeAndRemoveBookmark();n&&this.setSelection(n),this.fireEvent("undoStateChange",{canUndo:!0,canRedo:e+2<t}),this.fireEvent("input")}return this},Ve.hasFormat=function(e,t,n){if(e=e.toUpperCase(),t||(t={}),!n&&!(n=this.getSelection()))return!1;!n.collapsed&&n.startContainer.nodeType===i&&n.startOffset===n.startContainer.length&&n.startContainer.nextSibling&&n.setStartBefore(n.startContainer.nextSibling),!n.collapsed&&n.endContainer.nodeType===i&&0===n.endOffset&&n.endContainer.previousSibling&&n.setEndAfter(n.endContainer.previousSibling);var o,r,a=this._root,s=n.commonAncestorContainer;if(Q(s,a,e,t))return!0;if(s.nodeType===i)return!1;o=new A(s,4,function(e){return pe(n,e,!0)});for(var d=!1;r=o.nextNode();){if(!Q(r,a,e,t))return!1;d=!0}return d},Ve.getFontInfo=function(e){var n,o,r,a={color:t,backgroundColor:t,family:t,size:t},s=0;if(!e&&!(e=this.getSelection()))return a;if(n=e.commonAncestorContainer,e.collapsed||n.nodeType===i)for(n.nodeType===i&&(n=n.parentNode);s<4&&n;)(o=n.style)&&(!a.color&&(r=o.color)&&(a.color=r,s+=1),!a.backgroundColor&&(r=o.backgroundColor)&&(a.backgroundColor=r,s+=1),!a.family&&(r=o.fontFamily)&&(a.family=r,s+=1),!a.size&&(r=o.fontSize)&&(a.size=r,s+=1)),n=n.parentNode;return a},Ve._addFormat=function(e,t,n){var o,r,s,d,l,c,h,f,u=this._root;if(n.collapsed){for(o=ne(this.createElement(e,t),u),ce(n,o),n.setStart(o.firstChild,o.firstChild.length),n.collapse(!0),f=o;H(f);)f=f.parentNode;it(f,o)}else{if(r=new A(n.commonAncestorContainer,4|a,function(e){return(e.nodeType===i||"BR"===e.nodeName||"IMG"===e.nodeName)&&pe(n,e,!0)}),s=n.startContainer,l=n.startOffset,d=n.endContainer,c=n.endOffset,r.currentNode=s,r.filter(s)||(s=r.nextNode(),l=0),!s)return n;do{!Q(h=r.currentNode,u,e,t)&&(h===d&&h.length>c&&h.splitText(c),h===s&&l&&(h=h.splitText(l),d===s&&(d=h,c-=l),s=h,l=0),J(h,o=this.createElement(e,t)),o.appendChild(h))}while(r.nextNode());d.nodeType!==i&&(h.nodeType===i?(d=h,c=h.length):(d=h.parentNode,c=1)),n=this.createRange(s,l,d,c)}return n},Ve._removeFormat=function(e,t,n,o){this._saveRangeToBookmark(n);var r,a=this._doc;n.collapsed&&(y?(r=a.createTextNode(s),this._didAddZWS()):r=a.createTextNode(""),ce(n,r));for(var d=n.commonAncestorContainer;H(d);)d=d.parentNode;var l=n.startContainer,c=n.startOffset,h=n.endContainer,f=n.endOffset,u=[],p=function(e,t){if(!pe(n,e,!1)){var o,r,a=e.nodeType===i;if(pe(n,e,!0))if(a)e===h&&f!==e.length&&u.push([t,e.splitText(f)]),e===l&&c&&(e.splitText(c),u.push([t,e]));else for(o=e.firstChild;o;o=r)r=o.nextSibling,p(o,t);else"INPUT"===e.nodeName||a&&!e.data||u.push([t,e])}},g=Array.prototype.filter.call(d.getElementsByTagName(e),function(i){return pe(n,i,!0)&&$(i,e,t)});return o||g.forEach(function(e){p(e,e)}),u.forEach(function(e){var t=e[0].cloneNode(!1),n=e[1];J(n,t),t.appendChild(n)}),g.forEach(function(e){J(e,ee(e))}),this._getRangeAndRemoveBookmark(n),r&&n.collapse(!1),re(d,n),n},Ve.changeFormat=function(e,t,n,i){return n||(n=this.getSelection())?(this.saveUndoState(n),t&&(n=this._removeFormat(t.tag.toUpperCase(),t.attributes||{},n,i)),e&&(n=this._addFormat(e.tag.toUpperCase(),e.attributes||{},n)),this.setSelection(n),this._updatePath(n,!0),E||this._docWasChanged(),this):this};var rt={DT:"DD",DD:"DT",LI:"LI",PRE:"PRE"},at=function(e,t,n,i){var o=rt[t.nodeName],r=null,a=oe(n,i,t.parentNode,e._root),s=e._config;return o||(o=s.blockTag,r=s.blockAttributes),$(a,o,r)||(t=te(a.ownerDocument,o,r),a.dir&&(t.dir=a.dir),J(a,t),t.appendChild(ee(a)),a=t),a};Ve.forEachBlock=function(e,t,n){if(!n&&!(n=this.getSelection()))return this;t&&this.saveUndoState(n);var i=this._root,o=ve(n,i),r=_e(n,i);if(o&&r)do{if(e(o)||o===r)break}while(o=G(o,i));return t&&(this.setSelection(n),this._updatePath(n,!0),E||this._docWasChanged()),this},Ve.modifyBlocks=function(e,t){if(!t&&!(t=this.getSelection()))return this;this._recordUndoState(t,this._isInUndoState);var n,i=this._root;return ye(t,i),me(t,i,i,i),n=he(t,i,i),ce(t,e.call(this,n)),t.endOffset<t.endContainer.childNodes.length&&se(t.endContainer.childNodes[t.endOffset],i),se(t.startContainer.childNodes[t.startOffset],i),this._getRangeAndRemoveBookmark(t),this.setSelection(t),this._updatePath(t,!0),E||this._docWasChanged(),this};var st=function(e){var t=this._root,n=e.querySelectorAll("blockquote");return Array.prototype.filter.call(n,function(e){return!Q(e.parentNode,t,"BLOCKQUOTE")}).forEach(function(e){J(e,ee(e))}),e},dt=function(){return this.createDefaultBlock([this.createElement("INPUT",{id:"squire-selection-start",type:"hidden"}),this.createElement("INPUT",{id:ot,type:"hidden"})])},lt=function(e,t,n){for(var i,o,r,a,s=q(t,e._root),d=e._config.tagAttributes,l=d[n.toLowerCase()],c=d.li;i=s.nextNode();)"LI"===i.parentNode.nodeName&&(i=i.parentNode,s.currentNode=i.lastChild),"LI"!==i.nodeName?(a=e.createElement("LI",c),i.dir&&(a.dir=i.dir),(r=i.previousSibling)&&r.nodeName===n?(r.appendChild(a),X(i)):J(i,e.createElement(n,l,[a])),a.appendChild(ee(i)),s.currentNode=a):(o=(i=i.parentNode).nodeName)!==n&&/^[OU]L$/.test(o)&&J(i,e.createElement(n,l,[ee(i)]))},ct=function(e,t){for(var n=e.commonAncestorContainer,i=e.startContainer,o=e.endContainer;n&&n!==t&&!/^[OU]L$/.test(n.nodeName);)n=n.parentNode;if(!n||n===t)return null;for(i===n&&(i=i.childNodes[e.startOffset]),o===n&&(o=o.childNodes[e.endOffset]);i&&i.parentNode!==n;)i=i.parentNode;for(;o&&o.parentNode!==n;)o=o.parentNode;return[n,i,o]};Ve.increaseListLevel=function(e){if(!e&&!(e=this.getSelection()))return this.focus();var t=this._root,n=ct(e,t);if(!n)return this.focus();var i=n[0],o=n[1],r=n[2];if(!o||o===i.firstChild)return this.focus();this._recordUndoState(e,this._isInUndoState);var a,s,d=i.nodeName,l=o.previousSibling;l.nodeName!==d&&(a=this._config.tagAttributes[d.toLowerCase()],l=this.createElement(d,a),i.insertBefore(l,o));do{s=o===r?null:o.nextSibling,l.appendChild(o)}while(o=s);return(s=l.nextSibling)&&se(s,t),this._getRangeAndRemoveBookmark(e),this.setSelection(e),this._updatePath(e,!0),E||this._docWasChanged(),this.focus()},Ve.decreaseListLevel=function(e){if(!e&&!(e=this.getSelection()))return this.focus();var t=this._root,n=ct(e,t);if(!n)return this.focus();var i,o,r,a,s=n[0],d=n[1],l=n[2];if(d||(d=s.firstChild),l||(l=s.lastChild),this._recordUndoState(e,this._isInUndoState),d){if(i=s.parentNode,r=l.nextSibling?oe(s,l.nextSibling,i,t):s.nextSibling,i!==t&&"LI"===i.nodeName){for(i=i.parentNode;r;)o=r.nextSibling,l.appendChild(r),r=o;r=s.parentNode.nextSibling}a=!/^[OU]L$/.test(i.nodeName);do{o=d===l?null:d.nextSibling,s.removeChild(d),a&&"LI"===d.nodeName&&(d=this.createDefaultBlock([ee(d)])),i.insertBefore(d,r)}while(d=o)}return s.firstChild||X(s),r&&se(r,t),this._getRangeAndRemoveBookmark(e),this.setSelection(e),this._updatePath(e,!0),E||this._docWasChanged(),this.focus()},Ve._ensureBottomLine=function(){var e=this._root,t=e.lastElementChild;t&&t.nodeName===this._config.blockTag&&W(t)||e.appendChild(this.createDefaultBlock())},Ve.setKeyHandler=function(e,t){return this._keyHandlers[e]=t,this},Ve._getHTML=function(){return this._root.innerHTML},Ve._setHTML=function(e){var t=this._root,n=t;n.innerHTML=e;do{ne(n,t)}while(n=G(n,t));this._ignoreChange=!0},Ve.getHTML=function(e){var t,n,i,o,r,a,s=[];if(e&&(a=this.getSelection())&&this._saveRangeToBookmark(a),S)for(n=t=this._root;n=G(n,t);)n.textContent||n.querySelector("BR")||(i=this.createElement("BR"),n.appendChild(i),s.push(i));if(o=this._getHTML().replace(/\u200B/g,""),S)for(r=s.length;r--;)X(s[r]);return a&&this._getRangeAndRemoveBookmark(a),o},Ve.setHTML=function(e){var t,n,i,o=this._config,r=o.isSetHTMLSanitized?o.sanitizeToDOMFragment:null,a=this._root;"function"==typeof r?n=r(e,!1,this):((t=this.createElement("DIV")).innerHTML=e,(n=this._doc.createDocumentFragment()).appendChild(ee(t))),we(n,o),We(n,a,!1),ie(n,a);for(var s=n;s=G(s,a);)ne(s,a);for(this._ignoreChange=!0;i=a.lastChild;)a.removeChild(i);a.appendChild(n),ne(a,a),this._undoIndex=-1,this._undoStack.length=0,this._undoStackLength=0,this._isInUndoState=!1;var d=this._getRangeAndRemoveBookmark()||this.createRange(a.firstChild,0);return this.saveUndoState(d),this._lastSelection=d,et.call(this),this._updatePath(d,!0),this},Ve.insertElement=function(e,t){if(t||(t=this.getSelection()),t.collapse(!0),H(e))ce(t,e),t.setStartAfter(e);else{for(var n,i=this._root,o=ve(t,i)||i;o!==i&&!o.nextSibling;)o=o.parentNode;o!==i&&(n=oe(o.parentNode,o.nextSibling,i,i)),n?i.insertBefore(e,n):(i.appendChild(e),n=this.createDefaultBlock(),i.appendChild(n)),t.setStart(n,0),t.setEnd(n,0),ge(t)}return this.focus(),this.setSelection(t),this._updatePath(t),E||this._docWasChanged(),this},Ve.insertImage=function(e,t){var n=this.createElement("IMG",$e({src:e},t,!0));return this.insertElement(n),n},Ve.linkRegExp=/\b(?:((?:(?:ht|f)tps?:\/\/|www\d{0,3}[.]|[a-z0-9][a-z0-9.\-]*[.][a-z]{2,}\/)(?:[^\s()<>]+|\([^\s()<>]+\))+(?:[^\s?&`!()\[\]{};:'".,<>«»“”‘’]|\([^\s()<>]+\)))|([\w\-.%+]+@(?:[\w\-]+\.)+[a-z]{2,}\b(?:[?][^&?\s]+=[^\s?&`!()\[\]{};:'".,<>«»“”‘’]+(?:&[^&?\s]+=[^\s?&`!()\[\]{};:'".,<>«»“”‘’]+)*)?))/i;var ht=function(e,t,n){var i,o,r,a,s,d,l,c=e.ownerDocument,h=new A(e,4,function(e){return!Q(e,t,"A")}),f=n.linkRegExp,u=n._config.tagAttributes.a;if(f)for(;i=h.nextNode();)for(o=i.data,r=i.parentNode;a=f.exec(o);)d=(s=a.index)+a[0].length,s&&(l=c.createTextNode(o.slice(0,s)),r.insertBefore(l,i)),(l=n.createElement("A",$e({href:a[1]?/^(?:ht|f)tps?:/i.test(a[1])?a[1]:"http://"+a[1]:"mailto:"+a[0]},u,!1))).textContent=o.slice(s,d),r.insertBefore(l,i),i.data=o=o.slice(d)};Ve.insertHTML=function(e,t){var n,i,o,r,a,s,d,l=this._config,c=l.isInsertedHTMLSanitized?l.sanitizeToDOMFragment:null,h=this.getSelection(),f=this._doc;"function"==typeof c?r=c(e,t,this):(t&&(n=e.indexOf("\x3c!--StartFragment--\x3e"),i=e.lastIndexOf("\x3c!--EndFragment--\x3e"),n>-1&&i>-1&&(e=e.slice(n+20,i))),/<\/td>((?!<\/tr>)[\s\S])*$/i.test(e)&&(e="<TR>"+e+"</TR>"),/<\/tr>((?!<\/table>)[\s\S])*$/i.test(e)&&(e="<TABLE>"+e+"</TABLE>"),(o=this.createElement("DIV")).innerHTML=e,(r=f.createDocumentFragment()).appendChild(ee(o))),this.saveUndoState(h);try{for(a=this._root,s=r,d={fragment:r,preventDefault:function(){this.defaultPrevented=!0},defaultPrevented:!1},ht(r,r,this),we(r,l),We(r,a,!1),Fe(r),r.normalize();s=G(s,r);)ne(s,a);t&&this.fireEvent("willPaste",d),d.defaultPrevented||(ue(h,d.fragment,a),E||this._docWasChanged(),h.collapse(!1),this._ensureBottomLine()),this.setSelection(h),this._updatePath(h,!0),t&&this.focus()}catch(e){this.didError(e)}return this};var ft=function(e){return e.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;").split('"').join("&quot;")};Ve.insertPlainText=function(e,t){var n=this.getSelection();if(n.collapsed&&Q(n.startContainer,this._root,"PRE")){var o,r,a=n.startContainer,s=n.startOffset;return a&&a.nodeType===i||(o=this._doc.createTextNode(""),a.insertBefore(o,a.childNodes[s]),a=o,s=0),r={text:e,preventDefault:function(){this.defaultPrevented=!0},defaultPrevented:!1},t&&this.fireEvent("willPaste",r),r.defaultPrevented||(e=r.text,a.insertData(s,e),n.setStart(a,s+e.length),n.collapse(!0)),this.setSelection(n),this}var d,l,c,h,f=e.split("\n"),u=this._config,p=u.blockTag,g=u.blockAttributes,m="</"+p+">",v="<"+p;for(d in g)v+=" "+d+'="'+ft(g[d])+'"';for(v+=">",l=1,c=f.length;l<c;l+=1)h=f[l],h=ft(h).replace(/ (?= )/g,"&nbsp;"),f[l]=v+(h||"<BR>")+m;return this.insertHTML(f.join(""),t)};var ut=function(e,t,n){return function(){return this[e](t,n),this.focus()}};Ve.addStyles=function(e){if(e){var t=this._doc.documentElement.firstChild,n=this.createElement("STYLE",{type:"text/css"});n.appendChild(this._doc.createTextNode(e)),t.appendChild(n)}return this},Ve.bold=ut("changeFormat",{tag:"B"}),Ve.italic=ut("changeFormat",{tag:"I"}),Ve.underline=ut("changeFormat",{tag:"U"}),Ve.strikethrough=ut("changeFormat",{tag:"S"}),Ve.subscript=ut("changeFormat",{tag:"SUB"},{tag:"SUP"}),Ve.superscript=ut("changeFormat",{tag:"SUP"},{tag:"SUB"}),Ve.removeBold=ut("changeFormat",null,{tag:"B"}),Ve.removeItalic=ut("changeFormat",null,{tag:"I"}),Ve.removeUnderline=ut("changeFormat",null,{tag:"U"}),Ve.removeStrikethrough=ut("changeFormat",null,{tag:"S"}),Ve.removeSubscript=ut("changeFormat",null,{tag:"SUB"}),Ve.removeSuperscript=ut("changeFormat",null,{tag:"SUP"}),Ve.makeLink=function(e,t){var n=this.getSelection();if(n.collapsed){var i=e.indexOf(":")+1;if(i)for(;"/"===e[i];)i+=1;ce(n,this._doc.createTextNode(e.slice(i)))}return t=$e($e({href:e},t,!0),this._config.tagAttributes.a,!1),this.changeFormat({tag:"A",attributes:t},{tag:"A"},n),this.focus()},Ve.removeLink=function(){return this.changeFormat(null,{tag:"A"},this.getSelection(),!0),this.focus()},Ve.setFontFace=function(e){var t=this._config.classNames.fontFamily;return this.changeFormat(e?{tag:"SPAN",attributes:{class:t,style:"font-family: "+e+", sans-serif;"}}:null,{tag:"SPAN",attributes:{class:t}}),this.focus()},Ve.setFontSize=function(e){var t=this._config.classNames.fontSize;return this.changeFormat(e?{tag:"SPAN",attributes:{class:t,style:"font-size: "+("number"==typeof e?e+"px":e)}}:null,{tag:"SPAN",attributes:{class:t}}),this.focus()},Ve.setTextColour=function(e){var t=this._config.classNames.colour;return this.changeFormat(e?{tag:"SPAN",attributes:{class:t,style:"color:"+e}}:null,{tag:"SPAN",attributes:{class:t}}),this.focus()},Ve.setHighlightColour=function(e){var t=this._config.classNames.highlight;return this.changeFormat(e?{tag:"SPAN",attributes:{class:t,style:"background-color:"+e}}:e,{tag:"SPAN",attributes:{class:t}}),this.focus()},Ve.setTextAlignment=function(e){return this.forEachBlock(function(t){var n=t.className.split(/\s+/).filter(function(e){return!!e&&!/^align/.test(e)}).join(" ");e?(t.className=n+" align-"+e,t.style.textAlign=e):(t.className=n,t.style.textAlign="")},!0),this.focus()},Ve.setTextDirection=function(e){return this.forEachBlock(function(t){e?t.dir=e:t.removeAttribute("dir")},!0),this.focus()};var pt=function(e){for(var t,n=this._root,i=this._doc,o=i.createDocumentFragment(),r=q(e,n);t=r.nextNode();){var a,s,d=t.querySelectorAll("BR"),l=[],c=d.length;for(a=0;a<c;a+=1)l[a]=He(d[a],!1);for(;c--;)s=d[c],l[c]?J(s,i.createTextNode("\n")):X(s);for(c=(d=t.querySelectorAll("CODE")).length;c--;)X(d[c]);o.childNodes.length&&o.appendChild(i.createTextNode("\n")),o.appendChild(ee(t))}for(r=new A(o,4);t=r.nextNode();)t.data=t.data.replace(/ /g," ");return o.normalize(),ne(this.createElement("PRE",this._config.tagAttributes.pre,[o]),n)},gt=function(e){for(var t,n,i,o,r,a,s=this._doc,d=this._root,l=e.querySelectorAll("PRE"),c=l.length;c--;){for(n=new A(t=l[c],4);i=n.nextNode();){for(o=(o=i.data).replace(/ (?= )/g," "),r=s.createDocumentFragment();(a=o.indexOf("\n"))>-1;)r.appendChild(s.createTextNode(o.slice(0,a))),r.appendChild(s.createElement("BR")),o=o.slice(a+1);i.parentNode.insertBefore(r,i),i.data=o}ie(t,d),J(t,ee(t))}return e};Ve.code=function(){var e=this.getSelection();return e.collapsed||z(e.commonAncestorContainer)?this.modifyBlocks(pt,e):this.changeFormat({tag:"CODE",attributes:this._config.tagAttributes.code},null,e),this.focus()},Ve.removeCode=function(){var e=this.getSelection();return Q(e.commonAncestorContainer,this._root,"PRE")?this.modifyBlocks(gt,e):this.changeFormat(null,{tag:"CODE"},e),this.focus()},Ve.toggleCode=function(){return this.hasFormat("PRE")||this.hasFormat("CODE")?this.removeCode():this.code(),this},Ve.removeAllFormatting=function(e){if(!e&&!(e=this.getSelection())||e.collapsed)return this;for(var t=this._root,n=e.commonAncestorContainer;n&&!W(n);)n=n.parentNode;if(n||(ye(e,t),n=t),n.nodeType===i)return this;this.saveUndoState(e),me(e,n,n,t);for(var o,r,a=n.ownerDocument,s=e.startContainer,d=e.startOffset,l=e.endContainer,c=e.endOffset,h=a.createDocumentFragment(),f=a.createDocumentFragment(),u=oe(l,c,n,t),p=oe(s,d,n,t);p!==u;)o=p.nextSibling,h.appendChild(p),p=o;return function e(t,n,o){var r,a;for(r=n.firstChild;r;r=a){if(a=r.nextSibling,H(r)){if(r.nodeType===i||"BR"===r.nodeName||"IMG"===r.nodeName){o.appendChild(r);continue}}else if(W(r)){o.appendChild(t.createDefaultBlock([e(t,r,t._doc.createDocumentFragment())]));continue}e(t,r,o)}return o}(this,h,f),f.normalize(),p=f.firstChild,o=f.lastChild,r=n.childNodes,p?(n.insertBefore(f,u),d=x.call(r,p),c=x.call(r,o)+1):c=d=x.call(r,u),e.setStart(n,d),e.setEnd(n,c),re(n,e),ge(e),this.setSelection(e),this._updatePath(e,!0),this.focus()},Ve.increaseQuoteLevel=ut("modifyBlocks",function(e){return this.createElement("BLOCKQUOTE",this._config.tagAttributes.blockquote,[e])}),Ve.decreaseQuoteLevel=ut("modifyBlocks",st),Ve.makeUnorderedList=ut("modifyBlocks",function(e){return lt(this,e,"UL"),e}),Ve.makeOrderedList=ut("modifyBlocks",function(e){return lt(this,e,"OL"),e}),Ve.removeList=ut("modifyBlocks",function(e){var t,n,i,o,r,a=e.querySelectorAll("UL, OL"),s=e.querySelectorAll("LI"),d=this._root;for(t=0,n=a.length;t<n;t+=1)ie(o=ee(i=a[t]),d),J(i,o);for(t=0,n=s.length;t<n;t+=1)W(r=s[t])?J(r,this.createDefaultBlock([ee(r)])):(ie(r,d),J(r,ee(r)));return e}),Qe.isInline=H,Qe.isBlock=W,Qe.isContainer=z,Qe.getBlockWalker=q,Qe.getPreviousBlock=K,Qe.getNextBlock=G,Qe.areAlike=j,Qe.hasTagAttributes=$,Qe.getNearest=Q,Qe.isOrContains=V,Qe.detach=X,Qe.replaceWith=J,Qe.empty=ee,Qe.getNodeBefore=de,Qe.getNodeAfter=le,Qe.insertNodeInRange=ce,Qe.extractContentsOfRange=he,Qe.deleteContentsOfRange=fe,Qe.insertTreeFragmentIntoRange=ue,Qe.isNodeContainedInRange=pe,Qe.moveRangeBoundariesDownTree=ge,Qe.moveRangeBoundariesUpTree=me,Qe.getStartBlockOfRange=ve,Qe.getEndBlockOfRange=_e,Qe.contentWalker=Ce,Qe.rangeDoesStartAtBlockBoundary=Ne,Qe.rangeDoesEndAtBlockBoundary=Se,Qe.expandRangeToBlockBoundaries=ye,Qe.onPaste=Ze,Qe.addLinks=ht,Qe.splitBlock=at,Qe.startSelectionId="squire-selection-start",Qe.endSelectionId=ot,"object"==typeof exports?module.exports=Qe:"function"==typeof define&&define.amd?define(function(){return Qe}):(d.Squire=Qe,top!==d&&"true"===e.documentElement.getAttribute("data-squireinit")&&(d.editor=new Qe(e),d.onEditorLoad&&(d.onEditorLoad(d.editor),d.onEditorLoad=null)))}(document);
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import pyrotein as pr # Give a name to the analysis... job_name = "xfam" drc_i = f"{job_name}.psa.i" drc_o = f"{job_name}.psa.o" fl_dat = f"{job_name}.req_refine.dat" lines = pr.utils.read_file(fl_dat) def fli_for_needle(pdb, chain): return [ f"tmp.{pdb}_{chain}.fasta", ] def flo_from_needle(pdb, chain): return [ f"out.{pdb}_{chain}.aln.txt", f"out.{pdb}_{chain}.bsequence.txt", f"out.{pdb}_{chain}.asequence.txt", f"out.{pdb}_{chain}.submission.params", ] for line in lines: pdb, chain = line for fl in fli_for_needle(pdb, chain): path_fl = os.path.join(drc_i, fl) print(f"Removing {path_fl}") if os.path.exists(path_fl): os.remove(path_fl) for fl in flo_from_needle(pdb, chain): path_fl = os.path.join(drc_o, fl) print(f"Removing {path_fl}") if os.path.exists(path_fl): os.remove(path_fl)
import os NAME='alarm_speech' uwsgi_os = os.uname()[0] LDFLAGS = [] if uwsgi_os == "Darwin": CFLAGS = [] LIBS = ['-framework appkit'] else: CFLAGS = ['-I /usr/include/GNUstep'] LIBS = [] GCC_LIST = ['alarm_speech.m']
from io import BytesIO, StringIO import multiprocessing import os from pathlib import Path import shutil import subprocess import sys import warnings import numpy as np import pytest from matplotlib.font_manager import ( findfont, findSystemFonts, FontProperties, fontManager, json_dump, json_load, get_font, get_fontconfig_fonts, is_opentype_cff_font, MSUserFontDirectories, _call_fc_list) from matplotlib import pyplot as plt, rc_context has_fclist = shutil.which('fc-list') is not None def test_font_priority(): with rc_context(rc={ 'font.sans-serif': ['cmmi10', 'Bitstream Vera Sans']}): font = findfont(FontProperties(family=["sans-serif"])) assert Path(font).name == 'cmmi10.ttf' # Smoketest get_charmap, which isn't used internally anymore font = get_font(font) cmap = font.get_charmap() assert len(cmap) == 131 assert cmap[8729] == 30 def test_score_weight(): assert 0 == fontManager.score_weight("regular", "regular") assert 0 == fontManager.score_weight("bold", "bold") assert (0 < fontManager.score_weight(400, 400) < fontManager.score_weight("normal", "bold")) assert (0 < fontManager.score_weight("normal", "regular") < fontManager.score_weight("normal", "bold")) assert (fontManager.score_weight("normal", "regular") == fontManager.score_weight(400, 400)) def test_json_serialization(tmpdir): # Can't open a NamedTemporaryFile twice on Windows, so use a temporary # directory instead. path = Path(tmpdir, "fontlist.json") json_dump(fontManager, path) copy = json_load(path) with warnings.catch_warnings(): warnings.filterwarnings('ignore', 'findfont: Font family.*not found') for prop in ({'family': 'STIXGeneral'}, {'family': 'Bitstream Vera Sans', 'weight': 700}, {'family': 'no such font family'}): fp = FontProperties(**prop) assert (fontManager.findfont(fp, rebuild_if_missing=False) == copy.findfont(fp, rebuild_if_missing=False)) def test_otf(): fname = '/usr/share/fonts/opentype/freefont/FreeMono.otf' if Path(fname).exists(): assert is_opentype_cff_font(fname) for f in fontManager.ttflist: if 'otf' in f.fname: with open(f.fname, 'rb') as fd: res = fd.read(4) == b'OTTO' assert res == is_opentype_cff_font(f.fname) @pytest.mark.skipif(not has_fclist, reason='no fontconfig installed') def test_get_fontconfig_fonts(): assert len(get_fontconfig_fonts()) > 1 @pytest.mark.parametrize('factor', [2, 4, 6, 8]) def test_hinting_factor(factor): font = findfont(FontProperties(family=["sans-serif"])) font1 = get_font(font, hinting_factor=1) font1.clear() font1.set_size(12, 100) font1.set_text('abc') expected = font1.get_width_height() hinted_font = get_font(font, hinting_factor=factor) hinted_font.clear() hinted_font.set_size(12, 100) hinted_font.set_text('abc') # Check that hinting only changes text layout by a small (10%) amount. np.testing.assert_allclose(hinted_font.get_width_height(), expected, rtol=0.1) def test_utf16m_sfnt(): try: # seguisbi = Microsoft Segoe UI Semibold entry = next(entry for entry in fontManager.ttflist if Path(entry.fname).name == "seguisbi.ttf") except StopIteration: pytest.skip("Couldn't find font to test against.") else: # Check that we successfully read "semibold" from the font's sfnt table # and set its weight accordingly. assert entry.weight == 600 def test_find_ttc(): fp = FontProperties(family=["WenQuanYi Zen Hei"]) if Path(findfont(fp)).name != "wqy-zenhei.ttc": pytest.skip("Font may be missing") fig, ax = plt.subplots() ax.text(.5, .5, "\N{KANGXI RADICAL DRAGON}", fontproperties=fp) for fmt in ["raw", "svg", "pdf", "ps"]: fig.savefig(BytesIO(), format=fmt) def test_find_invalid(tmpdir): tmp_path = Path(tmpdir) with pytest.raises(FileNotFoundError): get_font(tmp_path / 'non-existent-font-name.ttf') with pytest.raises(FileNotFoundError): get_font(str(tmp_path / 'non-existent-font-name.ttf')) with pytest.raises(FileNotFoundError): get_font(bytes(tmp_path / 'non-existent-font-name.ttf')) # Not really public, but get_font doesn't expose non-filename constructor. from matplotlib.ft2font import FT2Font with pytest.raises(TypeError, match='path or binary-mode file'): FT2Font(StringIO()) @pytest.mark.skipif(sys.platform != 'linux', reason='Linux only') def test_user_fonts_linux(tmpdir, monkeypatch): font_test_file = 'mpltest.ttf' # Precondition: the test font should not be available fonts = findSystemFonts() if any(font_test_file in font for font in fonts): pytest.skip(f'{font_test_file} already exists in system fonts') # Prepare a temporary user font directory user_fonts_dir = tmpdir.join('fonts') user_fonts_dir.ensure(dir=True) shutil.copyfile(Path(__file__).parent / font_test_file, user_fonts_dir.join(font_test_file)) with monkeypatch.context() as m: m.setenv('XDG_DATA_HOME', str(tmpdir)) _call_fc_list.cache_clear() # Now, the font should be available fonts = findSystemFonts() assert any(font_test_file in font for font in fonts) # Make sure the temporary directory is no longer cached. _call_fc_list.cache_clear() @pytest.mark.skipif(sys.platform != 'win32', reason='Windows only') def test_user_fonts_win32(): if not (os.environ.get('APPVEYOR') or os.environ.get('TF_BUILD')): pytest.xfail("This test should only run on CI (appveyor or azure) " "as the developer's font directory should remain " "unchanged.") font_test_file = 'mpltest.ttf' # Precondition: the test font should not be available fonts = findSystemFonts() if any(font_test_file in font for font in fonts): pytest.skip(f'{font_test_file} already exists in system fonts') user_fonts_dir = MSUserFontDirectories[0] # Make sure that the user font directory exists (this is probably not the # case on Windows versions < 1809) os.makedirs(user_fonts_dir) # Copy the test font to the user font directory shutil.copy(Path(__file__).parent / font_test_file, user_fonts_dir) # Now, the font should be available fonts = findSystemFonts() assert any(font_test_file in font for font in fonts) def _model_handler(_): fig, ax = plt.subplots() fig.savefig(BytesIO(), format="pdf") plt.close() @pytest.mark.skipif(not hasattr(os, "register_at_fork"), reason="Cannot register at_fork handlers") def test_fork(): _model_handler(0) # Make sure the font cache is filled. ctx = multiprocessing.get_context("fork") with ctx.Pool(processes=2) as pool: pool.map(_model_handler, range(2)) def test_missing_family(caplog): plt.rcParams["font.sans-serif"] = ["this-font-does-not-exist"] with caplog.at_level("WARNING"): findfont("sans") assert [rec.getMessage() for rec in caplog.records] == [ "findfont: Font family ['sans'] not found. " "Falling back to DejaVu Sans.", "findfont: Generic family 'sans' not found because none of the " "following families were found: this-font-does-not-exist", ] def _test_threading(): import threading from matplotlib.ft2font import LOAD_NO_HINTING import matplotlib.font_manager as fm N = 10 b = threading.Barrier(N) def bad_idea(n): b.wait() for j in range(100): font = fm.get_font(fm.findfont("DejaVu Sans")) font.set_text(str(n), 0.0, flags=LOAD_NO_HINTING) threads = [ threading.Thread(target=bad_idea, name=f"bad_thread_{j}", args=(j,)) for j in range(N) ] for t in threads: t.start() for t in threads: t.join() def test_fontcache_thread_safe(): pytest.importorskip('threading') import inspect proc = subprocess.run( [sys.executable, "-c", inspect.getsource(_test_threading) + '\n_test_threading()'] ) if proc.returncode: pytest.fail("The subprocess returned with non-zero exit status " f"{proc.returncode}.")
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # 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. # ############################################################################### import asyncio import binascii import os import uuid from autobahn.wamp.types import RegisterOptions, CallDetails from autobahn.wamp.exception import ApplicationError, TransportLost from autobahn.wamp.protocol import ApplicationSession from ._util import unpack_uint256, pack_uint256 from txaio import time_ns import cbor2 import eth_keys import nacl.secret import nacl.utils import nacl.public import txaio from ._util import hl, hlval from ._eip712_channel_close import sign_eip712_channel_close, recover_eip712_channel_close class KeySeries(object): """ Data encryption key series with automatic (time-based) key rotation and key offering (to the XBR market maker). """ def __init__(self, api_id, price, interval=None, count=None, on_rotate=None): """ :param api_id: ID of the API for which to generate keys. :type api_id: bytes :param price: Price per key in key series. :type price: int :param interval: Interval in seconds after which to auto-rotate key. :type interval: int :param count: Number of encryption operations after which to auto-rotate key. :type count: int :param on_rotate: Optional user callback fired after key was rotated. :type on_rotate: callable """ assert type(api_id) == bytes and len(api_id) == 16 assert type(price) == int and price >= 0 assert interval is None or (type(interval) == int and interval > 0) assert count is None or (type(count) == int and count > 0) assert (interval is None and count is not None) or (interval is not None and count is None) assert on_rotate is None or callable(on_rotate) self._api_id = api_id self._price = price self._interval = interval self._count = count self._count_current = 0 self._on_rotate = on_rotate self._id = None self._key = None self._box = None self._archive = {} @property def key_id(self): """ Get current XBR data encryption key ID (of the keys being rotated in a series). :return: Current key ID in key series (16 bytes). :rtype: bytes """ return self._id async def encrypt(self, payload): """ Encrypt data with the current XBR data encryption key. :param payload: Application payload to encrypt. :type payload: object :return: The ciphertext for the encrypted application payload. :rtype: bytes """ data = cbor2.dumps(payload) if self._count is not None: self._count_current += 1 if self._count_current >= self._count: await self._rotate() self._count_current = 0 ciphertext = self._box.encrypt(data) return self._id, 'cbor', ciphertext def encrypt_key(self, key_id, buyer_pubkey): """ Encrypt a (previously used) XBR data encryption key with a buyer public key. :param key_id: ID of the data encryption key to encrypt. :type key_id: bytes :param buyer_pubkey: Buyer WAMP public key (Ed25519) to asymmetrically encrypt the data encryption key (selected by ``key_id``) against. :type buyer_pubkey: bytes :return: The ciphertext for the encrypted data encryption key. :rtype: bytes """ assert type(key_id) == bytes and len(key_id) == 16 assert type(buyer_pubkey) == bytes and len(buyer_pubkey) == 32 key, _ = self._archive[key_id] sendkey_box = nacl.public.SealedBox(nacl.public.PublicKey(buyer_pubkey, encoder=nacl.encoding.RawEncoder)) encrypted_key = sendkey_box.encrypt(key, encoder=nacl.encoding.RawEncoder) return encrypted_key def start(self): raise NotImplementedError() def stop(self): raise NotImplementedError() async def _rotate(self): # generate new ID for next key in key series self._id = os.urandom(16) # generate next data encryption key in key series self._key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE) # create secretbox from new key self._box = nacl.secret.SecretBox(self._key) # add key to archive self._archive[self._id] = (self._key, self._box) self.log.debug( '{tx_type} key "{key_id}" rotated [api_id="{api_id}"]', tx_type=hl('XBR ROTATE', color='magenta'), key_id=hl(uuid.UUID(bytes=self._id)), api_id=hl(uuid.UUID(bytes=self._api_id))) # maybe fire user callback if self._on_rotate: await self._on_rotate(self) class PayingChannel(object): def __init__(self, adr, seq, balance): assert type(adr) == bytes and len(adr) == 16 assert type(seq) == int and seq >= 0 assert type(balance) == int and balance >= 0 self._adr = adr self._seq = seq self._balance = balance class SimpleSeller(object): log = None KeySeries = None STATE_NONE = 0 STATE_STARTING = 1 STATE_STARTED = 2 STATE_STOPPING = 3 STATE_STOPPED = 4 def __init__(self, market_maker_adr, seller_key, provider_id=None): """ :param market_maker_adr: Market maker public Ethereum address (20 bytes). :type market_maker_adr: bytes :param seller_key: Seller (delegate) private Ethereum key (32 bytes). :type seller_key: bytes :param provider_id: Optional explicit data provider ID. When not given, the seller delegate public WAMP key (Ed25519 in Hex) is used as the provider ID. This must be a valid WAMP URI part. :type provider_id: string """ assert type(market_maker_adr) == bytes and len(market_maker_adr) == 20, 'market_maker_adr must be bytes[20], but got "{}"'.format(market_maker_adr) assert type(seller_key) == bytes and len(seller_key) == 32, 'seller delegate must be bytes[32], but got "{}"'.format(seller_key) assert provider_id is None or type(provider_id) == str, 'provider_id must be None or string, but got "{}"'.format(provider_id) self.log = txaio.make_logger() # current seller state self._state = SimpleSeller.STATE_NONE # market maker address self._market_maker_adr = market_maker_adr self._xbrmm_config = None # seller raw ethereum private key (32 bytes) self._pkey_raw = seller_key # seller ethereum private key object self._pkey = eth_keys.keys.PrivateKey(seller_key) # seller ethereum private account from raw private key # FIXME # self._acct = Account.privateKeyToAccount(self._pkey) self._acct = None # seller ethereum account canonical address self._addr = self._pkey.public_key.to_canonical_address() # seller ethereum account canonical checksummed address # FIXME # self._caddr = web3.Web3.toChecksumAddress(self._addr) self._caddr = None # seller provider ID self._provider_id = provider_id or str(self._pkey.public_key) self._channels = {} # will be filled with on-chain payment channel contract, once started self._channel = None # channel current (off-chain) balance self._balance = 0 # channel sequence number self._seq = 0 self._keys = {} self._keys_map = {} # after start() is running, these will be set self._session = None self._session_regs = None @property def public_key(self): """ This seller delegate public Ethereum key. :return: Ethereum public key of this seller delegate. :rtype: bytes """ return self._pkey.public_key def add(self, api_id, prefix, price, interval=None, count=None, categories=None): """ Add a new (rotating) private encryption key for encrypting data on the given API. :param api_id: API for which to create a new series of rotating encryption keys. :type api_id: bytes :param price: Price in XBR token per key. :type price: int :param interval: Interval (in seconds) after which to auto-rotate the encryption key. :type interval: int :param count: Number of encryption operations after which to auto-rotate the encryption key. :type count: int """ assert type(api_id) == bytes and len(api_id) == 16 and api_id not in self._keys assert type(price) == int and price >= 0 assert interval is None or (type(interval) == int and interval > 0) assert count is None or (type(count) == int and count > 0) assert (interval is None and count is not None) or (interval is not None and count is None) assert categories is None or (type(categories) == dict and (type(k) == str for k in categories.keys()) and (type(v) == str for v in categories.values())), 'invalid categories type (must be dict) or category key or value type (must both be string)' async def on_rotate(key_series): key_id = key_series.key_id self._keys_map[key_id] = key_series # FIXME: expose the knobs hard-coded in below .. # offer the key to the market maker (retry 5x in specific error cases) retries = 5 while retries: try: valid_from = time_ns() - 10 * 10 ** 9 delegate = self._addr # FIXME: sign the supplied offer information using self._pkey signature = os.urandom(65) provider_id = self._provider_id offer = await self._session.call('xbr.marketmaker.place_offer', key_id, api_id, prefix, valid_from, delegate, signature, privkey=None, price=pack_uint256(price) if price is not None else None, categories=categories, expires=None, copies=None, provider_id=provider_id) self.log.debug( '{tx_type} key "{key_id}" offered for {price} [api_id={api_id}, prefix="{prefix}", delegate="{delegate}"]', tx_type=hl('XBR OFFER ', color='magenta'), key_id=hl(uuid.UUID(bytes=key_id)), api_id=hl(uuid.UUID(bytes=api_id)), price=hl(str(int(price / 10 ** 18) if price is not None else 0) + ' XBR', color='magenta'), delegate=hl(binascii.b2a_hex(delegate).decode()), prefix=hl(prefix)) self.log.debug('offer={offer}', offer=offer) break except ApplicationError as e: if e.error == 'wamp.error.no_such_procedure': self.log.warn('xbr.marketmaker.offer: procedure unavailable!') else: self.log.failure() break except TransportLost: self.log.warn('TransportLost while calling xbr.marketmaker.offer!') break except: self.log.failure() retries -= 1 self.log.warn('Failed to place offer for key! Retrying {retries}/5 ..', retries=retries) await asyncio.sleep(1) key_series = self.KeySeries(api_id, price, interval=interval, count=count, on_rotate=on_rotate) self._keys[api_id] = key_series self.log.debug('Created new key series {key_series}', key_series=key_series) return key_series async def start(self, session): """ Start rotating keys and placing key offers with the XBR market maker. :param session: WAMP session over which to communicate with the XBR market maker. :type session: :class:`autobahn.wamp.protocol.ApplicationSession` """ assert isinstance(session, ApplicationSession), 'session must be an ApplicationSession, was "{}"'.format(session) assert self._state in [SimpleSeller.STATE_NONE, SimpleSeller.STATE_STOPPED], 'seller already running' self._state = SimpleSeller.STATE_STARTING self._session = session self._session_regs = [] self.log.debug('Start selling from seller delegate address {address} (public key 0x{public_key}..)', address=hl(self._caddr), public_key=binascii.b2a_hex(self._pkey.public_key[:10]).decode()) # get the currently active (if any) paying channel for the delegate self._channel = await session.call('xbr.marketmaker.get_active_paying_channel', self._addr) if not self._channel: raise Exception('no active paying channel found') channel_oid = self._channel['channel_oid'] assert type(channel_oid) == bytes and len(channel_oid) == 16 self._channel_oid = uuid.UUID(bytes=channel_oid) procedure = 'xbr.provider.{}.sell'.format(self._provider_id) reg = await session.register(self.sell, procedure, options=RegisterOptions(details_arg='details')) self._session_regs.append(reg) self.log.debug('Registered procedure "{procedure}"', procedure=hl(reg.procedure)) procedure = 'xbr.provider.{}.close_channel'.format(self._provider_id) reg = await session.register(self.close_channel, procedure, options=RegisterOptions(details_arg='details')) self._session_regs.append(reg) self.log.debug('Registered procedure "{procedure}"', procedure=hl(reg.procedure)) for key_series in self._keys.values(): await key_series.start() self._xbrmm_config = await session.call('xbr.marketmaker.get_config') # get the current (off-chain) balance of the paying channel paying_balance = await session.call('xbr.marketmaker.get_paying_channel_balance', self._channel_oid.bytes) # FIXME if type(paying_balance['remaining']) == bytes: paying_balance['remaining'] = unpack_uint256(paying_balance['remaining']) if not paying_balance['remaining'] > 0: raise Exception('no off-chain balance remaining on paying channel') self._channels[channel_oid] = PayingChannel(channel_oid, paying_balance['seq'], paying_balance['remaining']) self._state = SimpleSeller.STATE_STARTED # FIXME self._balance = paying_balance['remaining'] if type(self._balance) == bytes: self._balance = unpack_uint256(self._balance) self._seq = paying_balance['seq'] self.log.info('Ok, seller delegate started [active paying channel {channel_oid} with remaining balance {remaining} at sequence {seq}]', channel_oid=hl(self._channel_oid), remaining=hlval(self._balance), seq=hlval(self._seq)) return paying_balance['remaining'] async def stop(self): """ Stop rotating/offering keys to the XBR market maker. """ assert self._state in [SimpleSeller.STATE_STARTED], 'seller not running' self._state = SimpleSeller.STATE_STOPPING dl = [] for key_series in self._keys.values(): d = key_series.stop() dl.append(d) if self._session_regs: if self._session and self._session.is_attached(): # voluntarily unregister interface for reg in self._session_regs: d = reg.unregister() dl.append(d) self._session_regs = None d = txaio.gather(dl) try: await d except: self.log.failure() finally: self._state = SimpleSeller.STATE_STOPPED self._session = None self.log.info('Ok, seller delegate stopped.') async def balance(self): """ Return current (off-chain) balance of paying channel: * ``amount``: The initial amount with which the paying channel was opened. * ``remaining``: The remaining amount of XBR in the paying channel that can be earned. * ``inflight``: The amount of XBR allocated to sell transactions that are currently processed. :return: Current paying balance. :rtype: dict """ if self._state not in [SimpleSeller.STATE_STARTED]: raise RuntimeError('seller not running') if not self._session or not self._session.is_attached(): raise RuntimeError('market-maker session not attached') paying_balance = await self._session.call('xbr.marketmaker.get_paying_channel_balance', self._channel['channel_oid']) return paying_balance async def wrap(self, api_id, uri, payload): """ Encrypt and wrap application payload for a given API and destined for a specific WAMP URI. :param api_id: API for which to encrypt and wrap the application payload for. :type api_id: bytes :param uri: WAMP URI the application payload is destined for (eg the procedure or topic URI). :type uri: str :param payload: Application payload to encrypt and wrap. :type payload: object :return: The encrypted and wrapped application payload: a tuple with ``(key_id, serializer, ciphertext)``. :rtype: tuple """ assert type(api_id) == bytes and len(api_id) == 16 and api_id in self._keys assert type(uri) == str assert payload is not None keyseries = self._keys[api_id] key_id, serializer, ciphertext = await keyseries.encrypt(payload) return key_id, serializer, ciphertext def close_channel(self, market_maker_adr, channel_oid, channel_seq, channel_balance, channel_is_final, marketmaker_signature, details=None): """ Called by a XBR Market Maker to close a paying channel. """ assert type(market_maker_adr) == bytes and len(market_maker_adr) == 20, 'market_maker_adr must be bytes[20], but was {}'.format(type(market_maker_adr)) assert type(channel_oid) == bytes and len(channel_oid) == 16, 'channel_oid must be bytes[16], but was {}'.format(type(channel_oid)) assert type(channel_seq) == int, 'channel_seq must be int, but was {}'.format(type(channel_seq)) assert type(channel_balance) == bytes and len(channel_balance) == 32, 'channel_balance must be bytes[32], but was {}'.format(type(channel_balance)) assert type(channel_is_final) == bool, 'channel_is_final must be bool, but was {}'.format(type(channel_is_final)) assert type(marketmaker_signature) == bytes and len(marketmaker_signature) == (32 + 32 + 1), 'marketmaker_signature must be bytes[65], but was {}'.format(type(marketmaker_signature)) assert details is None or isinstance(details, CallDetails), 'details must be autobahn.wamp.types.CallDetails' # check that the delegate_adr fits what we expect for the market maker if market_maker_adr != self._market_maker_adr: raise ApplicationError('xbr.error.unexpected_delegate_adr', '{}.sell() - unexpected market maker (delegate) address: expected 0x{}, but got 0x{}'.format(self.__class__.__name__, binascii.b2a_hex(self._market_maker_adr).decode(), binascii.b2a_hex(market_maker_adr).decode())) # FIXME: must be the currently active channel .. and we need to track all of these if channel_oid != self._channel['channel_oid']: self._session.leave() raise ApplicationError('xbr.error.unexpected_channel_oid', '{}.sell() - unexpected paying channel address: expected 0x{}, but got 0x{}'.format(self.__class__.__name__, binascii.b2a_hex(self._channel['channel_oid']).decode(), binascii.b2a_hex(channel_oid).decode())) # channel sequence number: check we have consensus on off-chain channel state with peer (which is the market maker) if channel_seq != self._seq: raise ApplicationError('xbr.error.unexpected_channel_seq', '{}.sell() - unexpected channel (after tx) sequence number: expected {}, but got {}'.format(self.__class__.__name__, self._seq + 1, channel_seq)) # channel balance: check we have consensus on off-chain channel state with peer (which is the market maker) channel_balance = unpack_uint256(channel_balance) if channel_balance != self._balance: raise ApplicationError('xbr.error.unexpected_channel_balance', '{}.sell() - unexpected channel (after tx) balance: expected {}, but got {}'.format(self.__class__.__name__, self._balance, channel_balance)) # XBRSIG: check the signature (over all input data for the buying of the key) signer_address = recover_eip712_channel_close(channel_oid, channel_seq, channel_balance, channel_is_final, marketmaker_signature) if signer_address != market_maker_adr: self.log.warn('{klass}.sell()::XBRSIG[4/8] - EIP712 signature invalid: signer_address={signer_address}, delegate_adr={delegate_adr}', klass=self.__class__.__name__, signer_address=hl(binascii.b2a_hex(signer_address).decode()), delegate_adr=hl(binascii.b2a_hex(market_maker_adr).decode())) raise ApplicationError('xbr.error.invalid_signature', '{}.sell()::XBRSIG[4/8] - EIP712 signature invalid or not signed by market maker'.format(self.__class__.__name__)) # XBRSIG: compute EIP712 typed data signature seller_signature = sign_eip712_channel_close(self._pkey_raw, channel_oid, channel_seq, channel_balance, channel_is_final) receipt = { 'delegate': self._addr, 'seq': channel_seq, 'balance': pack_uint256(channel_balance), 'is_final': channel_is_final, 'signature': seller_signature, } self.log.debug('{klass}.close_channel() - {tx_type} closing channel {channel_oid}, closing balance {channel_balance}, closing sequence {channel_seq} [caller={caller}, caller_authid="{caller_authid}"]', klass=self.__class__.__name__, tx_type=hl('XBR CLOSE ', color='magenta'), channel_balance=hl(str(int(channel_balance / 10 ** 18)) + ' XBR', color='magenta'), channel_seq=hl(channel_seq), channel_oid=hl(binascii.b2a_hex(channel_oid).decode()), caller=hl(details.caller), caller_authid=hl(details.caller_authid)) return receipt def sell(self, market_maker_adr, buyer_pubkey, key_id, channel_oid, channel_seq, amount, balance, signature, details=None): """ Called by a XBR Market Maker to buy a data encyption key. The XBR Market Maker here is acting for (triggered by) the XBR buyer delegate. :param market_maker_adr: The market maker Ethereum address. The technical buyer is usually the XBR market maker (== the XBR delegate of the XBR market operator). :type market_maker_adr: bytes of length 20 :param buyer_pubkey: The buyer delegate Ed25519 public key. :type buyer_pubkey: bytes of length 32 :param key_id: The UUID of the data encryption key to buy. :type key_id: bytes of length 16 :param channel_oid: The on-chain channel contract address. :type channel_oid: bytes of length 16 :param channel_seq: Paying channel sequence off-chain transaction number. :type channel_seq: int :param amount: The amount paid by the XBR Buyer via the XBR Market Maker. :type amount: bytes :param balance: Balance remaining in the payment channel (from the market maker to the seller) after successfully buying the key. :type balance: bytes :param signature: Signature over the supplied buying information, using the Ethereum private key of the market maker (which is the delegate of the marker operator). :type signature: bytes of length 65 :param details: Caller details. The call will come from the XBR Market Maker. :type details: :class:`autobahn.wamp.types.CallDetails` :return: The data encryption key, itself encrypted to the public key of the original buyer. :rtype: bytes """ assert type(market_maker_adr) == bytes and len(market_maker_adr) == 20, 'delegate_adr must be bytes[20]' assert type(buyer_pubkey) == bytes and len(buyer_pubkey) == 32, 'buyer_pubkey must be bytes[32]' assert type(key_id) == bytes and len(key_id) == 16, 'key_id must be bytes[16]' assert type(channel_oid) == bytes and len(channel_oid) == 16, 'channel_oid must be bytes[16]' assert type(channel_seq) == int, 'channel_seq must be int' assert type(amount) == bytes and len(amount) == 32, 'amount_paid must be bytes[32], but was {}'.format(type(amount)) assert type(balance) == bytes and len(amount) == 32, 'post_balance must be bytes[32], but was {}'.format(type(balance)) assert type(signature) == bytes and len(signature) == (32 + 32 + 1), 'signature must be bytes[65]' assert details is None or isinstance(details, CallDetails), 'details must be autobahn.wamp.types.CallDetails' amount = unpack_uint256(amount) balance = unpack_uint256(balance) # check that the delegate_adr fits what we expect for the market maker if market_maker_adr != self._market_maker_adr: raise ApplicationError('xbr.error.unexpected_marketmaker_adr', '{}.sell() - unexpected market maker address: expected 0x{}, but got 0x{}'.format(self.__class__.__name__, binascii.b2a_hex(self._market_maker_adr).decode(), binascii.b2a_hex(market_maker_adr).decode())) # get the key series given the key_id if key_id not in self._keys_map: raise ApplicationError('crossbar.error.no_such_object', '{}.sell() - no key with ID "{}"'.format(self.__class__.__name__, key_id)) key_series = self._keys_map[key_id] # FIXME: must be the currently active channel .. and we need to track all of these if channel_oid != self._channel['channel_oid']: self._session.leave() raise ApplicationError('xbr.error.unexpected_channel_oid', '{}.sell() - unexpected paying channel address: expected 0x{}, but got 0x{}'.format(self.__class__.__name__, binascii.b2a_hex(self._channel['channel_oid']).decode(), binascii.b2a_hex(channel_oid).decode())) # channel sequence number: check we have consensus on off-chain channel state with peer (which is the market maker) if channel_seq != self._seq + 1: raise ApplicationError('xbr.error.unexpected_channel_seq', '{}.sell() - unexpected channel (after tx) sequence number: expected {}, but got {}'.format(self.__class__.__name__, self._seq + 1, channel_seq)) # channel balance: check we have consensus on off-chain channel state with peer (which is the market maker) if balance != self._balance - amount: raise ApplicationError('xbr.error.unexpected_channel_balance', '{}.sell() - unexpected channel (after tx) balance: expected {}, but got {}'.format(self.__class__.__name__, self._balance - amount, balance)) # FIXME current_block_number = 1 verifying_chain_id = self._xbrmm_config['verifying_chain_id'] verifying_contract_adr = binascii.a2b_hex(self._xbrmm_config['verifying_contract_adr'][2:]) market_oid = self._channel['market_oid'] # XBRSIG[4/8]: check the signature (over all input data for the buying of the key) signer_address = recover_eip712_channel_close(verifying_chain_id, verifying_contract_adr, current_block_number, market_oid, channel_oid, channel_seq, balance, False, signature) if signer_address != market_maker_adr: self.log.warn('{klass}.sell()::XBRSIG[4/8] - EIP712 signature invalid: signer_address={signer_address}, delegate_adr={delegate_adr}', klass=self.__class__.__name__, signer_address=hl(binascii.b2a_hex(signer_address).decode()), delegate_adr=hl(binascii.b2a_hex(market_maker_adr).decode())) raise ApplicationError('xbr.error.invalid_signature', '{}.sell()::XBRSIG[4/8] - EIP712 signature invalid or not signed by market maker'.format(self.__class__.__name__)) # now actually update our local knowledge of the channel state # FIXME: what if code down below fails? self._seq += 1 self._balance -= amount # encrypt the data encryption key against the original buyer delegate Ed25519 public key sealed_key = key_series.encrypt_key(key_id, buyer_pubkey) assert type(sealed_key) == bytes and len(sealed_key) == 80, '{}.sell() - unexpected sealed key computed (expected bytes[80]): {}'.format(self.__class__.__name__, sealed_key) # XBRSIG[5/8]: compute EIP712 typed data signature seller_signature = sign_eip712_channel_close(self._pkey_raw, verifying_chain_id, verifying_contract_adr, current_block_number, market_oid, channel_oid, self._seq, self._balance, False) receipt = { # key ID that has been bought 'key_id': key_id, # seller delegate address that sold the key 'delegate': self._addr, # buyer delegate Ed25519 public key with which the bought key was sealed 'buyer_pubkey': buyer_pubkey, # finally return what the consumer (buyer) was actually interested in: # the data encryption key, sealed (public key Ed25519 encrypted) to the # public key of the buyer delegate 'sealed_key': sealed_key, # paying channel off-chain transaction sequence numbers 'channel_seq': self._seq, # amount paid for the key 'amount': amount, # paying channel amount remaining 'balance': self._balance, # seller (delegate) signature 'signature': seller_signature, } self.log.info('{klass}.sell() - {tx_type} key "{key_id}" sold for {amount_earned} - balance is {balance} [caller={caller}, caller_authid="{caller_authid}", buyer_pubkey="{buyer_pubkey}"]', klass=self.__class__.__name__, tx_type=hl('XBR SELL ', color='magenta'), key_id=hl(uuid.UUID(bytes=key_id)), amount_earned=hl(str(int(amount / 10 ** 18)) + ' XBR', color='magenta'), balance=hl(str(int(self._balance / 10 ** 18)) + ' XBR', color='magenta'), # paying_channel=hl(binascii.b2a_hex(paying_channel).decode()), caller=hl(details.caller), caller_authid=hl(details.caller_authid), buyer_pubkey=hl(binascii.b2a_hex(buyer_pubkey).decode())) return receipt
symbols = [] exports = [{'type': 'function', 'name': 'generateMessageBusUniqueId', 'address': '0x7ffb2227fc60'}, {'type': 'function', 'name': 'getMessageBusInterface', 'address': '0x7ffb2227fd40'}, {'type': 'function', 'name': 'getMessageBusInterfaceWithConfig', 'address': '0x7ffb2227fd50'}, {'type': 'function', 'name': 'getSharedMessageBusInterface', 'address': '0x7ffb2227feb0'}, {'type': 'function', 'name': 'getSharedMessageBusInterfaceWithConfig', 'address': '0x7ffb2227fec0'}, {'type': 'function', 'name': 'messageBusAddObserver', 'address': '0x7ffb22282930'}, {'type': 'function', 'name': 'messageBusDelete', 'address': '0x7ffb22282940'}, {'type': 'function', 'name': 'messageBusNew', 'address': '0x7ffb22282960'}, {'type': 'function', 'name': 'messageBusPostEncryptedMessage', 'address': '0x7ffb222829d0'}, {'type': 'function', 'name': 'messageBusPostMessage', 'address': '0x7ffb22282a00'}, {'type': 'function', 'name': 'messageBusRemoveObserver', 'address': '0x7ffb22282a30'}, {'type': 'function', 'name': 'releaseMessageBusInterface', 'address': '0x7ffb222802f0'}]
/* global angular:false */ "use strict"; const app = angular.module("TodoApp", []);
// @ts-check 'use strict'; const CircularDependencyPlugin = require('circular-dependency-plugin'); const path = require('path'); const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin'); /** @type {import('webpack').Configuration} */ const config = { target: 'node', // vscode extensions run in a Node.js-context 📖 -> https://webpack.js.org/configuration/node/ entry: './src/extension.ts', // the entry point of this extension, 📖 -> https://webpack.js.org/configuration/entry-context/ output: { // the bundle is stored in the 'dist' folder (check package.json), 📖 -> https://webpack.js.org/configuration/output/ path: path.resolve(__dirname, 'dist'), filename: 'extension.js', libraryTarget: 'commonjs2', devtoolModuleFilenameTemplate: '../[resource-path]' }, devtool: 'source-map', externals: { vscode: 'commonjs vscode' // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed, 📖 -> https://webpack.js.org/configuration/externals/ }, resolve: { // support reading TypeScript and JavaScript files, 📖 -> https://github.com/TypeStrong/ts-loader extensions: ['.ts', '.js'], plugins: [ new TsconfigPathsPlugin() ] }, module: { rules: [ { test: /\.ts$/, exclude: /node_modules/, use: [ { loader: 'ts-loader' } ] } ] }, node: { __dirname: false }, plugins: [ new CircularDependencyPlugin({ // exclude detection of files based on a RegExp exclude: /a\.js|node_modules/, // add errors to webpack instead of warnings failOnError: true, // allow import cycles that include an asyncronous import, // e.g. via import(/* webpackMode: "weak" */ './file.js') allowAsyncCycles: false, // set the current working directory for displaying module paths cwd: process.cwd() }) ] }; module.exports = config;
export const getStyles = (rule, ownRules, matchedRules) => [...ownRules, ...matchedRules] .map(r => r.style[rule]) .filter(style => style !== undefined && style !== '') export const getGapValue = (unit, size) => { if (size.endsWith(unit)) { return Number(size.slice(0, -1 * unit.length)) } return null } export const firstNonZero = tracks => { // eslint-disable-next-line no-plusplus for (let i = 0; i < tracks.length; i++) { if (tracks[i].numeric > 0) { return i } } return null } export const NOOP = () => false export const defaultWriteStyle = (element, gridTemplateProp, style) => { // eslint-disable-next-line no-param-reassign element.style[gridTemplateProp] = style } export const getOption = (options, propName, def) => { const value = options[propName] if (value !== undefined) { return value } return def } export function range(from, to) { const result = []; if (from <= to) { for (let i = from; i < to; i++) { result.push(i); } } else { for (let i = from; i > to; i--) { result.push(i); } } return result; } export function clamp(value, min, max) { return Math.min(Math.max(value, min), max); } export function pushToStart(arr, value){ const index = arr.indexOf(value); if (index > -1) { arr.splice(index, 1); arr.unshift(value); } } export function pushToEnd(arr, value) { const index = arr.indexOf(value); if (index > -1) { arr.splice(index, 1); arr.push(value); } } export function isUndefined(obj){ return (typeof obj === 'undefined'); }
# Copyright 2017 The TensorFlow 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. """Convolutional Neural Network Estimator for MNIST, built with tf.layers.""" import traceback from functools import partial from typing import Tuple, Union import numpy as np import tensorflow as tf from nninst import AttrMap, mode from nninst.backend.tensorflow.dataset import imagenet from nninst.backend.tensorflow.graph import model_fn_with_fetch_hook from nninst.backend.tensorflow.model import ResNet50 from nninst.backend.tensorflow.trace.common import reconstruct_class_trace_from_tf from nninst.statistics import calc_iou, self_similarity_matrix from nninst.utils.fs import IOAction, abspath from nninst.utils.numpy import arg_approx from nninst.utils.ray import ray_init, ray_iter __all__ = ["resnet_50_imagenet_class_trace", "resnet_50_imagenet_self_similarity"] def resnet_50_imagenet_class_trace( class_id: int, threshold: float, batch_size: int = 256, label: str = None, cache: bool = False, ) -> IOAction[AttrMap]: def get_class_trace() -> AttrMap: try: mode.check(False) data_dir = abspath("/home/yxqiu/data/imagenet") # data_dir = abspath("/state/ssd0/yxqiu/data/imagenet") class_trace = reconstruct_class_trace_from_tf( class_id, model_fn=partial( model_fn_with_fetch_hook, create_model=lambda: ResNet50(), graph=ResNet50.graph().load(), ), input_fn=lambda: imagenet.train( data_dir, batch_size, transform_fn=lambda dataset: dataset.filter( lambda image, label: tf.equal( tf.convert_to_tensor(class_id, dtype=tf.int32), label ) ).take(140), ), # ).skip(3).take(1)), select_fn=lambda input: arg_approx(input, threshold), model_dir=abspath("tf/resnet-50-v2/model/"), # model_dir=abspath("/state/ssd0/yxqiu/workspace/nninst/tf/resnet-50-v2/model/"), parallel=4, ) return class_trace except Exception as cause: raise RuntimeError(f"error when handling class {class_id}") from cause threshold_name = "{0:.3f}".format(threshold) if label is None: name = "resnet_50_imagenet" else: name = f"resnet_50_imagenet_{label}" path = f"store/analysis/class_trace/{name}/approx_{threshold_name}/{class_id}.pkl" return IOAction(path, init_fn=get_class_trace, cache=cache) def resnet_50_imagenet_self_similarity( threshold: float, label: str = None ) -> IOAction[np.ndarray]: def get_self_similarity() -> np.ndarray: return self_similarity_matrix( range(1000), trace_fn=lambda class_id: resnet_50_imagenet_class_trace( class_id, threshold, label ).load(), similarity_fn=calc_iou, ) threshold_name = "{0:.3f}".format(threshold) if label is None: name = "resnet_50_imagenet" else: name = f"resnet_50_imagenet_{label}" path = f"store/analysis/self_similarity/{name}/approx_{threshold_name}/self_similarity.pkl" return IOAction(path, init_fn=get_self_similarity) if __name__ == "__main__": # mode.check(False) # mode.debug() # mode.local() mode.distributed() ray_init() threshold = 0.5 # threshold = 1 # threshold = 0.8 label = None print(f"generate class trace for label {label}") def class_trace(class_id: int) -> Union[int, Tuple[int, str]]: try: resnet_50_imagenet_class_trace( class_id, threshold=threshold, batch_size=16, label=label, cache=True ).save() # resnet_50_imagenet_class_trace(class_id, threshold=threshold, batch_size=1, label=label).save() return class_id except Exception: return class_id, traceback.format_exc() results = ray_iter( class_trace, np.arange(1, 1001), chunksize=1, out_of_order=True, num_gpus=0, huge_task=True, ) # ray_map(class_trace, [454], chunksize=1, out_of_order=True, num_gpus=1) for result in results: if not isinstance(result, int): class_id, tb = result print(f"## raise exception from class {class_id}:") print(tb) else: print(f"finish class {result}") print("finish") # ray_map(class_trace, range(1, 1001), chunksize=1, out_of_order=True, num_gpus=1) # for class_id in range(10): # resnet_50_imagenet_class_trace(class_id, threshold=threshold, label=label).save() # lenet_mnist_class_trace(class_id, threshold=threshold).save() # trace = class_trace(class_id, threshold=threshold).load() # print(trace) # lenet_mnist_self_similarity(threshold, label="early").save() # similarity = lenet_mnist_self_similarity(threshold).load() # print(similarity)
/*numPass=5, numTotal=5 Verdict:ACCEPTED, Visibility:1, Input:"3 23", ExpOutput:"3 5 7 11 13 17 19 23 ", Output:"3 5 7 11 13 17 19 23 " Verdict:ACCEPTED, Visibility:1, Input:"5 31", ExpOutput:"5 7 11 13 17 19 23 29 31 ", Output:"5 7 11 13 17 19 23 29 31 " Verdict:ACCEPTED, Visibility:1, Input:"1 20", ExpOutput:"2 3 5 7 11 13 17 19 ", Output:"2 3 5 7 11 13 17 19 " Verdict:ACCEPTED, Visibility:0, Input:"23 57", ExpOutput:"23 29 31 37 41 43 47 53 ", Output:"23 29 31 37 41 43 47 53 " Verdict:ACCEPTED, Visibility:0, Input:"31 47", ExpOutput:"31 37 41 43 47 ", Output:"31 37 41 43 47 " */ #include<stdio.h> int check_prime(int num) {int i; for(i=2;i<num;i++) { if(num%i==0) return 0; } return 1; } int main(){ int n1,n2,i; scanf("%d %d",&n1,&n2); for(i=n1;i<=n2;i++) { if (check_prime(i)==1&&i!=1) { printf("%d ",i); } } return 0; }
""" peewee-async tests ================== Create tests.ini file to configure tests. """ import os import sys import json import logging import asyncio import contextlib import unittest import uuid import peewee import peewee_async import peewee_asyncext ########## # Config # ########## # logging.basicConfig(level=logging.DEBUG) DB_DEFAULTS = { 'postgres': { 'database': 'test', 'host': '127.0.0.1', # 'port': 5432, 'user': 'postgres', }, 'postgres-ext': { 'database': 'test', 'host': '127.0.0.1', # 'port': 5432, 'user': 'postgres', }, 'postgres-pool': { 'database': 'test', 'host': '127.0.0.1', # 'port': 5432, 'user': 'postgres', 'max_connections': 4, }, 'postgres-pool-ext': { 'database': 'test', 'host': '127.0.0.1', # 'port': 5432, 'user': 'postgres', 'max_connections': 4, }, 'mysql': { 'database': 'test', 'host': '127.0.0.1', 'port': 3306, 'user': 'root', }, 'mysql-pool': { 'database': 'test', 'host': '127.0.0.1', 'port': 3306, 'user': 'root', } } DB_OVERRIDES = {} DB_CLASSES = { 'postgres': peewee_async.PostgresqlDatabase, 'postgres-ext': peewee_asyncext.PostgresqlExtDatabase, 'postgres-pool': peewee_async.PooledPostgresqlDatabase, 'postgres-pool-ext': peewee_asyncext.PooledPostgresqlExtDatabase, 'mysql': peewee_async.MySQLDatabase, 'mysql-pool': peewee_async.PooledMySQLDatabase } try: import aiopg except ImportError: aiopg = None try: import aiomysql except ImportError: aiomysql = None def setUpModule(): try: with open('tests.json', 'r') as tests_fp: DB_OVERRIDES.update(json.load(tests_fp)) except FileNotFoundError: print("'tests.json' file not found, will use defaults") if not aiopg: print("aiopg is not installed, ignoring PostgreSQL tests") for key in list(DB_CLASSES.keys()): if key.startswith('postgres'): DB_CLASSES.pop(key) if not aiomysql: print("aiomysql is not installed, ignoring MySQL tests") for key in list(DB_CLASSES.keys()): if key.startswith('mysql'): DB_CLASSES.pop(key) loop = asyncio.new_event_loop() all_databases = load_databases(only=None) for key, database in all_databases.items(): connect = database.connect_async(loop=loop) loop.run_until_complete(connect) if database._async_conn is not None: disconnect = database.close_async() loop.run_until_complete(disconnect) else: print("Can't setup connection for %s" % key) DB_CLASSES.pop(key) def load_managers(*, loop, only): managers = {} for key in DB_CLASSES: if only and key not in only: continue params = DB_DEFAULTS.get(key) or {} params.update(DB_OVERRIDES.get(key) or {}) database = DB_CLASSES[key](**params) managers[key] = peewee_async.Manager(database, loop=loop) return managers def load_databases(*, only): databases = {} for key in DB_CLASSES: if only and key not in only: continue params = DB_DEFAULTS.get(key) or {} params.update(DB_OVERRIDES.get(key) or {}) databases[key] = DB_CLASSES[key](**params) return databases ########## # Models # ########## class TestModel(peewee.Model): text = peewee.CharField(max_length=100, unique=True) data = peewee.TextField(default='') def __str__(self): return '<%s id=%s> %s' % (self.__class__.__name__, self.id, self.text) class TestModelAlpha(peewee.Model): text = peewee.CharField() def __str__(self): return '<%s id=%s> %s' % (self.__class__.__name__, self.id, self.text) class TestModelBeta(peewee.Model): alpha = peewee.ForeignKeyField(TestModelAlpha, backref='betas') text = peewee.CharField() def __str__(self): return '<%s id=%s> %s' % (self.__class__.__name__, self.id, self.text) class TestModelGamma(peewee.Model): text = peewee.CharField() beta = peewee.ForeignKeyField(TestModelBeta, backref='gammas') def __str__(self): return '<%s id=%s> %s' % (self.__class__.__name__, self.id, self.text) class UUIDTestModel(peewee.Model): id = peewee.UUIDField(primary_key=True, default=uuid.uuid4) text = peewee.CharField() def __str__(self): return '<%s id=%s> %s' % (self.__class__.__name__, self.id, self.text) class CompositeTestModel(peewee.Model): """A simple "through" table for many-to-many relationship.""" uuid = peewee.ForeignKeyField(UUIDTestModel) alpha = peewee.ForeignKeyField(TestModelAlpha) class Meta: primary_key = peewee.CompositeKey('uuid', 'alpha') #################### # Base tests class # #################### class BaseManagerTestCase(unittest.TestCase): only = None models = [TestModel, UUIDTestModel, TestModelAlpha, TestModelBeta, TestModelGamma, CompositeTestModel] @classmethod @contextlib.contextmanager def manager(cls, objects, allow_sync=False): for model in cls.models: model._meta.database = objects.database if allow_sync: with objects.allow_sync(): yield else: yield def setUp(self): """Setup the new event loop, and database configs, reset counter. """ self.run_count = 0 self.loop = asyncio.new_event_loop() self.managers = load_managers(loop=self.loop, only=self.only) # Clean up before tests for _, objects in self.managers.items(): objects.database.set_allow_sync(False) with self.manager(objects, allow_sync=True): for model in self.models: model.create_table(True) for model in reversed(self.models): model.delete().execute() def tearDown(self): """Check if test was actually passed by counter, clean up. """ self.assertEqual(len(self.managers), self.run_count) for _, objects in self.managers.items(): self.loop.run_until_complete(objects.close()) self.loop.close() for _, objects in self.managers.items(): with self.manager(objects, allow_sync=True): for model in reversed(self.models): model.drop_table(fail_silently=True) self.managers = None def run_with_managers(self, test, exclude=None): """Run test coroutine against available Manager instances. test -- coroutine with single parameter, Manager instance exclude -- exclude list or string for manager key Example: async def test(objects): # ... run_with_managers(test, exclude=['mysql', 'mysql-pool']) """ for key, objects in self.managers.items(): if exclude is None or (key not in exclude): with self.manager(objects, allow_sync=False): self.loop.run_until_complete(test(objects)) with self.manager(objects, allow_sync=True): for model in reversed(self.models): model.delete().execute() self.run_count += 1 ################ # Common tests # ################ class DatabaseTestCase(unittest.TestCase): def test_deferred_init(self): for key in DB_CLASSES: params = DB_DEFAULTS.get(key) or {} params.update(DB_OVERRIDES.get(key) or {}) database = DB_CLASSES[key](None) self.assertTrue(database.deferred) database.init(**params) self.assertTrue(not database.deferred) TestModel._meta.database = database TestModel.create_table(True) TestModel.drop_table(True) def test_proxy_database(self): loop = asyncio.new_event_loop() database = peewee.Proxy() TestModel._meta.database = database objects = peewee_async.Manager(database, loop=loop) async def test(objects): text = "Test %s" % uuid.uuid4() await objects.create(TestModel, text=text) await objects.get(TestModel, text=text) for key in DB_CLASSES: params = DB_DEFAULTS.get(key) or {} params.update(DB_OVERRIDES.get(key) or {}) database.initialize(DB_CLASSES[key](**params)) TestModel.create_table(True) loop.run_until_complete(test(objects)) loop.run_until_complete(objects.close()) TestModel.drop_table(True) loop.close() class OlderTestCase(unittest.TestCase): # only = ['postgres', 'postgres-ext', 'postgres-pool', 'postgres-pool-ext'] only = None models = [TestModel, UUIDTestModel, TestModelAlpha, TestModelBeta, TestModelGamma] @classmethod @contextlib.contextmanager def current_database(cls, database, allow_sync=False): for model in cls.models: model._meta.database = database yield @classmethod def setUpClass(cls, *args, **kwargs): """Configure database managers, create test tables. """ cls.loop = asyncio.new_event_loop() asyncio.set_event_loop(cls.loop) cls.databases = load_databases(only=cls.only) for k, database in cls.databases.items(): database.set_allow_sync(True) with cls.current_database(database): for model in cls.models: model.create_table(True) database.set_allow_sync(False) @classmethod def tearDownClass(cls, *args, **kwargs): """Remove all test tables and close connections. """ for _, database in cls.databases.items(): cls.loop.run_until_complete(database.close_async()) cls.loop.close() for _, database in cls.databases.items(): database.set_allow_sync(True) with cls.current_database(database): for model in reversed(cls.models): model.drop_table(fail_silently=True) database.set_allow_sync(False) cls.databases = None def setUp(self): """Reset all data. """ self.run_count = 0 for k, database in self.databases.items(): with self.current_database(database): database.set_allow_sync(True) for model in reversed(self.models): model.delete().execute() database.set_allow_sync(False) def tearDown(self): """Check if test was actually passed by counter. """ self.assertEqual(len(self.databases), self.run_count) def run_with_databases(self, test, exclude=None): """Run test coroutine against available databases. """ for k, database in self.databases.items(): if exclude is None or (k not in exclude): with self.current_database(database): database.set_allow_sync(False) self.loop.run_until_complete(test(database)) database.set_allow_sync(True) for model in reversed(self.models): model.delete().execute() database.set_allow_sync(False) self.run_count += 1 def test_create_obj(self): async def test(database): text = "Test %s" % uuid.uuid4() obj = await peewee_async.create_object(TestModel, text=text) self.assertTrue(obj is not None) self.assertEqual(obj.text, text) self.run_with_databases(test) def test_get_and_delete_obj(self): async def test(database): text = "Test %s" % uuid.uuid4() obj1 = await peewee_async.create_object( TestModel, text=text) obj2 = await peewee_async.get_object( TestModel, TestModel.id == obj1.id) await peewee_async.delete_object(obj2) try: obj3 = await peewee_async.get_object( TestModel, TestModel.id == obj1.id) except TestModel.DoesNotExist: obj3 = None self.assertTrue(obj3 is None, "Error, object wasn't deleted") self.run_with_databases(test) def test_get_and_update_obj(self): async def test(database): text = "Test %s" % uuid.uuid4() obj1 = await peewee_async.create_object( TestModel, text=text) obj1.text = "Test update object" await peewee_async.update_object(obj1) obj2 = await peewee_async.get_object( TestModel, TestModel.id == obj1.id) self.assertEqual(obj2.text, "Test update object") self.run_with_databases(test) class ManagerTestCase(BaseManagerTestCase): # only = ['postgres', 'postgres-ext', 'postgres-pool', 'postgres-pool-ext'] only = None def test_connect_close(self): async def get_conn(objects): await objects.connect() # await asyncio.sleep(0.05, loop=self.loop) # NOTE: "private" member access return objects.database._async_conn async def test(objects): c1 = await get_conn(objects) c2 = await get_conn(objects) self.assertEqual(c1, c2) self.assertTrue(objects.is_connected) await objects.close() self.assertTrue(not objects.is_connected) done, not_done = await asyncio.wait([ get_conn(objects), get_conn(objects), get_conn(objects), ], loop=self.loop) conn = next(iter(done)).result() self.assertEqual(len(done), 3) self.assertTrue(objects.is_connected) self.assertTrue(all(map(lambda t: t.result() == conn, done))) await objects.close() self.assertTrue(not objects.is_connected) self.run_with_managers(test) def test_many_requests(self): async def test(objects): max_connections = getattr(objects.database, 'max_connections', 1) text = "Test %s" % uuid.uuid4() obj = await objects.create(TestModel, text=text) n = 2 * max_connections # number of requests done, not_done = await asyncio.wait( [objects.get(TestModel, id=obj.id) for _ in range(n)], loop=self.loop) self.assertEqual(len(done), n) self.run_with_managers(test) def test_create_obj(self): async def test(objects): text = "Test %s" % uuid.uuid4() obj = await objects.create(TestModel, text=text) self.assertTrue(obj is not None) self.assertEqual(obj.text, text) self.run_with_managers(test) def test_create_or_get(self): async def test(objects): text = "Test %s" % uuid.uuid4() obj1, created1 = await objects.create_or_get( TestModel, text=text, data="Data 1") obj2, created2 = await objects.create_or_get( TestModel, text=text, data="Data 2") self.assertTrue(created1) self.assertTrue(not created2) self.assertEqual(obj1, obj2) self.assertEqual(obj1.data, "Data 1") self.assertEqual(obj2.data, "Data 1") self.run_with_managers(test) def test_get_or_none(self): async def test(objects): text = "Test %s" % uuid.uuid4() obj1 = await objects.create(TestModel, text=text) obj2 = await objects.get_or_none(TestModel, id=obj1.id) await objects.delete(obj1) obj3 = await objects.get_or_none(TestModel, id=obj1.id) self.assertIsNotNone(obj2) self.assertEqual(obj1, obj2) self.assertIsNone(obj3) self.run_with_managers(test) def test_get_or_create(self): async def test(objects): text = "Test %s" % uuid.uuid4() obj1, created1 = await objects.get_or_create( TestModel, text=text, defaults={'data': "Data 1"}) obj2, created2 = await objects.get_or_create( TestModel, text=text, defaults={'data': "Data 2"}) self.assertTrue(created1) self.assertTrue(not created2) self.assertEqual(obj1, obj2) self.assertEqual(obj1.data, "Data 1") self.assertEqual(obj2.data, "Data 1") self.run_with_managers(test) def test_create_uuid_obj(self): async def test(objects): text = "Test %s" % uuid.uuid4() obj = await objects.create(UUIDTestModel, text=text) self.assertEqual(len(str(obj.id)), 36) self.run_with_managers(test, exclude=['mysql', 'mysql-pool']) def test_get_obj_by_id(self): async def test(objects): text = "Test %s" % uuid.uuid4() obj1 = await objects.create(TestModel, text=text) obj2 = await objects.get(TestModel, id=obj1.id) self.assertEqual(obj1, obj2) self.assertEqual(obj1.id, obj2.id) self.run_with_managers(test) def test_get_obj_by_uuid(self): async def test(objects): text = "Test %s" % uuid.uuid4() obj1 = await objects.create(UUIDTestModel, text=text) obj2 = await objects.get(UUIDTestModel, id=obj1.id) self.assertEqual(obj1, obj2) self.assertEqual(len(str(obj1.id)), 36) self.run_with_managers(test) def test_raw_query(self): async def test(objects): text = "Test %s" % uuid.uuid4() await objects.create(TestModel, text=text) result1 = await objects.execute(TestModel.raw( 'select id, text from testmodel')) result1 = list(result1) self.assertEqual(len(result1), 1) self.assertTrue(isinstance(result1[0], TestModel)) result2 = await objects.execute(TestModel.raw( 'select id, text from testmodel').tuples()) result2 = list(result2) self.assertEqual(len(result2), 1) self.assertTrue(isinstance(result2[0], tuple)) result3 = await objects.execute(TestModel.raw( 'select id, text from testmodel').dicts()) result3 = list(result3) self.assertEqual(len(result3), 1) self.assertTrue(isinstance(result3[0], dict)) self.run_with_managers(test) def test_select_many_objects(self): async def test(objects): text = "Test 1" obj1 = await objects.create(TestModel, text=text) text = "Test 2" obj2 = await objects.create(TestModel, text=text) select1 = [obj1, obj2] len1 = len(select1) select2 = await objects.execute( TestModel.select().order_by(TestModel.text)) len2 = len([o for o in select2]) self.assertEqual(len1, len2) for o1, o2 in zip(select1, select2): self.assertEqual(o1, o2) self.run_with_managers(test) def test_indexing_result(self): async def test(objects): await objects.create(TestModel, text="Test 1") obj = await objects.create(TestModel, text="Test 2") result = await objects.execute( TestModel.select().order_by(TestModel.text)) self.assertEqual(obj, result[1]) self.run_with_managers(test) def test_multiple_iterate_over_result(self): async def test(objects): obj1 = await objects.create(TestModel, text="Test 1") obj2 = await objects.create(TestModel, text="Test 2") result = await objects.execute( TestModel.select().order_by(TestModel.text)) self.assertEqual(list(result), [obj1, obj2]) self.assertEqual(list(result), [obj1, obj2]) self.run_with_managers(test) def test_insert_many_rows_query(self): async def test(objects): select1 = await objects.execute(TestModel.select()) self.assertEqual(len(select1), 0) query = TestModel.insert_many([ {'text': "Test %s" % uuid.uuid4()}, {'text': "Test %s" % uuid.uuid4()}, ]) last_id = await objects.execute(query) self.assertTrue(last_id is not None) select2 = await objects.execute(TestModel.select()) self.assertEqual(len(select2), 2) self.run_with_managers(test) def test_insert_one_row_query(self): async def test(objects): query = TestModel.insert(text="Test %s" % uuid.uuid4()) last_id = await objects.execute(query) self.assertTrue(last_id is not None) select1 = await objects.execute(TestModel.select()) self.assertEqual(len(select1), 1) self.run_with_managers(test) def test_insert_one_row_uuid_query(self): async def test(objects): query = UUIDTestModel.insert(text="Test %s" % uuid.uuid4()) last_id = await objects.execute(query) self.assertEqual(len(str(last_id)), 36) self.run_with_managers(test, exclude=['mysql', 'mysql-pool']) def test_update_query(self): async def test(objects): text = "Test %s" % uuid.uuid4() obj1 = await objects.create(TestModel, text=text) query = TestModel.update(text="Test update query") \ .where(TestModel.id == obj1.id) upd1 = await objects.execute(query) self.assertEqual(upd1, 1) obj2 = await objects.get(TestModel, id=obj1.id) self.assertEqual(obj2.text, "Test update query") self.run_with_managers(test) def test_update_obj(self): async def test(objects): text = "Test %s" % uuid.uuid4() obj1 = await objects.create(TestModel, text=text) obj1.text = "Test update object" await objects.update(obj1) obj2 = await objects.get(TestModel, id=obj1.id) self.assertEqual(obj2.text, "Test update object") self.run_with_managers(test) def test_delete_obj(self): async def test(objects): text = "Test %s" % uuid.uuid4() obj1 = await objects.create(TestModel, text=text) obj2 = await objects.get(TestModel, id=obj1.id) await objects.delete(obj2) try: obj3 = await objects.get(TestModel, id=obj1.id) except TestModel.DoesNotExist: obj3 = None self.assertTrue(obj3 is None, "Error, object wasn't deleted") self.run_with_managers(test) def test_scalar_query(self): async def test(objects): text = "Test %s" % uuid.uuid4() await objects.create(TestModel, text=text) text = "Test %s" % uuid.uuid4() await objects.create(TestModel, text=text) fn = peewee.fn.Count(TestModel.id) count = await objects.scalar(TestModel.select(fn)) self.assertEqual(count, 2) self.run_with_managers(test) def test_count_query(self): async def test(objects): text = "Test %s" % uuid.uuid4() await objects.create(TestModel, text=text) text = "Test %s" % uuid.uuid4() await objects.create(TestModel, text=text) text = "Test %s" % uuid.uuid4() await objects.create(TestModel, text=text) count = await objects.count(TestModel.select()) self.assertEqual(count, 3) self.run_with_managers(test) def test_count_query_with_limit(self): async def test(objects): text = "Test %s" % uuid.uuid4() await objects.create(TestModel, text=text) text = "Test %s" % uuid.uuid4() await objects.create(TestModel, text=text) text = "Test %s" % uuid.uuid4() await objects.create(TestModel, text=text) count = await objects.count(TestModel.select().limit(1)) self.assertEqual(count, 1) self.run_with_managers(test) def test_prefetch(self): async def test(objects): alpha_1 = await objects.create( TestModelAlpha, text='Alpha 1') alpha_2 = await objects.create( TestModelAlpha, text='Alpha 2') beta_11 = await objects.create( TestModelBeta, alpha=alpha_1, text='Beta 11') beta_12 = await objects.create( TestModelBeta, alpha=alpha_1, text='Beta 12') _ = await objects.create( TestModelBeta, alpha=alpha_2, text='Beta 21') _ = await objects.create( TestModelBeta, alpha=alpha_2, text='Beta 22') gamma_111 = await objects.create( TestModelGamma, beta=beta_11, text='Gamma 111') gamma_112 = await objects.create( TestModelGamma, beta=beta_11, text='Gamma 112') result = await objects.prefetch( TestModelAlpha.select(), TestModelBeta.select(), TestModelGamma.select()) self.assertEqual(tuple(result), (alpha_1, alpha_2)) self.assertEqual(tuple(result[0].betas), (beta_11, beta_12)) self.assertEqual(tuple(result[0].betas[0].gammas), (gamma_111, gamma_112)) self.run_with_managers(test) def test_composite_key(self): async def test(objects): obj_uuid = await objects.create(UUIDTestModel, text='UUID') obj_alpha = await objects.create(TestModelAlpha, text='Alpha') comp = await objects.create(CompositeTestModel, uuid=obj_uuid, alpha=obj_alpha) self.assertEqual((obj_uuid, obj_alpha), comp.get_id()) self.run_with_managers(test) ###################### # Transactions tests # ###################### class FakeUpdateError(Exception): """Fake error while updating database. """ pass class ManagerTransactionsTestCase(BaseManagerTestCase): # only = ['postgres', 'postgres-ext', 'postgres-pool', 'postgres-pool-ext'] only = None def test_atomic_success(self): """Successful update in transaction. """ async def test(objects): obj = await objects.create(TestModel, text='FOO') obj_id = obj.id async with objects.atomic(): obj.text = 'BAR' await objects.update(obj) res = await objects.get(TestModel, id=obj_id) self.assertEqual(res.text, 'BAR') self.run_with_managers(test) def test_atomic_failed(self): """Failed update in transaction. """ async def test(objects): obj = await objects.create(TestModel, text='FOO') obj_id = obj.id try: async with objects.atomic(): obj.text = 'BAR' await objects.update(obj) raise FakeUpdateError() except FakeUpdateError as e: error = True res = await objects.get(TestModel, id=obj_id) self.assertTrue(error) self.assertEqual(res.text, 'FOO') self.run_with_managers(test) def test_several_transactions(self): """Run several transactions in parallel tasks. """ wait = lambda tasks: self.loop.run_until_complete( asyncio.wait([ self.loop.create_task(t) for t in tasks ], loop=self.loop)) async def t1(objects): async with objects.atomic(): self.assertEqual(objects.database.transaction_depth_async(), 1) await asyncio.sleep(0.25, loop=self.loop) async def t2(objects): async with objects.atomic(): self.assertEqual(objects.database.transaction_depth_async(), 1) await asyncio.sleep(0.0625, loop=self.loop) async def t3(objects): async with objects.atomic(): self.assertEqual(objects.database.transaction_depth_async(), 1) await asyncio.sleep(0.125, loop=self.loop) for _, objects in self.managers.items(): wait([ t1(objects), t2(objects), t3(objects), ]) with self.manager(objects, allow_sync=True): for model in reversed(self.models): model.delete().execute() self.run_count += 1 def test_atomic_fail_with_disconnect(self): """Database gone in transaction. """ async def test(objects): error = False try: async with objects.atomic(): await objects.database.close_async() raise FakeUpdateError() except FakeUpdateError: error = True self.assertTrue(error) self.run_with_managers(test)
import pytest @pytest.fixture(scope='function') def disable_automatic_scheduling(settings): settings.AUTOMATIC_HARVESTING_ENABLED = False @pytest.fixture(scope='function') def enable_automatic_scheduling(settings): settings.AUTOMATIC_HARVESTING_ENABLED = True
function initialState() { return { all: [], loading: false, } } const getters = { data: state => { let rows = state.all return rows }, loading: state => state.loading } const actions = { fetchData({ commit, state }) { commit('setLoading', true) $http.get('/api/core/settings') .then(response => { commit('setAll', response.data.data) }) .catch(error => { let message = error.response.data.message || error.message this.$eventHub.$emit('message', 'error', 'error', message) console.log(message) }) .finally(() => { commit('setLoading', false) }) }, destroyData({ commit, state }, id) { return new Promise((resolve) => { $http.delete('/api/core/settings/' + id) .then(response => { if (response.data.code == 204) { commit('setAll', state.all.filter((item) => { return item.id != id })) } resolve(response) }) .catch(error => { let message = error.response.data.message || error.message this.$eventHub.$emit('message', 'error', 'error', message) }) }) }, resetState({ commit }) { commit('resetState') } } const mutations = { setAll(state, items) { state.all = items }, setLoading(state, loading) { state.loading = loading }, resetState(state) { state = Object.assign(state, initialState()) } } export default { namespaced: true, state: initialState, getters, actions, mutations }
#!/usr/bin/env python def main(): pass if __name__ == '__main__': main()
from . import CommandExecuterBase, DEFAULT_MAX_QUEUE_SIZE, DEFAULT_TIMEOUT, SCSIReadCommand, SCSIWriteCommand from . import SCSI_STATUS_CODES, gevent_friendly from .errors import AsiSCSIError, AsiRequestQueueFullError, AsiReservationConflictError from ctypes import * from logging import getLogger logger = getLogger(__name__) """ From /usr/include/scsi/sg.h See http://tldp.org/HOWTO/SCSI-Generic-HOWTO/sg_io_hdr_t.html typedef struct sg_io_hdr { int interface_id; /* [i] 'S' for SCSI generic (required) */ int dxfer_direction; /* [i] data transfer direction */ unsigned char cmd_len; /* [i] SCSI command length ( <= 16 bytes) */ unsigned char mx_sb_len; /* [i] max length to write to sbp */ unsigned short int iovec_count; /* [i] 0 implies no scatter gather */ unsigned int dxfer_len; /* [i] byte count of data transfer */ void * dxferp; /* [i], [*io] points to data transfer memory or scatter gather list */ unsigned char * cmdp; /* [i], [*i] points to command to perform */ unsigned char * sbp; /* [i], [*o] points to sense_buffer memory */ unsigned int timeout; /* [i] MAX_UINT->no timeout (unit: millisec) */ unsigned int flags; /* [i] 0 -> default, see SG_FLAG... */ int pack_id; /* [i->o] unused internally (normally) */ void * usr_ptr; /* [i->o] unused internally */ unsigned char status; /* [o] scsi status */ unsigned char masked_status;/* [o] shifted, masked scsi status */ unsigned char msg_status; /* [o] messaging level data (optional) */ unsigned char sb_len_wr; /* [o] byte count actually written to sbp */ unsigned short int host_status; /* [o] errors from host adapter */ unsigned short int driver_status;/* [o] errors from software driver */ int resid; /* [o] dxfer_len - actual_transferred */ unsigned int duration; /* [o] time taken by cmd (unit: millisec) */ unsigned int info; /* [o] auxiliary information */ } sg_io_hdr_t; #define SG_DXFER_NONE -1 /* e.g. a SCSI Test Unit Ready command */ #define SG_DXFER_TO_DEV -2 /* e.g. a SCSI WRITE command */ #define SG_DXFER_FROM_DEV -3 /* e.g. a SCSI READ command */ #define SG_DXFER_TO_FROM_DEV -4 /* treated like SG_DXFER_FROM_DEV with the additional property than during indirect IO the user buffer is copied into the kernel buffers before the transfer */ /* following flag values can be "or"-ed together */ #define SG_FLAG_DIRECT_IO 1 /* default is indirect IO */ #define SG_FLAG_LUN_INHIBIT 2 /* default is to put device's lun into */ /* the 2nd byte of SCSI command */ #define SG_FLAG_NO_DXFER 0x10000 /* no transfer of kernel buffers to/from */ /* user space (debug indirect IO) */ /* The following 'info' values are "or"-ed together. */ #define SG_INFO_OK_MASK 0x1 #define SG_INFO_OK 0x0 /* no sense, host nor driver "noise" */ #define SG_INFO_CHECK 0x1 /* something abnormal happened */ #define SG_INFO_DIRECT_IO_MASK 0x6 #define SG_INFO_INDIRECT_IO 0x0 /* data xfer via kernel buffers (or no xfer) */ #define SG_INFO_DIRECT_IO 0x2 /* direct IO requested and performed */ #define SG_INFO_MIXED_IO 0x4 /* part direct, part indirect IO */ """ SG_DXFER_NONE = -1 SG_DXFER_TO_DEV = -2 SG_DXFER_FROM_DEV = -3 SG_DXFER_TO_FROM_DEV = -4 SG_FLAG_DIRECT_IO = 1 SG_FLAG_LUN_INHIBIT = 2 SG_FLAG_NO_DXFER = 0x10000 # Driver errors (from sg_err.h). The lower nibble is ORed with the upper one. DRIVER_STATUS_CODES = dict( SG_ERR_DRIVER_OK = 0x00, # Typically no suggestion SG_ERR_DRIVER_BUSY = 0x01, SG_ERR_DRIVER_SOFT = 0x02, SG_ERR_DRIVER_MEDIA = 0x03, SG_ERR_DRIVER_ERROR = 0x04, SG_ERR_DRIVER_INVALID = 0x05, SG_ERR_DRIVER_TIMEOUT = 0x06, # Adapter driver is unable to control the SCSI bus to its is setting its devices offline (and giving up) SG_ERR_DRIVER_HARD = 0x07, SG_ERR_DRIVER_SENSE = 0x08, # Implies sense_buffer output above status 'or'ed with one of the following suggestions SG_ERR_SUGGEST_RETRY = 0x10, SG_ERR_SUGGEST_ABORT = 0x20, SG_ERR_SUGGEST_REMAP = 0x30, SG_ERR_SUGGEST_DIE = 0x40, SG_ERR_SUGGEST_SENSE = 0x80 ) # Host errors (from sg_err.h) HOST_STATUS_CODES = dict( SG_ERR_DID_OK = 0x00, # NO error SG_ERR_DID_NO_CONNECT = 0x01, # Couldn't connect before timeout period SG_ERR_DID_BUS_BUSY = 0x02, # BUS stayed busy through time out period SG_ERR_DID_TIME_OUT = 0x03, # TIMED OUT for other reason (often this an unexpected device selection timeout) SG_ERR_DID_BAD_TARGET = 0x04, # BAD target, device not responding? SG_ERR_DID_ABORT = 0x05, # Told to abort for some other reason. From lk 2.4.15 the SCSI subsystem supports 16 byte commands however few adapter drivers do. Those HBA drivers that don't support 16 byte commands will yield this error code if a 16 byte command is passed to a SCSI device they control. SG_ERR_DID_PARITY = 0x06, # Parity error. Older SCSI parallel buses have a parity bit for error detection. This probably indicates a cable or termination problem. SG_ERR_DID_ERROR = 0x07, # Internal error detected in the host adapter. This may not be fatal (and the command may have succeeded). The aic7xxx and sym53c8xx adapter drivers sometimes report this for data underruns or overruns. [9] SG_ERR_DID_RESET = 0x08, # The SCSI bus (or this device) has been reset. Any SCSI device on a SCSI bus is capable of instigating a reset. SG_ERR_DID_BAD_INTR = 0x09, # Got an interrupt we weren't expecting SG_ERR_DID_PASSTHROUGH = 0x0a, # Force command past mid-layer SG_ERR_DID_SOFT_ERROR = 0x0b # The low level driver wants a retry ) SENSE_SIZE = 0xFF def prettify_status(code, status_dict): code_string = [key for key, value in status_dict.items() if value == code] or [''] return "%s 0x%02x" % (code_string[0], code) class SGIO(Structure): _fields_ = [ ("interface_id", c_int), ("dxfer_direction", c_int), ("cmd_len", c_ubyte), ("mx_sb_len", c_ubyte), ("iovec_count", c_ushort), ("dxfer_len", c_uint), ("dxferp", c_void_p), ("cmdp", c_void_p), ("sbp", c_void_p), ("timeout", c_uint), ("flags", c_uint), ("pack_id", c_int), ("usr_ptr", c_void_p), ("status", c_ubyte), ("masked_status", c_ubyte), ("msg_status", c_ubyte), ("sb_len_wr", c_ubyte), ("host_status", c_ushort), ("driver_status", c_ushort), ("resid", c_int), ("duration", c_uint), ("info", c_uint) ] def __init__(self, *args, **kwargs): super(SGIO, self).__init__(*args, **kwargs) self.source_buffer = None def init_sense_buffer(self): self.sense_buffer = create_string_buffer(SENSE_SIZE) self.sbp = cast(self.sense_buffer, c_void_p) self.mx_sb_len = sizeof(self.sense_buffer) def init_command_buffer(self, command): self.command_buffer = create_string_buffer(command, len(command)) self.cmdp = cast(self.command_buffer, c_void_p) self.cmd_len = sizeof(self.command_buffer) def set_data_buffer(self, buf): if buf is not None: self.data_buffer = buf self.dxferp = cast(self.data_buffer, c_void_p) self.dxfer_len = sizeof(self.data_buffer) else: self.dxferp = 0 self.dxfer_len = 0 def to_raw(self): return self.source_buffer.raw def __repr__(self): return ("SGIO(interface_id={self.interface_id}, dxfer_direction={self.dxfer_direction}, " + "cmd_len={self.cmd_len}, mx_sb_len={self.mx_sb_len}, iovec_count={self.iovec_count}, " + "dxfer_len={self.dxfer_len}, dxferp={self.dxferp}, cmdp={self.cmdp}, sbp={self.sbp}, " + "timeout={self.timeout}, flags={self.flags}, pack_id={self.pack_id}, usr_ptr={self.usr_ptr}, " + "status={self.status}, masked_status={self.masked_status}, msg_status={self.msg_status}, " + "sb_len_wr={self.sb_len_wr}, host_status={self.host_status}, driver_status={self.driver_status}, " + "resid={self.resid}, duration={self.duration}, info={self.info})").format(self=self) @classmethod def create(cls, pack_id, command, timeout=0): buf = create_string_buffer(sizeof(SGIO)) memset(buf, 0, sizeof(SGIO)) sgio = SGIO.from_buffer(buf) sgio.source_buffer = buf sgio.interface_id = ord('S') sgio.pack_id = pack_id sgio.init_sense_buffer() sgio.init_command_buffer(command.command) sgio.timeout = timeout if isinstance(command, SCSIReadCommand): if command.max_response_length > 0: sgio.dxfer_direction = SG_DXFER_FROM_DEV sgio.set_data_buffer(create_string_buffer(command.max_response_length)) else: sgio.dxfer_direction = SG_DXFER_NONE sgio.set_data_buffer(None) else: sgio.dxfer_direction = SG_DXFER_TO_DEV sgio.set_data_buffer(create_string_buffer(command.data, len(command.data))) sgio.flags = SG_FLAG_DIRECT_IO return sgio @classmethod def from_string(cls, string): buf = create_string_buffer(string, len(string)) sgio = SGIO.from_buffer(buf) sgio.source_buffer = buf return sgio @classmethod def sizeof(cls): return sizeof(cls) class LinuxCommandExecuter(CommandExecuterBase): def __init__(self, io, max_queue_size=DEFAULT_MAX_QUEUE_SIZE, timeout=DEFAULT_TIMEOUT): super(LinuxCommandExecuter, self).__init__(max_queue_size) self.io = io self.timeout = timeout def _os_prepare_to_send(self, command, packet_index): return SGIO.create(packet_index, command, self.timeout) def _os_send(self, os_data): yield gevent_friendly(self.io.write)(os_data.to_raw()) def _handle_raw_response(self, raw): response_sgio = SGIO.from_string(raw) packet_id = response_sgio.pack_id request_sgio = self._get_os_data(packet_id) if (response_sgio.status & SCSI_STATUS_CODES['SCSI_STATUS_CHECK_CONDITION']) != 0 or \ (response_sgio.driver_status & DRIVER_STATUS_CODES['SG_ERR_DRIVER_SENSE'] != 0): logger.debug("response_sgio.status = 0x{:x}".format(response_sgio.status)) logger.debug("response_sgio.driver_status = 0x{:x}".format(response_sgio.driver_status)) return (self._check_condition(string_at(response_sgio.sbp, SENSE_SIZE)), packet_id) if response_sgio.status != 0: if response_sgio.host_status == 0x07: return (AsiRequestQueueFullError(), packet_id) if response_sgio.host_status == SCSI_STATUS_CODES['SCSI_STATUS_RESERVATION_CONFLICT']: return (AsiReservationConflictError(), packet_id) error = AsiSCSIError(("SCSI response status is not zero: %s" + "(driver status: %s, host status: %s)") % (prettify_status(response_sgio.status, SCSI_STATUS_CODES), prettify_status(response_sgio.driver_status & 0x0f, DRIVER_STATUS_CODES), prettify_status(response_sgio.host_status, HOST_STATUS_CODES))) return (error, packet_id) if (response_sgio.driver_status & 0x0F) != 0: error = AsiSCSIError("SCSI driver response status is not zero: %s (host status: %s)" % (prettify_status(response_sgio.status, SCSI_STATUS_CODES), prettify_status(response_sgio.driver_status & 0x0f, DRIVER_STATUS_CODES))) return (error, packet_id) if response_sgio.host_status != 0: error = AsiSCSIError(("SCSI host status is not zero: %s" + "(driver status: %s, host status: %s)") % (prettify_status(response_sgio.status, SCSI_STATUS_CODES), prettify_status(response_sgio.driver_status & 0x0f, DRIVER_STATUS_CODES), prettify_status(response_sgio.host_status, HOST_STATUS_CODES))) return (error, packet_id) data = None if request_sgio.dxfer_direction == SG_DXFER_FROM_DEV and request_sgio.dxfer_len != 0: data = request_sgio.data_buffer.raw return (data, packet_id) def _os_receive(self): raw = yield gevent_friendly(self.io.read)(SGIO.sizeof()) yield self._handle_raw_response(raw) SG_IO = 0x2285 class LinuxIoctlCommandExecuter(LinuxCommandExecuter): def __init__(self, io, max_queue_size=1, timeout=DEFAULT_TIMEOUT): super(LinuxIoctlCommandExecuter, self).__init__(io, max_queue_size, timeout) self.io = io self.timeout = timeout def _os_send(self, os_data): from fcntl import ioctl self.buffer = os_data.to_raw() gevent_friendly(ioctl)(self.io.fd, SG_IO, self.buffer) yield len(self.buffer) def _os_receive(self): raw = yield self.buffer yield self._handle_raw_response(raw)
"""GUI Table related functions and classes.""" from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.recycleboxlayout import RecycleBoxLayout from kivy.uix.recycleview import RecycleView from utils.helpers import get_archives, get_key_pairs, get_table_width # Global values for the width of tables. Set globally to avoid recalculation ARCH_MAX_WIDTH = 0 KEYS_MAX_WIDTH = 0 class ArchiveRecycleView(RecycleView): """Extension of Kivy's RecycleView to present Archive meta data. A RecycleView is used as it allows the table data to be handled more efficiently by Kivy. Args: kwargs: Any additional keyword arguments. Attributes: viewclass (str): The class that sets the content for this view. scroll_type (list[str]): The ways the widget can be scrolled. bar_width (int): The width of the displayed scroll bar. do_scroll_x (bool): Set to True to allow horizontal scrolling. do_scroll_y (bool): Set to True to allow vertical scrolling. size_hint (tuple[int, int]): Set to fill the parent viewport. """ def __init__(self, **kwargs): super(ArchiveRecycleView, self).__init__(**kwargs) # Set the RecycleView's widgets and parameters self.add_widget(TableRecycleBoxLayout()) self.viewclass = "ArchiveTableRow" self.scroll_type = ["bars", "content"] self.bar_width = "12dp" self.do_scroll_x = True self.do_scroll_y = True # self.size_hint = (1, 1) # Set the data for the RecycleView with a bold faced header row tmp_data = [ { "name": "[b]Name[/b]", "src_path": "[b]Source[/b]", "dst_path": "[b]Destination[/b]", "kp": "[b]Key Pair Name[/b]", "timestamp": "[b]Timestamp[/b]", } ] tmp_data += get_archives() self.data = tmp_data # Set the max width for the Archive table data set_max_width(tmp_data) class ArchiveTableRow(BoxLayout): """Represents a single row of Archive meta data using Kivy's BoxLayout. Args: kwargs: Any additional keyword arguments. Attributes: orientation (str): The direction in which widgets are arranged. size_hint: Set to None to force the desired sizing. width (int): The overall width of the row. height (int): The overall height of the row. """ def __init__(self, **kwargs): super(ArchiveTableRow, self).__init__(**kwargs) self.orientation = "horizontal" self.size_hint = (None, None) self.width = ARCH_MAX_WIDTH self.height = "32dp" self.name_lbl = Label(markup=True, text="") self.src_path_lbl = Label(markup=True, text="") self.dst_path_lbl = Label(markup=True, text="") self.kp_lbl = Label(markup=True, text="") self.timestamp_lbl = Label(markup=True, text="") self.add_widget(self.name_lbl) self.add_widget(self.src_path_lbl) self.add_widget(self.dst_path_lbl) self.add_widget(self.kp_lbl) self.add_widget(self.timestamp_lbl) def on_parent(self, _screen, _parent): """Updates the row values when parent events are fired. Args: _screen (Widget): Required for Kivy on_parent. _parent (Widget): Required for Kivy on_parent. """ self.name_lbl.text = self.name self.src_path_lbl.text = self.src_path self.dst_path_lbl.text = self.dst_path self.kp_lbl.text = self.kp self.timestamp_lbl.text = self.timestamp class KeysRecycleView(RecycleView): """Extension of Kivy's RecycleView to present Key Pair meta data. A RecycleView is used as it allows the table data to be handled more efficiently by Kivy. Args: kwargs: Any additional keyword arguments. Attributes: viewclass (str): The class that sets the content for this view. scroll_type (list[str]): The ways the widget can be scrolled. bar_width (int): The width of the displayed scroll bar. do_scroll_x (bool): Set to True to allow horizontal scrolling. do_scroll_y (bool): Set to True to allow vertical scrolling. size_hint (tuple[int, int]): Set to fill the parent viewport. """ def __init__(self, **kwargs): super(KeysRecycleView, self).__init__(**kwargs) # Set the RecycleView's widgets and parameters self.add_widget(TableRecycleBoxLayout()) self.viewclass = "KeysTableRow" self.scroll_type = ["bars", "content"] self.bar_width = "12dp" self.do_scroll_x = True self.do_scroll_y = True # self.size_hint = (1, 1) # Set the data for the RecycleView with a bold faced header row tmp_data = [ { "name": "[b]Name[/b]", "pw": "[b]Has Password[/b]", "hint": "[b]Password Hint[/b]", "strong": "[b]Strong Password[/b]", "timestamp": "[b]Timestamp[/b]", } ] tmp_data += get_key_pairs() self.data = tmp_data # Set the max width for the Key Pairs table data set_max_width(tmp_data, keys=True) class KeysTableRow(BoxLayout): """Represents a single row of Key Pair meta data using Kivy's BoxLayout. Args: kwargs: Any additional keyword arguments. Attributes: orientation (str): The direction in which widgets are arranged. size_hint: Set to None to force the desired sizing. width (int): The overall width of the row. height (int): The overall height of the row. """ def __init__(self, **kwargs): super(KeysTableRow, self).__init__(**kwargs) self.orientation = "horizontal" self.size_hint = (None, None) self.width = KEYS_MAX_WIDTH self.height = "32dp" self.name_lbl = Label(markup=True, text="") self.pw_lbl = Label(markup=True, text="") self.hint_lbl = Label(markup=True, text="") self.strong_lbl = Label(markup=True, text="") self.timestamp_lbl = Label(markup=True, text="") self.add_widget(self.name_lbl) self.add_widget(self.pw_lbl) self.add_widget(self.hint_lbl) self.add_widget(self.strong_lbl) self.add_widget(self.timestamp_lbl) def on_parent(self, _screen, _parent): """Updates the row values when parent events are fired. Args: _screen (Widget): Required for Kivy on_parent. _parent (Widget): Required for Kivy on_parent. """ self.name_lbl.text = self.name self.pw_lbl.text = self.pw self.hint_lbl.text = self.hint self.strong_lbl.text = self.strong self.timestamp_lbl.text = self.timestamp class TableRecycleBoxLayout(RecycleBoxLayout): """Layout used for tables implemented using Kivy's RecycleBoxLayout. Args: kwargs: Any additional keyword arguments. Attributes: default_size: Set to None to force the desired sizing. default_size_hint: Set to None to force the desired sizing. size_hint_y: Set to None to force the desired sizing. size_hint_x: Set to None to force the desired sizing. orientation (str): The direction in which widgets are arranged. """ def __init__(self, **kwargs): super(TableRecycleBoxLayout, self).__init__(**kwargs) self.default_size = (None, None) self.default_size_hint = (None, None) self.size_hint_y = None self.size_hint_x = None self.orientation = "vertical" # Force the height and width to be equal to the minimum height and # width. Equivalent to kv language of: height: self.minimum_height self.bind(minimum_height=self._min_height) self.bind(minimum_width=self._min_width) def _min_height(self, _instance, value): """Method to set the height equal to the minimum height. Args: _instance (Widget): Required parameter for Kivy. value (int): The new value for the height. """ self.height = value def _min_width(self, _instance, value): """Method to set the width equal to the minimum width. Args: _instance (Widget): Required parameter for Kivy. value (int): The new value for the width. """ self.width = value def set_max_width(data, keys=False): """Sets the max width of tables displayed using Kivy's RecycleView. The max width parameters are stored as global variables to prevent having to set them for each and every row. Instead, they are set once when the RecycleView is instantiated. Args: data (list[dict[str, str]]): The table's data elements. keys (bool): True if key table max width is set, defaults to False. """ if keys: global KEYS_MAX_WIDTH KEYS_MAX_WIDTH = get_table_width(data) else: global ARCH_MAX_WIDTH ARCH_MAX_WIDTH = get_table_width(data)
import modules.statistics as s def update_user_stats(): update_user_global_stats() update_user_mission_stats() def update_user_global_stats(): for stats in s.models.UserStats.objects.all(): stats.update() for stats in s.models.UserStats.objects.all(): stats.update_agreement_ranking() def update_user_mission_stats(): for stats in s.models.UserMissionStats.objects.all(): stats.update() for stats in s.models.UserMissionStats.objects.all(): stats.update_agreement_ranking()
# # Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # # Tests AZ Layer creation, property modification and interaction with entity CRUD operations in the editor import sys import azlmbr.layers as layers import azlmbr.editor as editor import azlmbr.bus as bus import azlmbr.entity as entity import azlmbr.math as math def add_component(typename, entityId): typeIdsList = editor.EditorComponentAPIBus(bus.Broadcast, 'FindComponentTypeIdsByEntityType', [typename], entity.EntityType().Game) componentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentsOfType', entityId, typeIdsList) return componentOutcome.IsSuccess() def change_entity_status(desiredStatusProperty, entityId): editor.EditorEntityAPIBus(bus.Event, 'SetStartStatus', entityId, desiredStatusProperty) status = editor.EditorEntityInfoRequestBus(bus.Event, 'GetStartStatus', entityId) if (status == desiredStatusProperty): print('[PASS] successfully changed status: ' + str(desiredStatusProperty)) else: print('[FAIL] unable to set status: ' + str(desiredStatusProperty)) return # Test creating layer entity layerId = layers.EditorLayerComponent_CreateLayerEntityFromName('testLayer') if(layerId): print('[PASS] layer has been created') else: print('[FAIL] layer was not created') azlmbr.framework.Terminate(1) # Test getting and setting the name property for the layer name = editor.EditorEntityInfoRequestBus(bus.Event, 'GetName', layerId); if(name): print('[PASS] Get name request succeeded') else: print('[FAIL] Get name request failed') editor.EditorEntityAPIBus(bus.Event, 'SetName', layerId, "test_layer") name = editor.EditorEntityInfoRequestBus(bus.Event, 'GetName', layerId) if(name == 'test_layer'): print('[PASS] Layer name changed') else: print('[FAIL] Did not complete layer name change') # Test Getting and Setting the color for the layer color = math.Color_ConstructFromValues(255,255,0,1) oldColor = layers.EditorLayerComponentRequestBus(bus.Event, 'GetColorPropertyValue', layerId) layers.EditorLayerComponentRequestBus(bus.Event, 'SetLayerColor', layerId, color) newColor = layers.EditorLayerComponentRequestBus(bus.Event, 'GetColorPropertyValue', layerId) if(oldColor and newColor): if (oldColor != newColor): print('[PASS] Layer color changed') else: print('[FAIL] Was unable to change layer color property') else: print('[FAIL] Was unable to get color property of layer') # Test creating child entity in layer entity layerChild = editor.ToolsApplicationRequestBus(bus.Broadcast, 'CreateNewEntity', layerId) if (layerChild): print('[PASS] layer child entity has been created') else: print('[FAIL] layer child entity was not created') queryParent = editor.EditorEntityInfoRequestBus(bus.Event, 'GetParent', layerChild) if(queryParent.ToString() == layerId.ToString()): print('[PASS] Query parent returned layer ID') else: print('[FAIL] layer is not parented to entity') # Test getting child entity IDs childList = editor.EditorEntityInfoRequestBus(bus.Event, 'GetChildren', layerId) if(childList): print('[PASS] EditorEntityInfoRequestBus GetChildren return list of decendants') else: print('[FAILL] EditorEntityInfoRequestBus GetChildren did not return list of decendants') # Test adding component to layer entity result = add_component('Comment', layerId) if(result == True): print('[PASS] comment component has been added') else: print('[FAIL] comment component was not added to layer') # Test locking layer entity. Note: layers themselves are not locked or unlocked; # setting lock on a layer effectively sets the lock for all child entities queryLock = editor.EditorEntityInfoRequestBus(bus.Event, 'IsLocked', layerId) if(queryLock == False): print('[INFO] layer is not locked') editor.EditorEntityAPIBus(bus.Event, 'SetLockState', layerId, True) queryLock = editor.EditorEntityInfoRequestBus(bus.Event, 'IsLocked', layerId) if(queryLock == True): print('[PASS] layer has been locked') else: print('[FAIL] layer was no locked') # Test layer visibility. Note: layers themselves are not visible or invisible; # setting visibility on a layer effectively sets visibility for all child entities queryVisibility = editor.EditorEntityInfoRequestBus(bus.Event, 'IsVisible', layerChild) if(queryVisibility == True): print('[INFO] layer children are visible') layers.EditorLayerComponentRequestBus(azlmbr.bus.Event, 'SetVisibility', layerId, False) queryVisibility = editor.EditorEntityInfoRequestBus(bus.Event, 'IsVisible', layerChild) if(queryVisibility == False): print('[PASS] layer children are hidden') else: print('[FAIL] unable to set layer visibility to hidden') # Test layer status property # start active change_entity_status(azlmbr.globals.property.EditorEntityStartStatus_StartActive, layerId) # start inactive change_entity_status(azlmbr.globals.property.EditorEntityStartStatus_StartInactive, layerId) # editor only change_entity_status(azlmbr.globals.property.EditorEntityStartStatus_EditorOnly, layerId) # Test deleting layer editor.ToolsApplicationRequestBus(bus.Broadcast, 'DeleteEntityAndAllDescendants', layerId) entityName = editor.EditorEntityInfoRequestBus(bus.Event, 'GetName', layerId) if (entityName): print('[FAIL] Layer entity found after delete request') else: print('[PASS] Layer entity not found after delete request') # Close editor without saving editor.EditorToolsApplicationRequestBus(bus.Broadcast, 'ExitNoPrompt')
# # Copyright (c) 2017 Intel 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. # import scipy.ndimage try: import matplotlib.pyplot as plt except: from logger import failed_imports failed_imports.append("matplotlib") import copy from renderer import Renderer from configurations import Preset from collections import deque from utils import LazyStack from collections import OrderedDict from utils import RunPhase, Signal, is_empty, RunningStat from architectures import * from exploration_policies import * from memories import * from memories.memory import * from logger import logger, screen import random import time import os import itertools from architectures.tensorflow_components.shared_variables import SharedRunningStats from six.moves import range class Agent(object): def __init__(self, env, tuning_parameters, replicated_device=None, task_id=0): """ :param env: An environment instance :type env: EnvironmentWrapper :param tuning_parameters: A Preset class instance with all the running paramaters :type tuning_parameters: Preset :param replicated_device: A tensorflow device for distributed training (optional) :type replicated_device: instancemethod :param thread_id: The current thread id :param thread_id: int """ screen.log_title("Creating agent {}".format(task_id)) self.task_id = task_id self.sess = tuning_parameters.sess self.env = tuning_parameters.env_instance = env self.imitation = False # i/o dimensions if not tuning_parameters.env.desired_observation_width or not tuning_parameters.env.desired_observation_height: tuning_parameters.env.desired_observation_width = self.env.width tuning_parameters.env.desired_observation_height = self.env.height self.action_space_size = tuning_parameters.env.action_space_size = self.env.action_space_size self.measurements_size = tuning_parameters.env.measurements_size = self.env.measurements_size if tuning_parameters.agent.use_accumulated_reward_as_measurement: self.measurements_size = tuning_parameters.env.measurements_size = (self.measurements_size[0] + 1,) # modules if tuning_parameters.agent.load_memory_from_file_path: screen.log_title("Loading replay buffer from pickle. Pickle path: {}" .format(tuning_parameters.agent.load_memory_from_file_path)) self.memory = read_pickle(tuning_parameters.agent.load_memory_from_file_path) else: self.memory = eval(tuning_parameters.memory + '(tuning_parameters)') # self.architecture = eval(tuning_parameters.architecture) self.has_global = replicated_device is not None self.replicated_device = replicated_device self.worker_device = "/job:worker/task:{}/cpu:0".format(task_id) if replicated_device is not None else "/gpu:0" self.exploration_policy = eval(tuning_parameters.exploration.policy + '(tuning_parameters)') self.evaluation_exploration_policy = eval(tuning_parameters.exploration.evaluation_policy + '(tuning_parameters)') self.evaluation_exploration_policy.change_phase(RunPhase.TEST) # initialize all internal variables self.tp = tuning_parameters self.in_heatup = False self.total_reward_in_current_episode = 0 self.total_steps_counter = 0 self.running_reward = None self.training_iteration = 0 self.current_episode = self.tp.current_episode = 0 self.curr_state = {} self.current_episode_steps_counter = 0 self.episode_running_info = {} self.last_episode_evaluation_ran = 0 self.running_observations = [] logger.set_current_time(self.current_episode) self.main_network = None self.networks = [] self.last_episode_images = [] self.renderer = Renderer() # signals self.signals = [] self.loss = Signal('Loss') self.signals.append(self.loss) self.curr_learning_rate = Signal('Learning Rate') self.signals.append(self.curr_learning_rate) if self.tp.env.normalize_observation and not self.env.is_state_type_image: if not self.tp.distributed or not self.tp.agent.share_statistics_between_workers: self.running_observation_stats = RunningStat((self.tp.env.desired_observation_width,)) self.running_reward_stats = RunningStat(()) if self.tp.checkpoint_restore_dir: print("checkpoint_path:", checkpoint_path) checkpoint_path = os.path.join(self.tp.checkpoint_restore_dir, "running_stats.p") self.running_observation_stats = read_pickle(checkpoint_path) else: self.running_observation_stats = RunningStat((self.tp.env.desired_observation_width,)) self.running_reward_stats = RunningStat(()) else: self.running_observation_stats = SharedRunningStats(self.tp, replicated_device, shape=(self.tp.env.desired_observation_width,), name='observation_stats') self.running_reward_stats = SharedRunningStats(self.tp, replicated_device, shape=(), name='reward_stats') # env is already reset at this point. Otherwise we're getting an error where you cannot # reset an env which is not done self.reset_game(do_not_reset_env=True) # use seed if self.tp.seed is not None: random.seed(self.tp.seed) np.random.seed(self.tp.seed) def log_to_screen(self, phase): # log to screen if self.current_episode >= 0: if phase == RunPhase.TRAIN: exploration = self.exploration_policy.get_control_param() else: exploration = self.evaluation_exploration_policy.get_control_param() screen.log_dict( OrderedDict([ ("Worker", self.task_id), ("Episode", self.current_episode), ("total reward", self.total_reward_in_current_episode), ("exploration", exploration), ("steps", self.total_steps_counter), ("training iteration", self.training_iteration) ]), prefix=phase ) def update_log(self, phase=RunPhase.TRAIN): """ Writes logging messages to screen and updates the log file with all the signal values. :return: None """ # log all the signals to file logger.set_current_time(self.current_episode) logger.create_signal_value('Training Iter', self.training_iteration) logger.create_signal_value('In Heatup', int(phase == RunPhase.HEATUP)) logger.create_signal_value('ER #Transitions', self.memory.num_transitions()) logger.create_signal_value('ER #Episodes', self.memory.length()) logger.create_signal_value('Episode Length', self.current_episode_steps_counter) logger.create_signal_value('Total steps', self.total_steps_counter) logger.create_signal_value("Epsilon", self.exploration_policy.get_control_param()) logger.create_signal_value("Training Reward", self.total_reward_in_current_episode if phase == RunPhase.TRAIN else np.nan) logger.create_signal_value('Evaluation Reward', self.total_reward_in_current_episode if phase == RunPhase.TEST else np.nan) logger.create_signal_value('Update Target Network', 0, overwrite=False) logger.update_wall_clock_time(self.current_episode) for signal in self.signals: logger.create_signal_value("{}/Mean".format(signal.name), signal.get_mean()) logger.create_signal_value("{}/Stdev".format(signal.name), signal.get_stdev()) logger.create_signal_value("{}/Max".format(signal.name), signal.get_max()) logger.create_signal_value("{}/Min".format(signal.name), signal.get_min()) # dump if self.current_episode % self.tp.visualization.dump_signals_to_csv_every_x_episodes == 0 \ and self.current_episode > 0: logger.dump_output_csv() def reset_game(self, do_not_reset_env=False): """ Resets all the episodic parameters and start a new environment episode. :param do_not_reset_env: A boolean that allows prevention of environment reset :return: None """ for signal in self.signals: signal.reset() self.total_reward_in_current_episode = 0 self.curr_state = {} self.last_episode_images = [] self.current_episode_steps_counter = 0 self.episode_running_info = {} if not do_not_reset_env: self.env.reset() self.exploration_policy.reset() # required for online plotting if self.tp.visualization.plot_action_values_online: if hasattr(self, 'episode_running_info') and hasattr(self.env, 'actions_description'): for action in self.env.actions_description: self.episode_running_info[action] = [] plt.clf() if self.tp.agent.middleware_type == MiddlewareTypes.LSTM: for network in self.networks: network.online_network.curr_rnn_c_in = network.online_network.middleware_embedder.c_init network.online_network.curr_rnn_h_in = network.online_network.middleware_embedder.h_init self.prepare_initial_state() def preprocess_observation(self, observation): """ Preprocesses the given observation. For images - convert to grayscale, resize and convert to int. For measurements vectors - normalize by a running average and std. :param observation: The agents observation :return: A processed version of the observation """ if self.env.is_state_type_image: # rescale observation = scipy.misc.imresize(observation, (self.tp.env.desired_observation_height, self.tp.env.desired_observation_width), interp=self.tp.rescaling_interpolation_type) # rgb to y if len(observation.shape) > 2 and observation.shape[2] > 1: r, g, b = observation[:, :, 0], observation[:, :, 1], observation[:, :, 2] observation = 0.2989 * r + 0.5870 * g + 0.1140 * b # Render the processed observation which is how the agent will see it # Warning: this cannot currently be done in parallel to rendering the environment if self.tp.visualization.render_observation: if not self.renderer.is_open: self.renderer.create_screen(observation.shape[0], observation.shape[1]) self.renderer.render_image(observation) return observation.astype('uint8') else: if self.tp.env.normalize_observation and self.sess is not None: # standardize the input observation using a running mean and std if not self.tp.distributed or not self.tp.agent.share_statistics_between_workers: self.running_observation_stats.push(observation) observation = (observation - self.running_observation_stats.mean) / \ (self.running_observation_stats.std + 1e-15) observation = np.clip(observation, -5.0, 5.0) return observation def learn_from_batch(self, batch): """ Given a batch of transitions, calculates their target values and updates the network. :param batch: A list of transitions :return: The loss of the training """ pass def train(self): """ A single training iteration. Sample a batch, train on it and update target networks. :return: The training loss. """ batch = self.memory.sample(self.tp.batch_size) loss = self.learn_from_batch(batch) if self.tp.learning_rate_decay_rate != 0: self.curr_learning_rate.add_sample(self.tp.sess.run(self.tp.learning_rate)) else: self.curr_learning_rate.add_sample(self.tp.learning_rate) # update the target network of every network that has a target network if self.total_steps_counter % self.tp.agent.num_steps_between_copying_online_weights_to_target == 0: for network in self.networks: network.update_target_network(self.tp.agent.rate_for_copying_weights_to_target) logger.create_signal_value('Update Target Network', 1) else: logger.create_signal_value('Update Target Network', 0, overwrite=False) return loss def extract_batch(self, batch): """ Extracts a single numpy array for each object in a batch of transitions (state, action, etc.) :param batch: An array of transitions :return: For each transition element, returns a numpy array of all the transitions in the batch """ current_states = {} next_states = {} current_states['observation'] = np.array([np.array(transition.state['observation']) for transition in batch]) next_states['observation'] = np.array([np.array(transition.next_state['observation']) for transition in batch]) actions = np.array([transition.action for transition in batch]) rewards = np.array([transition.reward for transition in batch]) game_overs = np.array([transition.game_over for transition in batch]) total_return = np.array([transition.total_return for transition in batch]) # get the entire state including measurements if available if self.tp.agent.use_measurements: current_states['measurements'] = np.array([transition.state['measurements'] for transition in batch]) next_states['measurements'] = np.array([transition.next_state['measurements'] for transition in batch]) return current_states, next_states, actions, rewards, game_overs, total_return def plot_action_values_online(self): """ Plot an animated graph of the value of each possible action during the episode :return: None """ plt.clf() for key, data_list in self.episode_running_info.items(): plt.plot(data_list, label=key) plt.legend() plt.pause(0.00000001) def choose_action(self, curr_state, phase=RunPhase.TRAIN): """ choose an action to act with in the current episode being played. Different behavior might be exhibited when training or testing. :param curr_state: the current state to act upon. :param phase: the current phase: training or testing. :return: chosen action, some action value describing the action (q-value, probability, etc) """ pass def preprocess_reward(self, reward): if self.tp.env.reward_scaling: reward /= float(self.tp.env.reward_scaling) if self.tp.env.reward_clipping_max: reward = min(reward, self.tp.env.reward_clipping_max) if self.tp.env.reward_clipping_min: reward = max(reward, self.tp.env.reward_clipping_min) return reward def tf_input_state(self, curr_state): """ convert curr_state into input tensors tensorflow is expecting. """ # add batch axis with length 1 onto each value # extract values from the state based on agent.input_types input_state = {} for input_name in self.tp.agent.input_types.keys(): input_state[input_name] = np.expand_dims(np.array(curr_state[input_name]), 0) return input_state def prepare_initial_state(self): """ Create an initial state when starting a new episode :return: None """ observation = self.preprocess_observation(self.env.state['observation']) self.curr_stack = deque([observation]*self.tp.env.observation_stack_size, maxlen=self.tp.env.observation_stack_size) observation = LazyStack(self.curr_stack, -1) self.curr_state = { 'observation': observation } if self.tp.agent.use_measurements: if 'measurements' in self.env.state.keys(): self.curr_state['measurements'] = self.env.state['measurements'] else: self.curr_state['measurements'] = np.zeros(0) if self.tp.agent.use_accumulated_reward_as_measurement: self.curr_state['measurements'] = np.append(self.curr_state['measurements'], 0) def act(self, phase=RunPhase.TRAIN): """ Take one step in the environment according to the network prediction and store the transition in memory :param phase: Either Train or Test to specify if greedy actions should be used and if transitions should be stored :return: A boolean value that signals an episode termination """ action = self.act_get_action(phase) result = self.env.step(action) return self.act_process_reward(result, phase) def act_get_action(self, phase=RunPhase.TRAIN): if phase != RunPhase.TEST: self.total_steps_counter += 1 self.current_episode_steps_counter += 1 # get new action action_info = {"action_probability": 1.0 / self.env.action_space_size, "action_value": 0, "max_action_value": 0} if phase == RunPhase.HEATUP and not self.tp.heatup_using_network_decisions: action = self.env.get_random_action() else: action, action_info = self.choose_action(self.curr_state, phase=phase) # perform action if type(action) == np.ndarray: action = action.squeeze() # save internal state for `act_process_reward()` self.action_info = action_info return action def act_process_reward(self, result, phase=RunPhase.TRAIN): # resume internal state from `act_get_action()` action_info = self.action_info shaped_reward = self.preprocess_reward(result['reward']) if 'action_intrinsic_reward' in action_info.keys(): shaped_reward += action_info['action_intrinsic_reward'] # TODO: should total_reward_in_current_episode include shaped_reward? self.total_reward_in_current_episode += result['reward'] next_state = copy.copy(result['state']) next_state['observation'] = self.preprocess_observation(next_state['observation']) # plot action values online if self.tp.visualization.plot_action_values_online and phase != RunPhase.HEATUP: self.plot_action_values_online() # initialize the next state # TODO: provide option to stack more than just the observation self.curr_stack.append(next_state['observation']) observation = LazyStack(self.curr_stack, -1) next_state['observation'] = observation if self.tp.agent.use_measurements: if 'measurements' in result['state'].keys(): next_state['measurements'] = result['state']['measurements'] else: next_state['measurements'] = np.zeros(0) if self.tp.agent.use_accumulated_reward_as_measurement: next_state['measurements'] = np.append(next_state['measurements'], self.total_reward_in_current_episode) # store the transition only if we are training if phase == RunPhase.TRAIN or phase == RunPhase.HEATUP: transition = Transition(self.curr_state, result['action'], shaped_reward, next_state, result['done']) for key in action_info.keys(): transition.info[key] = action_info[key] if self.tp.agent.add_a_normalized_timestep_to_the_observation: transition.info['timestep'] = float(self.current_episode_steps_counter) / self.env.timestep_limit self.memory.store(transition) elif phase == RunPhase.TEST and self.tp.visualization.dump_gifs: # we store the transitions only for saving gifs self.last_episode_images.append(self.env.get_rendered_image()) # update the current state for the next step self.curr_state = next_state # deal with episode termination if result['done']: #if self.tp.visualization.dump_csv: # self.update_log(phase=phase) self.update_log(phase=phase) self.log_to_screen(phase=phase) if phase == RunPhase.TRAIN or phase == RunPhase.HEATUP: self.reset_game() self.current_episode += 1 self.tp.current_episode = self.current_episode # return episode really ended return result['done'] def evaluate(self, num_episodes, keep_networks_synced=False): """ Run in an evaluation mode for several episodes. Actions will be chosen greedily. :param keep_networks_synced: keep the online network in sync with the global network after every episode :param num_episodes: The number of episodes to evaluate on :return: None """ max_reward_achieved = -float('inf') average_evaluation_reward = 0 screen.log_title("Running evaluation") self.env.change_phase(RunPhase.TEST) for i in range(num_episodes): # keep the online network in sync with the global network if keep_networks_synced: for network in self.networks: network.sync() episode_ended = False while not episode_ended: episode_ended = self.act(phase=RunPhase.TEST) if keep_networks_synced \ and self.total_steps_counter % self.tp.agent.update_evaluation_agent_network_after_every_num_steps: for network in self.networks: network.sync() if self.total_reward_in_current_episode > max_reward_achieved: max_reward_achieved = self.total_reward_in_current_episode frame_skipping = int(5/self.tp.env.frame_skip) if self.tp.visualization.dump_gifs: logger.create_gif(self.last_episode_images[::frame_skipping], name='score-{}'.format(max_reward_achieved), fps=10) average_evaluation_reward += self.total_reward_in_current_episode self.reset_game() average_evaluation_reward /= float(num_episodes) self.env.change_phase(RunPhase.TRAIN) screen.log_title("Evaluation done. Average reward = {}.".format(average_evaluation_reward)) def post_training_commands(self): pass def improve(self): """ Training algorithms wrapper. Heatup >> [ Evaluate >> Play >> Train >> Save checkpoint ] :return: None """ # synchronize the online network weights with the global network for network in self.networks: network.sync() # heatup phase if self.tp.num_heatup_steps != 0: self.in_heatup = True screen.log_title("Starting heatup {}".format(self.task_id)) num_steps_required_for_one_training_batch = self.tp.batch_size * self.tp.env.observation_stack_size for step in range(max(self.tp.num_heatup_steps, num_steps_required_for_one_training_batch)): self.act(phase=RunPhase.HEATUP) # training phase self.in_heatup = False screen.log_title("Starting training {}".format(self.task_id)) self.exploration_policy.change_phase(RunPhase.TRAIN) training_start_time = time.time() model_snapshots_periods_passed = -1 self.reset_game() while self.training_iteration < self.tp.num_training_iterations: # evaluate evaluate_agent = (self.last_episode_evaluation_ran is not self.current_episode) and \ (self.current_episode % self.tp.evaluate_every_x_episodes == 0) evaluate_agent = evaluate_agent or \ (self.imitation and self.training_iteration > 0 and self.training_iteration % self.tp.evaluate_every_x_training_iterations == 0) if evaluate_agent: self.env.reset(force_environment_reset=True) self.last_episode_evaluation_ran = self.current_episode self.evaluate(self.tp.evaluation_episodes) # snapshot model if self.tp.save_model_sec and self.tp.save_model_sec > 0 and not self.tp.distributed: total_training_time = time.time() - training_start_time current_snapshot_period = (int(total_training_time) // self.tp.save_model_sec) if current_snapshot_period > model_snapshots_periods_passed: model_snapshots_periods_passed = current_snapshot_period self.save_model(model_snapshots_periods_passed) if hasattr(self, 'running_observation_state') and self.running_observation_stats is not None: to_pickle(self.running_observation_stats, os.path.join(self.tp.save_model_dir, "running_stats.p".format(model_snapshots_periods_passed))) # play and record in replay buffer if self.tp.agent.collect_new_data: if self.tp.agent.step_until_collecting_full_episodes: step = 0 while step < self.tp.agent.num_consecutive_playing_steps or self.memory.get_episode(-1).length() != 0: #self.act() action = self.act_get_action() yield action result = self.env.step(action) self.act_process_reward(result) step += 1 else: for step in range(self.tp.agent.num_consecutive_playing_steps): #self.act() action = self.act_get_action() yield action result = self.env.step(action) self.act_process_reward(result) # train if self.tp.train: for step in range(self.tp.agent.num_consecutive_training_steps): loss = self.train() self.loss.add_sample(loss) self.training_iteration += 1 if self.imitation: self.log_to_screen(RunPhase.TRAIN) self.post_training_commands() def save_model(self, model_id): self.main_network.save_model(model_id) #print(self.main_network) #def save_model_to_dir(self, save_dir): # self.main_network.save_model_to_dir(save_dir) # #def restore_model_from_dir(self, restore_dir): # self.main_network.restore_model_from_dir(restore_dir)
module.exports = { maxWorkers: '50%', testMatch: ['<rootDir>/__tests__/**/**.spec.[jt]s?(x)'], testPathIgnorePatterns: ['/node_modules/', '/lib/', '<rootDir>/lib/'], collectCoverage: Boolean(process.env.COVERAGE), collectCoverageFrom: ['<rootDir>/src/**/*.ts?(x)'], coveragePathIgnorePatterns: ['generated'], };
import atexit import numpy as np from numpy import uint64 from numpy.random import RandomState from projectq import MainEngine from projectq.backends import Simulator from projectq.ops import (All, C, CNOT, DaggeredGate, H, Measure, R, Rx, Ry, Rz, S, SqrtX, Swap, T, X, Y, Z, Rxx, Rzz) from projectq.ops._basics import BasicGate, BasicRotationGate from . import IQuantumSimulator from ..hal import command_unpacker, string_to_opcode class SxGate(BasicGate): """Gate that consists of consecutive S and X gate (pi-rotation with axis in x-y-plane). """ @property def matrix(self): return np.array([[0, 1], [1j, 0]]) def __str__(self): return "SX" #: Shortcut (instance of) :class:`projectq.ops.SxGate` Sx = SxGate() class SyGate(BasicGate): """Gate that consists of consecutive S and Y gate (pi-rotation with axis in x-y-plane). """ @property def matrix(self): return np.array([[0, 1j], [1, 0]]) def __str__(self): return "SY" #: Shortcut (instance of) :class:`projectq.ops.SyGate` Sy = SyGate() class PiXY(BasicRotationGate): """Pi-rotation with axis in x-y-plane gate class.""" @property def matrix(self): return np.array([[0, -np.sin(self.angle) - 1j * np.cos(self.angle)], [np.sin(self.angle) - 1j * np.cos(self.angle), 0]]) class PiYZ(BasicRotationGate): """Pi-rotation with axis in y-z-plane gate class.""" @property def matrix(self): return np.array([[np.cos(self.angle), -1j * np.sin(self.angle)], [1j * np.sin(self.angle), -1 * np.cos(self.angle)]]) class PiZX(BasicRotationGate): """Pi-rotation with axis in z-x-plane gate class.""" @property def matrix(self): return np.array([[np.cos(self.angle), np.sin(self.angle)], [np.sin(self.angle), -1 * np.cos(self.angle)]]) class Pswap(BasicRotationGate): """Parameterised swap gate class.""" @property def matrix(self): return np.array([[1, 0, 0, 0], [0, 0, np.exp(1j * self.angle), 0], [0, np.exp(1j * self.angle), 0, 0], [0, 0, 0, 1]]) class ProjectqQuantumSimulator(IQuantumSimulator): """Concrete ProjectQ implementation of the IQuantumSimulator interface. Parameters ---------- register_size: int Size of the qubit register. seed : int Random number generator seed for both the ProjectQ Simulator and circuit errors. backend ProjectQ backend, could use CircuitDrawer for debugging purposes. """ def __init__(self, register_size: int = 16, seed: int = None, backend=Simulator): self._engine = None self.backend = backend self.seed = seed # if random numbers are needed to simulate quantum noise use this # state in the following way self._random_state.rand() self._random_state = RandomState(seed) self._qubit_register = None self._measured_qubits = [] self._offset_registers = [0, 0] # offsets for qubit indexes 0 and 1 # defaulted to 16 because the bitcode status return # has 16 bits assigned for measurement results. self._qubit_register_size = register_size # assign projectq gate to each opcode self._parameterised_gate_dict = { 'CONTROL': C, 'R': R, 'RX': Rx, 'RY': Ry, 'RZ': Rz, 'PIXY': PiXY, 'PIYZ': PiYZ, 'PIZX': PiZX, 'PSWAP': Pswap, 'RXX': Rxx, 'RZZ': Rzz } self._constant_gate_dict = { # SINGLE 'H': H, 'S': S, 'SQRT_X': SqrtX, 'T': T, 'X': X, 'Y': Y, 'Z': Z, 'INVT': DaggeredGate(T), 'INVS': DaggeredGate(S), 'SX': Sx, # consecutive S and X gate, needed for RC 'SY': Sy, # consecutive S and Y gate, needed for RC # DUAL 'CNOT': CNOT, 'SWAP': Swap } atexit.register(self.cleanup) def __getstate__(self): # Copy the object's state from self.__dict__ which contains # all our instance attributes. Always use the dict.copy() # method to avoid modifying the original state. state = self.__dict__.copy() # Remove the engine has it generally unpickable. del state['_engine'] return state def __setstate__(self, state): # Restore instance attributes (i.e., filename and lineno). self.__dict__.update(state) # Restore the engine if self.backend == Simulator and self.seed is not None: self._engine = MainEngine(backend=Simulator(rnd_seed=self.seed)) else: self._engine = MainEngine(backend=self.backend()) def cleanup(self): """Release all the qubits that haven't been handled yet.""" if self._engine is not None: if self._qubit_register is not None: All(Measure) | self._qubit_register self._engine.flush() self._engine = None def get_offset(self, qubit_index: int): return self._offset_registers[qubit_index] def apply_gate(self, gate: BasicGate, qubit_index_0: int, qubit_index_1: int = None, parameter_0: float = None, parameter_1: float = None): """Receives command information and implements the gate on the corresponding qubit. Parameters ---------- gate : BasicGate ProjectQ gate to be applied. qubit_index : int Index of qubit for gate to be applied to. parameter : float Angle of gate if parametrised. """ if self._qubit_register is not None: if qubit_index_1 is None: # single qubit gate if parameter_0 is not None: gate(parameter_0) | self._qubit_register[qubit_index_0] else: gate | self._qubit_register[qubit_index_0] else: # multi qubit gate if parameter_0 is not None: gate(parameter_0) | ( self._qubit_register[qubit_index_1], self._qubit_register[qubit_index_0] ) else: gate | ( self._qubit_register[qubit_index_1], self._qubit_register[qubit_index_0] ) self._engine.flush() def _init_engine(self): if self._engine is not None: raise ValueError("Simulator engine already initialised!") if self.backend == Simulator and self.seed is not None: self._engine = MainEngine(backend=Simulator(rnd_seed=self.seed)) else: self._engine = MainEngine(backend=self.backend()) def _init_qureg(self): if self._qubit_register is None: self._qubit_register = self._engine.allocate_qureg( self._qubit_register_size ) self._measured_qubits = [] else: raise ValueError("Qubit register has already been initialised!") def accept_command( self, command: uint64 ) -> uint64: op, cmd_type, args, qubit_indexes = command_unpacker(command) op_obj = string_to_opcode(op) q_index_0 = qubit_indexes[0] + self.get_offset(0) q_index_1 = 0 if len(qubit_indexes) > 1: q_index_1 = qubit_indexes[1] + self.get_offset(1) for index in qubit_indexes: assert index <= self._qubit_register_size, \ f"Qubit index {index} greater than register size " + \ f"({self._qubit_register_size})!" if op == "START_SESSION": self._init_engine() elif op == "STATE_PREPARATION_ALL": self._init_qureg() elif op == "STATE_PREPARATION": if self._qubit_register is None: self._init_qureg() elif q_index_0 in self._measured_qubits: if int(self._qubit_register[q_index_0]): X | self._qubit_register[q_index_0] self._measured_qubits.remove(q_index_0) else: raise ValueError("Qubit already prepared!") elif op == "END_SESSION": self.cleanup() elif op == "QUBIT_MEASURE": if q_index_0 in self._measured_qubits: raise ValueError("Qubit already measured!") # This measures a single qubit at the time. Measure | self._qubit_register[q_index_0] self._engine.flush() measurement = int(self._qubit_register[q_index_0]) self._measured_qubits.append(q_index_0) if len(self._qubit_register) == len(self._measured_qubits): self._qubit_register = None # QUBIT INDEX [63-52] | OFFSET [51-12] | STATUS [11-7] | PADDING [6-1] | VALUE [0] # TODO: add STATUS return ( (qubit_indexes[0] << 52) | (self._offset_registers[0] << 12) | measurement ) elif op.split("_")[0] == "PAGE": self._offset_registers[int(op.split("_")[3])] = qubit_indexes[0] elif op == "ID": pass elif op_obj.param == "PARAM": if q_index_0 in self._measured_qubits: raise ValueError("Qubit requires re-preparation!") angle = args[-1] * (2 * np.pi) / 65536 gate = self._parameterised_gate_dict[op] if cmd_type == "SINGLE": self.apply_gate(gate, q_index_0, parameter_0=angle) else: self.apply_gate( gate, qubit_index_0=q_index_0, qubit_index_1=q_index_1, parameter_0=angle ) elif op_obj.param == "CONST": if q_index_0 in self._measured_qubits: raise ValueError("Qubit requires re-preparation!") gate = self._constant_gate_dict[op] if cmd_type == "SINGLE": self.apply_gate(gate, q_index_0) else: self.apply_gate( gate, qubit_index_0=q_index_0, qubit_index_1=q_index_1 ) else: raise TypeError(f"{op} is not a recognised opcode!")
""" *Standard Context* The standard context is the default context of text. """ from ._context import Context class StandardContext( Context, ): pass
/** * @file test_multi_connection.c * @author Ian Miller <imiller@adva.com> * @brief test for edits performed using multiple connections * * @copyright * Copyright 2020 ADVA Optical Networking Inc. * * 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. */ #define _GNU_SOURCE #include <string.h> #include <unistd.h> #include <setjmp.h> #include <stdarg.h> #include <stdlib.h> #include <cmocka.h> #include <libyang/libyang.h> #include "tests/config.h" #include "sysrepo.h" struct state { sr_conn_ctx_t *conn1; sr_conn_ctx_t *conn2; sr_conn_ctx_t *conn3; sr_session_ctx_t *sess1; sr_session_ctx_t *sess2; sr_session_ctx_t *sess3; }; static int setup_f(void **state) { struct state *st; uint32_t conn_count; st = malloc(sizeof *st); if (!st) { return 1; } *state = st; sr_connection_count(&conn_count); assert_int_equal(conn_count, 0); if (sr_connect(0, &st->conn1) != SR_ERR_OK) { return 1; } if (sr_install_module(st->conn1, TESTS_DIR "/files/test.yang", TESTS_DIR "/files", NULL, 0) != SR_ERR_OK) { return 1; } if (sr_install_module(st->conn1, TESTS_DIR "/files/ietf-interfaces.yang", TESTS_DIR "/files", NULL, 0) != SR_ERR_OK) { return 1; } if (sr_install_module(st->conn1, TESTS_DIR "/files/iana-if-type.yang", TESTS_DIR "/files", NULL, 0) != SR_ERR_OK) { return 1; } sr_disconnect(st->conn1); // Connection 1 if (sr_connect(0, &(st->conn1)) != SR_ERR_OK) { return 1; } if (sr_session_start(st->conn1, SR_DS_RUNNING, &st->sess1) != SR_ERR_OK) { return 1; } // Connection 2 if (sr_connect(0, &(st->conn2)) != SR_ERR_OK) { return 1; } if (sr_session_start(st->conn2, SR_DS_RUNNING, &st->sess2) != SR_ERR_OK) { return 1; } // Connection 3 if (sr_connect(0, &(st->conn3)) != SR_ERR_OK) { return 1; } if (sr_session_start(st->conn3, SR_DS_RUNNING, &st->sess3) != SR_ERR_OK) { return 1; } return 0; } static int teardown_f(void **state) { struct state *st = (struct state *)*state; sr_remove_module(st->conn1, "ietf-interfaces"); sr_remove_module(st->conn1, "iana-if-type"); sr_remove_module(st->conn1, "test"); sr_disconnect(st->conn1); sr_disconnect(st->conn2); sr_disconnect(st->conn3); free(st); return 0; } static int clear_interfaces(void **state) { struct state *st = (struct state *)*state; sr_delete_item(st->sess1, "/ietf-interfaces:interfaces", 0); sr_apply_changes(st->sess1, 0, 1); return 0; } static void test_connection_count(void **state) { struct state *st = (struct state *)*state; int ret; uint32_t count = 0; ret = sr_connection_count(&count); assert_int_equal(ret, SR_ERR_OK); assert_int_equal(count, 3); sr_disconnect(st->conn2); ret = sr_connection_count(&count); assert_int_equal(ret, SR_ERR_OK); assert_int_equal(count, 2); ret = sr_connect(0, &(st->conn2)); assert_int_equal(ret, SR_ERR_OK); ret = sr_session_start(st->conn2, SR_DS_RUNNING, &st->sess2); assert_int_equal(ret, SR_ERR_OK); ret = sr_connection_count(&count); assert_int_equal(ret, SR_ERR_OK); assert_int_equal(count, 3); } static void test_create1(void **state) { struct state *st = (struct state *)*state; struct lyd_node *subtree; char *str; //const char *str2; int ret; /* Create via two connections, retrieve by a third */ ret = sr_set_item_str(st->sess1, "/ietf-interfaces:interfaces/interface[name='ethS1']", NULL, NULL, SR_EDIT_STRICT); assert_int_equal(ret, SR_ERR_OK); ret = sr_set_item_str(st->sess1, "/ietf-interfaces:interfaces/interface[name='ethS1']/type", "iana-if-type:ethernetCsmacd", NULL, SR_EDIT_STRICT); assert_int_equal(ret, SR_ERR_OK); ret = sr_apply_changes(st->sess1, 0, 1); assert_int_equal(ret, SR_ERR_OK); ret = sr_set_item_str(st->sess2, "/ietf-interfaces:interfaces/interface[name='ethS2']", NULL, NULL, SR_EDIT_STRICT); assert_int_equal(ret, SR_ERR_OK); ret = sr_set_item_str(st->sess2, "/ietf-interfaces:interfaces/interface[name='ethS2']/type", "iana-if-type:ethernetCsmacd", NULL, SR_EDIT_STRICT); assert_int_equal(ret, SR_ERR_OK); ret = sr_apply_changes(st->sess2, 0, 1); assert_int_equal(ret, SR_ERR_OK); ret = sr_get_subtree(st->sess3, "/ietf-interfaces:interfaces", 0, &subtree); assert_int_equal(ret, SR_ERR_OK); lyd_print_mem(&str, subtree, LYD_XML, LYP_WITHSIBLINGS); lyd_free(subtree); const char *ptr = strstr(str, "ethS1"); assert_non_null(ptr); ptr = strstr(str, "ethS2"); assert_non_null(ptr); ptr = strstr(str, "ethS3"); assert_null(ptr); free(str); } int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test(test_connection_count), cmocka_unit_test_teardown(test_create1, clear_interfaces), }; setenv("CMOCKA_TEST_ABORT", "1", 1); sr_log_stderr(SR_LL_INF); return cmocka_run_group_tests(tests, setup_f, teardown_f); }
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from ._enums import * __all__ = [ 'AdditionalUnattendContentArgs', 'ApiEntityReferenceArgs', 'AutoOSUpgradePolicyArgs', 'BootDiagnosticsArgs', 'CreationDataArgs', 'DataDiskArgs', 'DiagnosticsProfileArgs', 'DiskEncryptionSettingsArgs', 'DiskSkuArgs', 'EncryptionSettingsArgs', 'HardwareProfileArgs', 'ImageDataDiskArgs', 'ImageDiskReferenceArgs', 'ImageOSDiskArgs', 'ImageReferenceArgs', 'ImageStorageProfileArgs', 'InstanceViewStatusArgs', 'KeyVaultAndKeyReferenceArgs', 'KeyVaultAndSecretReferenceArgs', 'KeyVaultKeyReferenceArgs', 'KeyVaultSecretReferenceArgs', 'LinuxConfigurationArgs', 'ManagedDiskParametersArgs', 'NetworkInterfaceReferenceArgs', 'NetworkProfileArgs', 'OSDiskArgs', 'OSProfileArgs', 'PlanArgs', 'RollingUpgradePolicyArgs', 'SkuArgs', 'SnapshotSkuArgs', 'SourceVaultArgs', 'SshConfigurationArgs', 'SshPublicKeyArgs', 'StorageProfileArgs', 'SubResourceArgs', 'UpgradePolicyArgs', 'VaultCertificateArgs', 'VaultSecretGroupArgs', 'VirtualHardDiskArgs', 'VirtualMachineExtensionInstanceViewArgs', 'VirtualMachineIdentityArgs', 'VirtualMachineScaleSetDataDiskArgs', 'VirtualMachineScaleSetExtensionProfileArgs', 'VirtualMachineScaleSetExtensionArgs', 'VirtualMachineScaleSetIPConfigurationArgs', 'VirtualMachineScaleSetIdentityArgs', 'VirtualMachineScaleSetIpTagArgs', 'VirtualMachineScaleSetManagedDiskParametersArgs', 'VirtualMachineScaleSetNetworkConfigurationDnsSettingsArgs', 'VirtualMachineScaleSetNetworkConfigurationArgs', 'VirtualMachineScaleSetNetworkProfileArgs', 'VirtualMachineScaleSetOSDiskArgs', 'VirtualMachineScaleSetOSProfileArgs', 'VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettingsArgs', 'VirtualMachineScaleSetPublicIPAddressConfigurationArgs', 'VirtualMachineScaleSetStorageProfileArgs', 'VirtualMachineScaleSetVMProfileArgs', 'WinRMConfigurationArgs', 'WinRMListenerArgs', 'WindowsConfigurationArgs', ] @pulumi.input_type class AdditionalUnattendContentArgs: def __init__(__self__, *, component_name: Optional[pulumi.Input['ComponentNames']] = None, content: Optional[pulumi.Input[str]] = None, pass_name: Optional[pulumi.Input['PassNames']] = None, setting_name: Optional[pulumi.Input['SettingNames']] = None): """ Specifies additional XML formatted information that can be included in the Unattend.xml file, which is used by Windows Setup. Contents are defined by setting name, component name, and the pass in which the content is applied. :param pulumi.Input['ComponentNames'] component_name: The component name. Currently, the only allowable value is Microsoft-Windows-Shell-Setup. :param pulumi.Input[str] content: Specifies the XML formatted content that is added to the unattend.xml file for the specified path and component. The XML must be less than 4KB and must include the root element for the setting or feature that is being inserted. :param pulumi.Input['PassNames'] pass_name: The pass name. Currently, the only allowable value is OobeSystem. :param pulumi.Input['SettingNames'] setting_name: Specifies the name of the setting to which the content applies. Possible values are: FirstLogonCommands and AutoLogon. """ if component_name is not None: pulumi.set(__self__, "component_name", component_name) if content is not None: pulumi.set(__self__, "content", content) if pass_name is not None: pulumi.set(__self__, "pass_name", pass_name) if setting_name is not None: pulumi.set(__self__, "setting_name", setting_name) @property @pulumi.getter(name="componentName") def component_name(self) -> Optional[pulumi.Input['ComponentNames']]: """ The component name. Currently, the only allowable value is Microsoft-Windows-Shell-Setup. """ return pulumi.get(self, "component_name") @component_name.setter def component_name(self, value: Optional[pulumi.Input['ComponentNames']]): pulumi.set(self, "component_name", value) @property @pulumi.getter def content(self) -> Optional[pulumi.Input[str]]: """ Specifies the XML formatted content that is added to the unattend.xml file for the specified path and component. The XML must be less than 4KB and must include the root element for the setting or feature that is being inserted. """ return pulumi.get(self, "content") @content.setter def content(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "content", value) @property @pulumi.getter(name="passName") def pass_name(self) -> Optional[pulumi.Input['PassNames']]: """ The pass name. Currently, the only allowable value is OobeSystem. """ return pulumi.get(self, "pass_name") @pass_name.setter def pass_name(self, value: Optional[pulumi.Input['PassNames']]): pulumi.set(self, "pass_name", value) @property @pulumi.getter(name="settingName") def setting_name(self) -> Optional[pulumi.Input['SettingNames']]: """ Specifies the name of the setting to which the content applies. Possible values are: FirstLogonCommands and AutoLogon. """ return pulumi.get(self, "setting_name") @setting_name.setter def setting_name(self, value: Optional[pulumi.Input['SettingNames']]): pulumi.set(self, "setting_name", value) @pulumi.input_type class ApiEntityReferenceArgs: def __init__(__self__, *, id: Optional[pulumi.Input[str]] = None): """ The API entity reference. :param pulumi.Input[str] id: The ARM resource id in the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/... """ if id is not None: pulumi.set(__self__, "id", id) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ The ARM resource id in the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/... """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @pulumi.input_type class AutoOSUpgradePolicyArgs: def __init__(__self__, *, disable_auto_rollback: Optional[pulumi.Input[bool]] = None): """ The configuration parameters used for performing automatic OS upgrade. :param pulumi.Input[bool] disable_auto_rollback: Whether OS image rollback feature should be disabled. Default value is false. """ if disable_auto_rollback is not None: pulumi.set(__self__, "disable_auto_rollback", disable_auto_rollback) @property @pulumi.getter(name="disableAutoRollback") def disable_auto_rollback(self) -> Optional[pulumi.Input[bool]]: """ Whether OS image rollback feature should be disabled. Default value is false. """ return pulumi.get(self, "disable_auto_rollback") @disable_auto_rollback.setter def disable_auto_rollback(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "disable_auto_rollback", value) @pulumi.input_type class BootDiagnosticsArgs: def __init__(__self__, *, enabled: Optional[pulumi.Input[bool]] = None, storage_uri: Optional[pulumi.Input[str]] = None): """ Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. <br><br> You can easily view the output of your console log. <br><br> Azure also enables you to see a screenshot of the VM from the hypervisor. :param pulumi.Input[bool] enabled: Whether boot diagnostics should be enabled on the Virtual Machine. :param pulumi.Input[str] storage_uri: Uri of the storage account to use for placing the console output and screenshot. """ if enabled is not None: pulumi.set(__self__, "enabled", enabled) if storage_uri is not None: pulumi.set(__self__, "storage_uri", storage_uri) @property @pulumi.getter def enabled(self) -> Optional[pulumi.Input[bool]]: """ Whether boot diagnostics should be enabled on the Virtual Machine. """ return pulumi.get(self, "enabled") @enabled.setter def enabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "enabled", value) @property @pulumi.getter(name="storageUri") def storage_uri(self) -> Optional[pulumi.Input[str]]: """ Uri of the storage account to use for placing the console output and screenshot. """ return pulumi.get(self, "storage_uri") @storage_uri.setter def storage_uri(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "storage_uri", value) @pulumi.input_type class CreationDataArgs: def __init__(__self__, *, create_option: pulumi.Input[Union[str, 'DiskCreateOption']], image_reference: Optional[pulumi.Input['ImageDiskReferenceArgs']] = None, source_resource_id: Optional[pulumi.Input[str]] = None, source_uri: Optional[pulumi.Input[str]] = None, storage_account_id: Optional[pulumi.Input[str]] = None): """ Data used when creating a disk. :param pulumi.Input[Union[str, 'DiskCreateOption']] create_option: This enumerates the possible sources of a disk's creation. :param pulumi.Input['ImageDiskReferenceArgs'] image_reference: Disk source information. :param pulumi.Input[str] source_resource_id: If createOption is Copy, this is the ARM id of the source snapshot or disk. :param pulumi.Input[str] source_uri: If createOption is Import, this is the URI of a blob to be imported into a managed disk. :param pulumi.Input[str] storage_account_id: If createOption is Import, the Azure Resource Manager identifier of the storage account containing the blob to import as a disk. Required only if the blob is in a different subscription """ pulumi.set(__self__, "create_option", create_option) if image_reference is not None: pulumi.set(__self__, "image_reference", image_reference) if source_resource_id is not None: pulumi.set(__self__, "source_resource_id", source_resource_id) if source_uri is not None: pulumi.set(__self__, "source_uri", source_uri) if storage_account_id is not None: pulumi.set(__self__, "storage_account_id", storage_account_id) @property @pulumi.getter(name="createOption") def create_option(self) -> pulumi.Input[Union[str, 'DiskCreateOption']]: """ This enumerates the possible sources of a disk's creation. """ return pulumi.get(self, "create_option") @create_option.setter def create_option(self, value: pulumi.Input[Union[str, 'DiskCreateOption']]): pulumi.set(self, "create_option", value) @property @pulumi.getter(name="imageReference") def image_reference(self) -> Optional[pulumi.Input['ImageDiskReferenceArgs']]: """ Disk source information. """ return pulumi.get(self, "image_reference") @image_reference.setter def image_reference(self, value: Optional[pulumi.Input['ImageDiskReferenceArgs']]): pulumi.set(self, "image_reference", value) @property @pulumi.getter(name="sourceResourceId") def source_resource_id(self) -> Optional[pulumi.Input[str]]: """ If createOption is Copy, this is the ARM id of the source snapshot or disk. """ return pulumi.get(self, "source_resource_id") @source_resource_id.setter def source_resource_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "source_resource_id", value) @property @pulumi.getter(name="sourceUri") def source_uri(self) -> Optional[pulumi.Input[str]]: """ If createOption is Import, this is the URI of a blob to be imported into a managed disk. """ return pulumi.get(self, "source_uri") @source_uri.setter def source_uri(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "source_uri", value) @property @pulumi.getter(name="storageAccountId") def storage_account_id(self) -> Optional[pulumi.Input[str]]: """ If createOption is Import, the Azure Resource Manager identifier of the storage account containing the blob to import as a disk. Required only if the blob is in a different subscription """ return pulumi.get(self, "storage_account_id") @storage_account_id.setter def storage_account_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "storage_account_id", value) @pulumi.input_type class DataDiskArgs: def __init__(__self__, *, create_option: pulumi.Input[Union[str, 'DiskCreateOptionTypes']], lun: pulumi.Input[int], caching: Optional[pulumi.Input['CachingTypes']] = None, disk_size_gb: Optional[pulumi.Input[int]] = None, image: Optional[pulumi.Input['VirtualHardDiskArgs']] = None, managed_disk: Optional[pulumi.Input['ManagedDiskParametersArgs']] = None, name: Optional[pulumi.Input[str]] = None, vhd: Optional[pulumi.Input['VirtualHardDiskArgs']] = None, write_accelerator_enabled: Optional[pulumi.Input[bool]] = None): """ Describes a data disk. :param pulumi.Input[Union[str, 'DiskCreateOptionTypes']] create_option: Specifies how the virtual machine should be created.<br><br> Possible values are:<br><br> **Attach** \u2013 This value is used when you are using a specialized disk to create the virtual machine.<br><br> **FromImage** \u2013 This value is used when you are using an image to create the virtual machine. If you are using a platform image, you also use the imageReference element described above. If you are using a marketplace image, you also use the plan element previously described. :param pulumi.Input[int] lun: Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. :param pulumi.Input['CachingTypes'] caching: Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** :param pulumi.Input[int] disk_size_gb: Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB :param pulumi.Input['VirtualHardDiskArgs'] image: The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. If SourceImage is provided, the destination virtual hard drive must not exist. :param pulumi.Input['ManagedDiskParametersArgs'] managed_disk: The managed disk parameters. :param pulumi.Input[str] name: The disk name. :param pulumi.Input['VirtualHardDiskArgs'] vhd: The virtual hard disk. :param pulumi.Input[bool] write_accelerator_enabled: Specifies whether writeAccelerator should be enabled or disabled on the disk. """ pulumi.set(__self__, "create_option", create_option) pulumi.set(__self__, "lun", lun) if caching is not None: pulumi.set(__self__, "caching", caching) if disk_size_gb is not None: pulumi.set(__self__, "disk_size_gb", disk_size_gb) if image is not None: pulumi.set(__self__, "image", image) if managed_disk is not None: pulumi.set(__self__, "managed_disk", managed_disk) if name is not None: pulumi.set(__self__, "name", name) if vhd is not None: pulumi.set(__self__, "vhd", vhd) if write_accelerator_enabled is not None: pulumi.set(__self__, "write_accelerator_enabled", write_accelerator_enabled) @property @pulumi.getter(name="createOption") def create_option(self) -> pulumi.Input[Union[str, 'DiskCreateOptionTypes']]: """ Specifies how the virtual machine should be created.<br><br> Possible values are:<br><br> **Attach** \u2013 This value is used when you are using a specialized disk to create the virtual machine.<br><br> **FromImage** \u2013 This value is used when you are using an image to create the virtual machine. If you are using a platform image, you also use the imageReference element described above. If you are using a marketplace image, you also use the plan element previously described. """ return pulumi.get(self, "create_option") @create_option.setter def create_option(self, value: pulumi.Input[Union[str, 'DiskCreateOptionTypes']]): pulumi.set(self, "create_option", value) @property @pulumi.getter def lun(self) -> pulumi.Input[int]: """ Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. """ return pulumi.get(self, "lun") @lun.setter def lun(self, value: pulumi.Input[int]): pulumi.set(self, "lun", value) @property @pulumi.getter def caching(self) -> Optional[pulumi.Input['CachingTypes']]: """ Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** """ return pulumi.get(self, "caching") @caching.setter def caching(self, value: Optional[pulumi.Input['CachingTypes']]): pulumi.set(self, "caching", value) @property @pulumi.getter(name="diskSizeGB") def disk_size_gb(self) -> Optional[pulumi.Input[int]]: """ Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB """ return pulumi.get(self, "disk_size_gb") @disk_size_gb.setter def disk_size_gb(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "disk_size_gb", value) @property @pulumi.getter def image(self) -> Optional[pulumi.Input['VirtualHardDiskArgs']]: """ The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. If SourceImage is provided, the destination virtual hard drive must not exist. """ return pulumi.get(self, "image") @image.setter def image(self, value: Optional[pulumi.Input['VirtualHardDiskArgs']]): pulumi.set(self, "image", value) @property @pulumi.getter(name="managedDisk") def managed_disk(self) -> Optional[pulumi.Input['ManagedDiskParametersArgs']]: """ The managed disk parameters. """ return pulumi.get(self, "managed_disk") @managed_disk.setter def managed_disk(self, value: Optional[pulumi.Input['ManagedDiskParametersArgs']]): pulumi.set(self, "managed_disk", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ The disk name. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def vhd(self) -> Optional[pulumi.Input['VirtualHardDiskArgs']]: """ The virtual hard disk. """ return pulumi.get(self, "vhd") @vhd.setter def vhd(self, value: Optional[pulumi.Input['VirtualHardDiskArgs']]): pulumi.set(self, "vhd", value) @property @pulumi.getter(name="writeAcceleratorEnabled") def write_accelerator_enabled(self) -> Optional[pulumi.Input[bool]]: """ Specifies whether writeAccelerator should be enabled or disabled on the disk. """ return pulumi.get(self, "write_accelerator_enabled") @write_accelerator_enabled.setter def write_accelerator_enabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "write_accelerator_enabled", value) @pulumi.input_type class DiagnosticsProfileArgs: def __init__(__self__, *, boot_diagnostics: Optional[pulumi.Input['BootDiagnosticsArgs']] = None): """ Specifies the boot diagnostic settings state. <br><br>Minimum api-version: 2015-06-15. :param pulumi.Input['BootDiagnosticsArgs'] boot_diagnostics: Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. <br><br> You can easily view the output of your console log. <br><br> Azure also enables you to see a screenshot of the VM from the hypervisor. """ if boot_diagnostics is not None: pulumi.set(__self__, "boot_diagnostics", boot_diagnostics) @property @pulumi.getter(name="bootDiagnostics") def boot_diagnostics(self) -> Optional[pulumi.Input['BootDiagnosticsArgs']]: """ Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. <br><br> You can easily view the output of your console log. <br><br> Azure also enables you to see a screenshot of the VM from the hypervisor. """ return pulumi.get(self, "boot_diagnostics") @boot_diagnostics.setter def boot_diagnostics(self, value: Optional[pulumi.Input['BootDiagnosticsArgs']]): pulumi.set(self, "boot_diagnostics", value) @pulumi.input_type class DiskEncryptionSettingsArgs: def __init__(__self__, *, disk_encryption_key: Optional[pulumi.Input['KeyVaultSecretReferenceArgs']] = None, enabled: Optional[pulumi.Input[bool]] = None, key_encryption_key: Optional[pulumi.Input['KeyVaultKeyReferenceArgs']] = None): """ Describes a Encryption Settings for a Disk :param pulumi.Input['KeyVaultSecretReferenceArgs'] disk_encryption_key: Specifies the location of the disk encryption key, which is a Key Vault Secret. :param pulumi.Input[bool] enabled: Specifies whether disk encryption should be enabled on the virtual machine. :param pulumi.Input['KeyVaultKeyReferenceArgs'] key_encryption_key: Specifies the location of the key encryption key in Key Vault. """ if disk_encryption_key is not None: pulumi.set(__self__, "disk_encryption_key", disk_encryption_key) if enabled is not None: pulumi.set(__self__, "enabled", enabled) if key_encryption_key is not None: pulumi.set(__self__, "key_encryption_key", key_encryption_key) @property @pulumi.getter(name="diskEncryptionKey") def disk_encryption_key(self) -> Optional[pulumi.Input['KeyVaultSecretReferenceArgs']]: """ Specifies the location of the disk encryption key, which is a Key Vault Secret. """ return pulumi.get(self, "disk_encryption_key") @disk_encryption_key.setter def disk_encryption_key(self, value: Optional[pulumi.Input['KeyVaultSecretReferenceArgs']]): pulumi.set(self, "disk_encryption_key", value) @property @pulumi.getter def enabled(self) -> Optional[pulumi.Input[bool]]: """ Specifies whether disk encryption should be enabled on the virtual machine. """ return pulumi.get(self, "enabled") @enabled.setter def enabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "enabled", value) @property @pulumi.getter(name="keyEncryptionKey") def key_encryption_key(self) -> Optional[pulumi.Input['KeyVaultKeyReferenceArgs']]: """ Specifies the location of the key encryption key in Key Vault. """ return pulumi.get(self, "key_encryption_key") @key_encryption_key.setter def key_encryption_key(self, value: Optional[pulumi.Input['KeyVaultKeyReferenceArgs']]): pulumi.set(self, "key_encryption_key", value) @pulumi.input_type class DiskSkuArgs: def __init__(__self__, *, name: Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]] = None): """ The disks sku name. Can be Standard_LRS, Premium_LRS, or StandardSSD_LRS. :param pulumi.Input[Union[str, 'StorageAccountTypes']] name: The sku name. """ if name is not None: pulumi.set(__self__, "name", name) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]]: """ The sku name. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]]): pulumi.set(self, "name", value) @pulumi.input_type class EncryptionSettingsArgs: def __init__(__self__, *, disk_encryption_key: Optional[pulumi.Input['KeyVaultAndSecretReferenceArgs']] = None, enabled: Optional[pulumi.Input[bool]] = None, key_encryption_key: Optional[pulumi.Input['KeyVaultAndKeyReferenceArgs']] = None): """ Encryption settings for disk or snapshot :param pulumi.Input['KeyVaultAndSecretReferenceArgs'] disk_encryption_key: Key Vault Secret Url and vault id of the disk encryption key :param pulumi.Input[bool] enabled: Set this flag to true and provide DiskEncryptionKey and optional KeyEncryptionKey to enable encryption. Set this flag to false and remove DiskEncryptionKey and KeyEncryptionKey to disable encryption. If EncryptionSettings is null in the request object, the existing settings remain unchanged. :param pulumi.Input['KeyVaultAndKeyReferenceArgs'] key_encryption_key: Key Vault Key Url and vault id of the key encryption key """ if disk_encryption_key is not None: pulumi.set(__self__, "disk_encryption_key", disk_encryption_key) if enabled is not None: pulumi.set(__self__, "enabled", enabled) if key_encryption_key is not None: pulumi.set(__self__, "key_encryption_key", key_encryption_key) @property @pulumi.getter(name="diskEncryptionKey") def disk_encryption_key(self) -> Optional[pulumi.Input['KeyVaultAndSecretReferenceArgs']]: """ Key Vault Secret Url and vault id of the disk encryption key """ return pulumi.get(self, "disk_encryption_key") @disk_encryption_key.setter def disk_encryption_key(self, value: Optional[pulumi.Input['KeyVaultAndSecretReferenceArgs']]): pulumi.set(self, "disk_encryption_key", value) @property @pulumi.getter def enabled(self) -> Optional[pulumi.Input[bool]]: """ Set this flag to true and provide DiskEncryptionKey and optional KeyEncryptionKey to enable encryption. Set this flag to false and remove DiskEncryptionKey and KeyEncryptionKey to disable encryption. If EncryptionSettings is null in the request object, the existing settings remain unchanged. """ return pulumi.get(self, "enabled") @enabled.setter def enabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "enabled", value) @property @pulumi.getter(name="keyEncryptionKey") def key_encryption_key(self) -> Optional[pulumi.Input['KeyVaultAndKeyReferenceArgs']]: """ Key Vault Key Url and vault id of the key encryption key """ return pulumi.get(self, "key_encryption_key") @key_encryption_key.setter def key_encryption_key(self, value: Optional[pulumi.Input['KeyVaultAndKeyReferenceArgs']]): pulumi.set(self, "key_encryption_key", value) @pulumi.input_type class HardwareProfileArgs: def __init__(__self__, *, vm_size: Optional[pulumi.Input[Union[str, 'VirtualMachineSizeTypes']]] = None): """ Specifies the hardware settings for the virtual machine. :param pulumi.Input[Union[str, 'VirtualMachineSizeTypes']] vm_size: Specifies the size of the virtual machine. For more information about virtual machine sizes, see [Sizes for virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-sizes?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). <br><br> The available VM sizes depend on region and availability set. For a list of available sizes use these APIs: <br><br> [List all available virtual machine sizes in an availability set](https://docs.microsoft.com/rest/api/compute/availabilitysets/listavailablesizes) <br><br> [List all available virtual machine sizes in a region](https://docs.microsoft.com/rest/api/compute/virtualmachinesizes/list) <br><br> [List all available virtual machine sizes for resizing](https://docs.microsoft.com/rest/api/compute/virtualmachines/listavailablesizes) """ if vm_size is not None: pulumi.set(__self__, "vm_size", vm_size) @property @pulumi.getter(name="vmSize") def vm_size(self) -> Optional[pulumi.Input[Union[str, 'VirtualMachineSizeTypes']]]: """ Specifies the size of the virtual machine. For more information about virtual machine sizes, see [Sizes for virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-sizes?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). <br><br> The available VM sizes depend on region and availability set. For a list of available sizes use these APIs: <br><br> [List all available virtual machine sizes in an availability set](https://docs.microsoft.com/rest/api/compute/availabilitysets/listavailablesizes) <br><br> [List all available virtual machine sizes in a region](https://docs.microsoft.com/rest/api/compute/virtualmachinesizes/list) <br><br> [List all available virtual machine sizes for resizing](https://docs.microsoft.com/rest/api/compute/virtualmachines/listavailablesizes) """ return pulumi.get(self, "vm_size") @vm_size.setter def vm_size(self, value: Optional[pulumi.Input[Union[str, 'VirtualMachineSizeTypes']]]): pulumi.set(self, "vm_size", value) @pulumi.input_type class ImageDataDiskArgs: def __init__(__self__, *, lun: pulumi.Input[int], blob_uri: Optional[pulumi.Input[str]] = None, caching: Optional[pulumi.Input['CachingTypes']] = None, disk_size_gb: Optional[pulumi.Input[int]] = None, managed_disk: Optional[pulumi.Input['SubResourceArgs']] = None, snapshot: Optional[pulumi.Input['SubResourceArgs']] = None, storage_account_type: Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]] = None): """ Describes a data disk. :param pulumi.Input[int] lun: Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. :param pulumi.Input[str] blob_uri: The Virtual Hard Disk. :param pulumi.Input['CachingTypes'] caching: Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** :param pulumi.Input[int] disk_size_gb: Specifies the size of empty data disks in gigabytes. This element can be used to overwrite the name of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB :param pulumi.Input['SubResourceArgs'] managed_disk: The managedDisk. :param pulumi.Input['SubResourceArgs'] snapshot: The snapshot. :param pulumi.Input[Union[str, 'StorageAccountTypes']] storage_account_type: Specifies the storage account type for the managed disk. Possible values are: Standard_LRS, Premium_LRS, and StandardSSD_LRS. """ pulumi.set(__self__, "lun", lun) if blob_uri is not None: pulumi.set(__self__, "blob_uri", blob_uri) if caching is not None: pulumi.set(__self__, "caching", caching) if disk_size_gb is not None: pulumi.set(__self__, "disk_size_gb", disk_size_gb) if managed_disk is not None: pulumi.set(__self__, "managed_disk", managed_disk) if snapshot is not None: pulumi.set(__self__, "snapshot", snapshot) if storage_account_type is not None: pulumi.set(__self__, "storage_account_type", storage_account_type) @property @pulumi.getter def lun(self) -> pulumi.Input[int]: """ Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. """ return pulumi.get(self, "lun") @lun.setter def lun(self, value: pulumi.Input[int]): pulumi.set(self, "lun", value) @property @pulumi.getter(name="blobUri") def blob_uri(self) -> Optional[pulumi.Input[str]]: """ The Virtual Hard Disk. """ return pulumi.get(self, "blob_uri") @blob_uri.setter def blob_uri(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "blob_uri", value) @property @pulumi.getter def caching(self) -> Optional[pulumi.Input['CachingTypes']]: """ Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** """ return pulumi.get(self, "caching") @caching.setter def caching(self, value: Optional[pulumi.Input['CachingTypes']]): pulumi.set(self, "caching", value) @property @pulumi.getter(name="diskSizeGB") def disk_size_gb(self) -> Optional[pulumi.Input[int]]: """ Specifies the size of empty data disks in gigabytes. This element can be used to overwrite the name of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB """ return pulumi.get(self, "disk_size_gb") @disk_size_gb.setter def disk_size_gb(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "disk_size_gb", value) @property @pulumi.getter(name="managedDisk") def managed_disk(self) -> Optional[pulumi.Input['SubResourceArgs']]: """ The managedDisk. """ return pulumi.get(self, "managed_disk") @managed_disk.setter def managed_disk(self, value: Optional[pulumi.Input['SubResourceArgs']]): pulumi.set(self, "managed_disk", value) @property @pulumi.getter def snapshot(self) -> Optional[pulumi.Input['SubResourceArgs']]: """ The snapshot. """ return pulumi.get(self, "snapshot") @snapshot.setter def snapshot(self, value: Optional[pulumi.Input['SubResourceArgs']]): pulumi.set(self, "snapshot", value) @property @pulumi.getter(name="storageAccountType") def storage_account_type(self) -> Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]]: """ Specifies the storage account type for the managed disk. Possible values are: Standard_LRS, Premium_LRS, and StandardSSD_LRS. """ return pulumi.get(self, "storage_account_type") @storage_account_type.setter def storage_account_type(self, value: Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]]): pulumi.set(self, "storage_account_type", value) @pulumi.input_type class ImageDiskReferenceArgs: def __init__(__self__, *, id: pulumi.Input[str], lun: Optional[pulumi.Input[int]] = None): """ The source image used for creating the disk. :param pulumi.Input[str] id: A relative uri containing either a Platform Image Repository or user image reference. :param pulumi.Input[int] lun: If the disk is created from an image's data disk, this is an index that indicates which of the data disks in the image to use. For OS disks, this field is null. """ pulumi.set(__self__, "id", id) if lun is not None: pulumi.set(__self__, "lun", lun) @property @pulumi.getter def id(self) -> pulumi.Input[str]: """ A relative uri containing either a Platform Image Repository or user image reference. """ return pulumi.get(self, "id") @id.setter def id(self, value: pulumi.Input[str]): pulumi.set(self, "id", value) @property @pulumi.getter def lun(self) -> Optional[pulumi.Input[int]]: """ If the disk is created from an image's data disk, this is an index that indicates which of the data disks in the image to use. For OS disks, this field is null. """ return pulumi.get(self, "lun") @lun.setter def lun(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "lun", value) @pulumi.input_type class ImageOSDiskArgs: def __init__(__self__, *, os_state: pulumi.Input['OperatingSystemStateTypes'], os_type: pulumi.Input['OperatingSystemTypes'], blob_uri: Optional[pulumi.Input[str]] = None, caching: Optional[pulumi.Input['CachingTypes']] = None, disk_size_gb: Optional[pulumi.Input[int]] = None, managed_disk: Optional[pulumi.Input['SubResourceArgs']] = None, snapshot: Optional[pulumi.Input['SubResourceArgs']] = None, storage_account_type: Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]] = None): """ Describes an Operating System disk. :param pulumi.Input['OperatingSystemStateTypes'] os_state: The OS State. :param pulumi.Input['OperatingSystemTypes'] os_type: This property allows you to specify the type of the OS that is included in the disk if creating a VM from a custom image. <br><br> Possible values are: <br><br> **Windows** <br><br> **Linux** :param pulumi.Input[str] blob_uri: The Virtual Hard Disk. :param pulumi.Input['CachingTypes'] caching: Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** :param pulumi.Input[int] disk_size_gb: Specifies the size of empty data disks in gigabytes. This element can be used to overwrite the name of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB :param pulumi.Input['SubResourceArgs'] managed_disk: The managedDisk. :param pulumi.Input['SubResourceArgs'] snapshot: The snapshot. :param pulumi.Input[Union[str, 'StorageAccountTypes']] storage_account_type: Specifies the storage account type for the managed disk. Possible values are: Standard_LRS, Premium_LRS, and StandardSSD_LRS. """ pulumi.set(__self__, "os_state", os_state) pulumi.set(__self__, "os_type", os_type) if blob_uri is not None: pulumi.set(__self__, "blob_uri", blob_uri) if caching is not None: pulumi.set(__self__, "caching", caching) if disk_size_gb is not None: pulumi.set(__self__, "disk_size_gb", disk_size_gb) if managed_disk is not None: pulumi.set(__self__, "managed_disk", managed_disk) if snapshot is not None: pulumi.set(__self__, "snapshot", snapshot) if storage_account_type is not None: pulumi.set(__self__, "storage_account_type", storage_account_type) @property @pulumi.getter(name="osState") def os_state(self) -> pulumi.Input['OperatingSystemStateTypes']: """ The OS State. """ return pulumi.get(self, "os_state") @os_state.setter def os_state(self, value: pulumi.Input['OperatingSystemStateTypes']): pulumi.set(self, "os_state", value) @property @pulumi.getter(name="osType") def os_type(self) -> pulumi.Input['OperatingSystemTypes']: """ This property allows you to specify the type of the OS that is included in the disk if creating a VM from a custom image. <br><br> Possible values are: <br><br> **Windows** <br><br> **Linux** """ return pulumi.get(self, "os_type") @os_type.setter def os_type(self, value: pulumi.Input['OperatingSystemTypes']): pulumi.set(self, "os_type", value) @property @pulumi.getter(name="blobUri") def blob_uri(self) -> Optional[pulumi.Input[str]]: """ The Virtual Hard Disk. """ return pulumi.get(self, "blob_uri") @blob_uri.setter def blob_uri(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "blob_uri", value) @property @pulumi.getter def caching(self) -> Optional[pulumi.Input['CachingTypes']]: """ Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** """ return pulumi.get(self, "caching") @caching.setter def caching(self, value: Optional[pulumi.Input['CachingTypes']]): pulumi.set(self, "caching", value) @property @pulumi.getter(name="diskSizeGB") def disk_size_gb(self) -> Optional[pulumi.Input[int]]: """ Specifies the size of empty data disks in gigabytes. This element can be used to overwrite the name of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB """ return pulumi.get(self, "disk_size_gb") @disk_size_gb.setter def disk_size_gb(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "disk_size_gb", value) @property @pulumi.getter(name="managedDisk") def managed_disk(self) -> Optional[pulumi.Input['SubResourceArgs']]: """ The managedDisk. """ return pulumi.get(self, "managed_disk") @managed_disk.setter def managed_disk(self, value: Optional[pulumi.Input['SubResourceArgs']]): pulumi.set(self, "managed_disk", value) @property @pulumi.getter def snapshot(self) -> Optional[pulumi.Input['SubResourceArgs']]: """ The snapshot. """ return pulumi.get(self, "snapshot") @snapshot.setter def snapshot(self, value: Optional[pulumi.Input['SubResourceArgs']]): pulumi.set(self, "snapshot", value) @property @pulumi.getter(name="storageAccountType") def storage_account_type(self) -> Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]]: """ Specifies the storage account type for the managed disk. Possible values are: Standard_LRS, Premium_LRS, and StandardSSD_LRS. """ return pulumi.get(self, "storage_account_type") @storage_account_type.setter def storage_account_type(self, value: Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]]): pulumi.set(self, "storage_account_type", value) @pulumi.input_type class ImageReferenceArgs: def __init__(__self__, *, id: Optional[pulumi.Input[str]] = None, offer: Optional[pulumi.Input[str]] = None, publisher: Optional[pulumi.Input[str]] = None, sku: Optional[pulumi.Input[str]] = None, version: Optional[pulumi.Input[str]] = None): """ Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations. NOTE: Image reference publisher and offer can only be set when you create the scale set. :param pulumi.Input[str] id: Resource Id :param pulumi.Input[str] offer: Specifies the offer of the platform image or marketplace image used to create the virtual machine. :param pulumi.Input[str] publisher: The image publisher. :param pulumi.Input[str] sku: The image SKU. :param pulumi.Input[str] version: Specifies the version of the platform image or marketplace image used to create the virtual machine. The allowed formats are Major.Minor.Build or 'latest'. Major, Minor, and Build are decimal numbers. Specify 'latest' to use the latest version of an image available at deploy time. Even if you use 'latest', the VM image will not automatically update after deploy time even if a new version becomes available. """ if id is not None: pulumi.set(__self__, "id", id) if offer is not None: pulumi.set(__self__, "offer", offer) if publisher is not None: pulumi.set(__self__, "publisher", publisher) if sku is not None: pulumi.set(__self__, "sku", sku) if version is not None: pulumi.set(__self__, "version", version) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ Resource Id """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter def offer(self) -> Optional[pulumi.Input[str]]: """ Specifies the offer of the platform image or marketplace image used to create the virtual machine. """ return pulumi.get(self, "offer") @offer.setter def offer(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "offer", value) @property @pulumi.getter def publisher(self) -> Optional[pulumi.Input[str]]: """ The image publisher. """ return pulumi.get(self, "publisher") @publisher.setter def publisher(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "publisher", value) @property @pulumi.getter def sku(self) -> Optional[pulumi.Input[str]]: """ The image SKU. """ return pulumi.get(self, "sku") @sku.setter def sku(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "sku", value) @property @pulumi.getter def version(self) -> Optional[pulumi.Input[str]]: """ Specifies the version of the platform image or marketplace image used to create the virtual machine. The allowed formats are Major.Minor.Build or 'latest'. Major, Minor, and Build are decimal numbers. Specify 'latest' to use the latest version of an image available at deploy time. Even if you use 'latest', the VM image will not automatically update after deploy time even if a new version becomes available. """ return pulumi.get(self, "version") @version.setter def version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "version", value) @pulumi.input_type class ImageStorageProfileArgs: def __init__(__self__, *, data_disks: Optional[pulumi.Input[Sequence[pulumi.Input['ImageDataDiskArgs']]]] = None, os_disk: Optional[pulumi.Input['ImageOSDiskArgs']] = None, zone_resilient: Optional[pulumi.Input[bool]] = None): """ Describes a storage profile. :param pulumi.Input[Sequence[pulumi.Input['ImageDataDiskArgs']]] data_disks: Specifies the parameters that are used to add a data disk to a virtual machine. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). :param pulumi.Input['ImageOSDiskArgs'] os_disk: Specifies information about the operating system disk used by the virtual machine. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). :param pulumi.Input[bool] zone_resilient: Specifies whether an image is zone resilient or not. Default is false. Zone resilient images can be created only in regions that provide Zone Redundant Storage (ZRS). """ if data_disks is not None: pulumi.set(__self__, "data_disks", data_disks) if os_disk is not None: pulumi.set(__self__, "os_disk", os_disk) if zone_resilient is not None: pulumi.set(__self__, "zone_resilient", zone_resilient) @property @pulumi.getter(name="dataDisks") def data_disks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ImageDataDiskArgs']]]]: """ Specifies the parameters that are used to add a data disk to a virtual machine. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). """ return pulumi.get(self, "data_disks") @data_disks.setter def data_disks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ImageDataDiskArgs']]]]): pulumi.set(self, "data_disks", value) @property @pulumi.getter(name="osDisk") def os_disk(self) -> Optional[pulumi.Input['ImageOSDiskArgs']]: """ Specifies information about the operating system disk used by the virtual machine. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). """ return pulumi.get(self, "os_disk") @os_disk.setter def os_disk(self, value: Optional[pulumi.Input['ImageOSDiskArgs']]): pulumi.set(self, "os_disk", value) @property @pulumi.getter(name="zoneResilient") def zone_resilient(self) -> Optional[pulumi.Input[bool]]: """ Specifies whether an image is zone resilient or not. Default is false. Zone resilient images can be created only in regions that provide Zone Redundant Storage (ZRS). """ return pulumi.get(self, "zone_resilient") @zone_resilient.setter def zone_resilient(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "zone_resilient", value) @pulumi.input_type class InstanceViewStatusArgs: def __init__(__self__, *, code: Optional[pulumi.Input[str]] = None, display_status: Optional[pulumi.Input[str]] = None, level: Optional[pulumi.Input['StatusLevelTypes']] = None, message: Optional[pulumi.Input[str]] = None, time: Optional[pulumi.Input[str]] = None): """ Instance view status. :param pulumi.Input[str] code: The status code. :param pulumi.Input[str] display_status: The short localizable label for the status. :param pulumi.Input['StatusLevelTypes'] level: The level code. :param pulumi.Input[str] message: The detailed status message, including for alerts and error messages. :param pulumi.Input[str] time: The time of the status. """ if code is not None: pulumi.set(__self__, "code", code) if display_status is not None: pulumi.set(__self__, "display_status", display_status) if level is not None: pulumi.set(__self__, "level", level) if message is not None: pulumi.set(__self__, "message", message) if time is not None: pulumi.set(__self__, "time", time) @property @pulumi.getter def code(self) -> Optional[pulumi.Input[str]]: """ The status code. """ return pulumi.get(self, "code") @code.setter def code(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "code", value) @property @pulumi.getter(name="displayStatus") def display_status(self) -> Optional[pulumi.Input[str]]: """ The short localizable label for the status. """ return pulumi.get(self, "display_status") @display_status.setter def display_status(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "display_status", value) @property @pulumi.getter def level(self) -> Optional[pulumi.Input['StatusLevelTypes']]: """ The level code. """ return pulumi.get(self, "level") @level.setter def level(self, value: Optional[pulumi.Input['StatusLevelTypes']]): pulumi.set(self, "level", value) @property @pulumi.getter def message(self) -> Optional[pulumi.Input[str]]: """ The detailed status message, including for alerts and error messages. """ return pulumi.get(self, "message") @message.setter def message(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "message", value) @property @pulumi.getter def time(self) -> Optional[pulumi.Input[str]]: """ The time of the status. """ return pulumi.get(self, "time") @time.setter def time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "time", value) @pulumi.input_type class KeyVaultAndKeyReferenceArgs: def __init__(__self__, *, key_url: pulumi.Input[str], source_vault: pulumi.Input['SourceVaultArgs']): """ Key Vault Key Url and vault id of KeK, KeK is optional and when provided is used to unwrap the encryptionKey :param pulumi.Input[str] key_url: Url pointing to a key or secret in KeyVault :param pulumi.Input['SourceVaultArgs'] source_vault: Resource id of the KeyVault containing the key or secret """ pulumi.set(__self__, "key_url", key_url) pulumi.set(__self__, "source_vault", source_vault) @property @pulumi.getter(name="keyUrl") def key_url(self) -> pulumi.Input[str]: """ Url pointing to a key or secret in KeyVault """ return pulumi.get(self, "key_url") @key_url.setter def key_url(self, value: pulumi.Input[str]): pulumi.set(self, "key_url", value) @property @pulumi.getter(name="sourceVault") def source_vault(self) -> pulumi.Input['SourceVaultArgs']: """ Resource id of the KeyVault containing the key or secret """ return pulumi.get(self, "source_vault") @source_vault.setter def source_vault(self, value: pulumi.Input['SourceVaultArgs']): pulumi.set(self, "source_vault", value) @pulumi.input_type class KeyVaultAndSecretReferenceArgs: def __init__(__self__, *, secret_url: pulumi.Input[str], source_vault: pulumi.Input['SourceVaultArgs']): """ Key Vault Secret Url and vault id of the encryption key :param pulumi.Input[str] secret_url: Url pointing to a key or secret in KeyVault :param pulumi.Input['SourceVaultArgs'] source_vault: Resource id of the KeyVault containing the key or secret """ pulumi.set(__self__, "secret_url", secret_url) pulumi.set(__self__, "source_vault", source_vault) @property @pulumi.getter(name="secretUrl") def secret_url(self) -> pulumi.Input[str]: """ Url pointing to a key or secret in KeyVault """ return pulumi.get(self, "secret_url") @secret_url.setter def secret_url(self, value: pulumi.Input[str]): pulumi.set(self, "secret_url", value) @property @pulumi.getter(name="sourceVault") def source_vault(self) -> pulumi.Input['SourceVaultArgs']: """ Resource id of the KeyVault containing the key or secret """ return pulumi.get(self, "source_vault") @source_vault.setter def source_vault(self, value: pulumi.Input['SourceVaultArgs']): pulumi.set(self, "source_vault", value) @pulumi.input_type class KeyVaultKeyReferenceArgs: def __init__(__self__, *, key_url: pulumi.Input[str], source_vault: pulumi.Input['SubResourceArgs']): """ Describes a reference to Key Vault Key :param pulumi.Input[str] key_url: The URL referencing a key encryption key in Key Vault. :param pulumi.Input['SubResourceArgs'] source_vault: The relative URL of the Key Vault containing the key. """ pulumi.set(__self__, "key_url", key_url) pulumi.set(__self__, "source_vault", source_vault) @property @pulumi.getter(name="keyUrl") def key_url(self) -> pulumi.Input[str]: """ The URL referencing a key encryption key in Key Vault. """ return pulumi.get(self, "key_url") @key_url.setter def key_url(self, value: pulumi.Input[str]): pulumi.set(self, "key_url", value) @property @pulumi.getter(name="sourceVault") def source_vault(self) -> pulumi.Input['SubResourceArgs']: """ The relative URL of the Key Vault containing the key. """ return pulumi.get(self, "source_vault") @source_vault.setter def source_vault(self, value: pulumi.Input['SubResourceArgs']): pulumi.set(self, "source_vault", value) @pulumi.input_type class KeyVaultSecretReferenceArgs: def __init__(__self__, *, secret_url: pulumi.Input[str], source_vault: pulumi.Input['SubResourceArgs']): """ Describes a reference to Key Vault Secret :param pulumi.Input[str] secret_url: The URL referencing a secret in a Key Vault. :param pulumi.Input['SubResourceArgs'] source_vault: The relative URL of the Key Vault containing the secret. """ pulumi.set(__self__, "secret_url", secret_url) pulumi.set(__self__, "source_vault", source_vault) @property @pulumi.getter(name="secretUrl") def secret_url(self) -> pulumi.Input[str]: """ The URL referencing a secret in a Key Vault. """ return pulumi.get(self, "secret_url") @secret_url.setter def secret_url(self, value: pulumi.Input[str]): pulumi.set(self, "secret_url", value) @property @pulumi.getter(name="sourceVault") def source_vault(self) -> pulumi.Input['SubResourceArgs']: """ The relative URL of the Key Vault containing the secret. """ return pulumi.get(self, "source_vault") @source_vault.setter def source_vault(self, value: pulumi.Input['SubResourceArgs']): pulumi.set(self, "source_vault", value) @pulumi.input_type class LinuxConfigurationArgs: def __init__(__self__, *, disable_password_authentication: Optional[pulumi.Input[bool]] = None, ssh: Optional[pulumi.Input['SshConfigurationArgs']] = None): """ Specifies the Linux operating system settings on the virtual machine. <br><br>For a list of supported Linux distributions, see [Linux on Azure-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-endorsed-distros?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) <br><br> For running non-endorsed distributions, see [Information for Non-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-create-upload-generic?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json). :param pulumi.Input[bool] disable_password_authentication: Specifies whether password authentication should be disabled. :param pulumi.Input['SshConfigurationArgs'] ssh: Specifies the ssh key configuration for a Linux OS. """ if disable_password_authentication is not None: pulumi.set(__self__, "disable_password_authentication", disable_password_authentication) if ssh is not None: pulumi.set(__self__, "ssh", ssh) @property @pulumi.getter(name="disablePasswordAuthentication") def disable_password_authentication(self) -> Optional[pulumi.Input[bool]]: """ Specifies whether password authentication should be disabled. """ return pulumi.get(self, "disable_password_authentication") @disable_password_authentication.setter def disable_password_authentication(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "disable_password_authentication", value) @property @pulumi.getter def ssh(self) -> Optional[pulumi.Input['SshConfigurationArgs']]: """ Specifies the ssh key configuration for a Linux OS. """ return pulumi.get(self, "ssh") @ssh.setter def ssh(self, value: Optional[pulumi.Input['SshConfigurationArgs']]): pulumi.set(self, "ssh", value) @pulumi.input_type class ManagedDiskParametersArgs: def __init__(__self__, *, id: Optional[pulumi.Input[str]] = None, storage_account_type: Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]] = None): """ The parameters of a managed disk. :param pulumi.Input[str] id: Resource Id :param pulumi.Input[Union[str, 'StorageAccountTypes']] storage_account_type: Specifies the storage account type for the managed disk. Possible values are: Standard_LRS, Premium_LRS, and StandardSSD_LRS. """ if id is not None: pulumi.set(__self__, "id", id) if storage_account_type is not None: pulumi.set(__self__, "storage_account_type", storage_account_type) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ Resource Id """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter(name="storageAccountType") def storage_account_type(self) -> Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]]: """ Specifies the storage account type for the managed disk. Possible values are: Standard_LRS, Premium_LRS, and StandardSSD_LRS. """ return pulumi.get(self, "storage_account_type") @storage_account_type.setter def storage_account_type(self, value: Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]]): pulumi.set(self, "storage_account_type", value) @pulumi.input_type class NetworkInterfaceReferenceArgs: def __init__(__self__, *, id: Optional[pulumi.Input[str]] = None, primary: Optional[pulumi.Input[bool]] = None): """ Describes a network interface reference. :param pulumi.Input[str] id: Resource Id :param pulumi.Input[bool] primary: Specifies the primary network interface in case the virtual machine has more than 1 network interface. """ if id is not None: pulumi.set(__self__, "id", id) if primary is not None: pulumi.set(__self__, "primary", primary) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ Resource Id """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter def primary(self) -> Optional[pulumi.Input[bool]]: """ Specifies the primary network interface in case the virtual machine has more than 1 network interface. """ return pulumi.get(self, "primary") @primary.setter def primary(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "primary", value) @pulumi.input_type class NetworkProfileArgs: def __init__(__self__, *, network_interfaces: Optional[pulumi.Input[Sequence[pulumi.Input['NetworkInterfaceReferenceArgs']]]] = None): """ Specifies the network interfaces of the virtual machine. :param pulumi.Input[Sequence[pulumi.Input['NetworkInterfaceReferenceArgs']]] network_interfaces: Specifies the list of resource Ids for the network interfaces associated with the virtual machine. """ if network_interfaces is not None: pulumi.set(__self__, "network_interfaces", network_interfaces) @property @pulumi.getter(name="networkInterfaces") def network_interfaces(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['NetworkInterfaceReferenceArgs']]]]: """ Specifies the list of resource Ids for the network interfaces associated with the virtual machine. """ return pulumi.get(self, "network_interfaces") @network_interfaces.setter def network_interfaces(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['NetworkInterfaceReferenceArgs']]]]): pulumi.set(self, "network_interfaces", value) @pulumi.input_type class OSDiskArgs: def __init__(__self__, *, create_option: pulumi.Input[Union[str, 'DiskCreateOptionTypes']], caching: Optional[pulumi.Input['CachingTypes']] = None, disk_size_gb: Optional[pulumi.Input[int]] = None, encryption_settings: Optional[pulumi.Input['DiskEncryptionSettingsArgs']] = None, image: Optional[pulumi.Input['VirtualHardDiskArgs']] = None, managed_disk: Optional[pulumi.Input['ManagedDiskParametersArgs']] = None, name: Optional[pulumi.Input[str]] = None, os_type: Optional[pulumi.Input['OperatingSystemTypes']] = None, vhd: Optional[pulumi.Input['VirtualHardDiskArgs']] = None, write_accelerator_enabled: Optional[pulumi.Input[bool]] = None): """ Specifies information about the operating system disk used by the virtual machine. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). :param pulumi.Input[Union[str, 'DiskCreateOptionTypes']] create_option: Specifies how the virtual machine should be created.<br><br> Possible values are:<br><br> **Attach** \u2013 This value is used when you are using a specialized disk to create the virtual machine.<br><br> **FromImage** \u2013 This value is used when you are using an image to create the virtual machine. If you are using a platform image, you also use the imageReference element described above. If you are using a marketplace image, you also use the plan element previously described. :param pulumi.Input['CachingTypes'] caching: Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** :param pulumi.Input[int] disk_size_gb: Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB :param pulumi.Input['DiskEncryptionSettingsArgs'] encryption_settings: Specifies the encryption settings for the OS Disk. <br><br> Minimum api-version: 2015-06-15 :param pulumi.Input['VirtualHardDiskArgs'] image: The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. If SourceImage is provided, the destination virtual hard drive must not exist. :param pulumi.Input['ManagedDiskParametersArgs'] managed_disk: The managed disk parameters. :param pulumi.Input[str] name: The disk name. :param pulumi.Input['OperatingSystemTypes'] os_type: This property allows you to specify the type of the OS that is included in the disk if creating a VM from user-image or a specialized VHD. <br><br> Possible values are: <br><br> **Windows** <br><br> **Linux** :param pulumi.Input['VirtualHardDiskArgs'] vhd: The virtual hard disk. :param pulumi.Input[bool] write_accelerator_enabled: Specifies whether writeAccelerator should be enabled or disabled on the disk. """ pulumi.set(__self__, "create_option", create_option) if caching is not None: pulumi.set(__self__, "caching", caching) if disk_size_gb is not None: pulumi.set(__self__, "disk_size_gb", disk_size_gb) if encryption_settings is not None: pulumi.set(__self__, "encryption_settings", encryption_settings) if image is not None: pulumi.set(__self__, "image", image) if managed_disk is not None: pulumi.set(__self__, "managed_disk", managed_disk) if name is not None: pulumi.set(__self__, "name", name) if os_type is not None: pulumi.set(__self__, "os_type", os_type) if vhd is not None: pulumi.set(__self__, "vhd", vhd) if write_accelerator_enabled is not None: pulumi.set(__self__, "write_accelerator_enabled", write_accelerator_enabled) @property @pulumi.getter(name="createOption") def create_option(self) -> pulumi.Input[Union[str, 'DiskCreateOptionTypes']]: """ Specifies how the virtual machine should be created.<br><br> Possible values are:<br><br> **Attach** \u2013 This value is used when you are using a specialized disk to create the virtual machine.<br><br> **FromImage** \u2013 This value is used when you are using an image to create the virtual machine. If you are using a platform image, you also use the imageReference element described above. If you are using a marketplace image, you also use the plan element previously described. """ return pulumi.get(self, "create_option") @create_option.setter def create_option(self, value: pulumi.Input[Union[str, 'DiskCreateOptionTypes']]): pulumi.set(self, "create_option", value) @property @pulumi.getter def caching(self) -> Optional[pulumi.Input['CachingTypes']]: """ Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** """ return pulumi.get(self, "caching") @caching.setter def caching(self, value: Optional[pulumi.Input['CachingTypes']]): pulumi.set(self, "caching", value) @property @pulumi.getter(name="diskSizeGB") def disk_size_gb(self) -> Optional[pulumi.Input[int]]: """ Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB """ return pulumi.get(self, "disk_size_gb") @disk_size_gb.setter def disk_size_gb(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "disk_size_gb", value) @property @pulumi.getter(name="encryptionSettings") def encryption_settings(self) -> Optional[pulumi.Input['DiskEncryptionSettingsArgs']]: """ Specifies the encryption settings for the OS Disk. <br><br> Minimum api-version: 2015-06-15 """ return pulumi.get(self, "encryption_settings") @encryption_settings.setter def encryption_settings(self, value: Optional[pulumi.Input['DiskEncryptionSettingsArgs']]): pulumi.set(self, "encryption_settings", value) @property @pulumi.getter def image(self) -> Optional[pulumi.Input['VirtualHardDiskArgs']]: """ The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. If SourceImage is provided, the destination virtual hard drive must not exist. """ return pulumi.get(self, "image") @image.setter def image(self, value: Optional[pulumi.Input['VirtualHardDiskArgs']]): pulumi.set(self, "image", value) @property @pulumi.getter(name="managedDisk") def managed_disk(self) -> Optional[pulumi.Input['ManagedDiskParametersArgs']]: """ The managed disk parameters. """ return pulumi.get(self, "managed_disk") @managed_disk.setter def managed_disk(self, value: Optional[pulumi.Input['ManagedDiskParametersArgs']]): pulumi.set(self, "managed_disk", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ The disk name. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter(name="osType") def os_type(self) -> Optional[pulumi.Input['OperatingSystemTypes']]: """ This property allows you to specify the type of the OS that is included in the disk if creating a VM from user-image or a specialized VHD. <br><br> Possible values are: <br><br> **Windows** <br><br> **Linux** """ return pulumi.get(self, "os_type") @os_type.setter def os_type(self, value: Optional[pulumi.Input['OperatingSystemTypes']]): pulumi.set(self, "os_type", value) @property @pulumi.getter def vhd(self) -> Optional[pulumi.Input['VirtualHardDiskArgs']]: """ The virtual hard disk. """ return pulumi.get(self, "vhd") @vhd.setter def vhd(self, value: Optional[pulumi.Input['VirtualHardDiskArgs']]): pulumi.set(self, "vhd", value) @property @pulumi.getter(name="writeAcceleratorEnabled") def write_accelerator_enabled(self) -> Optional[pulumi.Input[bool]]: """ Specifies whether writeAccelerator should be enabled or disabled on the disk. """ return pulumi.get(self, "write_accelerator_enabled") @write_accelerator_enabled.setter def write_accelerator_enabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "write_accelerator_enabled", value) @pulumi.input_type class OSProfileArgs: def __init__(__self__, *, admin_password: Optional[pulumi.Input[str]] = None, admin_username: Optional[pulumi.Input[str]] = None, computer_name: Optional[pulumi.Input[str]] = None, custom_data: Optional[pulumi.Input[str]] = None, linux_configuration: Optional[pulumi.Input['LinuxConfigurationArgs']] = None, secrets: Optional[pulumi.Input[Sequence[pulumi.Input['VaultSecretGroupArgs']]]] = None, windows_configuration: Optional[pulumi.Input['WindowsConfigurationArgs']] = None): """ Specifies the operating system settings for the virtual machine. :param pulumi.Input[str] admin_password: Specifies the password of the administrator account. <br><br> **Minimum-length (Windows):** 8 characters <br><br> **Minimum-length (Linux):** 6 characters <br><br> **Max-length (Windows):** 123 characters <br><br> **Max-length (Linux):** 72 characters <br><br> **Complexity requirements:** 3 out of 4 conditions below need to be fulfilled <br> Has lower characters <br>Has upper characters <br> Has a digit <br> Has a special character (Regex match [\W_]) <br><br> **Disallowed values:** "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", "Password22", "iloveyou!" <br><br> For resetting the password, see [How to reset the Remote Desktop service or its login password in a Windows VM](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-reset-rdp?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> For resetting root password, see [Manage users, SSH, and check or repair disks on Azure Linux VMs using the VMAccess Extension](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-vmaccess-extension?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json#reset-root-password) :param pulumi.Input[str] admin_username: Specifies the name of the administrator account. <br><br> **Windows-only restriction:** Cannot end in "." <br><br> **Disallowed values:** "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5". <br><br> **Minimum-length (Linux):** 1 character <br><br> **Max-length (Linux):** 64 characters <br><br> **Max-length (Windows):** 20 characters <br><br><li> For root access to the Linux VM, see [Using root privileges on Linux virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-use-root-privileges?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json)<br><li> For a list of built-in system users on Linux that should not be used in this field, see [Selecting User Names for Linux on Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-usernames?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) :param pulumi.Input[str] computer_name: Specifies the host OS name of the virtual machine. <br><br> This name cannot be updated after the VM is created. <br><br> **Max-length (Windows):** 15 characters <br><br> **Max-length (Linux):** 64 characters. <br><br> For naming conventions and restrictions see [Azure infrastructure services implementation guidelines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-infrastructure-subscription-accounts-guidelines?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json#1-naming-conventions). :param pulumi.Input[str] custom_data: Specifies a base-64 encoded string of custom data. The base-64 encoded string is decoded to a binary array that is saved as a file on the Virtual Machine. The maximum length of the binary array is 65535 bytes. <br><br> For using cloud-init for your VM, see [Using cloud-init to customize a Linux VM during creation](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-cloud-init?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) :param pulumi.Input['LinuxConfigurationArgs'] linux_configuration: Specifies the Linux operating system settings on the virtual machine. <br><br>For a list of supported Linux distributions, see [Linux on Azure-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-endorsed-distros?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) <br><br> For running non-endorsed distributions, see [Information for Non-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-create-upload-generic?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json). :param pulumi.Input[Sequence[pulumi.Input['VaultSecretGroupArgs']]] secrets: Specifies set of certificates that should be installed onto the virtual machine. :param pulumi.Input['WindowsConfigurationArgs'] windows_configuration: Specifies Windows operating system settings on the virtual machine. """ if admin_password is not None: pulumi.set(__self__, "admin_password", admin_password) if admin_username is not None: pulumi.set(__self__, "admin_username", admin_username) if computer_name is not None: pulumi.set(__self__, "computer_name", computer_name) if custom_data is not None: pulumi.set(__self__, "custom_data", custom_data) if linux_configuration is not None: pulumi.set(__self__, "linux_configuration", linux_configuration) if secrets is not None: pulumi.set(__self__, "secrets", secrets) if windows_configuration is not None: pulumi.set(__self__, "windows_configuration", windows_configuration) @property @pulumi.getter(name="adminPassword") def admin_password(self) -> Optional[pulumi.Input[str]]: """ Specifies the password of the administrator account. <br><br> **Minimum-length (Windows):** 8 characters <br><br> **Minimum-length (Linux):** 6 characters <br><br> **Max-length (Windows):** 123 characters <br><br> **Max-length (Linux):** 72 characters <br><br> **Complexity requirements:** 3 out of 4 conditions below need to be fulfilled <br> Has lower characters <br>Has upper characters <br> Has a digit <br> Has a special character (Regex match [\W_]) <br><br> **Disallowed values:** "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", "Password22", "iloveyou!" <br><br> For resetting the password, see [How to reset the Remote Desktop service or its login password in a Windows VM](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-reset-rdp?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> For resetting root password, see [Manage users, SSH, and check or repair disks on Azure Linux VMs using the VMAccess Extension](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-vmaccess-extension?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json#reset-root-password) """ return pulumi.get(self, "admin_password") @admin_password.setter def admin_password(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "admin_password", value) @property @pulumi.getter(name="adminUsername") def admin_username(self) -> Optional[pulumi.Input[str]]: """ Specifies the name of the administrator account. <br><br> **Windows-only restriction:** Cannot end in "." <br><br> **Disallowed values:** "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5". <br><br> **Minimum-length (Linux):** 1 character <br><br> **Max-length (Linux):** 64 characters <br><br> **Max-length (Windows):** 20 characters <br><br><li> For root access to the Linux VM, see [Using root privileges on Linux virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-use-root-privileges?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json)<br><li> For a list of built-in system users on Linux that should not be used in this field, see [Selecting User Names for Linux on Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-usernames?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) """ return pulumi.get(self, "admin_username") @admin_username.setter def admin_username(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "admin_username", value) @property @pulumi.getter(name="computerName") def computer_name(self) -> Optional[pulumi.Input[str]]: """ Specifies the host OS name of the virtual machine. <br><br> This name cannot be updated after the VM is created. <br><br> **Max-length (Windows):** 15 characters <br><br> **Max-length (Linux):** 64 characters. <br><br> For naming conventions and restrictions see [Azure infrastructure services implementation guidelines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-infrastructure-subscription-accounts-guidelines?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json#1-naming-conventions). """ return pulumi.get(self, "computer_name") @computer_name.setter def computer_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "computer_name", value) @property @pulumi.getter(name="customData") def custom_data(self) -> Optional[pulumi.Input[str]]: """ Specifies a base-64 encoded string of custom data. The base-64 encoded string is decoded to a binary array that is saved as a file on the Virtual Machine. The maximum length of the binary array is 65535 bytes. <br><br> For using cloud-init for your VM, see [Using cloud-init to customize a Linux VM during creation](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-cloud-init?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) """ return pulumi.get(self, "custom_data") @custom_data.setter def custom_data(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "custom_data", value) @property @pulumi.getter(name="linuxConfiguration") def linux_configuration(self) -> Optional[pulumi.Input['LinuxConfigurationArgs']]: """ Specifies the Linux operating system settings on the virtual machine. <br><br>For a list of supported Linux distributions, see [Linux on Azure-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-endorsed-distros?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) <br><br> For running non-endorsed distributions, see [Information for Non-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-create-upload-generic?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json). """ return pulumi.get(self, "linux_configuration") @linux_configuration.setter def linux_configuration(self, value: Optional[pulumi.Input['LinuxConfigurationArgs']]): pulumi.set(self, "linux_configuration", value) @property @pulumi.getter def secrets(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VaultSecretGroupArgs']]]]: """ Specifies set of certificates that should be installed onto the virtual machine. """ return pulumi.get(self, "secrets") @secrets.setter def secrets(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VaultSecretGroupArgs']]]]): pulumi.set(self, "secrets", value) @property @pulumi.getter(name="windowsConfiguration") def windows_configuration(self) -> Optional[pulumi.Input['WindowsConfigurationArgs']]: """ Specifies Windows operating system settings on the virtual machine. """ return pulumi.get(self, "windows_configuration") @windows_configuration.setter def windows_configuration(self, value: Optional[pulumi.Input['WindowsConfigurationArgs']]): pulumi.set(self, "windows_configuration", value) @pulumi.input_type class PlanArgs: def __init__(__self__, *, name: Optional[pulumi.Input[str]] = None, product: Optional[pulumi.Input[str]] = None, promotion_code: Optional[pulumi.Input[str]] = None, publisher: Optional[pulumi.Input[str]] = None): """ Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click **Want to deploy programmatically, Get Started ->**. Enter any required information and then click **Save**. :param pulumi.Input[str] name: The plan ID. :param pulumi.Input[str] product: Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element. :param pulumi.Input[str] promotion_code: The promotion code. :param pulumi.Input[str] publisher: The publisher ID. """ if name is not None: pulumi.set(__self__, "name", name) if product is not None: pulumi.set(__self__, "product", product) if promotion_code is not None: pulumi.set(__self__, "promotion_code", promotion_code) if publisher is not None: pulumi.set(__self__, "publisher", publisher) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ The plan ID. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def product(self) -> Optional[pulumi.Input[str]]: """ Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element. """ return pulumi.get(self, "product") @product.setter def product(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "product", value) @property @pulumi.getter(name="promotionCode") def promotion_code(self) -> Optional[pulumi.Input[str]]: """ The promotion code. """ return pulumi.get(self, "promotion_code") @promotion_code.setter def promotion_code(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "promotion_code", value) @property @pulumi.getter def publisher(self) -> Optional[pulumi.Input[str]]: """ The publisher ID. """ return pulumi.get(self, "publisher") @publisher.setter def publisher(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "publisher", value) @pulumi.input_type class RollingUpgradePolicyArgs: def __init__(__self__, *, max_batch_instance_percent: Optional[pulumi.Input[int]] = None, max_unhealthy_instance_percent: Optional[pulumi.Input[int]] = None, max_unhealthy_upgraded_instance_percent: Optional[pulumi.Input[int]] = None, pause_time_between_batches: Optional[pulumi.Input[str]] = None): """ The configuration parameters used while performing a rolling upgrade. :param pulumi.Input[int] max_batch_instance_percent: The maximum percent of total virtual machine instances that will be upgraded simultaneously by the rolling upgrade in one batch. As this is a maximum, unhealthy instances in previous or future batches can cause the percentage of instances in a batch to decrease to ensure higher reliability. The default value for this parameter is 20%. :param pulumi.Input[int] max_unhealthy_instance_percent: The maximum percentage of the total virtual machine instances in the scale set that can be simultaneously unhealthy, either as a result of being upgraded, or by being found in an unhealthy state by the virtual machine health checks before the rolling upgrade aborts. This constraint will be checked prior to starting any batch. The default value for this parameter is 20%. :param pulumi.Input[int] max_unhealthy_upgraded_instance_percent: The maximum percentage of upgraded virtual machine instances that can be found to be in an unhealthy state. This check will happen after each batch is upgraded. If this percentage is ever exceeded, the rolling update aborts. The default value for this parameter is 20%. :param pulumi.Input[str] pause_time_between_batches: The wait time between completing the update for all virtual machines in one batch and starting the next batch. The time duration should be specified in ISO 8601 format. The default value is 0 seconds (PT0S). """ if max_batch_instance_percent is not None: pulumi.set(__self__, "max_batch_instance_percent", max_batch_instance_percent) if max_unhealthy_instance_percent is not None: pulumi.set(__self__, "max_unhealthy_instance_percent", max_unhealthy_instance_percent) if max_unhealthy_upgraded_instance_percent is not None: pulumi.set(__self__, "max_unhealthy_upgraded_instance_percent", max_unhealthy_upgraded_instance_percent) if pause_time_between_batches is not None: pulumi.set(__self__, "pause_time_between_batches", pause_time_between_batches) @property @pulumi.getter(name="maxBatchInstancePercent") def max_batch_instance_percent(self) -> Optional[pulumi.Input[int]]: """ The maximum percent of total virtual machine instances that will be upgraded simultaneously by the rolling upgrade in one batch. As this is a maximum, unhealthy instances in previous or future batches can cause the percentage of instances in a batch to decrease to ensure higher reliability. The default value for this parameter is 20%. """ return pulumi.get(self, "max_batch_instance_percent") @max_batch_instance_percent.setter def max_batch_instance_percent(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "max_batch_instance_percent", value) @property @pulumi.getter(name="maxUnhealthyInstancePercent") def max_unhealthy_instance_percent(self) -> Optional[pulumi.Input[int]]: """ The maximum percentage of the total virtual machine instances in the scale set that can be simultaneously unhealthy, either as a result of being upgraded, or by being found in an unhealthy state by the virtual machine health checks before the rolling upgrade aborts. This constraint will be checked prior to starting any batch. The default value for this parameter is 20%. """ return pulumi.get(self, "max_unhealthy_instance_percent") @max_unhealthy_instance_percent.setter def max_unhealthy_instance_percent(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "max_unhealthy_instance_percent", value) @property @pulumi.getter(name="maxUnhealthyUpgradedInstancePercent") def max_unhealthy_upgraded_instance_percent(self) -> Optional[pulumi.Input[int]]: """ The maximum percentage of upgraded virtual machine instances that can be found to be in an unhealthy state. This check will happen after each batch is upgraded. If this percentage is ever exceeded, the rolling update aborts. The default value for this parameter is 20%. """ return pulumi.get(self, "max_unhealthy_upgraded_instance_percent") @max_unhealthy_upgraded_instance_percent.setter def max_unhealthy_upgraded_instance_percent(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "max_unhealthy_upgraded_instance_percent", value) @property @pulumi.getter(name="pauseTimeBetweenBatches") def pause_time_between_batches(self) -> Optional[pulumi.Input[str]]: """ The wait time between completing the update for all virtual machines in one batch and starting the next batch. The time duration should be specified in ISO 8601 format. The default value is 0 seconds (PT0S). """ return pulumi.get(self, "pause_time_between_batches") @pause_time_between_batches.setter def pause_time_between_batches(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "pause_time_between_batches", value) @pulumi.input_type class SkuArgs: def __init__(__self__, *, capacity: Optional[pulumi.Input[float]] = None, name: Optional[pulumi.Input[str]] = None, tier: Optional[pulumi.Input[str]] = None): """ Describes a virtual machine scale set sku. NOTE: If the new VM SKU is not supported on the hardware the scale set is currently on, you need to deallocate the VMs in the scale set before you modify the SKU name. :param pulumi.Input[float] capacity: Specifies the number of virtual machines in the scale set. :param pulumi.Input[str] name: The sku name. :param pulumi.Input[str] tier: Specifies the tier of virtual machines in a scale set.<br /><br /> Possible Values:<br /><br /> **Standard**<br /><br /> **Basic** """ if capacity is not None: pulumi.set(__self__, "capacity", capacity) if name is not None: pulumi.set(__self__, "name", name) if tier is not None: pulumi.set(__self__, "tier", tier) @property @pulumi.getter def capacity(self) -> Optional[pulumi.Input[float]]: """ Specifies the number of virtual machines in the scale set. """ return pulumi.get(self, "capacity") @capacity.setter def capacity(self, value: Optional[pulumi.Input[float]]): pulumi.set(self, "capacity", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ The sku name. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def tier(self) -> Optional[pulumi.Input[str]]: """ Specifies the tier of virtual machines in a scale set.<br /><br /> Possible Values:<br /><br /> **Standard**<br /><br /> **Basic** """ return pulumi.get(self, "tier") @tier.setter def tier(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "tier", value) @pulumi.input_type class SnapshotSkuArgs: def __init__(__self__, *, name: Optional[pulumi.Input[Union[str, 'SnapshotStorageAccountTypes']]] = None): """ The snapshots sku name. Can be Standard_LRS, Premium_LRS, or Standard_ZRS. :param pulumi.Input[Union[str, 'SnapshotStorageAccountTypes']] name: The sku name. """ if name is not None: pulumi.set(__self__, "name", name) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[Union[str, 'SnapshotStorageAccountTypes']]]: """ The sku name. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[Union[str, 'SnapshotStorageAccountTypes']]]): pulumi.set(self, "name", value) @pulumi.input_type class SourceVaultArgs: def __init__(__self__, *, id: Optional[pulumi.Input[str]] = None): """ The vault id is an Azure Resource Manager Resource id in the form /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName} :param pulumi.Input[str] id: Resource Id """ if id is not None: pulumi.set(__self__, "id", id) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ Resource Id """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @pulumi.input_type class SshConfigurationArgs: def __init__(__self__, *, public_keys: Optional[pulumi.Input[Sequence[pulumi.Input['SshPublicKeyArgs']]]] = None): """ SSH configuration for Linux based VMs running on Azure :param pulumi.Input[Sequence[pulumi.Input['SshPublicKeyArgs']]] public_keys: The list of SSH public keys used to authenticate with linux based VMs. """ if public_keys is not None: pulumi.set(__self__, "public_keys", public_keys) @property @pulumi.getter(name="publicKeys") def public_keys(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['SshPublicKeyArgs']]]]: """ The list of SSH public keys used to authenticate with linux based VMs. """ return pulumi.get(self, "public_keys") @public_keys.setter def public_keys(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['SshPublicKeyArgs']]]]): pulumi.set(self, "public_keys", value) @pulumi.input_type class SshPublicKeyArgs: def __init__(__self__, *, key_data: Optional[pulumi.Input[str]] = None, path: Optional[pulumi.Input[str]] = None): """ Contains information about SSH certificate public key and the path on the Linux VM where the public key is placed. :param pulumi.Input[str] key_data: SSH public key certificate used to authenticate with the VM through ssh. The key needs to be at least 2048-bit and in ssh-rsa format. <br><br> For creating ssh keys, see [Create SSH keys on Linux and Mac for Linux VMs in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-mac-create-ssh-keys?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json). :param pulumi.Input[str] path: Specifies the full path on the created VM where ssh public key is stored. If the file already exists, the specified key is appended to the file. Example: /home/user/.ssh/authorized_keys """ if key_data is not None: pulumi.set(__self__, "key_data", key_data) if path is not None: pulumi.set(__self__, "path", path) @property @pulumi.getter(name="keyData") def key_data(self) -> Optional[pulumi.Input[str]]: """ SSH public key certificate used to authenticate with the VM through ssh. The key needs to be at least 2048-bit and in ssh-rsa format. <br><br> For creating ssh keys, see [Create SSH keys on Linux and Mac for Linux VMs in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-mac-create-ssh-keys?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json). """ return pulumi.get(self, "key_data") @key_data.setter def key_data(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "key_data", value) @property @pulumi.getter def path(self) -> Optional[pulumi.Input[str]]: """ Specifies the full path on the created VM where ssh public key is stored. If the file already exists, the specified key is appended to the file. Example: /home/user/.ssh/authorized_keys """ return pulumi.get(self, "path") @path.setter def path(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "path", value) @pulumi.input_type class StorageProfileArgs: def __init__(__self__, *, data_disks: Optional[pulumi.Input[Sequence[pulumi.Input['DataDiskArgs']]]] = None, image_reference: Optional[pulumi.Input['ImageReferenceArgs']] = None, os_disk: Optional[pulumi.Input['OSDiskArgs']] = None): """ Specifies the storage settings for the virtual machine disks. :param pulumi.Input[Sequence[pulumi.Input['DataDiskArgs']]] data_disks: Specifies the parameters that are used to add a data disk to a virtual machine. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). :param pulumi.Input['ImageReferenceArgs'] image_reference: Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations. :param pulumi.Input['OSDiskArgs'] os_disk: Specifies information about the operating system disk used by the virtual machine. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). """ if data_disks is not None: pulumi.set(__self__, "data_disks", data_disks) if image_reference is not None: pulumi.set(__self__, "image_reference", image_reference) if os_disk is not None: pulumi.set(__self__, "os_disk", os_disk) @property @pulumi.getter(name="dataDisks") def data_disks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['DataDiskArgs']]]]: """ Specifies the parameters that are used to add a data disk to a virtual machine. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). """ return pulumi.get(self, "data_disks") @data_disks.setter def data_disks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['DataDiskArgs']]]]): pulumi.set(self, "data_disks", value) @property @pulumi.getter(name="imageReference") def image_reference(self) -> Optional[pulumi.Input['ImageReferenceArgs']]: """ Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations. """ return pulumi.get(self, "image_reference") @image_reference.setter def image_reference(self, value: Optional[pulumi.Input['ImageReferenceArgs']]): pulumi.set(self, "image_reference", value) @property @pulumi.getter(name="osDisk") def os_disk(self) -> Optional[pulumi.Input['OSDiskArgs']]: """ Specifies information about the operating system disk used by the virtual machine. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). """ return pulumi.get(self, "os_disk") @os_disk.setter def os_disk(self, value: Optional[pulumi.Input['OSDiskArgs']]): pulumi.set(self, "os_disk", value) @pulumi.input_type class SubResourceArgs: def __init__(__self__, *, id: Optional[pulumi.Input[str]] = None): """ :param pulumi.Input[str] id: Resource Id """ if id is not None: pulumi.set(__self__, "id", id) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ Resource Id """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @pulumi.input_type class UpgradePolicyArgs: def __init__(__self__, *, auto_os_upgrade_policy: Optional[pulumi.Input['AutoOSUpgradePolicyArgs']] = None, automatic_os_upgrade: Optional[pulumi.Input[bool]] = None, mode: Optional[pulumi.Input['UpgradeMode']] = None, rolling_upgrade_policy: Optional[pulumi.Input['RollingUpgradePolicyArgs']] = None): """ Describes an upgrade policy - automatic, manual, or rolling. :param pulumi.Input['AutoOSUpgradePolicyArgs'] auto_os_upgrade_policy: Configuration parameters used for performing automatic OS Upgrade. :param pulumi.Input[bool] automatic_os_upgrade: Whether OS upgrades should automatically be applied to scale set instances in a rolling fashion when a newer version of the image becomes available. :param pulumi.Input['UpgradeMode'] mode: Specifies the mode of an upgrade to virtual machines in the scale set.<br /><br /> Possible values are:<br /><br /> **Manual** - You control the application of updates to virtual machines in the scale set. You do this by using the manualUpgrade action.<br /><br /> **Automatic** - All virtual machines in the scale set are automatically updated at the same time. :param pulumi.Input['RollingUpgradePolicyArgs'] rolling_upgrade_policy: The configuration parameters used while performing a rolling upgrade. """ if auto_os_upgrade_policy is not None: pulumi.set(__self__, "auto_os_upgrade_policy", auto_os_upgrade_policy) if automatic_os_upgrade is not None: pulumi.set(__self__, "automatic_os_upgrade", automatic_os_upgrade) if mode is not None: pulumi.set(__self__, "mode", mode) if rolling_upgrade_policy is not None: pulumi.set(__self__, "rolling_upgrade_policy", rolling_upgrade_policy) @property @pulumi.getter(name="autoOSUpgradePolicy") def auto_os_upgrade_policy(self) -> Optional[pulumi.Input['AutoOSUpgradePolicyArgs']]: """ Configuration parameters used for performing automatic OS Upgrade. """ return pulumi.get(self, "auto_os_upgrade_policy") @auto_os_upgrade_policy.setter def auto_os_upgrade_policy(self, value: Optional[pulumi.Input['AutoOSUpgradePolicyArgs']]): pulumi.set(self, "auto_os_upgrade_policy", value) @property @pulumi.getter(name="automaticOSUpgrade") def automatic_os_upgrade(self) -> Optional[pulumi.Input[bool]]: """ Whether OS upgrades should automatically be applied to scale set instances in a rolling fashion when a newer version of the image becomes available. """ return pulumi.get(self, "automatic_os_upgrade") @automatic_os_upgrade.setter def automatic_os_upgrade(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "automatic_os_upgrade", value) @property @pulumi.getter def mode(self) -> Optional[pulumi.Input['UpgradeMode']]: """ Specifies the mode of an upgrade to virtual machines in the scale set.<br /><br /> Possible values are:<br /><br /> **Manual** - You control the application of updates to virtual machines in the scale set. You do this by using the manualUpgrade action.<br /><br /> **Automatic** - All virtual machines in the scale set are automatically updated at the same time. """ return pulumi.get(self, "mode") @mode.setter def mode(self, value: Optional[pulumi.Input['UpgradeMode']]): pulumi.set(self, "mode", value) @property @pulumi.getter(name="rollingUpgradePolicy") def rolling_upgrade_policy(self) -> Optional[pulumi.Input['RollingUpgradePolicyArgs']]: """ The configuration parameters used while performing a rolling upgrade. """ return pulumi.get(self, "rolling_upgrade_policy") @rolling_upgrade_policy.setter def rolling_upgrade_policy(self, value: Optional[pulumi.Input['RollingUpgradePolicyArgs']]): pulumi.set(self, "rolling_upgrade_policy", value) @pulumi.input_type class VaultCertificateArgs: def __init__(__self__, *, certificate_store: Optional[pulumi.Input[str]] = None, certificate_url: Optional[pulumi.Input[str]] = None): """ Describes a single certificate reference in a Key Vault, and where the certificate should reside on the VM. :param pulumi.Input[str] certificate_store: For Windows VMs, specifies the certificate store on the Virtual Machine to which the certificate should be added. The specified certificate store is implicitly in the LocalMachine account. <br><br>For Linux VMs, the certificate file is placed under the /var/lib/waagent directory, with the file name &lt;UppercaseThumbprint&gt;.crt for the X509 certificate file and &lt;UppercaseThumbprint&gt;.prv for private key. Both of these files are .pem formatted. :param pulumi.Input[str] certificate_url: This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, see [Add a key or secret to the key vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). In this case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8: <br><br> {<br> "data":"<Base64-encoded-certificate>",<br> "dataType":"pfx",<br> "password":"<pfx-file-password>"<br>} """ if certificate_store is not None: pulumi.set(__self__, "certificate_store", certificate_store) if certificate_url is not None: pulumi.set(__self__, "certificate_url", certificate_url) @property @pulumi.getter(name="certificateStore") def certificate_store(self) -> Optional[pulumi.Input[str]]: """ For Windows VMs, specifies the certificate store on the Virtual Machine to which the certificate should be added. The specified certificate store is implicitly in the LocalMachine account. <br><br>For Linux VMs, the certificate file is placed under the /var/lib/waagent directory, with the file name &lt;UppercaseThumbprint&gt;.crt for the X509 certificate file and &lt;UppercaseThumbprint&gt;.prv for private key. Both of these files are .pem formatted. """ return pulumi.get(self, "certificate_store") @certificate_store.setter def certificate_store(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "certificate_store", value) @property @pulumi.getter(name="certificateUrl") def certificate_url(self) -> Optional[pulumi.Input[str]]: """ This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, see [Add a key or secret to the key vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). In this case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8: <br><br> {<br> "data":"<Base64-encoded-certificate>",<br> "dataType":"pfx",<br> "password":"<pfx-file-password>"<br>} """ return pulumi.get(self, "certificate_url") @certificate_url.setter def certificate_url(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "certificate_url", value) @pulumi.input_type class VaultSecretGroupArgs: def __init__(__self__, *, source_vault: Optional[pulumi.Input['SubResourceArgs']] = None, vault_certificates: Optional[pulumi.Input[Sequence[pulumi.Input['VaultCertificateArgs']]]] = None): """ Describes a set of certificates which are all in the same Key Vault. :param pulumi.Input['SubResourceArgs'] source_vault: The relative URL of the Key Vault containing all of the certificates in VaultCertificates. :param pulumi.Input[Sequence[pulumi.Input['VaultCertificateArgs']]] vault_certificates: The list of key vault references in SourceVault which contain certificates. """ if source_vault is not None: pulumi.set(__self__, "source_vault", source_vault) if vault_certificates is not None: pulumi.set(__self__, "vault_certificates", vault_certificates) @property @pulumi.getter(name="sourceVault") def source_vault(self) -> Optional[pulumi.Input['SubResourceArgs']]: """ The relative URL of the Key Vault containing all of the certificates in VaultCertificates. """ return pulumi.get(self, "source_vault") @source_vault.setter def source_vault(self, value: Optional[pulumi.Input['SubResourceArgs']]): pulumi.set(self, "source_vault", value) @property @pulumi.getter(name="vaultCertificates") def vault_certificates(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VaultCertificateArgs']]]]: """ The list of key vault references in SourceVault which contain certificates. """ return pulumi.get(self, "vault_certificates") @vault_certificates.setter def vault_certificates(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VaultCertificateArgs']]]]): pulumi.set(self, "vault_certificates", value) @pulumi.input_type class VirtualHardDiskArgs: def __init__(__self__, *, uri: Optional[pulumi.Input[str]] = None): """ Describes the uri of a disk. :param pulumi.Input[str] uri: Specifies the virtual hard disk's uri. """ if uri is not None: pulumi.set(__self__, "uri", uri) @property @pulumi.getter def uri(self) -> Optional[pulumi.Input[str]]: """ Specifies the virtual hard disk's uri. """ return pulumi.get(self, "uri") @uri.setter def uri(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "uri", value) @pulumi.input_type class VirtualMachineExtensionInstanceViewArgs: def __init__(__self__, *, name: Optional[pulumi.Input[str]] = None, statuses: Optional[pulumi.Input[Sequence[pulumi.Input['InstanceViewStatusArgs']]]] = None, substatuses: Optional[pulumi.Input[Sequence[pulumi.Input['InstanceViewStatusArgs']]]] = None, type: Optional[pulumi.Input[str]] = None, type_handler_version: Optional[pulumi.Input[str]] = None): """ The instance view of a virtual machine extension. :param pulumi.Input[str] name: The virtual machine extension name. :param pulumi.Input[Sequence[pulumi.Input['InstanceViewStatusArgs']]] statuses: The resource status information. :param pulumi.Input[Sequence[pulumi.Input['InstanceViewStatusArgs']]] substatuses: The resource status information. :param pulumi.Input[str] type: Specifies the type of the extension; an example is "CustomScriptExtension". :param pulumi.Input[str] type_handler_version: Specifies the version of the script handler. """ if name is not None: pulumi.set(__self__, "name", name) if statuses is not None: pulumi.set(__self__, "statuses", statuses) if substatuses is not None: pulumi.set(__self__, "substatuses", substatuses) if type is not None: pulumi.set(__self__, "type", type) if type_handler_version is not None: pulumi.set(__self__, "type_handler_version", type_handler_version) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ The virtual machine extension name. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter def statuses(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['InstanceViewStatusArgs']]]]: """ The resource status information. """ return pulumi.get(self, "statuses") @statuses.setter def statuses(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['InstanceViewStatusArgs']]]]): pulumi.set(self, "statuses", value) @property @pulumi.getter def substatuses(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['InstanceViewStatusArgs']]]]: """ The resource status information. """ return pulumi.get(self, "substatuses") @substatuses.setter def substatuses(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['InstanceViewStatusArgs']]]]): pulumi.set(self, "substatuses", value) @property @pulumi.getter def type(self) -> Optional[pulumi.Input[str]]: """ Specifies the type of the extension; an example is "CustomScriptExtension". """ return pulumi.get(self, "type") @type.setter def type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "type", value) @property @pulumi.getter(name="typeHandlerVersion") def type_handler_version(self) -> Optional[pulumi.Input[str]]: """ Specifies the version of the script handler. """ return pulumi.get(self, "type_handler_version") @type_handler_version.setter def type_handler_version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "type_handler_version", value) @pulumi.input_type class VirtualMachineIdentityArgs: def __init__(__self__, *, identity_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, type: Optional[pulumi.Input['ResourceIdentityType']] = None): """ Identity for the virtual machine. :param pulumi.Input[Sequence[pulumi.Input[str]]] identity_ids: The list of user identities associated with the Virtual Machine. The user identity references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/identities/{identityName}'. :param pulumi.Input['ResourceIdentityType'] type: The type of identity used for the virtual machine. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine. """ if identity_ids is not None: pulumi.set(__self__, "identity_ids", identity_ids) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter(name="identityIds") def identity_ids(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ The list of user identities associated with the Virtual Machine. The user identity references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/identities/{identityName}'. """ return pulumi.get(self, "identity_ids") @identity_ids.setter def identity_ids(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "identity_ids", value) @property @pulumi.getter def type(self) -> Optional[pulumi.Input['ResourceIdentityType']]: """ The type of identity used for the virtual machine. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine. """ return pulumi.get(self, "type") @type.setter def type(self, value: Optional[pulumi.Input['ResourceIdentityType']]): pulumi.set(self, "type", value) @pulumi.input_type class VirtualMachineScaleSetDataDiskArgs: def __init__(__self__, *, create_option: pulumi.Input[Union[str, 'DiskCreateOptionTypes']], lun: pulumi.Input[int], caching: Optional[pulumi.Input['CachingTypes']] = None, disk_size_gb: Optional[pulumi.Input[int]] = None, managed_disk: Optional[pulumi.Input['VirtualMachineScaleSetManagedDiskParametersArgs']] = None, name: Optional[pulumi.Input[str]] = None, write_accelerator_enabled: Optional[pulumi.Input[bool]] = None): """ Describes a virtual machine scale set data disk. :param pulumi.Input[Union[str, 'DiskCreateOptionTypes']] create_option: The create option. :param pulumi.Input[int] lun: Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. :param pulumi.Input['CachingTypes'] caching: Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** :param pulumi.Input[int] disk_size_gb: Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB :param pulumi.Input['VirtualMachineScaleSetManagedDiskParametersArgs'] managed_disk: The managed disk parameters. :param pulumi.Input[str] name: The disk name. :param pulumi.Input[bool] write_accelerator_enabled: Specifies whether writeAccelerator should be enabled or disabled on the disk. """ pulumi.set(__self__, "create_option", create_option) pulumi.set(__self__, "lun", lun) if caching is not None: pulumi.set(__self__, "caching", caching) if disk_size_gb is not None: pulumi.set(__self__, "disk_size_gb", disk_size_gb) if managed_disk is not None: pulumi.set(__self__, "managed_disk", managed_disk) if name is not None: pulumi.set(__self__, "name", name) if write_accelerator_enabled is not None: pulumi.set(__self__, "write_accelerator_enabled", write_accelerator_enabled) @property @pulumi.getter(name="createOption") def create_option(self) -> pulumi.Input[Union[str, 'DiskCreateOptionTypes']]: """ The create option. """ return pulumi.get(self, "create_option") @create_option.setter def create_option(self, value: pulumi.Input[Union[str, 'DiskCreateOptionTypes']]): pulumi.set(self, "create_option", value) @property @pulumi.getter def lun(self) -> pulumi.Input[int]: """ Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. """ return pulumi.get(self, "lun") @lun.setter def lun(self, value: pulumi.Input[int]): pulumi.set(self, "lun", value) @property @pulumi.getter def caching(self) -> Optional[pulumi.Input['CachingTypes']]: """ Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** """ return pulumi.get(self, "caching") @caching.setter def caching(self, value: Optional[pulumi.Input['CachingTypes']]): pulumi.set(self, "caching", value) @property @pulumi.getter(name="diskSizeGB") def disk_size_gb(self) -> Optional[pulumi.Input[int]]: """ Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB """ return pulumi.get(self, "disk_size_gb") @disk_size_gb.setter def disk_size_gb(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "disk_size_gb", value) @property @pulumi.getter(name="managedDisk") def managed_disk(self) -> Optional[pulumi.Input['VirtualMachineScaleSetManagedDiskParametersArgs']]: """ The managed disk parameters. """ return pulumi.get(self, "managed_disk") @managed_disk.setter def managed_disk(self, value: Optional[pulumi.Input['VirtualMachineScaleSetManagedDiskParametersArgs']]): pulumi.set(self, "managed_disk", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ The disk name. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter(name="writeAcceleratorEnabled") def write_accelerator_enabled(self) -> Optional[pulumi.Input[bool]]: """ Specifies whether writeAccelerator should be enabled or disabled on the disk. """ return pulumi.get(self, "write_accelerator_enabled") @write_accelerator_enabled.setter def write_accelerator_enabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "write_accelerator_enabled", value) @pulumi.input_type class VirtualMachineScaleSetExtensionProfileArgs: def __init__(__self__, *, extensions: Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetExtensionArgs']]]] = None): """ Describes a virtual machine scale set extension profile. :param pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetExtensionArgs']]] extensions: The virtual machine scale set child extension resources. """ if extensions is not None: pulumi.set(__self__, "extensions", extensions) @property @pulumi.getter def extensions(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetExtensionArgs']]]]: """ The virtual machine scale set child extension resources. """ return pulumi.get(self, "extensions") @extensions.setter def extensions(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetExtensionArgs']]]]): pulumi.set(self, "extensions", value) @pulumi.input_type class VirtualMachineScaleSetExtensionArgs: def __init__(__self__, *, auto_upgrade_minor_version: Optional[pulumi.Input[bool]] = None, force_update_tag: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, protected_settings: Optional[Any] = None, publisher: Optional[pulumi.Input[str]] = None, settings: Optional[Any] = None, type: Optional[pulumi.Input[str]] = None, type_handler_version: Optional[pulumi.Input[str]] = None): """ Describes a Virtual Machine Scale Set Extension. :param pulumi.Input[bool] auto_upgrade_minor_version: Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. :param pulumi.Input[str] force_update_tag: If a value is provided and is different from the previous value, the extension handler will be forced to update even if the extension configuration has not changed. :param pulumi.Input[str] name: The name of the extension. :param Any protected_settings: The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. :param pulumi.Input[str] publisher: The name of the extension handler publisher. :param Any settings: Json formatted public settings for the extension. :param pulumi.Input[str] type: Specifies the type of the extension; an example is "CustomScriptExtension". :param pulumi.Input[str] type_handler_version: Specifies the version of the script handler. """ if auto_upgrade_minor_version is not None: pulumi.set(__self__, "auto_upgrade_minor_version", auto_upgrade_minor_version) if force_update_tag is not None: pulumi.set(__self__, "force_update_tag", force_update_tag) if name is not None: pulumi.set(__self__, "name", name) if protected_settings is not None: pulumi.set(__self__, "protected_settings", protected_settings) if publisher is not None: pulumi.set(__self__, "publisher", publisher) if settings is not None: pulumi.set(__self__, "settings", settings) if type is not None: pulumi.set(__self__, "type", type) if type_handler_version is not None: pulumi.set(__self__, "type_handler_version", type_handler_version) @property @pulumi.getter(name="autoUpgradeMinorVersion") def auto_upgrade_minor_version(self) -> Optional[pulumi.Input[bool]]: """ Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. """ return pulumi.get(self, "auto_upgrade_minor_version") @auto_upgrade_minor_version.setter def auto_upgrade_minor_version(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "auto_upgrade_minor_version", value) @property @pulumi.getter(name="forceUpdateTag") def force_update_tag(self) -> Optional[pulumi.Input[str]]: """ If a value is provided and is different from the previous value, the extension handler will be forced to update even if the extension configuration has not changed. """ return pulumi.get(self, "force_update_tag") @force_update_tag.setter def force_update_tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "force_update_tag", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ The name of the extension. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter(name="protectedSettings") def protected_settings(self) -> Optional[Any]: """ The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. """ return pulumi.get(self, "protected_settings") @protected_settings.setter def protected_settings(self, value: Optional[Any]): pulumi.set(self, "protected_settings", value) @property @pulumi.getter def publisher(self) -> Optional[pulumi.Input[str]]: """ The name of the extension handler publisher. """ return pulumi.get(self, "publisher") @publisher.setter def publisher(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "publisher", value) @property @pulumi.getter def settings(self) -> Optional[Any]: """ Json formatted public settings for the extension. """ return pulumi.get(self, "settings") @settings.setter def settings(self, value: Optional[Any]): pulumi.set(self, "settings", value) @property @pulumi.getter def type(self) -> Optional[pulumi.Input[str]]: """ Specifies the type of the extension; an example is "CustomScriptExtension". """ return pulumi.get(self, "type") @type.setter def type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "type", value) @property @pulumi.getter(name="typeHandlerVersion") def type_handler_version(self) -> Optional[pulumi.Input[str]]: """ Specifies the version of the script handler. """ return pulumi.get(self, "type_handler_version") @type_handler_version.setter def type_handler_version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "type_handler_version", value) @pulumi.input_type class VirtualMachineScaleSetIPConfigurationArgs: def __init__(__self__, *, name: pulumi.Input[str], application_gateway_backend_address_pools: Optional[pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]]] = None, id: Optional[pulumi.Input[str]] = None, load_balancer_backend_address_pools: Optional[pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]]] = None, load_balancer_inbound_nat_pools: Optional[pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]]] = None, primary: Optional[pulumi.Input[bool]] = None, private_ip_address_version: Optional[pulumi.Input[Union[str, 'IPVersion']]] = None, public_ip_address_configuration: Optional[pulumi.Input['VirtualMachineScaleSetPublicIPAddressConfigurationArgs']] = None, subnet: Optional[pulumi.Input['ApiEntityReferenceArgs']] = None): """ Describes a virtual machine scale set network profile's IP configuration. :param pulumi.Input[str] name: The IP configuration name. :param pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]] application_gateway_backend_address_pools: Specifies an array of references to backend address pools of application gateways. A scale set can reference backend address pools of multiple application gateways. Multiple scale sets cannot use the same application gateway. :param pulumi.Input[str] id: Resource Id :param pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]] load_balancer_backend_address_pools: Specifies an array of references to backend address pools of load balancers. A scale set can reference backend address pools of one public and one internal load balancer. Multiple scale sets cannot use the same load balancer. :param pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]] load_balancer_inbound_nat_pools: Specifies an array of references to inbound Nat pools of the load balancers. A scale set can reference inbound nat pools of one public and one internal load balancer. Multiple scale sets cannot use the same load balancer :param pulumi.Input[bool] primary: Specifies the primary network interface in case the virtual machine has more than 1 network interface. :param pulumi.Input[Union[str, 'IPVersion']] private_ip_address_version: Available from Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. :param pulumi.Input['VirtualMachineScaleSetPublicIPAddressConfigurationArgs'] public_ip_address_configuration: The publicIPAddressConfiguration. :param pulumi.Input['ApiEntityReferenceArgs'] subnet: Specifies the identifier of the subnet. """ pulumi.set(__self__, "name", name) if application_gateway_backend_address_pools is not None: pulumi.set(__self__, "application_gateway_backend_address_pools", application_gateway_backend_address_pools) if id is not None: pulumi.set(__self__, "id", id) if load_balancer_backend_address_pools is not None: pulumi.set(__self__, "load_balancer_backend_address_pools", load_balancer_backend_address_pools) if load_balancer_inbound_nat_pools is not None: pulumi.set(__self__, "load_balancer_inbound_nat_pools", load_balancer_inbound_nat_pools) if primary is not None: pulumi.set(__self__, "primary", primary) if private_ip_address_version is not None: pulumi.set(__self__, "private_ip_address_version", private_ip_address_version) if public_ip_address_configuration is not None: pulumi.set(__self__, "public_ip_address_configuration", public_ip_address_configuration) if subnet is not None: pulumi.set(__self__, "subnet", subnet) @property @pulumi.getter def name(self) -> pulumi.Input[str]: """ The IP configuration name. """ return pulumi.get(self, "name") @name.setter def name(self, value: pulumi.Input[str]): pulumi.set(self, "name", value) @property @pulumi.getter(name="applicationGatewayBackendAddressPools") def application_gateway_backend_address_pools(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]]]: """ Specifies an array of references to backend address pools of application gateways. A scale set can reference backend address pools of multiple application gateways. Multiple scale sets cannot use the same application gateway. """ return pulumi.get(self, "application_gateway_backend_address_pools") @application_gateway_backend_address_pools.setter def application_gateway_backend_address_pools(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]]]): pulumi.set(self, "application_gateway_backend_address_pools", value) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ Resource Id """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter(name="loadBalancerBackendAddressPools") def load_balancer_backend_address_pools(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]]]: """ Specifies an array of references to backend address pools of load balancers. A scale set can reference backend address pools of one public and one internal load balancer. Multiple scale sets cannot use the same load balancer. """ return pulumi.get(self, "load_balancer_backend_address_pools") @load_balancer_backend_address_pools.setter def load_balancer_backend_address_pools(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]]]): pulumi.set(self, "load_balancer_backend_address_pools", value) @property @pulumi.getter(name="loadBalancerInboundNatPools") def load_balancer_inbound_nat_pools(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]]]: """ Specifies an array of references to inbound Nat pools of the load balancers. A scale set can reference inbound nat pools of one public and one internal load balancer. Multiple scale sets cannot use the same load balancer """ return pulumi.get(self, "load_balancer_inbound_nat_pools") @load_balancer_inbound_nat_pools.setter def load_balancer_inbound_nat_pools(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['SubResourceArgs']]]]): pulumi.set(self, "load_balancer_inbound_nat_pools", value) @property @pulumi.getter def primary(self) -> Optional[pulumi.Input[bool]]: """ Specifies the primary network interface in case the virtual machine has more than 1 network interface. """ return pulumi.get(self, "primary") @primary.setter def primary(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "primary", value) @property @pulumi.getter(name="privateIPAddressVersion") def private_ip_address_version(self) -> Optional[pulumi.Input[Union[str, 'IPVersion']]]: """ Available from Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. """ return pulumi.get(self, "private_ip_address_version") @private_ip_address_version.setter def private_ip_address_version(self, value: Optional[pulumi.Input[Union[str, 'IPVersion']]]): pulumi.set(self, "private_ip_address_version", value) @property @pulumi.getter(name="publicIPAddressConfiguration") def public_ip_address_configuration(self) -> Optional[pulumi.Input['VirtualMachineScaleSetPublicIPAddressConfigurationArgs']]: """ The publicIPAddressConfiguration. """ return pulumi.get(self, "public_ip_address_configuration") @public_ip_address_configuration.setter def public_ip_address_configuration(self, value: Optional[pulumi.Input['VirtualMachineScaleSetPublicIPAddressConfigurationArgs']]): pulumi.set(self, "public_ip_address_configuration", value) @property @pulumi.getter def subnet(self) -> Optional[pulumi.Input['ApiEntityReferenceArgs']]: """ Specifies the identifier of the subnet. """ return pulumi.get(self, "subnet") @subnet.setter def subnet(self, value: Optional[pulumi.Input['ApiEntityReferenceArgs']]): pulumi.set(self, "subnet", value) @pulumi.input_type class VirtualMachineScaleSetIdentityArgs: def __init__(__self__, *, identity_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, type: Optional[pulumi.Input['ResourceIdentityType']] = None): """ Identity for the virtual machine scale set. :param pulumi.Input[Sequence[pulumi.Input[str]]] identity_ids: The list of user identities associated with the virtual machine scale set. The user identity references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/identities/{identityName}'. :param pulumi.Input['ResourceIdentityType'] type: The type of identity used for the virtual machine scale set. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine scale set. """ if identity_ids is not None: pulumi.set(__self__, "identity_ids", identity_ids) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter(name="identityIds") def identity_ids(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ The list of user identities associated with the virtual machine scale set. The user identity references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/identities/{identityName}'. """ return pulumi.get(self, "identity_ids") @identity_ids.setter def identity_ids(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "identity_ids", value) @property @pulumi.getter def type(self) -> Optional[pulumi.Input['ResourceIdentityType']]: """ The type of identity used for the virtual machine scale set. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine scale set. """ return pulumi.get(self, "type") @type.setter def type(self, value: Optional[pulumi.Input['ResourceIdentityType']]): pulumi.set(self, "type", value) @pulumi.input_type class VirtualMachineScaleSetIpTagArgs: def __init__(__self__, *, ip_tag_type: Optional[pulumi.Input[str]] = None, tag: Optional[pulumi.Input[str]] = None): """ Contains the IP tag associated with the public IP address. :param pulumi.Input[str] ip_tag_type: IP tag type. Example: FirstPartyUsage. :param pulumi.Input[str] tag: IP tag associated with the public IP. Example: SQL, Storage etc. """ if ip_tag_type is not None: pulumi.set(__self__, "ip_tag_type", ip_tag_type) if tag is not None: pulumi.set(__self__, "tag", tag) @property @pulumi.getter(name="ipTagType") def ip_tag_type(self) -> Optional[pulumi.Input[str]]: """ IP tag type. Example: FirstPartyUsage. """ return pulumi.get(self, "ip_tag_type") @ip_tag_type.setter def ip_tag_type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "ip_tag_type", value) @property @pulumi.getter def tag(self) -> Optional[pulumi.Input[str]]: """ IP tag associated with the public IP. Example: SQL, Storage etc. """ return pulumi.get(self, "tag") @tag.setter def tag(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "tag", value) @pulumi.input_type class VirtualMachineScaleSetManagedDiskParametersArgs: def __init__(__self__, *, storage_account_type: Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]] = None): """ Describes the parameters of a ScaleSet managed disk. :param pulumi.Input[Union[str, 'StorageAccountTypes']] storage_account_type: Specifies the storage account type for the managed disk. Managed OS disk storage account type can only be set when you create the scale set. Possible values are: Standard_LRS, Premium_LRS, and StandardSSD_LRS. """ if storage_account_type is not None: pulumi.set(__self__, "storage_account_type", storage_account_type) @property @pulumi.getter(name="storageAccountType") def storage_account_type(self) -> Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]]: """ Specifies the storage account type for the managed disk. Managed OS disk storage account type can only be set when you create the scale set. Possible values are: Standard_LRS, Premium_LRS, and StandardSSD_LRS. """ return pulumi.get(self, "storage_account_type") @storage_account_type.setter def storage_account_type(self, value: Optional[pulumi.Input[Union[str, 'StorageAccountTypes']]]): pulumi.set(self, "storage_account_type", value) @pulumi.input_type class VirtualMachineScaleSetNetworkConfigurationDnsSettingsArgs: def __init__(__self__, *, dns_servers: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None): """ Describes a virtual machines scale sets network configuration's DNS settings. :param pulumi.Input[Sequence[pulumi.Input[str]]] dns_servers: List of DNS servers IP addresses """ if dns_servers is not None: pulumi.set(__self__, "dns_servers", dns_servers) @property @pulumi.getter(name="dnsServers") def dns_servers(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ List of DNS servers IP addresses """ return pulumi.get(self, "dns_servers") @dns_servers.setter def dns_servers(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "dns_servers", value) @pulumi.input_type class VirtualMachineScaleSetNetworkConfigurationArgs: def __init__(__self__, *, ip_configurations: pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetIPConfigurationArgs']]], name: pulumi.Input[str], dns_settings: Optional[pulumi.Input['VirtualMachineScaleSetNetworkConfigurationDnsSettingsArgs']] = None, enable_accelerated_networking: Optional[pulumi.Input[bool]] = None, enable_ip_forwarding: Optional[pulumi.Input[bool]] = None, id: Optional[pulumi.Input[str]] = None, network_security_group: Optional[pulumi.Input['SubResourceArgs']] = None, primary: Optional[pulumi.Input[bool]] = None): """ Describes a virtual machine scale set network profile's network configurations. :param pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetIPConfigurationArgs']]] ip_configurations: Specifies the IP configurations of the network interface. :param pulumi.Input[str] name: The network configuration name. :param pulumi.Input['VirtualMachineScaleSetNetworkConfigurationDnsSettingsArgs'] dns_settings: The dns settings to be applied on the network interfaces. :param pulumi.Input[bool] enable_accelerated_networking: Specifies whether the network interface is accelerated networking-enabled. :param pulumi.Input[bool] enable_ip_forwarding: Whether IP forwarding enabled on this NIC. :param pulumi.Input[str] id: Resource Id :param pulumi.Input['SubResourceArgs'] network_security_group: The network security group. :param pulumi.Input[bool] primary: Specifies the primary network interface in case the virtual machine has more than 1 network interface. """ pulumi.set(__self__, "ip_configurations", ip_configurations) pulumi.set(__self__, "name", name) if dns_settings is not None: pulumi.set(__self__, "dns_settings", dns_settings) if enable_accelerated_networking is not None: pulumi.set(__self__, "enable_accelerated_networking", enable_accelerated_networking) if enable_ip_forwarding is not None: pulumi.set(__self__, "enable_ip_forwarding", enable_ip_forwarding) if id is not None: pulumi.set(__self__, "id", id) if network_security_group is not None: pulumi.set(__self__, "network_security_group", network_security_group) if primary is not None: pulumi.set(__self__, "primary", primary) @property @pulumi.getter(name="ipConfigurations") def ip_configurations(self) -> pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetIPConfigurationArgs']]]: """ Specifies the IP configurations of the network interface. """ return pulumi.get(self, "ip_configurations") @ip_configurations.setter def ip_configurations(self, value: pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetIPConfigurationArgs']]]): pulumi.set(self, "ip_configurations", value) @property @pulumi.getter def name(self) -> pulumi.Input[str]: """ The network configuration name. """ return pulumi.get(self, "name") @name.setter def name(self, value: pulumi.Input[str]): pulumi.set(self, "name", value) @property @pulumi.getter(name="dnsSettings") def dns_settings(self) -> Optional[pulumi.Input['VirtualMachineScaleSetNetworkConfigurationDnsSettingsArgs']]: """ The dns settings to be applied on the network interfaces. """ return pulumi.get(self, "dns_settings") @dns_settings.setter def dns_settings(self, value: Optional[pulumi.Input['VirtualMachineScaleSetNetworkConfigurationDnsSettingsArgs']]): pulumi.set(self, "dns_settings", value) @property @pulumi.getter(name="enableAcceleratedNetworking") def enable_accelerated_networking(self) -> Optional[pulumi.Input[bool]]: """ Specifies whether the network interface is accelerated networking-enabled. """ return pulumi.get(self, "enable_accelerated_networking") @enable_accelerated_networking.setter def enable_accelerated_networking(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "enable_accelerated_networking", value) @property @pulumi.getter(name="enableIPForwarding") def enable_ip_forwarding(self) -> Optional[pulumi.Input[bool]]: """ Whether IP forwarding enabled on this NIC. """ return pulumi.get(self, "enable_ip_forwarding") @enable_ip_forwarding.setter def enable_ip_forwarding(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "enable_ip_forwarding", value) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ Resource Id """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter(name="networkSecurityGroup") def network_security_group(self) -> Optional[pulumi.Input['SubResourceArgs']]: """ The network security group. """ return pulumi.get(self, "network_security_group") @network_security_group.setter def network_security_group(self, value: Optional[pulumi.Input['SubResourceArgs']]): pulumi.set(self, "network_security_group", value) @property @pulumi.getter def primary(self) -> Optional[pulumi.Input[bool]]: """ Specifies the primary network interface in case the virtual machine has more than 1 network interface. """ return pulumi.get(self, "primary") @primary.setter def primary(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "primary", value) @pulumi.input_type class VirtualMachineScaleSetNetworkProfileArgs: def __init__(__self__, *, health_probe: Optional[pulumi.Input['ApiEntityReferenceArgs']] = None, network_interface_configurations: Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetNetworkConfigurationArgs']]]] = None): """ Describes a virtual machine scale set network profile. :param pulumi.Input['ApiEntityReferenceArgs'] health_probe: A reference to a load balancer probe used to determine the health of an instance in the virtual machine scale set. The reference will be in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}'. :param pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetNetworkConfigurationArgs']]] network_interface_configurations: The list of network configurations. """ if health_probe is not None: pulumi.set(__self__, "health_probe", health_probe) if network_interface_configurations is not None: pulumi.set(__self__, "network_interface_configurations", network_interface_configurations) @property @pulumi.getter(name="healthProbe") def health_probe(self) -> Optional[pulumi.Input['ApiEntityReferenceArgs']]: """ A reference to a load balancer probe used to determine the health of an instance in the virtual machine scale set. The reference will be in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}'. """ return pulumi.get(self, "health_probe") @health_probe.setter def health_probe(self, value: Optional[pulumi.Input['ApiEntityReferenceArgs']]): pulumi.set(self, "health_probe", value) @property @pulumi.getter(name="networkInterfaceConfigurations") def network_interface_configurations(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetNetworkConfigurationArgs']]]]: """ The list of network configurations. """ return pulumi.get(self, "network_interface_configurations") @network_interface_configurations.setter def network_interface_configurations(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetNetworkConfigurationArgs']]]]): pulumi.set(self, "network_interface_configurations", value) @pulumi.input_type class VirtualMachineScaleSetOSDiskArgs: def __init__(__self__, *, create_option: pulumi.Input[Union[str, 'DiskCreateOptionTypes']], caching: Optional[pulumi.Input['CachingTypes']] = None, disk_size_gb: Optional[pulumi.Input[int]] = None, image: Optional[pulumi.Input['VirtualHardDiskArgs']] = None, managed_disk: Optional[pulumi.Input['VirtualMachineScaleSetManagedDiskParametersArgs']] = None, name: Optional[pulumi.Input[str]] = None, os_type: Optional[pulumi.Input['OperatingSystemTypes']] = None, vhd_containers: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, write_accelerator_enabled: Optional[pulumi.Input[bool]] = None): """ Describes a virtual machine scale set operating system disk. :param pulumi.Input[Union[str, 'DiskCreateOptionTypes']] create_option: Specifies how the virtual machines in the scale set should be created.<br><br> The only allowed value is: **FromImage** \u2013 This value is used when you are using an image to create the virtual machine. If you are using a platform image, you also use the imageReference element described above. If you are using a marketplace image, you also use the plan element previously described. :param pulumi.Input['CachingTypes'] caching: Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** :param pulumi.Input[int] disk_size_gb: Specifies the size of the operating system disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB :param pulumi.Input['VirtualHardDiskArgs'] image: Specifies information about the unmanaged user image to base the scale set on. :param pulumi.Input['VirtualMachineScaleSetManagedDiskParametersArgs'] managed_disk: The managed disk parameters. :param pulumi.Input[str] name: The disk name. :param pulumi.Input['OperatingSystemTypes'] os_type: This property allows you to specify the type of the OS that is included in the disk if creating a VM from user-image or a specialized VHD. <br><br> Possible values are: <br><br> **Windows** <br><br> **Linux** :param pulumi.Input[Sequence[pulumi.Input[str]]] vhd_containers: Specifies the container urls that are used to store operating system disks for the scale set. :param pulumi.Input[bool] write_accelerator_enabled: Specifies whether writeAccelerator should be enabled or disabled on the disk. """ pulumi.set(__self__, "create_option", create_option) if caching is not None: pulumi.set(__self__, "caching", caching) if disk_size_gb is not None: pulumi.set(__self__, "disk_size_gb", disk_size_gb) if image is not None: pulumi.set(__self__, "image", image) if managed_disk is not None: pulumi.set(__self__, "managed_disk", managed_disk) if name is not None: pulumi.set(__self__, "name", name) if os_type is not None: pulumi.set(__self__, "os_type", os_type) if vhd_containers is not None: pulumi.set(__self__, "vhd_containers", vhd_containers) if write_accelerator_enabled is not None: pulumi.set(__self__, "write_accelerator_enabled", write_accelerator_enabled) @property @pulumi.getter(name="createOption") def create_option(self) -> pulumi.Input[Union[str, 'DiskCreateOptionTypes']]: """ Specifies how the virtual machines in the scale set should be created.<br><br> The only allowed value is: **FromImage** \u2013 This value is used when you are using an image to create the virtual machine. If you are using a platform image, you also use the imageReference element described above. If you are using a marketplace image, you also use the plan element previously described. """ return pulumi.get(self, "create_option") @create_option.setter def create_option(self, value: pulumi.Input[Union[str, 'DiskCreateOptionTypes']]): pulumi.set(self, "create_option", value) @property @pulumi.getter def caching(self) -> Optional[pulumi.Input['CachingTypes']]: """ Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage** """ return pulumi.get(self, "caching") @caching.setter def caching(self, value: Optional[pulumi.Input['CachingTypes']]): pulumi.set(self, "caching", value) @property @pulumi.getter(name="diskSizeGB") def disk_size_gb(self) -> Optional[pulumi.Input[int]]: """ Specifies the size of the operating system disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB """ return pulumi.get(self, "disk_size_gb") @disk_size_gb.setter def disk_size_gb(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "disk_size_gb", value) @property @pulumi.getter def image(self) -> Optional[pulumi.Input['VirtualHardDiskArgs']]: """ Specifies information about the unmanaged user image to base the scale set on. """ return pulumi.get(self, "image") @image.setter def image(self, value: Optional[pulumi.Input['VirtualHardDiskArgs']]): pulumi.set(self, "image", value) @property @pulumi.getter(name="managedDisk") def managed_disk(self) -> Optional[pulumi.Input['VirtualMachineScaleSetManagedDiskParametersArgs']]: """ The managed disk parameters. """ return pulumi.get(self, "managed_disk") @managed_disk.setter def managed_disk(self, value: Optional[pulumi.Input['VirtualMachineScaleSetManagedDiskParametersArgs']]): pulumi.set(self, "managed_disk", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: """ The disk name. """ return pulumi.get(self, "name") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "name", value) @property @pulumi.getter(name="osType") def os_type(self) -> Optional[pulumi.Input['OperatingSystemTypes']]: """ This property allows you to specify the type of the OS that is included in the disk if creating a VM from user-image or a specialized VHD. <br><br> Possible values are: <br><br> **Windows** <br><br> **Linux** """ return pulumi.get(self, "os_type") @os_type.setter def os_type(self, value: Optional[pulumi.Input['OperatingSystemTypes']]): pulumi.set(self, "os_type", value) @property @pulumi.getter(name="vhdContainers") def vhd_containers(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ Specifies the container urls that are used to store operating system disks for the scale set. """ return pulumi.get(self, "vhd_containers") @vhd_containers.setter def vhd_containers(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "vhd_containers", value) @property @pulumi.getter(name="writeAcceleratorEnabled") def write_accelerator_enabled(self) -> Optional[pulumi.Input[bool]]: """ Specifies whether writeAccelerator should be enabled or disabled on the disk. """ return pulumi.get(self, "write_accelerator_enabled") @write_accelerator_enabled.setter def write_accelerator_enabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "write_accelerator_enabled", value) @pulumi.input_type class VirtualMachineScaleSetOSProfileArgs: def __init__(__self__, *, admin_password: Optional[pulumi.Input[str]] = None, admin_username: Optional[pulumi.Input[str]] = None, computer_name_prefix: Optional[pulumi.Input[str]] = None, custom_data: Optional[pulumi.Input[str]] = None, linux_configuration: Optional[pulumi.Input['LinuxConfigurationArgs']] = None, secrets: Optional[pulumi.Input[Sequence[pulumi.Input['VaultSecretGroupArgs']]]] = None, windows_configuration: Optional[pulumi.Input['WindowsConfigurationArgs']] = None): """ Describes a virtual machine scale set OS profile. :param pulumi.Input[str] admin_password: Specifies the password of the administrator account. <br><br> **Minimum-length (Windows):** 8 characters <br><br> **Minimum-length (Linux):** 6 characters <br><br> **Max-length (Windows):** 123 characters <br><br> **Max-length (Linux):** 72 characters <br><br> **Complexity requirements:** 3 out of 4 conditions below need to be fulfilled <br> Has lower characters <br>Has upper characters <br> Has a digit <br> Has a special character (Regex match [\W_]) <br><br> **Disallowed values:** "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", "Password22", "iloveyou!" <br><br> For resetting the password, see [How to reset the Remote Desktop service or its login password in a Windows VM](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-reset-rdp?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> For resetting root password, see [Manage users, SSH, and check or repair disks on Azure Linux VMs using the VMAccess Extension](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-vmaccess-extension?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json#reset-root-password) :param pulumi.Input[str] admin_username: Specifies the name of the administrator account. <br><br> **Windows-only restriction:** Cannot end in "." <br><br> **Disallowed values:** "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5". <br><br> **Minimum-length (Linux):** 1 character <br><br> **Max-length (Linux):** 64 characters <br><br> **Max-length (Windows):** 20 characters <br><br><li> For root access to the Linux VM, see [Using root privileges on Linux virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-use-root-privileges?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json)<br><li> For a list of built-in system users on Linux that should not be used in this field, see [Selecting User Names for Linux on Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-usernames?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) :param pulumi.Input[str] computer_name_prefix: Specifies the computer name prefix for all of the virtual machines in the scale set. Computer name prefixes must be 1 to 15 characters long. :param pulumi.Input[str] custom_data: Specifies a base-64 encoded string of custom data. The base-64 encoded string is decoded to a binary array that is saved as a file on the Virtual Machine. The maximum length of the binary array is 65535 bytes. <br><br> For using cloud-init for your VM, see [Using cloud-init to customize a Linux VM during creation](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-cloud-init?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) :param pulumi.Input['LinuxConfigurationArgs'] linux_configuration: Specifies the Linux operating system settings on the virtual machine. <br><br>For a list of supported Linux distributions, see [Linux on Azure-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-endorsed-distros?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) <br><br> For running non-endorsed distributions, see [Information for Non-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-create-upload-generic?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json). :param pulumi.Input[Sequence[pulumi.Input['VaultSecretGroupArgs']]] secrets: Specifies set of certificates that should be installed onto the virtual machines in the scale set. :param pulumi.Input['WindowsConfigurationArgs'] windows_configuration: Specifies Windows operating system settings on the virtual machine. """ if admin_password is not None: pulumi.set(__self__, "admin_password", admin_password) if admin_username is not None: pulumi.set(__self__, "admin_username", admin_username) if computer_name_prefix is not None: pulumi.set(__self__, "computer_name_prefix", computer_name_prefix) if custom_data is not None: pulumi.set(__self__, "custom_data", custom_data) if linux_configuration is not None: pulumi.set(__self__, "linux_configuration", linux_configuration) if secrets is not None: pulumi.set(__self__, "secrets", secrets) if windows_configuration is not None: pulumi.set(__self__, "windows_configuration", windows_configuration) @property @pulumi.getter(name="adminPassword") def admin_password(self) -> Optional[pulumi.Input[str]]: """ Specifies the password of the administrator account. <br><br> **Minimum-length (Windows):** 8 characters <br><br> **Minimum-length (Linux):** 6 characters <br><br> **Max-length (Windows):** 123 characters <br><br> **Max-length (Linux):** 72 characters <br><br> **Complexity requirements:** 3 out of 4 conditions below need to be fulfilled <br> Has lower characters <br>Has upper characters <br> Has a digit <br> Has a special character (Regex match [\W_]) <br><br> **Disallowed values:** "abc@123", "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", "Password22", "iloveyou!" <br><br> For resetting the password, see [How to reset the Remote Desktop service or its login password in a Windows VM](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-reset-rdp?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> For resetting root password, see [Manage users, SSH, and check or repair disks on Azure Linux VMs using the VMAccess Extension](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-vmaccess-extension?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json#reset-root-password) """ return pulumi.get(self, "admin_password") @admin_password.setter def admin_password(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "admin_password", value) @property @pulumi.getter(name="adminUsername") def admin_username(self) -> Optional[pulumi.Input[str]]: """ Specifies the name of the administrator account. <br><br> **Windows-only restriction:** Cannot end in "." <br><br> **Disallowed values:** "administrator", "admin", "user", "user1", "test", "user2", "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", "david", "guest", "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", "user5". <br><br> **Minimum-length (Linux):** 1 character <br><br> **Max-length (Linux):** 64 characters <br><br> **Max-length (Windows):** 20 characters <br><br><li> For root access to the Linux VM, see [Using root privileges on Linux virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-use-root-privileges?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json)<br><li> For a list of built-in system users on Linux that should not be used in this field, see [Selecting User Names for Linux on Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-usernames?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) """ return pulumi.get(self, "admin_username") @admin_username.setter def admin_username(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "admin_username", value) @property @pulumi.getter(name="computerNamePrefix") def computer_name_prefix(self) -> Optional[pulumi.Input[str]]: """ Specifies the computer name prefix for all of the virtual machines in the scale set. Computer name prefixes must be 1 to 15 characters long. """ return pulumi.get(self, "computer_name_prefix") @computer_name_prefix.setter def computer_name_prefix(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "computer_name_prefix", value) @property @pulumi.getter(name="customData") def custom_data(self) -> Optional[pulumi.Input[str]]: """ Specifies a base-64 encoded string of custom data. The base-64 encoded string is decoded to a binary array that is saved as a file on the Virtual Machine. The maximum length of the binary array is 65535 bytes. <br><br> For using cloud-init for your VM, see [Using cloud-init to customize a Linux VM during creation](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-using-cloud-init?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) """ return pulumi.get(self, "custom_data") @custom_data.setter def custom_data(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "custom_data", value) @property @pulumi.getter(name="linuxConfiguration") def linux_configuration(self) -> Optional[pulumi.Input['LinuxConfigurationArgs']]: """ Specifies the Linux operating system settings on the virtual machine. <br><br>For a list of supported Linux distributions, see [Linux on Azure-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-endorsed-distros?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json) <br><br> For running non-endorsed distributions, see [Information for Non-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-create-upload-generic?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json). """ return pulumi.get(self, "linux_configuration") @linux_configuration.setter def linux_configuration(self, value: Optional[pulumi.Input['LinuxConfigurationArgs']]): pulumi.set(self, "linux_configuration", value) @property @pulumi.getter def secrets(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VaultSecretGroupArgs']]]]: """ Specifies set of certificates that should be installed onto the virtual machines in the scale set. """ return pulumi.get(self, "secrets") @secrets.setter def secrets(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VaultSecretGroupArgs']]]]): pulumi.set(self, "secrets", value) @property @pulumi.getter(name="windowsConfiguration") def windows_configuration(self) -> Optional[pulumi.Input['WindowsConfigurationArgs']]: """ Specifies Windows operating system settings on the virtual machine. """ return pulumi.get(self, "windows_configuration") @windows_configuration.setter def windows_configuration(self, value: Optional[pulumi.Input['WindowsConfigurationArgs']]): pulumi.set(self, "windows_configuration", value) @pulumi.input_type class VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettingsArgs: def __init__(__self__, *, domain_name_label: pulumi.Input[str]): """ Describes a virtual machines scale sets network configuration's DNS settings. :param pulumi.Input[str] domain_name_label: The Domain name label.The concatenation of the domain name label and vm index will be the domain name labels of the PublicIPAddress resources that will be created """ pulumi.set(__self__, "domain_name_label", domain_name_label) @property @pulumi.getter(name="domainNameLabel") def domain_name_label(self) -> pulumi.Input[str]: """ The Domain name label.The concatenation of the domain name label and vm index will be the domain name labels of the PublicIPAddress resources that will be created """ return pulumi.get(self, "domain_name_label") @domain_name_label.setter def domain_name_label(self, value: pulumi.Input[str]): pulumi.set(self, "domain_name_label", value) @pulumi.input_type class VirtualMachineScaleSetPublicIPAddressConfigurationArgs: def __init__(__self__, *, name: pulumi.Input[str], dns_settings: Optional[pulumi.Input['VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettingsArgs']] = None, idle_timeout_in_minutes: Optional[pulumi.Input[int]] = None, ip_tags: Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetIpTagArgs']]]] = None): """ Describes a virtual machines scale set IP Configuration's PublicIPAddress configuration :param pulumi.Input[str] name: The publicIP address configuration name. :param pulumi.Input['VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettingsArgs'] dns_settings: The dns settings to be applied on the publicIP addresses . :param pulumi.Input[int] idle_timeout_in_minutes: The idle timeout of the public IP address. :param pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetIpTagArgs']]] ip_tags: The list of IP tags associated with the public IP address. """ pulumi.set(__self__, "name", name) if dns_settings is not None: pulumi.set(__self__, "dns_settings", dns_settings) if idle_timeout_in_minutes is not None: pulumi.set(__self__, "idle_timeout_in_minutes", idle_timeout_in_minutes) if ip_tags is not None: pulumi.set(__self__, "ip_tags", ip_tags) @property @pulumi.getter def name(self) -> pulumi.Input[str]: """ The publicIP address configuration name. """ return pulumi.get(self, "name") @name.setter def name(self, value: pulumi.Input[str]): pulumi.set(self, "name", value) @property @pulumi.getter(name="dnsSettings") def dns_settings(self) -> Optional[pulumi.Input['VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettingsArgs']]: """ The dns settings to be applied on the publicIP addresses . """ return pulumi.get(self, "dns_settings") @dns_settings.setter def dns_settings(self, value: Optional[pulumi.Input['VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettingsArgs']]): pulumi.set(self, "dns_settings", value) @property @pulumi.getter(name="idleTimeoutInMinutes") def idle_timeout_in_minutes(self) -> Optional[pulumi.Input[int]]: """ The idle timeout of the public IP address. """ return pulumi.get(self, "idle_timeout_in_minutes") @idle_timeout_in_minutes.setter def idle_timeout_in_minutes(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "idle_timeout_in_minutes", value) @property @pulumi.getter(name="ipTags") def ip_tags(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetIpTagArgs']]]]: """ The list of IP tags associated with the public IP address. """ return pulumi.get(self, "ip_tags") @ip_tags.setter def ip_tags(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetIpTagArgs']]]]): pulumi.set(self, "ip_tags", value) @pulumi.input_type class VirtualMachineScaleSetStorageProfileArgs: def __init__(__self__, *, data_disks: Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetDataDiskArgs']]]] = None, image_reference: Optional[pulumi.Input['ImageReferenceArgs']] = None, os_disk: Optional[pulumi.Input['VirtualMachineScaleSetOSDiskArgs']] = None): """ Describes a virtual machine scale set storage profile. :param pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetDataDiskArgs']]] data_disks: Specifies the parameters that are used to add data disks to the virtual machines in the scale set. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). :param pulumi.Input['ImageReferenceArgs'] image_reference: Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations. :param pulumi.Input['VirtualMachineScaleSetOSDiskArgs'] os_disk: Specifies information about the operating system disk used by the virtual machines in the scale set. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). """ if data_disks is not None: pulumi.set(__self__, "data_disks", data_disks) if image_reference is not None: pulumi.set(__self__, "image_reference", image_reference) if os_disk is not None: pulumi.set(__self__, "os_disk", os_disk) @property @pulumi.getter(name="dataDisks") def data_disks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetDataDiskArgs']]]]: """ Specifies the parameters that are used to add data disks to the virtual machines in the scale set. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). """ return pulumi.get(self, "data_disks") @data_disks.setter def data_disks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineScaleSetDataDiskArgs']]]]): pulumi.set(self, "data_disks", value) @property @pulumi.getter(name="imageReference") def image_reference(self) -> Optional[pulumi.Input['ImageReferenceArgs']]: """ Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations. """ return pulumi.get(self, "image_reference") @image_reference.setter def image_reference(self, value: Optional[pulumi.Input['ImageReferenceArgs']]): pulumi.set(self, "image_reference", value) @property @pulumi.getter(name="osDisk") def os_disk(self) -> Optional[pulumi.Input['VirtualMachineScaleSetOSDiskArgs']]: """ Specifies information about the operating system disk used by the virtual machines in the scale set. <br><br> For more information about disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-about-disks-vhds?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). """ return pulumi.get(self, "os_disk") @os_disk.setter def os_disk(self, value: Optional[pulumi.Input['VirtualMachineScaleSetOSDiskArgs']]): pulumi.set(self, "os_disk", value) @pulumi.input_type class VirtualMachineScaleSetVMProfileArgs: def __init__(__self__, *, diagnostics_profile: Optional[pulumi.Input['DiagnosticsProfileArgs']] = None, eviction_policy: Optional[pulumi.Input[Union[str, 'VirtualMachineEvictionPolicyTypes']]] = None, extension_profile: Optional[pulumi.Input['VirtualMachineScaleSetExtensionProfileArgs']] = None, license_type: Optional[pulumi.Input[str]] = None, network_profile: Optional[pulumi.Input['VirtualMachineScaleSetNetworkProfileArgs']] = None, os_profile: Optional[pulumi.Input['VirtualMachineScaleSetOSProfileArgs']] = None, priority: Optional[pulumi.Input[Union[str, 'VirtualMachinePriorityTypes']]] = None, storage_profile: Optional[pulumi.Input['VirtualMachineScaleSetStorageProfileArgs']] = None): """ Describes a virtual machine scale set virtual machine profile. :param pulumi.Input['DiagnosticsProfileArgs'] diagnostics_profile: Specifies the boot diagnostic settings state. <br><br>Minimum api-version: 2015-06-15. :param pulumi.Input[Union[str, 'VirtualMachineEvictionPolicyTypes']] eviction_policy: Specifies the eviction policy for virtual machines in a low priority scale set. <br><br>Minimum api-version: 2017-10-30-preview :param pulumi.Input['VirtualMachineScaleSetExtensionProfileArgs'] extension_profile: Specifies a collection of settings for extensions installed on virtual machines in the scale set. :param pulumi.Input[str] license_type: Specifies that the image or disk that is being used was licensed on-premises. This element is only used for images that contain the Windows Server operating system. <br><br> Possible values are: <br><br> Windows_Client <br><br> Windows_Server <br><br> If this element is included in a request for an update, the value must match the initial value. This value cannot be updated. <br><br> For more information, see [Azure Hybrid Use Benefit for Windows Server](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-hybrid-use-benefit-licensing?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Minimum api-version: 2015-06-15 :param pulumi.Input['VirtualMachineScaleSetNetworkProfileArgs'] network_profile: Specifies properties of the network interfaces of the virtual machines in the scale set. :param pulumi.Input['VirtualMachineScaleSetOSProfileArgs'] os_profile: Specifies the operating system settings for the virtual machines in the scale set. :param pulumi.Input[Union[str, 'VirtualMachinePriorityTypes']] priority: Specifies the priority for the virtual machines in the scale set. <br><br>Minimum api-version: 2017-10-30-preview :param pulumi.Input['VirtualMachineScaleSetStorageProfileArgs'] storage_profile: Specifies the storage settings for the virtual machine disks. """ if diagnostics_profile is not None: pulumi.set(__self__, "diagnostics_profile", diagnostics_profile) if eviction_policy is not None: pulumi.set(__self__, "eviction_policy", eviction_policy) if extension_profile is not None: pulumi.set(__self__, "extension_profile", extension_profile) if license_type is not None: pulumi.set(__self__, "license_type", license_type) if network_profile is not None: pulumi.set(__self__, "network_profile", network_profile) if os_profile is not None: pulumi.set(__self__, "os_profile", os_profile) if priority is not None: pulumi.set(__self__, "priority", priority) if storage_profile is not None: pulumi.set(__self__, "storage_profile", storage_profile) @property @pulumi.getter(name="diagnosticsProfile") def diagnostics_profile(self) -> Optional[pulumi.Input['DiagnosticsProfileArgs']]: """ Specifies the boot diagnostic settings state. <br><br>Minimum api-version: 2015-06-15. """ return pulumi.get(self, "diagnostics_profile") @diagnostics_profile.setter def diagnostics_profile(self, value: Optional[pulumi.Input['DiagnosticsProfileArgs']]): pulumi.set(self, "diagnostics_profile", value) @property @pulumi.getter(name="evictionPolicy") def eviction_policy(self) -> Optional[pulumi.Input[Union[str, 'VirtualMachineEvictionPolicyTypes']]]: """ Specifies the eviction policy for virtual machines in a low priority scale set. <br><br>Minimum api-version: 2017-10-30-preview """ return pulumi.get(self, "eviction_policy") @eviction_policy.setter def eviction_policy(self, value: Optional[pulumi.Input[Union[str, 'VirtualMachineEvictionPolicyTypes']]]): pulumi.set(self, "eviction_policy", value) @property @pulumi.getter(name="extensionProfile") def extension_profile(self) -> Optional[pulumi.Input['VirtualMachineScaleSetExtensionProfileArgs']]: """ Specifies a collection of settings for extensions installed on virtual machines in the scale set. """ return pulumi.get(self, "extension_profile") @extension_profile.setter def extension_profile(self, value: Optional[pulumi.Input['VirtualMachineScaleSetExtensionProfileArgs']]): pulumi.set(self, "extension_profile", value) @property @pulumi.getter(name="licenseType") def license_type(self) -> Optional[pulumi.Input[str]]: """ Specifies that the image or disk that is being used was licensed on-premises. This element is only used for images that contain the Windows Server operating system. <br><br> Possible values are: <br><br> Windows_Client <br><br> Windows_Server <br><br> If this element is included in a request for an update, the value must match the initial value. This value cannot be updated. <br><br> For more information, see [Azure Hybrid Use Benefit for Windows Server](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-hybrid-use-benefit-licensing?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Minimum api-version: 2015-06-15 """ return pulumi.get(self, "license_type") @license_type.setter def license_type(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "license_type", value) @property @pulumi.getter(name="networkProfile") def network_profile(self) -> Optional[pulumi.Input['VirtualMachineScaleSetNetworkProfileArgs']]: """ Specifies properties of the network interfaces of the virtual machines in the scale set. """ return pulumi.get(self, "network_profile") @network_profile.setter def network_profile(self, value: Optional[pulumi.Input['VirtualMachineScaleSetNetworkProfileArgs']]): pulumi.set(self, "network_profile", value) @property @pulumi.getter(name="osProfile") def os_profile(self) -> Optional[pulumi.Input['VirtualMachineScaleSetOSProfileArgs']]: """ Specifies the operating system settings for the virtual machines in the scale set. """ return pulumi.get(self, "os_profile") @os_profile.setter def os_profile(self, value: Optional[pulumi.Input['VirtualMachineScaleSetOSProfileArgs']]): pulumi.set(self, "os_profile", value) @property @pulumi.getter def priority(self) -> Optional[pulumi.Input[Union[str, 'VirtualMachinePriorityTypes']]]: """ Specifies the priority for the virtual machines in the scale set. <br><br>Minimum api-version: 2017-10-30-preview """ return pulumi.get(self, "priority") @priority.setter def priority(self, value: Optional[pulumi.Input[Union[str, 'VirtualMachinePriorityTypes']]]): pulumi.set(self, "priority", value) @property @pulumi.getter(name="storageProfile") def storage_profile(self) -> Optional[pulumi.Input['VirtualMachineScaleSetStorageProfileArgs']]: """ Specifies the storage settings for the virtual machine disks. """ return pulumi.get(self, "storage_profile") @storage_profile.setter def storage_profile(self, value: Optional[pulumi.Input['VirtualMachineScaleSetStorageProfileArgs']]): pulumi.set(self, "storage_profile", value) @pulumi.input_type class WinRMConfigurationArgs: def __init__(__self__, *, listeners: Optional[pulumi.Input[Sequence[pulumi.Input['WinRMListenerArgs']]]] = None): """ Describes Windows Remote Management configuration of the VM :param pulumi.Input[Sequence[pulumi.Input['WinRMListenerArgs']]] listeners: The list of Windows Remote Management listeners """ if listeners is not None: pulumi.set(__self__, "listeners", listeners) @property @pulumi.getter def listeners(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['WinRMListenerArgs']]]]: """ The list of Windows Remote Management listeners """ return pulumi.get(self, "listeners") @listeners.setter def listeners(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['WinRMListenerArgs']]]]): pulumi.set(self, "listeners", value) @pulumi.input_type class WinRMListenerArgs: def __init__(__self__, *, certificate_url: Optional[pulumi.Input[str]] = None, protocol: Optional[pulumi.Input['ProtocolTypes']] = None): """ Describes Protocol and thumbprint of Windows Remote Management listener :param pulumi.Input[str] certificate_url: This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, see [Add a key or secret to the key vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). In this case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8: <br><br> {<br> "data":"<Base64-encoded-certificate>",<br> "dataType":"pfx",<br> "password":"<pfx-file-password>"<br>} :param pulumi.Input['ProtocolTypes'] protocol: Specifies the protocol of listener. <br><br> Possible values are: <br>**http** <br><br> **https** """ if certificate_url is not None: pulumi.set(__self__, "certificate_url", certificate_url) if protocol is not None: pulumi.set(__self__, "protocol", protocol) @property @pulumi.getter(name="certificateUrl") def certificate_url(self) -> Optional[pulumi.Input[str]]: """ This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, see [Add a key or secret to the key vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). In this case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8: <br><br> {<br> "data":"<Base64-encoded-certificate>",<br> "dataType":"pfx",<br> "password":"<pfx-file-password>"<br>} """ return pulumi.get(self, "certificate_url") @certificate_url.setter def certificate_url(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "certificate_url", value) @property @pulumi.getter def protocol(self) -> Optional[pulumi.Input['ProtocolTypes']]: """ Specifies the protocol of listener. <br><br> Possible values are: <br>**http** <br><br> **https** """ return pulumi.get(self, "protocol") @protocol.setter def protocol(self, value: Optional[pulumi.Input['ProtocolTypes']]): pulumi.set(self, "protocol", value) @pulumi.input_type class WindowsConfigurationArgs: def __init__(__self__, *, additional_unattend_content: Optional[pulumi.Input[Sequence[pulumi.Input['AdditionalUnattendContentArgs']]]] = None, enable_automatic_updates: Optional[pulumi.Input[bool]] = None, provision_vm_agent: Optional[pulumi.Input[bool]] = None, time_zone: Optional[pulumi.Input[str]] = None, win_rm: Optional[pulumi.Input['WinRMConfigurationArgs']] = None): """ Specifies Windows operating system settings on the virtual machine. :param pulumi.Input[Sequence[pulumi.Input['AdditionalUnattendContentArgs']]] additional_unattend_content: Specifies additional base-64 encoded XML formatted information that can be included in the Unattend.xml file, which is used by Windows Setup. :param pulumi.Input[bool] enable_automatic_updates: Indicates whether virtual machine is enabled for automatic updates. :param pulumi.Input[bool] provision_vm_agent: Indicates whether virtual machine agent should be provisioned on the virtual machine. <br><br> When this property is not specified in the request body, default behavior is to set it to true. This will ensure that VM Agent is installed on the VM so that extensions can be added to the VM later. :param pulumi.Input[str] time_zone: Specifies the time zone of the virtual machine. e.g. "Pacific Standard Time" :param pulumi.Input['WinRMConfigurationArgs'] win_rm: Specifies the Windows Remote Management listeners. This enables remote Windows PowerShell. """ if additional_unattend_content is not None: pulumi.set(__self__, "additional_unattend_content", additional_unattend_content) if enable_automatic_updates is not None: pulumi.set(__self__, "enable_automatic_updates", enable_automatic_updates) if provision_vm_agent is not None: pulumi.set(__self__, "provision_vm_agent", provision_vm_agent) if time_zone is not None: pulumi.set(__self__, "time_zone", time_zone) if win_rm is not None: pulumi.set(__self__, "win_rm", win_rm) @property @pulumi.getter(name="additionalUnattendContent") def additional_unattend_content(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AdditionalUnattendContentArgs']]]]: """ Specifies additional base-64 encoded XML formatted information that can be included in the Unattend.xml file, which is used by Windows Setup. """ return pulumi.get(self, "additional_unattend_content") @additional_unattend_content.setter def additional_unattend_content(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['AdditionalUnattendContentArgs']]]]): pulumi.set(self, "additional_unattend_content", value) @property @pulumi.getter(name="enableAutomaticUpdates") def enable_automatic_updates(self) -> Optional[pulumi.Input[bool]]: """ Indicates whether virtual machine is enabled for automatic updates. """ return pulumi.get(self, "enable_automatic_updates") @enable_automatic_updates.setter def enable_automatic_updates(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "enable_automatic_updates", value) @property @pulumi.getter(name="provisionVMAgent") def provision_vm_agent(self) -> Optional[pulumi.Input[bool]]: """ Indicates whether virtual machine agent should be provisioned on the virtual machine. <br><br> When this property is not specified in the request body, default behavior is to set it to true. This will ensure that VM Agent is installed on the VM so that extensions can be added to the VM later. """ return pulumi.get(self, "provision_vm_agent") @provision_vm_agent.setter def provision_vm_agent(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "provision_vm_agent", value) @property @pulumi.getter(name="timeZone") def time_zone(self) -> Optional[pulumi.Input[str]]: """ Specifies the time zone of the virtual machine. e.g. "Pacific Standard Time" """ return pulumi.get(self, "time_zone") @time_zone.setter def time_zone(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "time_zone", value) @property @pulumi.getter(name="winRM") def win_rm(self) -> Optional[pulumi.Input['WinRMConfigurationArgs']]: """ Specifies the Windows Remote Management listeners. This enables remote Windows PowerShell. """ return pulumi.get(self, "win_rm") @win_rm.setter def win_rm(self, value: Optional[pulumi.Input['WinRMConfigurationArgs']]): pulumi.set(self, "win_rm", value)
import os import sys if __name__ != '__main__': print("Currently not support importing.") raise KeyboardInterrupt("Force Exit") print("Supported: ") print("Pictures: png, jpg, jpeg, tif, tiff, bmp, gif, ico") print("Videos: mp4, webm, mov, mkv, avi, flv(RIP), wmv") print("Audio: mp3, ape, flac, wav, m4a") print("Please copy this file to the folder, that has all these files.") print("Press Enter to continue, or press 'q' and enter to exit.") t = input("") if t == "q": print("Quitting..") sys.exit(1) print("Working on it...") print("Outputting to 'vap.html'...") print("Getting files' properties...") fp = open("vap.html", 'w') os.system("dir /b *.png *.jpg *.jpeg *.tif *.tiff *.bmp *.gif *.ico > pictures.vap.tmp") os.system("dir /b *.mp4 *.webm *.mov *.mkv *.avi *.flv *.wmv > videos.vap.tmp") os.system("dir /b *.mp3 *.ape *.flac *.wav *.m4a > audio.vap.tmp") #os.system("echo \nEOF > pictures.vap.tmp") #os.system("echo \nEOF > videos.vap.tmp") #os.system("echo \nEOF > audio.vap.tmp") pic = open("pictures.vap.tmp") vid = open("videos.vap.tmp") ado = open("audio.vap.tmp") print("Processing Pictures...") p = "" v = "" a = "" for picline in pic: picline = picline.strip("\n") p += '\n<img src="' + str(picline) + '" style="width:100%;"></img>' print("Processing Videos...") for vidline in vid: vidline = vidline.strip("\n") v += '\n<video src="' + str(vidline) + '" controls></video>' print("Processing Audio...") for adoline in ado: adoline = adoline.strip("\n") a += '\n<audio src="' + str(adoline) + '" controls="controls"></audio>' print("Writting to file...") fp.write("<!DOCTYPE HTML>\n<HTML>\n<HEAD><TITLE>VAP OUTPUT</TITLE>\n</HEAD>\n<BODY>\n" + str(p) + "\n" + str(v) + "\n" + str(a) + "\n</BODY>\n</HTML>") pic.close() vid.close() ado.close() fp.close() os.remove("pictures.vap.tmp") os.remove("videos.vap.tmp") os.remove("audio.vap.tmp") print("Done.") os.system("vap.html")
var name = "Master of the Hi Coup"; var collection_type = 0; var is_secret = 0; var desc = "Hit the Mega-Hi 311 times"; var status_text = "It's nice to say Hi. And with all these matching signs, you got a new badge!"; var last_published = 1351302650; var is_shareworthy = 1; var url = "master-of-the-hi-coup"; var category = "social"; var url_swf = "\/c2.glitch.bz\/achievements\/2012-10-26\/master_of_the_hi_coup_1351296896.swf"; var url_img_180 = "\/c2.glitch.bz\/achievements\/2012-10-26\/master_of_the_hi_coup_1351296896_180.png"; var url_img_60 = "\/c2.glitch.bz\/achievements\/2012-10-26\/master_of_the_hi_coup_1351296896_60.png"; var url_img_40 = "\/c2.glitch.bz\/achievements\/2012-10-26\/master_of_the_hi_coup_1351296896_40.png"; function on_apply(pc){ } var conditions = { 845 : { type : "group_sum", group : "hi_jackpot", value : "311" }, }; function onComplete(pc){ // generated from rewards var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_achievement_modifier(); if (/completist/i.exec(this.name)) { var level = pc.stats_get_level(); if (level > 4) { multiplier *= (pc.stats_get_level()/4); } } pc.stats_add_xp(round_to_5(1500 * multiplier), true); pc.stats_add_favor_points("friendly", round_to_5(250 * multiplier)); if(pc.buffs_has('gift_of_gab')) { pc.buffs_remove('gift_of_gab'); } else if(pc.buffs_has('silvertongue')) { pc.buffs_remove('silvertongue'); } } var rewards = { "xp" : 1500, "favor" : { "giant" : "friendly", "points" : 250 } }; // generated ok (NO DATE)
const { Group } = require('@antv/g/lib'); const Util = require('../util'); const Grid = function(cfg) { Grid.superclass.constructor.call(this, cfg); }; Util.extend(Grid, Group); Util.augment(Grid, { getDefaultCfg() { // const cfg = super.getDefaultCfg(); return { zIndex: 1, /** * 栅格线的类型 * - line 不封闭的线 * - polygon 封闭的多边形 * @type {String} */ type: 'line', /** * 线的样式配置 * @type {Object} */ lineStyle: null, /** * 线集合的配置 * @type {Array} */ items: null, /** * 为网格设置交替的背景色,指定一个值则先渲染奇数层,两个值则交替渲染 * @type {String | Array} */ alternateColor: null, matrix: null, /** * 是否隐藏第一条网格线,默认为 false * @type {Boolean} */ hideFirstLine: false, /** * 是否隐藏最后一条网格线,默认为 false * @type {Boolean} */ hideLastLine: false, /** * 0基线不在轴线上时,是否强调0基线 * @type {Boolean} */ hightLightZero: false, /** * 0基线样式 * @type {Object} */ zeroLineStyle: { stroke: '#595959', lineDash: [ 0, 0 ] } }; }, _renderUI() { Grid.superclass._renderUI.call(this); this._drawLines(); }, _drawLines() { const self = this; const lineStyle = self.get('lineStyle'); const items = self.get('items'); if (items && items.length) { self._precessItems(items); self._drawGridLines(items, lineStyle); } }, _precessItems(items) { const self = this; let preItem; Util.each(items, (item, index) => { if (preItem && self.get('alternateColor')) { self._drawAlternativeBg(item, preItem, index); } preItem = item; }); }, _drawGridLines(items, lineStyle) { const self = this; const type = this.get('type'); let gridLine; let path; let cfg; let points; const itemsLength = items.length; if (type === 'line' || type === 'polygon') { Util.each(items, (item, idx) => { if (self.get('hideFirstLine') && idx === 0) { // 不展示第一条网格线 return; } if (self.get('hideLastLine') && idx === (itemsLength - 1)) { // 不展示最后一条网格线 return; } points = item.points; path = []; if (type === 'line') { path.push([ 'M', points[0].x, points[0].y ]); path.push([ 'L', points[ points.length - 1 ].x, points[ points.length - 1 ].y ]); } else { Util.each(points, function(point, index) { if (index === 0) { path.push([ 'M', point.x, point.y ]); } else { path.push([ 'L', point.x, point.y ]); } }); } if (self._drawZeroLine(type, idx)) { cfg = Util.mix({}, self.get('zeroLineStyle'), { path }); } else { cfg = Util.mix({}, lineStyle, { path }); } gridLine = self.addShape('path', { attrs: cfg }); gridLine.name = 'axis-grid'; gridLine._id = item._id; gridLine.set('coord', self.get('coord')); self.get('appendInfo') && gridLine.setSilent('appendInfo', self.get('appendInfo')); }); } else { Util.each(items, (item, idx) => { if (self.get('hideFirstLine') && idx === 0) { // 不展示第一条网格线 return; } if (self.get('hideLastLine') && idx === (itemsLength - 1)) { // 不展示最后一条网格线 return; } points = item.points; path = []; Util.each(points, function(point, index) { const radius = point.radius; if (index === 0) { path.push([ 'M', point.x, point.y ]); } else { path.push([ 'A', radius, radius, 0, 0, point.flag, point.x, point.y ]); } }); cfg = Util.mix({}, lineStyle, { path }); gridLine = self.addShape('path', { attrs: cfg }); gridLine.name = 'axis-grid'; gridLine._id = item._id; gridLine.set('coord', self.get('coord')); self.get('appendInfo') && gridLine.setSilent('appendInfo', self.get('appendInfo')); }); } }, _drawZeroLine(type, idx) { const self = this; const tickValues = self.get('tickValues'); if (type === 'line' && tickValues) { if (tickValues[idx] === 0 && self.get('hightLightZero')) { return true; } } return false; }, _drawAlternativeBg(item, preItem, index) { const self = this; const alternateColor = self.get('alternateColor'); let attrs; let oddColor; let evenColor; if (Util.isString(alternateColor)) { oddColor = alternateColor; } else if (Util.isArray(alternateColor)) { oddColor = alternateColor[0]; evenColor = alternateColor[1]; } if (index % 2 === 0) { if (evenColor) { attrs = self._getBackItem(preItem.points, item.points, evenColor); } } else if (oddColor) { attrs = self._getBackItem(preItem.points, item.points, oddColor); } const shape = self.addShape('Path', { attrs }); shape.name = 'axis-grid-rect'; shape._id = item._id && item._id.replace('grid', 'grid-rect'); shape.set('coord', self.get('coord')); self.get('appendInfo') && shape.setSilent('appendInfo', self.get('appendInfo')); }, _getBackItem(start, end, bgColor) { const path = []; const type = this.get('type'); if (type === 'line') { path.push([ 'M', start[0].x, start[0].y ]); path.push([ 'L', start[start.length - 1].x, start[start.length - 1].y ]); path.push([ 'L', end[end.length - 1].x, end[end.length - 1].y ]); path.push([ 'L', end[0].x, end[0].y ]); path.push([ 'Z' ]); } else if (type === 'polygon') { Util.each(start, (subItem, index) => { if (index === 0) { path.push([ 'M', subItem.x, subItem.y ]); } else { path.push([ 'L', subItem.x, subItem.y ]); } }); for (let i = end.length - 1; i >= 0; i--) { path.push([ 'L', end[i].x, end[i].y ]); } path.push([ 'Z' ]); } else { const flag = start[0].flag; Util.each(start, function(subItem, index) { const radius = subItem.radius; if (index === 0) { path.push([ 'M', subItem.x, subItem.y ]); } else { path.push([ 'A', radius, radius, 0, 0, subItem.flag, subItem.x, subItem.y ]); } }); for (let j = end.length - 1; j >= 0; j--) { const endSubItem = end[j]; const endRadius = endSubItem.radius; if (j === end.length - 1) { path.push([ 'M', endSubItem.x, endSubItem.y ]); } else { path.push([ 'A', endRadius, endRadius, 0, 0, flag === 1 ? 0 : 1, endSubItem.x, endSubItem.y ]); } } } return { fill: bgColor, path }; } }); module.exports = Grid;
from digitalio import DigitalInOut, Direction, Pull import board import storage import usb_midi import usb_cdc import usb_hid btn_usb_state = DigitalInOut(board.D10) btn_usb_state.direction = Direction.INPUT btn_usb_state.pull = Pull.UP if btn_usb_state.value: # Executed when button at pin 10 is pressed print("Developer mode disabled") storage.disable_usb_drive() usb_cdc.disable() usb_midi.disable() usb_hid.enable((usb_hid.Device.MOUSE)) else: print("Developer mode enabled")
import gzip import mimetypes import os import re from datetime import datetime from functools import wraps from io import BytesIO, UnsupportedOperation from time import time import magic from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.files import File from django.core.files.storage import Storage from six.moves.urllib import parse as urlparse try: from django.utils.deconstruct import deconstructible except ImportError: def deconstructible(arg): return arg try: import swiftclient from swiftclient.utils import generate_temp_url except ImportError: raise ImproperlyConfigured("Could not load swiftclient library") def setting(name, default=None): return getattr(settings, name, default) def validate_settings(backend): # Check mandatory parameters if not backend.api_auth_url: raise ImproperlyConfigured("The SWIFT_AUTH_URL setting is required") if not backend.api_username: raise ImproperlyConfigured("The SWIFT_USERNAME setting is required") if not backend.api_key: raise ImproperlyConfigured("The SWIFT_KEY or SWIFT_PASSWORD setting is required") if not backend.container_name: raise ImproperlyConfigured("No container name defined. Use SWIFT_CONTAINER_NAME \ or SWIFT_STATIC_CONTAINER_NAME depending on the backend") # Detect auth version if not defined # http://docs.openstack.org/developer/python-swiftclient/cli.html#authentication if not backend.auth_version: if (backend.user_domain_name or backend.user_domain_id) and \ (backend.project_domain_name or backend.project_domain_id): # Set version 3 if domain and project scoping is defined backend.auth_version = '3' else: if backend.tenant_name or backend.tenant_id: # Set version 2 if a tenant is defined backend.auth_version = '2' else: # Set version 1 if no tenant is not defined backend.auth_version = '1' # Enforce auth_version into a string (more future proof) backend.auth_version = str(backend.auth_version) # Validate v2 auth parameters if backend.auth_version == '2': if not (backend.tenant_name or backend.tenant_id): raise ImproperlyConfigured("SWIFT_TENANT_ID or SWIFT_TENANT_NAME must \ be defined when using version 2 auth") # Validate v3 auth parameters if backend.auth_version == '3': if not (backend.user_domain_name or backend.user_domain_id): raise ImproperlyConfigured("SWIFT_USER_DOMAIN_NAME or \ SWIFT_USER_DOMAIN_ID must be defined when using version 3 auth") if not (backend.project_domain_name or backend.project_domain_id): raise ImproperlyConfigured("SWIFT_PROJECT_DOMAIN_NAME or \ SWIFT_PROJECT_DOMAIN_ID must be defined when using version 3 auth") if not (backend.tenant_name or backend.tenant_id): raise ImproperlyConfigured("SWIFT_PROJECT_ID or SWIFT_PROJECT_NAME must \ be defined when using version 3 auth") # Validate temp_url parameters if backend.use_temp_urls: if backend.temp_url_key is None: raise ImproperlyConfigured("SWIFT_TEMP_URL_KEY must be set when \ SWIFT_USE_TEMP_URL is True") # Encode temp_url_key as bytes try: backend.temp_url_key = backend.temp_url_key.encode('ascii') except UnicodeEncodeError: raise ImproperlyConfigured("SWIFT_TEMP_URL_KEY must ascii") # Misc sanity checks if not isinstance(backend.os_extra_options, dict): raise ImproperlyConfigured("SWIFT_EXTRA_OPTIONS must be a dict") def prepend_name_prefix(func): """ Decorator that wraps instance methods to prepend the instance's filename prefix to the beginning of the referenced filename. Must only be used on instance methods where the first parameter after `self` is `name` or a comparable parameter of a different name. """ @wraps(func) def prepend_prefix(self, name, *args, **kwargs): name = self.name_prefix + name return func(self, name, *args, **kwargs) return prepend_prefix @deconstructible class SwiftStorage(Storage): api_auth_url = setting('SWIFT_AUTH_URL') api_username = setting('SWIFT_USERNAME') api_key = setting('SWIFT_KEY') or setting('SWIFT_PASSWORD') auth_version = setting('SWIFT_AUTH_VERSION') tenant_name = setting('SWIFT_TENANT_NAME') or setting('SWIFT_PROJECT_NAME') tenant_id = setting('SWIFT_TENANT_ID') or setting('SWIFT_PROJECT_ID') user_domain_name = setting('SWIFT_USER_DOMAIN_NAME') user_domain_id = setting('SWIFT_USER_DOMAIN_ID') project_domain_name = setting('SWIFT_PROJECT_DOMAIN_NAME') project_domain_id = setting('SWIFT_PROJECT_DOMAIN_ID') region_name = setting('SWIFT_REGION_NAME') container_name = setting('SWIFT_CONTAINER_NAME') auto_create_container = setting('SWIFT_AUTO_CREATE_CONTAINER', False) auto_create_container_public = setting( 'SWIFT_AUTO_CREATE_CONTAINER_PUBLIC', False) auto_create_container_allow_orgin = setting( 'SWIFT_AUTO_CREATE_CONTAINER_ALLOW_ORIGIN') auto_base_url = setting('SWIFT_AUTO_BASE_URL', True) override_base_url = setting('SWIFT_BASE_URL') use_temp_urls = setting('SWIFT_USE_TEMP_URLS', False) temp_url_key = setting('SWIFT_TEMP_URL_KEY') temp_url_duration = setting('SWIFT_TEMP_URL_DURATION', 30 * 60) auth_token_duration = setting('SWIFT_AUTH_TOKEN_DURATION', 60 * 60 * 23) os_extra_options = setting('SWIFT_EXTRA_OPTIONS', {}) auto_overwrite = setting('SWIFT_AUTO_OVERWRITE', False) lazy_connect = setting('SWIFT_LAZY_CONNECT', False) content_type_from_fd = setting('SWIFT_CONTENT_TYPE_FROM_FD', False) content_length_from_fd = setting('SWIFT_CONTENT_LENGTH_FROM_FD', True) gzip_content_types = setting('SWIFT_GZIP_CONTENT_TYPES', []) gzip_unknown_content_type = setting('SWIFT_GZIP_UNKNOWN_CONTENT_TYPE', False) gzip_compression_level = setting('SWIFT_GZIP_COMPRESSION_LEVEL', 4) _token_creation_time = 0 _token = '' _swift_conn = None _base_url = None name_prefix = setting('SWIFT_NAME_PREFIX', '') full_listing = setting('SWIFT_FULL_LISTING', True) max_retries = setting('SWIFT_MAX_RETRIES', 5) cache_headers = setting('SWIFT_CACHE_HEADERS', False) def __init__(self, **settings): # check if some of the settings provided as class attributes # should be overwritten for name, value in settings.items(): if hasattr(self, name): setattr(self, name, value) validate_settings(self) self.last_headers_name = None self.last_headers_value = None self.os_options = { 'tenant_id': self.tenant_id, 'tenant_name': self.tenant_name, 'user_domain_id': self.user_domain_id, 'user_domain_name': self.user_domain_name, 'project_domain_id': self.project_domain_id, 'project_domain_name': self.project_domain_name, 'region_name': self.region_name, } self.os_options.update(self.os_extra_options) if not self.lazy_connect: self.swift_conn @property def swift_conn(self): """Get swift connection wrapper""" if not self._swift_conn: self._swift_conn = swiftclient.Connection( authurl=self.api_auth_url, user=self.api_username, key=self.api_key, retries=self.max_retries, tenant_name=self.tenant_name, os_options=self.os_options, auth_version=self.auth_version) self._check_container() return self._swift_conn def _check_container(self): """ Check that container exists; raises exception if not. """ try: self.swift_conn.head_container(self.container_name) except swiftclient.ClientException: headers = {} if self.auto_create_container: if self.auto_create_container_public: headers['X-Container-Read'] = '.r:*' if self.auto_create_container_allow_orgin: headers['X-Container-Meta-Access-Control-Allow-Origin'] = \ self.auto_create_container_allow_orgin self.swift_conn.put_container(self.container_name, headers=headers) else: raise ImproperlyConfigured( "Container %s does not exist." % self.container_name) @property def base_url(self): if self._base_url is None: if self.auto_base_url: # Derive a base URL based on the authentication information from # the server, optionally overriding the protocol, host/port and # potentially adding a path fragment before the auth information. self._base_url = self.swift_conn.url + '/' if self.override_base_url is not None: # override the protocol and host, append any path fragments split_derived = urlparse.urlsplit(self._base_url) split_override = urlparse.urlsplit(self.override_base_url) split_result = [''] * 5 split_result[0:2] = split_override[0:2] split_result[2] = (split_override[2] + split_derived[2] ).replace('//', '/') self._base_url = urlparse.urlunsplit(split_result) self._base_url = urlparse.urljoin(self._base_url, self.container_name) self._base_url += '/' else: self._base_url = self.override_base_url return self._base_url def _open(self, name, mode='rb'): original_name = name name = self.name_prefix + name headers, content = self.swift_conn.get_object(self.container_name, name) buf = BytesIO(content) buf.name = os.path.basename(original_name) buf.mode = mode return File(buf) def _save(self, name, content, headers=None): original_name = name name = self.name_prefix + name # Django rewinds file position to the beginning before saving, # so should we. # See django.core.files.storage.FileSystemStorage#_save # and django.core.files.base.File#chunks try: content.seek(0) except (AttributeError, UnsupportedOperation): # pragma: no cover pass if self.content_type_from_fd: content_type = magic.from_buffer(content.read(1024), mime=True) # Go back to the beginning of the file content.seek(0) else: content_type = mimetypes.guess_type(name)[0] if self.content_length_from_fd: content_length = content.size else: content_length = None if content_type in self.gzip_content_types or ( content_type is None and self.gzip_unknown_content_type): gz_data = BytesIO() gzf = gzip.GzipFile(filename=name, fileobj=gz_data, mode='wb', compresslevel=self.gzip_compression_level) gzf.write(content.file.read()) gzf.close() content = gz_data.getvalue() content_length = None if not headers: headers = {} headers['Content-Encoding'] = 'gzip' self.swift_conn.put_object(self.container_name, name, content, content_length=content_length, content_type=content_type, headers=headers) return original_name def get_headers(self, name): if self.cache_headers: """ Optimization : only fetch headers once when several calls are made requiring information for the same name. When the caller is collectstatic, this makes a huge difference. According to my test, we get a *2 speed up. Which makes sense : two api calls were made.. """ if name != self.last_headers_name: # miss -> update self.last_headers_value = self.swift_conn.head_object(self.container_name, name) self.last_headers_name = name else: self.last_headers_value = self.swift_conn.head_object(self.container_name, name) self.last_headers_name = name return self.last_headers_value @prepend_name_prefix def exists(self, name): try: self.get_headers(name) except swiftclient.ClientException: return False return True @prepend_name_prefix def delete(self, name): try: self.swift_conn.delete_object(self.container_name, name) except swiftclient.ClientException: pass def get_valid_name(self, name): s = name.strip().replace(' ', '_') return re.sub(r'(?u)[^-_\w./]', '', s) @prepend_name_prefix def get_available_name(self, name, max_length=None): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ if not self.auto_overwrite: if max_length is None: name = super(SwiftStorage, self).get_available_name(name) else: name = super(SwiftStorage, self).get_available_name( name, max_length) if self.name_prefix: # Split out the name prefix so we can just return the bit of # the name that's relevant upstream, since the prefix will # be automatically added on subsequent requests anyway. empty, prefix, final = name.partition(self.name_prefix) return final else: return name @prepend_name_prefix def size(self, name): return int(self.get_headers(name)['content-length']) @prepend_name_prefix def modified_time(self, name): return datetime.fromtimestamp( float(self.get_headers(name)['x-timestamp'])) @prepend_name_prefix def url(self, name): return self._path(name) def _path(self, name): try: name = name.encode('utf-8') except UnicodeDecodeError: pass url = urlparse.urljoin(self.base_url, urlparse.quote(name)) # Are we building a temporary url? if self.use_temp_urls: expires = int(time() + int(self.temp_url_duration)) path = urlparse.unquote(urlparse.urlsplit(url).path) tmp_path = generate_temp_url(path, expires, self.temp_url_key, 'GET', absolute=True) url = urlparse.urljoin(self.base_url, tmp_path) return url def path(self, name): raise NotImplementedError @prepend_name_prefix def isdir(self, name): return '.' not in name @prepend_name_prefix def listdir(self, path): container = self.swift_conn.get_container( self.container_name, prefix=path, full_listing=self.full_listing) files = [] dirs = [] for obj in container[1]: remaining_path = obj['name'][len(path):].split('/') key = remaining_path[0] if remaining_path[0] else remaining_path[1] if not self.isdir(key): files.append(key) elif key not in dirs: dirs.append(key) return dirs, files @prepend_name_prefix def makedirs(self, dirs): self.swift_conn.put_object(self.container_name, '%s/.' % (self.name_prefix + dirs), contents='') @prepend_name_prefix def rmtree(self, abs_path): container = self.swift_conn.get_container(self.container_name) for obj in container[1]: if obj['name'].startswith(abs_path): self.swift_conn.delete_object(self.container_name, obj['name']) class StaticSwiftStorage(SwiftStorage): container_name = setting('SWIFT_STATIC_CONTAINER_NAME', '') name_prefix = setting('SWIFT_STATIC_NAME_PREFIX', '') override_base_url = setting('SWIFT_STATIC_BASE_URL') def get_available_name(self, name, max_length=None): """ When running collectstatic we don't want to return an available name, we want to return the same name because if the file exists we want to overwrite it. """ return name
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $(document).ready(function(){ /*if ($('#noRapport').attr('checked')) { alert("OUIIIIIIIIIII"); $("#description").hide(); $("#fichier").hide(); } else { $("#description").show(); $("#fichier").show(); }*/ $('input:checkbox').change( function(){ if ($(this).is(':checked')) { // $("#description").hide(); // $("#fichier").hide(); $( "#description" ).prop( "disabled", true ); $( "#fichier" ).prop( "disabled", true ); } else { // $("#description").show(); // $("#fichier").show(); $( "#description" ).prop( "disabled", false ); $( "#fichier" ).prop( "disabled", false ); } }); }); function hideComfirmation(id){ $('#'+id).modal('show'); }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """Multi arch dockerized build tool. """ __author__ = 'Marco de Abreu, Kellen Sunderland, Anton Chernov, Pedro Larroy' __version__ = '0.1' import argparse import glob import logging import os import re import shutil import subprocess import sys from copy import deepcopy from itertools import chain from subprocess import call, check_call from typing import * def get_platforms(path: Optional[str]="docker"): """Get a list of architectures given our dockerfiles""" dockerfiles = glob.glob(os.path.join(path, "Dockerfile.build.*")) dockerfiles = list(filter(lambda x: x[-1] != '~', dockerfiles)) files = list(map(lambda x: re.sub(r"Dockerfile.build.(.*)", r"\1", x), dockerfiles)) platforms = list(map(lambda x: os.path.split(x)[1], sorted(files))) return platforms def get_docker_tag(platform: str) -> str: return "mxnet/build.{0}".format(platform) def get_dockerfile(platform: str, path="docker") -> str: return os.path.join(path, "Dockerfile.build.{0}".format(platform)) def get_docker_binary(use_nvidia_docker: bool) -> str: return "nvidia-docker" if use_nvidia_docker else "docker" def build_docker(platform: str, docker_binary: str) -> None: """ Build a container for the given platform :param platform: Platform :param docker_binary: docker binary to use (docker/nvidia-docker) :return: Id of the top level image """ tag = get_docker_tag(platform) logging.info("Building container tagged '%s' with %s", tag, docker_binary) cmd = [docker_binary, "build", "-f", get_dockerfile(platform), "--rm=false", # Keep intermediary layers to prime the build cache "--build-arg", "USER_ID={}".format(os.getuid()), "--cache-from", tag, "-t", tag, "docker"] logging.info("Running command: '%s'", ' '.join(cmd)) check_call(cmd) # Get image id by reading the tag. It's guaranteed (except race condition) that the tag exists. Otherwise, the # check_call would have failed image_id = _get_local_image_id(docker_binary=docker_binary, docker_tag=tag) if not image_id: raise FileNotFoundError('Unable to find docker image id matching with {}'.format(tag)) return image_id def _get_local_image_id(docker_binary, docker_tag): """ Get the image id of the local docker layer with the passed tag :param docker_tag: docker tag :return: Image id as string or None if tag does not exist """ cmd = [docker_binary, "images", "-q", docker_tag] image_id_b = subprocess.check_output(cmd) image_id = image_id_b.decode('utf-8').strip() return image_id def get_mxnet_root() -> str: curpath = os.path.abspath(os.path.dirname(__file__)) def is_mxnet_root(path: str) -> bool: return os.path.exists(os.path.join(path, ".mxnet_root")) while not is_mxnet_root(curpath): parent = os.path.abspath(os.path.join(curpath, os.pardir)) if parent == curpath: raise RuntimeError("Got to the root and couldn't find a parent folder with .mxnet_root") curpath = parent return curpath def buildir() -> str: return os.path.join(get_mxnet_root(), "build") def container_run(platform: str, docker_binary: str, shared_memory_size: str, command: List[str], dry_run: bool = False, into_container: bool = False) -> str: tag = get_docker_tag(platform) mx_root = get_mxnet_root() local_build_folder = buildir() # We need to create it first, otherwise it will be created by the docker daemon with root only permissions os.makedirs(local_build_folder, exist_ok=True) runlist = [docker_binary, 'run', '--rm', '-t', '--shm-size={}'.format(shared_memory_size), '-v', "{}:/work/mxnet".format(mx_root), # mount mxnet root '-v', "{}:/work/build".format(local_build_folder), # mount mxnet/build for storing build artifacts '-u', '{}:{}'.format(os.getuid(), os.getgid()), tag] runlist.extend(command) cmd = ' '.join(runlist) if not dry_run and not into_container: logging.info("Running %s in container %s", command, tag) logging.info("Executing: %s", cmd) ret = call(runlist) into_cmd = deepcopy(runlist) idx = into_cmd.index('-u') + 2 into_cmd[idx:idx] = ['-ti', '--entrypoint', '/bin/bash'] docker_run_cmd = ' '.join(into_cmd) if not dry_run and into_container: check_call(into_cmd) if not dry_run and ret != 0: logging.error("Running of command in container failed (%s): %s", ret, cmd) logging.error("You can try to get into the container by using the following command: %s", docker_run_cmd) raise subprocess.CalledProcessError(ret, cmd) return docker_run_cmd def list_platforms() -> str: print("\nSupported platforms:\n{}".format('\n'.join(get_platforms()))) def main() -> int: # We need to be in the same directory than the script so the commands in the dockerfiles work as # expected. But the script can be invoked from a different path base = os.path.split(os.path.realpath(__file__))[0] os.chdir(base) logging.getLogger().setLevel(logging.INFO) def script_name() -> str: return os.path.split(sys.argv[0])[1] logging.basicConfig(format='{}: %(asctime)-15s %(message)s'.format(script_name())) parser = argparse.ArgumentParser(description="""Utility for building and testing MXNet on docker containers""",epilog="") parser.add_argument("-p", "--platform", help="platform", type=str) parser.add_argument("--build-only", help="Only build the container, don't build the project", action='store_true') parser.add_argument("-a", "--all", help="build for all platforms", action='store_true') parser.add_argument("-n", "--nvidiadocker", help="Use nvidia docker", action='store_true') parser.add_argument("--shm-size", help="Size of the shared memory /dev/shm allocated in the container (e.g '1g')", default='500m', dest="shared_memory_size") parser.add_argument("-l", "--list", help="List platforms", action='store_true') parser.add_argument("--print-docker-run", help="print docker run command for manual inspection", action='store_true') parser.add_argument("-i", "--into-container", help="go in a shell inside the container", action='store_true') parser.add_argument("--download-docker-cache", help="Download the docker cache from our central repository instead of rebuilding locally", action='store_true') parser.add_argument("--docker-cache-bucket", help="S3 docker cache bucket, e.g. mxnet-ci-docker-cache", type=str) parser.add_argument("command", help="command to run in the container", nargs='*', action='append', type=str) args = parser.parse_args() command = list(chain(*args.command)) docker_binary = get_docker_binary(args.nvidiadocker) shared_memory_size = args.shared_memory_size print("into container: {}".format(args.into_container)) if args.list: list_platforms() elif args.platform: platform = args.platform tag = get_docker_tag(platform) if args.download_docker_cache: import docker_cache logging.info('Docker cache download is enabled') docker_cache.load_docker_cache(bucket_name=args.docker_cache_bucket, docker_tag=tag) build_docker(platform, docker_binary) if args.build_only: logging.warning("Container was just built. Exiting due to build-only.") return 0 if command: container_run(platform, docker_binary, shared_memory_size, command) elif args.print_docker_run: print(container_run(platform, docker_binary, shared_memory_size, [], True)) elif args.into_container: container_run(platform, docker_binary, shared_memory_size, [], False, True) else: cmd = ["/work/mxnet/ci/docker/runtime_functions.sh", "build_{}".format(platform)] logging.info("No command specified, trying default build: %s", ' '.join(cmd)) container_run(platform, docker_binary, shared_memory_size, cmd) elif args.all: platforms = get_platforms() logging.info("Building for all architectures: {}".format(platforms)) logging.info("Artifacts will be produced in the build/ directory.") for platform in platforms: if args.download_docker_cache: import docker_cache tag = get_docker_tag(platform) logging.info('Docker cache download is enabled') docker_cache.load_docker_cache(bucket_name=args.docker_cache_bucket, docker_tag=tag) build_docker(platform, docker_binary) if args.build_only: continue build_platform = "build_{}".format(platform) cmd = ["/work/mxnet/ci/docker/runtime_functions.sh", build_platform] shutil.rmtree(buildir(), ignore_errors=True) container_run(platform, docker_binary, shared_memory_size, cmd) plat_buildir = os.path.join(get_mxnet_root(), build_platform) shutil.move(buildir(), plat_buildir) logging.info("Built files left in: %s", plat_buildir) else: parser.print_help() list_platforms() print(""" Examples: ./build.py -p armv7 Will build a docker container with cross compilation tools and build MXNet for armv7 by running: ci/docker/runtime_functions.sh build_armv7 inside the container. ./build.py -p armv7 ls Will execute the given command inside the armv7 container ./build.py -p armv7 --print-docker-run Will print a docker run command to get inside the container in an interactive shell ./build.py -p armv7 --into-container Will execute a shell into the container ./build.py -a Builds for all platforms and leaves artifacts in build_<platform> """) return 0 if __name__ == '__main__': sys.exit(main())
$NetBSD: patch-src_mapi_u__current.c,v 1.3 2019/10/18 09:57:07 nia Exp $ NetBSD only supports zero-initialized initial-exec tls variables in conjuction with dlopen(3) at the moment. --- src/mapi/u_current.c.orig 2019-10-09 16:52:00.000000000 +0000 +++ src/mapi/u_current.c @@ -101,7 +101,11 @@ extern void (*__glapi_noop_table[])(void __thread struct _glapi_table *u_current_table __attribute__((tls_model("initial-exec"))) +#if defined(__NetBSD__) + = NULL; /* non-zero initializers not supported with dlopen */ +#else = (struct _glapi_table *) table_noop_array; +#endif __thread void *u_current_context __attribute__((tls_model("initial-exec"))); @@ -283,7 +287,11 @@ struct _glapi_table * u_current_get_table_internal(void) { #if defined(USE_ELF_TLS) +# if defined(__NetBSD__) + return (likely(u_current_table) ? u_current_table : (struct _glapi_table *) table_noop_array); +# else return u_current_table; +# endif #else if (ThreadSafe) return (struct _glapi_table *) tss_get(u_current_table_tsd);
""" Provenance-related functions. """ from datetime import datetime import os.path from io import StringIO import git import git.exc def get_version(file_path=__file__): """ Get version information about ``file_path`` using the ``git`` package. If ``file_path`` is within the scope of a Git repository then a string including the Git commit hash and date of ``HEAD`` is returned. The message has format ``commit <HASH> date <DATE>``. If ``file_path`` is not within the scope of a Git repository then the string ``unknown`` is returned. :param file_path: File path :type file_path: str or unicode :return: Version information :rtype: str or unicode """ location = os.path.dirname(os.path.abspath(file_path)) try: repository = git.Repo(location, search_parent_directories=True) sha = repository.head.object.hexsha time = repository.head.commit.authored_datetime version = "commit {} date {}".format(sha, str(time)) except git.exc.InvalidGitRepositoryError: # pylint: disable=E1101 version = "unknown" return version def write_provenance(file_handle, file_path, prefix="# ", eol="\n"): """ Write a provenance header to a file including version information about ``file_path`` obtained using the ``git`` package. See also :py:func:`get_version`. The header has form:: <prefix> Created by: RiboViz <prefix> Date: <YYYY>-<MM>-<DD> <HH>:<MM>:<SS>.<SSSSS> <prefix> Command-line tool: <MAIN_MODULE> <prefix> File: <file_path> <prefix> Version: commit <HASH> date <DATE> where ``<MAIN_MODULE>`` is the Python module defined as ``__main__`` (i.e. the identify of the currently running program). :param file_handle: File handle to which content is to be written :type file_handle: _io.TextIOWrapper :param file_path: File path :type file_path: str or unicode :param prefix: Prefix for each line e.g. a comment symbol :type prefix: str or unicode :param eol: End of line character :type eol: str or unicode """ file_handle.write("{}Created by: RiboViz{}".format(prefix, eol)) file_handle.write("{}Date: {}{}".format(prefix, datetime.today(), eol)) import __main__ if hasattr(__main__, "__file__"): file_handle.write("{}Command-line tool: {}{}".format( prefix, __main__.__file__, eol)) file_handle.write("{}File: {}{}".format(prefix, file_path, eol)) file_handle.write("{}Version: {}{}".format( prefix, get_version(file_path), eol)) def write_provenance_header(file_path, provenance_file, prefix="# "): """ Write a provenance header to a file including version information about ``file_path`` obtained using the ``git`` package. See :py:func:`write_provenance`. :param file_path: File path :type file_path: str or unicode :param provenance_file: File to which content is to be written :type provenance: _io.TextIOWrapper :param prefix: Prefix for each line e.g. a comment symbol :type prefix: str or unicode """ with open(provenance_file, 'w') as f: write_provenance(f, file_path, prefix) def write_provenance_to_str(file_path, eol="\n"): """ Write a provenance header to a string including version information about ``file_path`` obtained using the ``git`` package. See :py:func:`write_provenance`. :param file_path: File path :type file_path: str or unicode :param eol: End of line character :type eol: str or unicode :return: Provenance header as a string :rtype: str or unicode """ with StringIO() as s: write_provenance(s, file_path, "", eol) provenance = s.getvalue() return provenance
//constructor function for employee with name, idnum, email class Employee { constructor(name, id, email) { this.name = name; this.id = id; this.email = email; } getName() { return this.name; } getId() { return this.id; } getEmail() { return this.email; } getRole() { return "Employee"; } } //export employee class module.exports = Employee;
define(function(){ var pl = { modal: { cancel: "Anuluj", ok: "OK", }, project: { about: "O IoBlocks", create: "Nowy projekt", name: "Nazwa projektu:", open: "Otwórz projekt", save: "Zapisz projekt", title: "Projekt" }, workspace: { cleanWorkspace: "Usuń bloczki", clearConsole: "Wyczyść konsolę", run: "Uruchom", stop: "Zatrzymaj", toggleCode: "Pokaż/ukryj kod", toggleConsole: "Pokaż/ukryj konsolę" } }; return pl; });
#include "vas_firobject.h" #ifndef rwa_reverb_h #define rwa_reverb_h typedef struct vas_dynconv { #ifdef MAXMSPSDK RWA_FIROBJECT_MAX #endif #ifdef PUREDATA RWA_FIROBJECT_PD #endif } vas_dynconv; #ifdef PUREDATA void vas_dynconv_tilde_setup(void); #endif #endif
import importlib import inspect import os import re import sys import tempfile import threading from io import StringIO from pathlib import Path from unittest import mock from django.core import mail from django.core.files.uploadedfile import SimpleUploadedFile from django.db import DatabaseError, connection from django.http import Http404 from django.shortcuts import render from django.template import TemplateDoesNotExist from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import LoggingCaptureMixin from django.urls import path, reverse from django.urls.converters import IntConverter from django.utils.functional import SimpleLazyObject from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.views.debug import ( CallableSettingWrapper, ExceptionCycleWarning, ExceptionReporter, Path as DebugPath, SafeExceptionReporterFilter, default_urlconf, get_default_exception_reporter_filter, technical_404_response, technical_500_response, ) from django.views.decorators.debug import ( sensitive_post_parameters, sensitive_variables, ) from ..views import ( custom_exception_reporter_filter_view, index_page, multivalue_dict_key_error, non_sensitive_view, paranoid_view, sensitive_args_function_caller, sensitive_kwargs_function_caller, sensitive_method_view, sensitive_view, ) class User: def __str__(self): return 'jacob' class WithoutEmptyPathUrls: urlpatterns = [path('url/', index_page, name='url')] class CallableSettingWrapperTests(SimpleTestCase): """ Unittests for CallableSettingWrapper """ def test_repr(self): class WrappedCallable: def __repr__(self): return "repr from the wrapped callable" def __call__(self): pass actual = repr(CallableSettingWrapper(WrappedCallable())) self.assertEqual(actual, "repr from the wrapped callable") @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') class DebugViewTests(SimpleTestCase): def test_files(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises/') self.assertEqual(response.status_code, 500) data = { 'file_data.txt': SimpleUploadedFile('file_data.txt', b'haha'), } with self.assertLogs('django.request', 'ERROR'): response = self.client.post('/raises/', data) self.assertContains(response, 'file_data.txt', status_code=500) self.assertNotContains(response, 'haha', status_code=500) def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.security', 'WARNING'): response = self.client.get('/raises400/') self.assertContains(response, '<div class="context" id="', status_code=400) # Ensure no 403.html template exists to test the default case. @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', }]) def test_403(self): response = self.client.get('/raises403/') self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) # Set up a test 403.html template. @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '403.html': 'This is a test template for a 403 error ({{ exception }}).', }), ], }, }]) def test_403_template(self): response = self.client.get('/raises403/') self.assertContains(response, 'test template', status_code=403) self.assertContains(response, '(Insufficient Permissions).', status_code=403) def test_404(self): response = self.client.get('/raises404/') self.assertEqual(response.status_code, 404) self.assertContains(response, '<code>not-in-urls</code>, didn’t match', status_code=404) def test_404_not_in_urls(self): response = self.client.get('/not-in-urls') self.assertNotContains(response, "Raised by:", status_code=404) self.assertContains(response, "Django tried these URL patterns", status_code=404) self.assertContains(response, '<code>not-in-urls</code>, didn’t match', status_code=404) # Pattern and view name of a RegexURLPattern appear. self.assertContains(response, r"^regex-post/(?P&lt;pk&gt;[0-9]+)/$", status_code=404) self.assertContains(response, "[name='regex-post']", status_code=404) # Pattern and view name of a RoutePattern appear. self.assertContains(response, r"path-post/&lt;int:pk&gt;/", status_code=404) self.assertContains(response, "[name='path-post']", status_code=404) @override_settings(ROOT_URLCONF=WithoutEmptyPathUrls) def test_404_empty_path_not_in_urls(self): response = self.client.get('/') self.assertContains(response, 'The empty path didn’t match any of these.', status_code=404) def test_technical_404(self): response = self.client.get('/technical404/') self.assertContains(response, "Raised by:", status_code=404) self.assertContains(response, "view_tests.views.technical404", status_code=404) def test_classbased_technical_404(self): response = self.client.get('/classbased404/') self.assertContains(response, "Raised by:", status_code=404) self.assertContains(response, "view_tests.views.Http404View", status_code=404) def test_non_l10ned_numeric_ids(self): """ Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized. """ with self.settings(DEBUG=True, USE_L10N=True): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/') # We look for a HTML fragment of the form # '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"' self.assertContains(response, '<div class="context" id="', status_code=500) match = re.search(b'<div class="context" id="(?P<id>[^"]+)">', response.content) self.assertIsNotNone(match) id_repr = match['id'] self.assertFalse( re.search(b'[^c0-9]', id_repr), "Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % id_repr.decode() ) def test_template_exceptions(self): with self.assertLogs('django.request', 'ERROR'): try: self.client.get(reverse('template_exception')) except Exception: raising_loc = inspect.trace()[-1][-2][0].strip() self.assertNotEqual( raising_loc.find("raise Exception('boom')"), -1, "Failed to find 'raise Exception' in last frame of " "traceback, instead found: %s" % raising_loc ) def test_template_loader_postmortem(self): """Tests for not existing file""" template_name = "notfound.html" with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile: tempdir = os.path.dirname(tmpfile.name) template_path = os.path.join(tempdir, template_name) with override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [tempdir], }]), self.assertLogs('django.request', 'ERROR'): response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name})) self.assertContains(response, "%s (Source does not exist)" % template_path, status_code=500, count=2) # Assert as HTML. self.assertContains( response, '<li><code>django.template.loaders.filesystem.Loader</code>: ' '%s (Source does not exist)</li>' % os.path.join(tempdir, 'notfound.html'), status_code=500, html=True, ) def test_no_template_source_loaders(self): """ Make sure if you don't specify a template, the debug view doesn't blow up. """ with self.assertLogs('django.request', 'ERROR'): with self.assertRaises(TemplateDoesNotExist): self.client.get('/render_no_template/') @override_settings(ROOT_URLCONF='view_tests.default_urls') def test_default_urlconf_template(self): """ Make sure that the default URLconf template is shown shown instead of the technical 404 page, if the user has not altered their URLconf yet. """ response = self.client.get('/') self.assertContains( response, "<h2>The install worked successfully! Congratulations!</h2>" ) @override_settings(ROOT_URLCONF='view_tests.regression_21530_urls') def test_regression_21530(self): """ Regression test for bug #21530. If the admin app include is replaced with exactly one url pattern, then the technical 404 template should be displayed. The bug here was that an AttributeError caused a 500 response. """ response = self.client.get('/') self.assertContains( response, "Page not found <span>(404)</span>", status_code=404 ) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ with mock.patch.object(DebugPath, 'open') as m: default_urlconf(None) m.assert_called_once_with(encoding='utf-8') m.reset_mock() technical_404_response(mock.MagicMock(), mock.Mock()) m.assert_called_once_with(encoding='utf-8') def test_technical_404_converter_raise_404(self): with mock.patch.object(IntConverter, 'to_python', side_effect=Http404): response = self.client.get('/path-post/1/') self.assertContains(response, 'Page not found', status_code=404) def test_exception_reporter_from_request(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/custom_reporter_class_view/') self.assertContains(response, 'custom traceback text', status_code=500) @override_settings(DEFAULT_EXCEPTION_REPORTER='view_tests.views.CustomExceptionReporter') def test_exception_reporter_from_settings(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/') self.assertContains(response, 'custom traceback text', status_code=500) class DebugViewQueriesAllowedTests(SimpleTestCase): # May need a query to initialize MySQL connection databases = {'default'} def test_handle_db_exception(self): """ Ensure the debug view works when a database exception is raised by performing an invalid query and passing the exception to the debug view. """ with connection.cursor() as cursor: try: cursor.execute('INVALID SQL') except DatabaseError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get('/'), *exc_info) self.assertContains(response, 'OperationalError at /', status_code=500) @override_settings( DEBUG=True, ROOT_URLCONF='view_tests.urls', # No template directories are configured, so no templates will be found. TEMPLATES=[{ 'BACKEND': 'django.template.backends.dummy.TemplateStrings', }], ) class NonDjangoTemplatesDebugViewTests(SimpleTestCase): def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.security', 'WARNING'): response = self.client.get('/raises400/') self.assertContains(response, '<div class="context" id="', status_code=400) def test_403(self): response = self.client.get('/raises403/') self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) def test_404(self): response = self.client.get('/raises404/') self.assertEqual(response.status_code, 404) def test_template_not_found_error(self): # Raises a TemplateDoesNotExist exception and shows the debug view. url = reverse('raises_template_does_not_exist', kwargs={"path": "notfound.html"}) with self.assertLogs('django.request', 'ERROR'): response = self.client.get(url) self.assertContains(response, '<div class="context" id="', status_code=500) class ExceptionReporterTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get('/test_view/') request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<p>jacob</p>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) self.assertIn('<p>No POST data</p>', html) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError</h1>', html) self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html) self.assertNotIn('<th>Request Method:</th>', html) self.assertNotIn('<th>Request URL:</th>', html) self.assertNotIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) def test_eol_support(self): """The ExceptionReporter supports Unix, Windows and Macintosh EOL markers""" LINES = ['print %d' % i for i in range(1, 6)] reporter = ExceptionReporter(None, None, None, None) for newline in ['\n', '\r\n', '\r']: fd, filename = tempfile.mkstemp(text=False) os.write(fd, (newline.join(LINES) + newline).encode()) os.close(fd) try: self.assertEqual( reporter._get_lines_from_file(filename, 3, 2), (1, LINES[1:3], LINES[3], LINES[4:]) ) finally: os.unlink(filename) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">No exception message supplied</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertNotIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) def test_suppressed_context(self): try: try: raise RuntimeError("Can't find my keys") except RuntimeError: raise ValueError("Can't find my keys") from None except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError</h1>', html) self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) self.assertNotIn('During handling of the above exception', html) def test_reporting_of_nested_exceptions(self): request = self.rf.get('/test_view/') try: try: raise AttributeError(mark_safe('<p>Top level</p>')) except AttributeError as explicit: try: raise ValueError(mark_safe('<p>Second exception</p>')) from explicit except ValueError: raise IndexError(mark_safe('<p>Final exception</p>')) except Exception: # Custom exception handler, just pass it into ExceptionReporter exc_type, exc_value, tb = sys.exc_info() explicit_exc = 'The above exception ({0}) was the direct cause of the following exception:' implicit_exc = 'During handling of the above exception ({0}), another exception occurred:' reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;'))) self.assertEqual(2, html.count(implicit_exc.format('&lt;p&gt;Second exception&lt;/p&gt;'))) self.assertEqual(10, html.count('&lt;p&gt;Final exception&lt;/p&gt;')) text = reporter.get_traceback_text() self.assertIn(explicit_exc.format('<p>Top level</p>'), text) self.assertIn(implicit_exc.format('<p>Second exception</p>'), text) self.assertEqual(3, text.count('<p>Final exception</p>')) def test_reporting_frames_without_source(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, 'generated', 'exec') exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame['context_line'], '<source code not available>') self.assertEqual(last_frame['filename'], 'generated') self.assertEqual(last_frame['function'], 'funcName') self.assertEqual(last_frame['lineno'], 2) html = reporter.get_traceback_html() self.assertIn( '<span class="fname">generated</span>, line 2, in funcName', html, ) self.assertIn( '<code class="fname">generated</code>, line 2, in funcName', html, ) self.assertIn( '"generated", line 2, in funcName\n' ' &lt;source code not available&gt;', html, ) text = reporter.get_traceback_text() self.assertIn( '"generated", line 2, in funcName\n' ' <source code not available>', text, ) def test_reporting_frames_source_not_match(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, 'generated', 'exec') exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() with mock.patch( 'django.views.debug.ExceptionReporter._get_source', return_value=['wrong source'], ): request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame['context_line'], '<source code not available>') self.assertEqual(last_frame['filename'], 'generated') self.assertEqual(last_frame['function'], 'funcName') self.assertEqual(last_frame['lineno'], 2) html = reporter.get_traceback_html() self.assertIn( '<span class="fname">generated</span>, line 2, in funcName', html, ) self.assertIn( '<code class="fname">generated</code>, line 2, in funcName', html, ) self.assertIn( '"generated", line 2, in funcName\n' ' &lt;source code not available&gt;', html, ) text = reporter.get_traceback_text() self.assertIn( '"generated", line 2, in funcName\n' ' <source code not available>', text, ) def test_reporting_frames_for_cyclic_reference(self): try: def test_func(): try: raise RuntimeError('outer') from RuntimeError('inner') except RuntimeError as exc: raise exc.__cause__ test_func() except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) def generate_traceback_frames(*args, **kwargs): nonlocal tb_frames tb_frames = reporter.get_traceback_frames() tb_frames = None tb_generator = threading.Thread(target=generate_traceback_frames, daemon=True) msg = ( "Cycle in the exception chain detected: exception 'inner' " "encountered again." ) with self.assertWarnsMessage(ExceptionCycleWarning, msg): tb_generator.start() tb_generator.join(timeout=5) if tb_generator.is_alive(): # tb_generator is a daemon that runs until the main thread/process # exits. This is resource heavy when running the full test suite. # Setting the following values to None makes # reporter.get_traceback_frames() exit early. exc_value.__traceback__ = exc_value.__context__ = exc_value.__cause__ = None tb_generator.join() self.fail('Cyclic reference in Exception Reporter.get_traceback_frames()') if tb_frames is None: # can happen if the thread generating traceback got killed # or exception while generating the traceback self.fail('Traceback generation failed') last_frame = tb_frames[-1] self.assertIn('raise exc.__cause__', last_frame['context_line']) self.assertEqual(last_frame['filename'], __file__) self.assertEqual(last_frame['function'], 'test_func') def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">I&#x27;m a little teapot</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertNotIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report</h1>', html) self.assertIn('<pre class="exception_value">I&#x27;m a little teapot</pre>', html) self.assertNotIn('<th>Request Method:</th>', html) self.assertNotIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertNotIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) def test_non_utf8_values_handling(self): "Non-UTF-8 exceptions/values should not make the output generation choke." try: class NonUtf8Output(Exception): def __repr__(self): return b'EXC\xe9EXC' somevar = b'VAL\xe9VAL' # NOQA raise NonUtf8Output() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('VAL\\xe9VAL', html) self.assertIn('EXC\\xe9EXC', html) def test_local_variable_escaping(self): """Safe strings in local variables are escaped.""" try: local = mark_safe('<p>Local variable</p>') raise ValueError(local) except Exception: exc_type, exc_value, tb = sys.exc_info() html = ExceptionReporter(None, exc_type, exc_value, tb).get_traceback_html() self.assertIn('<td class="code"><pre>&#x27;&lt;p&gt;Local variable&lt;/p&gt;&#x27;</pre></td>', html) def test_unprintable_values_handling(self): "Unprintable values should not make the output generation choke." try: class OomOutput: def __repr__(self): raise MemoryError('OOM') oomvalue = OomOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<td class="code"><pre>Error in formatting', html) def test_too_large_values_handling(self): "Large values should not create a large HTML." large = 256 * 1024 repr_of_str_adds = len(repr('')) try: class LargeOutput: def __repr__(self): return repr('A' * large) largevalue = LargeOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertEqual(len(html) // 1024 // 128, 0) # still fit in 128Kb self.assertIn('&lt;trimmed %d bytes string&gt;' % (large + repr_of_str_adds,), html) def test_encoding_error(self): """ A UnicodeError displays a portion of the problematic string. HTML in safe strings is escaped. """ try: mark_safe('abcdefghijkl<p>mnὀp</p>qrstuwxyz').encode('ascii') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<h2>Unicode error hint</h2>', html) self.assertIn('The string that could not be encoded/decoded was: ', html) self.assertIn('<strong>&lt;p&gt;mnὀp&lt;/p&gt;</strong>', html) def test_unfrozen_importlib(self): """ importlib is not a frozen app, but its loader thinks it's frozen which results in an ImportError. Refs #21443. """ try: request = self.rf.get('/test_view/') importlib.import_module('abc.def.invalid.name') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ModuleNotFoundError at /test_view/</h1>', html) def test_ignore_traceback_evaluation_exceptions(self): """ Don't trip over exceptions generated by crafted objects when evaluating them while cleansing (#24455). """ class BrokenEvaluation(Exception): pass def broken_setup(): raise BrokenEvaluation request = self.rf.get('/test_view/') broken_lazy = SimpleLazyObject(broken_setup) try: bool(broken_lazy) except BrokenEvaluation: exc_type, exc_value, tb = sys.exc_info() self.assertIn( "BrokenEvaluation", ExceptionReporter(request, exc_type, exc_value, tb).get_traceback_html(), "Evaluation exception reason not mentioned in traceback" ) @override_settings(ALLOWED_HOSTS='example.com') def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get('/', HTTP_HOST='evil.com') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertIn("http://evil.com/", html) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ value = '<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>' # GET request = self.rf.get('/test_view/?items=Oops') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # POST request = self.rf.post('/test_view/', data={'items': 'Oops'}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # FILES fp = StringIO('filecontent') request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML( '<td>items</td><td class="code"><pre>&lt;InMemoryUploadedFile: ' 'items (application/octet-stream)&gt;</pre></td>', html ) # COOKIES rf = RequestFactory() rf.cookies['items'] = 'Oops' request = rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML('<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>', html) def test_exception_fetching_user(self): """ The error page can be rendered if the current user can't be retrieved (such as when the database is unavailable). """ class ExceptionUser: def __str__(self): raise Exception() request = self.rf.get('/test_view/') request.user = ExceptionUser() try: raise ValueError('Oops') except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<p>[unable to retrieve the current user]</p>', html) text = reporter.get_traceback_text() self.assertIn('USER: [unable to retrieve the current user]', text) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ reporter = ExceptionReporter(None, None, None, None) with mock.patch.object(DebugPath, 'open') as m: reporter.get_traceback_html() m.assert_called_once_with(encoding='utf-8') m.reset_mock() reporter.get_traceback_text() m.assert_called_once_with(encoding='utf-8') class PlainTextReportTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get('/test_view/') request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn('ValueError at /test_view/', text) self.assertIn("Can't find my keys", text) self.assertIn('Request Method:', text) self.assertIn('Request URL:', text) self.assertIn('USER: jacob', text) self.assertIn('Exception Type:', text) self.assertIn('Exception Value:', text) self.assertIn('Traceback (most recent call last):', text) self.assertIn('Request information:', text) self.assertNotIn('Request data not supplied', text) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn('ValueError', text) self.assertIn("Can't find my keys", text) self.assertNotIn('Request Method:', text) self.assertNotIn('Request URL:', text) self.assertNotIn('USER:', text) self.assertIn('Exception Type:', text) self.assertIn('Exception Value:', text) self.assertIn('Traceback (most recent call last):', text) self.assertIn('Request data not supplied', text) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) reporter.get_traceback_text() def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(DEBUG=True) def test_template_exception(self): request = self.rf.get('/test_view/') try: render(request, 'debug/template_error.html') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() templ_path = Path(Path(__file__).parents[1], 'templates', 'debug', 'template_error.html') self.assertIn( 'Template error:\n' 'In template %(path)s, error at line 2\n' ' \'cycle\' tag requires at least two arguments\n' ' 1 : Template with error:\n' ' 2 : {%% cycle %%} \n' ' 3 : ' % {'path': templ_path}, text ) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ # GET request = self.rf.get('/test_view/?items=Oops') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # POST request = self.rf.post('/test_view/', data={'items': 'Oops'}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # FILES fp = StringIO('filecontent') request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn('items = <InMemoryUploadedFile:', text) # COOKIES rf = RequestFactory() rf.cookies['items'] = 'Oops' request = rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(ALLOWED_HOSTS='example.com') def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get('/', HTTP_HOST='evil.com') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("http://evil.com/", text) class ExceptionReportTestMixin: # Mixin used in the ExceptionReporterFilterTests and # AjaxResponseExceptionReporterFilter tests below breakfast_data = { 'sausage-key': 'sausage-value', 'baked-beans-key': 'baked-beans-value', 'hash-brown-key': 'hash-brown-value', 'bacon-key': 'bacon-value', } def verify_unsafe_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # All variables are shown. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertContains(response, 'scrambled', status_code=500) self.assertContains(response, 'sauce', status_code=500) self.assertContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertContains(response, k, status_code=500) self.assertContains(response, v, status_code=500) def verify_safe_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # Non-sensitive variable's name and value are shown. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertContains(response, 'scrambled', status_code=500) # Sensitive variable's name is shown but not its value. self.assertContains(response, 'sauce', status_code=500) self.assertNotContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # Non-sensitive POST parameters' values are shown. self.assertContains(response, 'baked-beans-value', status_code=500) self.assertContains(response, 'hash-brown-value', status_code=500) # Sensitive POST parameters' values are not shown. self.assertNotContains(response, 'sausage-value', status_code=500) self.assertNotContains(response, 'bacon-value', status_code=500) def verify_paranoid_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that no variables or POST parameters are displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # Show variable names but not their values. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertNotContains(response, 'scrambled', status_code=500) self.assertContains(response, 'sauce', status_code=500) self.assertNotContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # No POST parameters' values are shown. self.assertNotContains(response, v, status_code=500) def verify_unsafe_email(self, view, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the email report. """ with self.settings(ADMINS=[('Admin', 'admin@fattie-breakie.com')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn('cooked_eggs', body_plain) self.assertNotIn('scrambled', body_plain) self.assertNotIn('sauce', body_plain) self.assertNotIn('worcestershire', body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn('cooked_eggs', body_html) self.assertIn('scrambled', body_html) self.assertIn('sauce', body_html) self.assertIn('worcestershire', body_html) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertIn(k, body_plain) self.assertIn(v, body_plain) self.assertIn(k, body_html) self.assertIn(v, body_html) def verify_safe_email(self, view, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the email report. """ with self.settings(ADMINS=[('Admin', 'admin@fattie-breakie.com')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn('cooked_eggs', body_plain) self.assertNotIn('scrambled', body_plain) self.assertNotIn('sauce', body_plain) self.assertNotIn('worcestershire', body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn('cooked_eggs', body_html) self.assertIn('scrambled', body_html) self.assertIn('sauce', body_html) self.assertNotIn('worcestershire', body_html) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertIn(k, body_plain) # Non-sensitive POST parameters' values are shown. self.assertIn('baked-beans-value', body_plain) self.assertIn('hash-brown-value', body_plain) self.assertIn('baked-beans-value', body_html) self.assertIn('hash-brown-value', body_html) # Sensitive POST parameters' values are not shown. self.assertNotIn('sausage-value', body_plain) self.assertNotIn('bacon-value', body_plain) self.assertNotIn('sausage-value', body_html) self.assertNotIn('bacon-value', body_html) def verify_paranoid_email(self, view): """ Asserts that no variables or POST parameters are displayed in the email report. """ with self.settings(ADMINS=[('Admin', 'admin@fattie-breakie.com')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body = str(email.body) self.assertNotIn('cooked_eggs', body) self.assertNotIn('scrambled', body) self.assertNotIn('sauce', body) self.assertNotIn('worcestershire', body) for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertIn(k, body) # No POST parameters' values are shown. self.assertNotIn(v, body) @override_settings(ROOT_URLCONF='view_tests.urls') class ExceptionReporterFilterTests(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase): """ Sensitive information can be filtered out of error reports (#14614). """ rf = RequestFactory() def test_non_sensitive_request(self): """ Everything (request info and frame variables) can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) def test_sensitive_request(self): """ Sensitive POST parameters and frame variables cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view) self.verify_unsafe_email(sensitive_view) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view) self.verify_safe_email(sensitive_view) def test_paranoid_request(self): """ No POST parameters and frame variables can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view) self.verify_unsafe_email(paranoid_view) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view) self.verify_paranoid_email(paranoid_view) def test_multivalue_dict_key_error(self): """ #21098 -- Sensitive POST parameters cannot be seen in the error reports for if request.POST['nonexistent_key'] throws an error. """ with self.settings(DEBUG=True): self.verify_unsafe_response(multivalue_dict_key_error) self.verify_unsafe_email(multivalue_dict_key_error) with self.settings(DEBUG=False): self.verify_safe_response(multivalue_dict_key_error) self.verify_safe_email(multivalue_dict_key_error) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) def test_sensitive_method(self): """ The sensitive_variables decorator works with object methods. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_method_view, check_for_POST_params=False) self.verify_unsafe_email(sensitive_method_view, check_for_POST_params=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_method_view, check_for_POST_params=False) self.verify_safe_email(sensitive_method_view, check_for_POST_params=False) def test_sensitive_function_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_args_function_caller) self.verify_unsafe_email(sensitive_args_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_args_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_args_function_caller, check_for_POST_params=False) def test_sensitive_function_keyword_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as keyword arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_kwargs_function_caller) self.verify_unsafe_email(sensitive_kwargs_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_kwargs_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_kwargs_function_caller, check_for_POST_params=False) def test_callable_settings(self): """ Callable settings should not be evaluated in the debug page (#21345). """ def callable_setting(): return "This should not be displayed" with self.settings(DEBUG=True, FOOBAR=callable_setting): response = self.client.get('/raises500/') self.assertNotContains(response, "This should not be displayed", status_code=500) def test_callable_settings_forbidding_to_set_attributes(self): """ Callable settings which forbid to set attributes should not break the debug page (#23070). """ class CallableSettingWithSlots: __slots__ = [] def __call__(self): return "This should not be displayed" with self.settings(DEBUG=True, WITH_SLOTS=CallableSettingWithSlots()): response = self.client.get('/raises500/') self.assertNotContains(response, "This should not be displayed", status_code=500) def test_dict_setting_with_non_str_key(self): """ A dict setting containing a non-string key should not break the debug page (#12744). """ with self.settings(DEBUG=True, FOOBAR={42: None}): response = self.client.get('/raises500/') self.assertContains(response, 'FOOBAR', status_code=500) def test_sensitive_settings(self): """ The debug page should not show some sensitive settings (password, secret key, ...). """ sensitive_settings = [ 'SECRET_KEY', 'PASSWORD', 'API_KEY', 'AUTH_TOKEN', ] for setting in sensitive_settings: with self.settings(DEBUG=True, **{setting: "should not be displayed"}): response = self.client.get('/raises500/') self.assertNotContains(response, 'should not be displayed', status_code=500) def test_settings_with_sensitive_keys(self): """ The debug page should filter out some sensitive information found in dict settings. """ sensitive_settings = [ 'SECRET_KEY', 'PASSWORD', 'API_KEY', 'AUTH_TOKEN', ] for setting in sensitive_settings: FOOBAR = { setting: "should not be displayed", 'recursive': {setting: "should not be displayed"}, } with self.settings(DEBUG=True, FOOBAR=FOOBAR): response = self.client.get('/raises500/') self.assertNotContains(response, 'should not be displayed', status_code=500) def test_cleanse_setting_basic(self): reporter_filter = SafeExceptionReporterFilter() self.assertEqual(reporter_filter.cleanse_setting('TEST', 'TEST'), 'TEST') self.assertEqual( reporter_filter.cleanse_setting('PASSWORD', 'super_secret'), reporter_filter.cleansed_substitute, ) def test_cleanse_setting_ignore_case(self): reporter_filter = SafeExceptionReporterFilter() self.assertEqual( reporter_filter.cleanse_setting('password', 'super_secret'), reporter_filter.cleansed_substitute, ) def test_cleanse_setting_recurses_in_dictionary(self): reporter_filter = SafeExceptionReporterFilter() initial = {'login': 'cooper', 'password': 'secret'} self.assertEqual( reporter_filter.cleanse_setting('SETTING_NAME', initial), {'login': 'cooper', 'password': reporter_filter.cleansed_substitute}, ) def test_cleanse_setting_recurses_in_list_tuples(self): reporter_filter = SafeExceptionReporterFilter() initial = [ { 'login': 'cooper', 'password': 'secret', 'apps': ( {'name': 'app1', 'api_key': 'a06b-c462cffae87a'}, {'name': 'app2', 'api_key': 'a9f4-f152e97ad808'}, ), 'tokens': ['98b37c57-ec62-4e39', '8690ef7d-8004-4916'], }, {'SECRET_KEY': 'c4d77c62-6196-4f17-a06b-c462cffae87a'}, ] cleansed = [ { 'login': 'cooper', 'password': reporter_filter.cleansed_substitute, 'apps': ( {'name': 'app1', 'api_key': reporter_filter.cleansed_substitute}, {'name': 'app2', 'api_key': reporter_filter.cleansed_substitute}, ), 'tokens': reporter_filter.cleansed_substitute, }, {'SECRET_KEY': reporter_filter.cleansed_substitute}, ] self.assertEqual( reporter_filter.cleanse_setting('SETTING_NAME', initial), cleansed, ) self.assertEqual( reporter_filter.cleanse_setting('SETTING_NAME', tuple(initial)), tuple(cleansed), ) def test_request_meta_filtering(self): request = self.rf.get('/', HTTP_SECRET_HEADER='super_secret') reporter_filter = SafeExceptionReporterFilter() self.assertEqual( reporter_filter.get_safe_request_meta(request)['HTTP_SECRET_HEADER'], reporter_filter.cleansed_substitute, ) def test_exception_report_uses_meta_filtering(self): response = self.client.get('/raises500/', HTTP_SECRET_HEADER='super_secret') self.assertNotIn(b'super_secret', response.content) response = self.client.get( '/raises500/', HTTP_SECRET_HEADER='super_secret', HTTP_ACCEPT='application/json', ) self.assertNotIn(b'super_secret', response.content) class CustomExceptionReporterFilter(SafeExceptionReporterFilter): cleansed_substitute = 'XXXXXXXXXXXXXXXXXXXX' hidden_settings = _lazy_re_compile('API|TOKEN|KEY|SECRET|PASS|SIGNATURE|DATABASE_URL', flags=re.I) @override_settings( ROOT_URLCONF='view_tests.urls', DEFAULT_EXCEPTION_REPORTER_FILTER='%s.CustomExceptionReporterFilter' % __name__, ) class CustomExceptionReporterFilterTests(SimpleTestCase): def setUp(self): get_default_exception_reporter_filter.cache_clear() def tearDown(self): get_default_exception_reporter_filter.cache_clear() def test_setting_allows_custom_subclass(self): self.assertIsInstance( get_default_exception_reporter_filter(), CustomExceptionReporterFilter, ) def test_cleansed_substitute_override(self): reporter_filter = get_default_exception_reporter_filter() self.assertEqual( reporter_filter.cleanse_setting('password', 'super_secret'), reporter_filter.cleansed_substitute, ) def test_hidden_settings_override(self): reporter_filter = get_default_exception_reporter_filter() self.assertEqual( reporter_filter.cleanse_setting('database_url', 'super_secret'), reporter_filter.cleansed_substitute, ) class NonHTMLResponseExceptionReporterFilter(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase): """ Sensitive information can be filtered out of error reports. The plain text 500 debug-only error page is served when it has been detected the request doesn't accept HTML content. Don't check for (non)existence of frames vars in the traceback information section of the response content because they're not included in these error pages. Refs #14614. """ rf = RequestFactory(HTTP_ACCEPT='application/json') def test_non_sensitive_request(self): """ Request info can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) def test_sensitive_request(self): """ Sensitive POST parameters cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view, check_for_vars=False) def test_paranoid_request(self): """ No POST parameters can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view, check_for_vars=False) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') def test_non_html_response_encoding(self): response = self.client.get('/raises500/', HTTP_ACCEPT='application/json') self.assertEqual(response['Content-Type'], 'text/plain; charset=utf-8') class DecoratorsTests(SimpleTestCase): def test_sensitive_variables_not_called(self): msg = ( 'sensitive_variables() must be called to use it as a decorator, ' 'e.g., use @sensitive_variables(), not @sensitive_variables.' ) with self.assertRaisesMessage(TypeError, msg): @sensitive_variables def test_func(password): pass def test_sensitive_post_parameters_not_called(self): msg = ( 'sensitive_post_parameters() must be called to use it as a ' 'decorator, e.g., use @sensitive_post_parameters(), not ' '@sensitive_post_parameters.' ) with self.assertRaisesMessage(TypeError, msg): @sensitive_post_parameters def test_func(request): return index_page(request)
import arc @arc.command() def main(vals: set): print("Unique values:") print("\n".join(vals)) main()
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: # create a cache numbers = {} # loop through list of nums # mapping nums to their indices for i, num in enumerate(nums): # if target - num is already cached, return it if target - num in numbers: return [numbers[target - num], i] # Otherwise, it's not cached yet so store it numbers[num] = i # If the loop runs and there is no sum, return empty brackets return []
class EntityAlreadyExist(Exception): pass class EntityNotFound(Exception): pass
from ..remote import RemoteModel from infoblox_netmri.utils.utils import check_api_availability class HubLocatorNetworkExplorerInventorySummaryGridRemote(RemoteModel): """ | ``id:`` none | ``attribute type:`` string | ``DeviceID:`` none | ``attribute type:`` string | ``InterfaceID:`` none | ``attribute type:`` string | ``DeviceIPDotted:`` none | ``attribute type:`` string | ``DeviceIPNumeric:`` none | ``attribute type:`` string | ``DeviceName:`` none | ``attribute type:`` string | ``DeviceType:`` none | ``attribute type:`` string | ``ifIndex:`` none | ``attribute type:`` string | ``ifName:`` none | ``attribute type:`` string | ``ifSpeed:`` none | ``attribute type:`` string | ``ifState:`` none | ``attribute type:`` string | ``ifLastChange:`` none | ``attribute type:`` string | ``ifPortControlInd:`` none | ``attribute type:`` string | ``NeighborCnt:`` none | ``attribute type:`` string | ``DeviceAssurance:`` none | ``attribute type:`` string """ properties = ("id", "DeviceID", "InterfaceID", "DeviceIPDotted", "DeviceIPNumeric", "DeviceName", "DeviceType", "ifIndex", "ifName", "ifSpeed", "ifState", "ifLastChange", "ifPortControlInd", "NeighborCnt", "DeviceAssurance", )
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.d (the "License"); # you may not use this file except in compliance with the License. # """Userbot help command""" from userbot import CMD_HELP from userbot.events import register @register(outgoing=True, pattern=r"^\.help(?: |$)(.*)") async def help(event): """For .help command""" args = event.pattern_match.group(1).lower() if args: if args in CMD_HELP: await event.edit(str(CMD_HELP[args])) else: await event.edit("Please specify a valid module name.") else: string = "Specify which module do you want help for !!\n**Usage:** `.help` <module name>\n\n" for i in sorted(CMD_HELP): string += "`" + str(i) + "`" string += "\t\t\t||\t\t\t " await event.edit(string)
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- import datetime import sphinx_rtd_theme # 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. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- # 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 = u'1.0' # The full version, including alpha/beta/rc tags. release = u'1.0' project = 'GLPI JSON Protocol' thisyear = datetime.datetime.now().year copyright = u'2016-%s, GLPI Project, Teclib\'' % thisyear author = u'GLPI Project, Teclib\'' # -- General configuration --------------------------------------------------- # 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_rtd_theme', 'sphinx-prompt', 'sphinx_substitution_extensions', 'sphinx.ext.todo', 'sphinx.ext.ifconfig', ] todo_include_todos = True # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # -- 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 = "sphinx_rtd_theme" html_logo = 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 true, links to the reST sources are added to the pages. # # html_show_sourcelink = True html_show_sourcelink = False html_theme_options = { #'style_nav_header_background': 'white', 'logo_only': False, # Toc options 'collapse_navigation': True, 'sticky_navigation': True, 'navigation_depth': 3, 'includehidden': True, 'titles_only': False, # Misc options 'prev_next_buttons_location': 'both', } html_favicon = '_static/images/favicon.ico' # Disable smartquotes smartquotes = False
""" Define extension dtypes. """ from __future__ import annotations import re from typing import ( TYPE_CHECKING, Any, Dict, List, MutableMapping, Optional, Tuple, Type, Union, cast, ) import numpy as np import pytz from pandas._libs.interval import Interval from pandas._libs.tslibs import ( BaseOffset, NaT, Period, Timestamp, dtypes, timezones, to_offset, tz_compare, ) from pandas._typing import Dtype, DtypeObj, NpDtype, Ordered from pandas.core.dtypes.base import ExtensionDtype, register_extension_dtype from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCIndex from pandas.core.dtypes.inference import is_bool, is_list_like if TYPE_CHECKING: import pyarrow from pandas import Categorical from pandas.core.arrays import ( DatetimeArray, IntervalArray, PandasArray, PeriodArray, ) str_type = str class PandasExtensionDtype(ExtensionDtype): """ A np.dtype duck-typed class, suitable for holding a custom dtype. THIS IS NOT A REAL NUMPY DTYPE """ type: Any kind: Any # The Any type annotations above are here only because mypy seems to have a # problem dealing with multiple inheritance from PandasExtensionDtype # and ExtensionDtype's @properties in the subclasses below. The kind and # type variables in those subclasses are explicitly typed below. subdtype = None str: str_type num = 100 shape: Tuple[int, ...] = () itemsize = 8 base = None isbuiltin = 0 isnative = 0 _cache: Dict[str_type, PandasExtensionDtype] = {} def __str__(self) -> str_type: """ Return a string representation for a particular Object """ return self.name def __repr__(self) -> str_type: """ Return a string representation for a particular object. """ return str(self) def __hash__(self) -> int: raise NotImplementedError("sub-classes should implement an __hash__ method") def __getstate__(self) -> Dict[str_type, Any]: # pickle support; we don't want to pickle the cache return {k: getattr(self, k, None) for k in self._metadata} @classmethod def reset_cache(cls) -> None: """ clear the cache """ cls._cache = {} class CategoricalDtypeType(type): """ the type of CategoricalDtype, this metaclass determines subclass ability """ pass @register_extension_dtype class CategoricalDtype(PandasExtensionDtype, ExtensionDtype): """ Type for categorical data with the categories and orderedness. Parameters ---------- categories : sequence, optional Must be unique, and must not contain any nulls. The categories are stored in an Index, and if an index is provided the dtype of that index will be used. ordered : bool or None, default False Whether or not this categorical is treated as a ordered categorical. None can be used to maintain the ordered value of existing categoricals when used in operations that combine categoricals, e.g. astype, and will resolve to False if there is no existing ordered to maintain. Attributes ---------- categories ordered Methods ------- None See Also -------- Categorical : Represent a categorical variable in classic R / S-plus fashion. Notes ----- This class is useful for specifying the type of a ``Categorical`` independent of the values. See :ref:`categorical.categoricaldtype` for more. Examples -------- >>> t = pd.CategoricalDtype(categories=['b', 'a'], ordered=True) >>> pd.Series(['a', 'b', 'a', 'c'], dtype=t) 0 a 1 b 2 a 3 NaN dtype: category Categories (2, object): ['b' < 'a'] An empty CategoricalDtype with a specific dtype can be created by providing an empty index. As follows, >>> pd.CategoricalDtype(pd.DatetimeIndex([])).categories.dtype dtype('<M8[ns]') """ # TODO: Document public vs. private API name = "category" type: Type[CategoricalDtypeType] = CategoricalDtypeType kind: str_type = "O" str = "|O08" base = np.dtype("O") _metadata = ("categories", "ordered") _cache: Dict[str_type, PandasExtensionDtype] = {} def __init__(self, categories=None, ordered: Ordered = False): self._finalize(categories, ordered, fastpath=False) @classmethod def _from_fastpath( cls, categories=None, ordered: Optional[bool] = None ) -> CategoricalDtype: self = cls.__new__(cls) self._finalize(categories, ordered, fastpath=True) return self @classmethod def _from_categorical_dtype( cls, dtype: CategoricalDtype, categories=None, ordered: Ordered = None ) -> CategoricalDtype: if categories is ordered is None: return dtype if categories is None: categories = dtype.categories if ordered is None: ordered = dtype.ordered return cls(categories, ordered) @classmethod def _from_values_or_dtype( cls, values=None, categories=None, ordered: Optional[bool] = None, dtype: Optional[Dtype] = None, ) -> CategoricalDtype: """ Construct dtype from the input parameters used in :class:`Categorical`. This constructor method specifically does not do the factorization step, if that is needed to find the categories. This constructor may therefore return ``CategoricalDtype(categories=None, ordered=None)``, which may not be useful. Additional steps may therefore have to be taken to create the final dtype. The return dtype is specified from the inputs in this prioritized order: 1. if dtype is a CategoricalDtype, return dtype 2. if dtype is the string 'category', create a CategoricalDtype from the supplied categories and ordered parameters, and return that. 3. if values is a categorical, use value.dtype, but override it with categories and ordered if either/both of those are not None. 4. if dtype is None and values is not a categorical, construct the dtype from categories and ordered, even if either of those is None. Parameters ---------- values : list-like, optional The list-like must be 1-dimensional. categories : list-like, optional Categories for the CategoricalDtype. ordered : bool, optional Designating if the categories are ordered. dtype : CategoricalDtype or the string "category", optional If ``CategoricalDtype``, cannot be used together with `categories` or `ordered`. Returns ------- CategoricalDtype Examples -------- >>> pd.CategoricalDtype._from_values_or_dtype() CategoricalDtype(categories=None, ordered=None) >>> pd.CategoricalDtype._from_values_or_dtype( ... categories=['a', 'b'], ordered=True ... ) CategoricalDtype(categories=['a', 'b'], ordered=True) >>> dtype1 = pd.CategoricalDtype(['a', 'b'], ordered=True) >>> dtype2 = pd.CategoricalDtype(['x', 'y'], ordered=False) >>> c = pd.Categorical([0, 1], dtype=dtype1, fastpath=True) >>> pd.CategoricalDtype._from_values_or_dtype( ... c, ['x', 'y'], ordered=True, dtype=dtype2 ... ) Traceback (most recent call last): ... ValueError: Cannot specify `categories` or `ordered` together with `dtype`. The supplied dtype takes precedence over values' dtype: >>> pd.CategoricalDtype._from_values_or_dtype(c, dtype=dtype2) CategoricalDtype(categories=['x', 'y'], ordered=False) """ if dtype is not None: # The dtype argument takes precedence over values.dtype (if any) if isinstance(dtype, str): if dtype == "category": dtype = CategoricalDtype(categories, ordered) else: raise ValueError(f"Unknown dtype {repr(dtype)}") elif categories is not None or ordered is not None: raise ValueError( "Cannot specify `categories` or `ordered` together with `dtype`." ) elif not isinstance(dtype, CategoricalDtype): raise ValueError(f"Cannot not construct CategoricalDtype from {dtype}") elif cls.is_dtype(values): # If no "dtype" was passed, use the one from "values", but honor # the "ordered" and "categories" arguments dtype = values.dtype._from_categorical_dtype( values.dtype, categories, ordered ) else: # If dtype=None and values is not categorical, create a new dtype. # Note: This could potentially have categories=None and # ordered=None. dtype = CategoricalDtype(categories, ordered) return cast(CategoricalDtype, dtype) @classmethod def construct_from_string(cls, string: str_type) -> CategoricalDtype: """ Construct a CategoricalDtype from a string. Parameters ---------- string : str Must be the string "category" in order to be successfully constructed. Returns ------- CategoricalDtype Instance of the dtype. Raises ------ TypeError If a CategoricalDtype cannot be constructed from the input. """ if not isinstance(string, str): raise TypeError( f"'construct_from_string' expects a string, got {type(string)}" ) if string != cls.name: raise TypeError(f"Cannot construct a 'CategoricalDtype' from '{string}'") # need ordered=None to ensure that operations specifying dtype="category" don't # override the ordered value for existing categoricals return cls(ordered=None) def _finalize(self, categories, ordered: Ordered, fastpath: bool = False) -> None: if ordered is not None: self.validate_ordered(ordered) if categories is not None: categories = self.validate_categories(categories, fastpath=fastpath) self._categories = categories self._ordered = ordered def __setstate__(self, state: MutableMapping[str_type, Any]) -> None: # for pickle compat. __get_state__ is defined in the # PandasExtensionDtype superclass and uses the public properties to # pickle -> need to set the settable private ones here (see GH26067) self._categories = state.pop("categories", None) self._ordered = state.pop("ordered", False) def __hash__(self) -> int: # _hash_categories returns a uint64, so use the negative # space for when we have unknown categories to avoid a conflict if self.categories is None: if self.ordered: return -1 else: return -2 # We *do* want to include the real self.ordered here return int(self._hash_categories(self.categories, self.ordered)) def __eq__(self, other: Any) -> bool: """ Rules for CDT equality: 1) Any CDT is equal to the string 'category' 2) Any CDT is equal to itself 3) Any CDT is equal to a CDT with categories=None regardless of ordered 4) A CDT with ordered=True is only equal to another CDT with ordered=True and identical categories in the same order 5) A CDT with ordered={False, None} is only equal to another CDT with ordered={False, None} and identical categories, but same order is not required. There is no distinction between False/None. 6) Any other comparison returns False """ if isinstance(other, str): return other == self.name elif other is self: return True elif not (hasattr(other, "ordered") and hasattr(other, "categories")): return False elif self.categories is None or other.categories is None: # For non-fully-initialized dtypes, these are only equal to # - the string "category" (handled above) # - other CategoricalDtype with categories=None return self.categories is other.categories elif self.ordered or other.ordered: # At least one has ordered=True; equal if both have ordered=True # and the same values for categories in the same order. return (self.ordered == other.ordered) and self.categories.equals( other.categories ) else: # Neither has ordered=True; equal if both have the same categories, # but same order is not necessary. There is no distinction between # ordered=False and ordered=None: CDT(., False) and CDT(., None) # will be equal if they have the same categories. left = self.categories right = other.categories # GH#36280 the ordering of checks here is for performance if not left.dtype == right.dtype: return False if len(left) != len(right): return False if self.categories.equals(other.categories): # Check and see if they happen to be identical categories return True if left.dtype != object: # Faster than calculating hash indexer = left.get_indexer(right) # Because left and right have the same length and are unique, # `indexer` not having any -1s implies that there is a # bijection between `left` and `right`. return (indexer != -1).all() # With object-dtype we need a comparison that identifies # e.g. int(2) as distinct from float(2) return hash(self) == hash(other) def __repr__(self) -> str_type: if self.categories is None: data = "None" else: data = self.categories._format_data(name=type(self).__name__) if data is None: # self.categories is RangeIndex data = str(self.categories._range) data = data.rstrip(", ") return f"CategoricalDtype(categories={data}, ordered={self.ordered})" @staticmethod def _hash_categories(categories, ordered: Ordered = True) -> int: from pandas.core.util.hashing import ( combine_hash_arrays, hash_array, hash_tuples, ) if len(categories) and isinstance(categories[0], tuple): # assumes if any individual category is a tuple, then all our. ATM # I don't really want to support just some of the categories being # tuples. categories = list(categories) # breaks if a np.array of categories cat_array = hash_tuples(categories) else: if categories.dtype == "O" and len({type(x) for x in categories}) != 1: # TODO: hash_array doesn't handle mixed types. It casts # everything to a str first, which means we treat # {'1', '2'} the same as {'1', 2} # find a better solution hashed = hash((tuple(categories), ordered)) return hashed if DatetimeTZDtype.is_dtype(categories.dtype): # Avoid future warning. categories = categories.view("datetime64[ns]") cat_array = hash_array(np.asarray(categories), categorize=False) if ordered: cat_array = np.vstack( [cat_array, np.arange(len(cat_array), dtype=cat_array.dtype)] ) else: cat_array = [cat_array] hashed = combine_hash_arrays(iter(cat_array), num_items=len(cat_array)) return np.bitwise_xor.reduce(hashed) @classmethod def construct_array_type(cls) -> Type[Categorical]: """ Return the array type associated with this dtype. Returns ------- type """ from pandas import Categorical return Categorical @staticmethod def validate_ordered(ordered: Ordered) -> None: """ Validates that we have a valid ordered parameter. If it is not a boolean, a TypeError will be raised. Parameters ---------- ordered : object The parameter to be verified. Raises ------ TypeError If 'ordered' is not a boolean. """ if not is_bool(ordered): raise TypeError("'ordered' must either be 'True' or 'False'") @staticmethod def validate_categories(categories, fastpath: bool = False): """ Validates that we have good categories Parameters ---------- categories : array-like fastpath : bool Whether to skip nan and uniqueness checks Returns ------- categories : Index """ from pandas.core.indexes.base import Index if not fastpath and not is_list_like(categories): raise TypeError( f"Parameter 'categories' must be list-like, was {repr(categories)}" ) elif not isinstance(categories, ABCIndex): categories = Index(categories, tupleize_cols=False) if not fastpath: if categories.hasnans: raise ValueError("Categorical categories cannot be null") if not categories.is_unique: raise ValueError("Categorical categories must be unique") if isinstance(categories, ABCCategoricalIndex): categories = categories.categories return categories def update_dtype( self, dtype: Union[str_type, CategoricalDtype] ) -> CategoricalDtype: """ Returns a CategoricalDtype with categories and ordered taken from dtype if specified, otherwise falling back to self if unspecified Parameters ---------- dtype : CategoricalDtype Returns ------- new_dtype : CategoricalDtype """ if isinstance(dtype, str) and dtype == "category": # dtype='category' should not change anything return self elif not self.is_dtype(dtype): raise ValueError( f"a CategoricalDtype must be passed to perform an update, " f"got {repr(dtype)}" ) else: # from here on, dtype is a CategoricalDtype dtype = cast(CategoricalDtype, dtype) # update categories/ordered unless they've been explicitly passed as None new_categories = ( dtype.categories if dtype.categories is not None else self.categories ) new_ordered = dtype.ordered if dtype.ordered is not None else self.ordered return CategoricalDtype(new_categories, new_ordered) @property def categories(self): """ An ``Index`` containing the unique categories allowed. """ return self._categories @property def ordered(self) -> Ordered: """ Whether the categories have an ordered relationship. """ return self._ordered @property def _is_boolean(self) -> bool: from pandas.core.dtypes.common import is_bool_dtype return is_bool_dtype(self.categories) def _get_common_dtype(self, dtypes: List[DtypeObj]) -> Optional[DtypeObj]: from pandas.core.arrays.sparse import SparseDtype # check if we have all categorical dtype with identical categories if all(isinstance(x, CategoricalDtype) for x in dtypes): first = dtypes[0] if all(first == other for other in dtypes[1:]): return first # special case non-initialized categorical # TODO we should figure out the expected return value in general non_init_cats = [ isinstance(x, CategoricalDtype) and x.categories is None for x in dtypes ] if all(non_init_cats): return self elif any(non_init_cats): return None # categorical is aware of Sparse -> extract sparse subdtypes dtypes = [x.subtype if isinstance(x, SparseDtype) else x for x in dtypes] # extract the categories' dtype non_cat_dtypes = [ x.categories.dtype if isinstance(x, CategoricalDtype) else x for x in dtypes ] # TODO should categorical always give an answer? from pandas.core.dtypes.cast import find_common_type return find_common_type(non_cat_dtypes) @register_extension_dtype class DatetimeTZDtype(PandasExtensionDtype): """ An ExtensionDtype for timezone-aware datetime data. **This is not an actual numpy dtype**, but a duck type. Parameters ---------- unit : str, default "ns" The precision of the datetime data. Currently limited to ``"ns"``. tz : str, int, or datetime.tzinfo The timezone. Attributes ---------- unit tz Methods ------- None Raises ------ pytz.UnknownTimeZoneError When the requested timezone cannot be found. Examples -------- >>> pd.DatetimeTZDtype(tz='UTC') datetime64[ns, UTC] >>> pd.DatetimeTZDtype(tz='dateutil/US/Central') datetime64[ns, tzfile('/usr/share/zoneinfo/US/Central')] """ type: Type[Timestamp] = Timestamp kind: str_type = "M" str = "|M8[ns]" num = 101 base = np.dtype("M8[ns]") na_value = NaT _metadata = ("unit", "tz") _match = re.compile(r"(datetime64|M8)\[(?P<unit>.+), (?P<tz>.+)\]") _cache: Dict[str_type, PandasExtensionDtype] = {} def __init__(self, unit: Union[str_type, DatetimeTZDtype] = "ns", tz=None): if isinstance(unit, DatetimeTZDtype): # error: "str" has no attribute "tz" unit, tz = unit.unit, unit.tz # type: ignore[attr-defined] if unit != "ns": if isinstance(unit, str) and tz is None: # maybe a string like datetime64[ns, tz], which we support for # now. result = type(self).construct_from_string(unit) unit = result.unit tz = result.tz msg = ( f"Passing a dtype alias like 'datetime64[ns, {tz}]' " "to DatetimeTZDtype is no longer supported. Use " "'DatetimeTZDtype.construct_from_string()' instead." ) raise ValueError(msg) else: raise ValueError("DatetimeTZDtype only supports ns units") if tz: tz = timezones.maybe_get_tz(tz) tz = timezones.tz_standardize(tz) elif tz is not None: raise pytz.UnknownTimeZoneError(tz) if tz is None: raise TypeError("A 'tz' is required.") self._unit = unit self._tz = tz @property def unit(self) -> str_type: """ The precision of the datetime data. """ return self._unit @property def tz(self): """ The timezone. """ return self._tz @classmethod def construct_array_type(cls) -> Type[DatetimeArray]: """ Return the array type associated with this dtype. Returns ------- type """ from pandas.core.arrays import DatetimeArray return DatetimeArray @classmethod def construct_from_string(cls, string: str_type) -> DatetimeTZDtype: """ Construct a DatetimeTZDtype from a string. Parameters ---------- string : str The string alias for this DatetimeTZDtype. Should be formatted like ``datetime64[ns, <tz>]``, where ``<tz>`` is the timezone name. Examples -------- >>> DatetimeTZDtype.construct_from_string('datetime64[ns, UTC]') datetime64[ns, UTC] """ if not isinstance(string, str): raise TypeError( f"'construct_from_string' expects a string, got {type(string)}" ) msg = f"Cannot construct a 'DatetimeTZDtype' from '{string}'" match = cls._match.match(string) if match: d = match.groupdict() try: return cls(unit=d["unit"], tz=d["tz"]) except (KeyError, TypeError, ValueError) as err: # KeyError if maybe_get_tz tries and fails to get a # pytz timezone (actually pytz.UnknownTimeZoneError). # TypeError if we pass a nonsense tz; # ValueError if we pass a unit other than "ns" raise TypeError(msg) from err raise TypeError(msg) def __str__(self) -> str_type: return f"datetime64[{self.unit}, {self.tz}]" @property def name(self) -> str_type: """A string representation of the dtype.""" return str(self) def __hash__(self) -> int: # make myself hashable # TODO: update this. return hash(str(self)) def __eq__(self, other: Any) -> bool: if isinstance(other, str): if other.startswith("M8["): other = "datetime64[" + other[3:] return other == self.name return ( isinstance(other, DatetimeTZDtype) and self.unit == other.unit and tz_compare(self.tz, other.tz) ) def __setstate__(self, state) -> None: # for pickle compat. __get_state__ is defined in the # PandasExtensionDtype superclass and uses the public properties to # pickle -> need to set the settable private ones here (see GH26067) self._tz = state["tz"] self._unit = state["unit"] @register_extension_dtype class PeriodDtype(dtypes.PeriodDtypeBase, PandasExtensionDtype): """ An ExtensionDtype for Period data. **This is not an actual numpy dtype**, but a duck type. Parameters ---------- freq : str or DateOffset The frequency of this PeriodDtype. Attributes ---------- freq Methods ------- None Examples -------- >>> pd.PeriodDtype(freq='D') period[D] >>> pd.PeriodDtype(freq=pd.offsets.MonthEnd()) period[M] """ type: Type[Period] = Period kind: str_type = "O" str = "|O08" base = np.dtype("O") num = 102 _metadata = ("freq",) _match = re.compile(r"(P|p)eriod\[(?P<freq>.+)\]") _cache: Dict[str_type, PandasExtensionDtype] = {} def __new__(cls, freq=None): """ Parameters ---------- freq : frequency """ if isinstance(freq, PeriodDtype): return freq elif freq is None: # empty constructor for pickle compat # -10_000 corresponds to PeriodDtypeCode.UNDEFINED u = dtypes.PeriodDtypeBase.__new__(cls, -10_000) u._freq = None return u if not isinstance(freq, BaseOffset): freq = cls._parse_dtype_strict(freq) try: return cls._cache[freq.freqstr] except KeyError: dtype_code = freq._period_dtype_code u = dtypes.PeriodDtypeBase.__new__(cls, dtype_code) u._freq = freq cls._cache[freq.freqstr] = u return u def __reduce__(self): return type(self), (self.freq,) @property def freq(self): """ The frequency object of this PeriodDtype. """ return self._freq @classmethod def _parse_dtype_strict(cls, freq): if isinstance(freq, str): if freq.startswith("period[") or freq.startswith("Period["): m = cls._match.search(freq) if m is not None: freq = m.group("freq") freq = to_offset(freq) if freq is not None: return freq raise ValueError("could not construct PeriodDtype") @classmethod def construct_from_string(cls, string: str_type) -> PeriodDtype: """ Strict construction from a string, raise a TypeError if not possible """ if ( isinstance(string, str) and (string.startswith("period[") or string.startswith("Period[")) or isinstance(string, BaseOffset) ): # do not parse string like U as period[U] # avoid tuple to be regarded as freq try: return cls(freq=string) except ValueError: pass if isinstance(string, str): msg = f"Cannot construct a 'PeriodDtype' from '{string}'" else: msg = f"'construct_from_string' expects a string, got {type(string)}" raise TypeError(msg) def __str__(self) -> str_type: return self.name @property def name(self) -> str_type: return f"period[{self.freq.freqstr}]" @property def na_value(self): return NaT def __hash__(self) -> int: # make myself hashable return hash(str(self)) def __eq__(self, other: Any) -> bool: if isinstance(other, str): return other in [self.name, self.name.title()] return isinstance(other, PeriodDtype) and self.freq == other.freq def __ne__(self, other: Any) -> bool: return not self.__eq__(other) def __setstate__(self, state): # for pickle compat. __getstate__ is defined in the # PandasExtensionDtype superclass and uses the public properties to # pickle -> need to set the settable private ones here (see GH26067) self._freq = state["freq"] @classmethod def is_dtype(cls, dtype: object) -> bool: """ Return a boolean if we if the passed type is an actual dtype that we can match (via string or type) """ if isinstance(dtype, str): # PeriodDtype can be instantiated from freq string like "U", # but doesn't regard freq str like "U" as dtype. if dtype.startswith("period[") or dtype.startswith("Period["): try: if cls._parse_dtype_strict(dtype) is not None: return True else: return False except ValueError: return False else: return False return super().is_dtype(dtype) @classmethod def construct_array_type(cls) -> Type[PeriodArray]: """ Return the array type associated with this dtype. Returns ------- type """ from pandas.core.arrays import PeriodArray return PeriodArray def __from_arrow__( self, array: Union[pyarrow.Array, pyarrow.ChunkedArray] ) -> PeriodArray: """ Construct PeriodArray from pyarrow Array/ChunkedArray. """ import pyarrow from pandas.core.arrays import PeriodArray from pandas.core.arrays._arrow_utils import pyarrow_array_to_numpy_and_mask if isinstance(array, pyarrow.Array): chunks = [array] else: chunks = array.chunks results = [] for arr in chunks: data, mask = pyarrow_array_to_numpy_and_mask(arr, dtype="int64") parr = PeriodArray(data.copy(), freq=self.freq, copy=False) parr[~mask] = NaT results.append(parr) return PeriodArray._concat_same_type(results) @register_extension_dtype class IntervalDtype(PandasExtensionDtype): """ An ExtensionDtype for Interval data. **This is not an actual numpy dtype**, but a duck type. Parameters ---------- subtype : str, np.dtype The dtype of the Interval bounds. Attributes ---------- subtype Methods ------- None Examples -------- >>> pd.IntervalDtype(subtype='int64', closed='both') interval[int64, both] """ name = "interval" kind: str_type = "O" str = "|O08" base = np.dtype("O") num = 103 _metadata = ( "subtype", "closed", ) _match = re.compile( r"(I|i)nterval\[(?P<subtype>[^,]+)(, (?P<closed>(right|left|both|neither)))?\]" ) _cache: Dict[str_type, PandasExtensionDtype] = {} def __new__(cls, subtype=None, closed: Optional[str_type] = None): from pandas.core.dtypes.common import is_string_dtype, pandas_dtype if closed is not None and closed not in {"right", "left", "both", "neither"}: raise ValueError("closed must be one of 'right', 'left', 'both', 'neither'") if isinstance(subtype, IntervalDtype): if closed is not None and closed != subtype.closed: raise ValueError( "dtype.closed and 'closed' do not match. " "Try IntervalDtype(dtype.subtype, closed) instead." ) return subtype elif subtype is None: # we are called as an empty constructor # generally for pickle compat u = object.__new__(cls) u._subtype = None u._closed = closed return u elif isinstance(subtype, str) and subtype.lower() == "interval": subtype = None else: if isinstance(subtype, str): m = cls._match.search(subtype) if m is not None: gd = m.groupdict() subtype = gd["subtype"] if gd.get("closed", None) is not None: if closed is not None: if closed != gd["closed"]: raise ValueError( "'closed' keyword does not match value " "specified in dtype string" ) closed = gd["closed"] try: subtype = pandas_dtype(subtype) except TypeError as err: raise TypeError("could not construct IntervalDtype") from err if CategoricalDtype.is_dtype(subtype) or is_string_dtype(subtype): # GH 19016 msg = ( "category, object, and string subtypes are not supported " "for IntervalDtype" ) raise TypeError(msg) key = str(subtype) + str(closed) try: return cls._cache[key] except KeyError: u = object.__new__(cls) u._subtype = subtype u._closed = closed cls._cache[key] = u return u @property def closed(self): return self._closed @property def subtype(self): """ The dtype of the Interval bounds. """ return self._subtype @classmethod def construct_array_type(cls) -> Type[IntervalArray]: """ Return the array type associated with this dtype. Returns ------- type """ from pandas.core.arrays import IntervalArray return IntervalArray @classmethod def construct_from_string(cls, string): """ attempt to construct this type from a string, raise a TypeError if its not possible """ if not isinstance(string, str): raise TypeError( f"'construct_from_string' expects a string, got {type(string)}" ) if string.lower() == "interval" or cls._match.search(string) is not None: return cls(string) msg = ( f"Cannot construct a 'IntervalDtype' from '{string}'.\n\n" "Incorrectly formatted string passed to constructor. " "Valid formats include Interval or Interval[dtype] " "where dtype is numeric, datetime, or timedelta" ) raise TypeError(msg) @property def type(self): return Interval def __str__(self) -> str_type: if self.subtype is None: return "interval" if self.closed is None: # Only partially initialized GH#38394 return f"interval[{self.subtype}]" return f"interval[{self.subtype}, {self.closed}]" def __hash__(self) -> int: # make myself hashable return hash(str(self)) def __eq__(self, other: Any) -> bool: if isinstance(other, str): return other.lower() in (self.name.lower(), str(self).lower()) elif not isinstance(other, IntervalDtype): return False elif self.subtype is None or other.subtype is None: # None should match any subtype return True elif self.closed != other.closed: return False else: from pandas.core.dtypes.common import is_dtype_equal return is_dtype_equal(self.subtype, other.subtype) def __setstate__(self, state): # for pickle compat. __get_state__ is defined in the # PandasExtensionDtype superclass and uses the public properties to # pickle -> need to set the settable private ones here (see GH26067) self._subtype = state["subtype"] # backward-compat older pickles won't have "closed" key self._closed = state.pop("closed", None) @classmethod def is_dtype(cls, dtype: object) -> bool: """ Return a boolean if we if the passed type is an actual dtype that we can match (via string or type) """ if isinstance(dtype, str): if dtype.lower().startswith("interval"): try: if cls.construct_from_string(dtype) is not None: return True else: return False except (ValueError, TypeError): return False else: return False return super().is_dtype(dtype) def __from_arrow__( self, array: Union[pyarrow.Array, pyarrow.ChunkedArray] ) -> IntervalArray: """ Construct IntervalArray from pyarrow Array/ChunkedArray. """ import pyarrow from pandas.core.arrays import IntervalArray if isinstance(array, pyarrow.Array): chunks = [array] else: chunks = array.chunks results = [] for arr in chunks: left = np.asarray(arr.storage.field("left"), dtype=self.subtype) right = np.asarray(arr.storage.field("right"), dtype=self.subtype) iarr = IntervalArray.from_arrays(left, right, closed=array.type.closed) results.append(iarr) return IntervalArray._concat_same_type(results) def _get_common_dtype(self, dtypes: List[DtypeObj]) -> Optional[DtypeObj]: # NB: this doesn't handle checking for closed match if not all(isinstance(x, IntervalDtype) for x in dtypes): return None closed = cast("IntervalDtype", dtypes[0]).closed if not all(cast("IntervalDtype", x).closed == closed for x in dtypes): return np.dtype(object) from pandas.core.dtypes.cast import find_common_type common = find_common_type([cast("IntervalDtype", x).subtype for x in dtypes]) if common == object: return np.dtype(object) return IntervalDtype(common, closed=closed) class PandasDtype(ExtensionDtype): """ A Pandas ExtensionDtype for NumPy dtypes. .. versionadded:: 0.24.0 This is mostly for internal compatibility, and is not especially useful on its own. Parameters ---------- dtype : object Object to be converted to a NumPy data type object. See Also -------- numpy.dtype """ _metadata = ("_dtype",) def __init__(self, dtype: Optional[Union[NpDtype, PandasDtype]]): if isinstance(dtype, PandasDtype): # make constructor univalent dtype = dtype.numpy_dtype self._dtype = np.dtype(dtype) def __repr__(self) -> str: return f"PandasDtype({repr(self.name)})" @property def numpy_dtype(self) -> np.dtype: """ The NumPy dtype this PandasDtype wraps. """ return self._dtype @property def name(self) -> str: """ A bit-width name for this data-type. """ return self._dtype.name @property def type(self) -> Type[np.generic]: """ The type object used to instantiate a scalar of this NumPy data-type. """ return self._dtype.type @property def _is_numeric(self) -> bool: # exclude object, str, unicode, void. return self.kind in set("biufc") @property def _is_boolean(self) -> bool: return self.kind == "b" @classmethod def construct_from_string(cls, string: str) -> PandasDtype: try: dtype = np.dtype(string) except TypeError as err: if not isinstance(string, str): msg = f"'construct_from_string' expects a string, got {type(string)}" else: msg = f"Cannot construct a 'PandasDtype' from '{string}'" raise TypeError(msg) from err return cls(dtype) @classmethod def construct_array_type(cls) -> Type[PandasArray]: """ Return the array type associated with this dtype. Returns ------- type """ from pandas.core.arrays import PandasArray return PandasArray @property def kind(self) -> str: """ A character code (one of 'biufcmMOSUV') identifying the general kind of data. """ return self._dtype.kind @property def itemsize(self) -> int: """ The element size of this data-type object. """ return self._dtype.itemsize
from setuptools import setup import m2h with open("README.md", "r") as fh: long_description = fh.read() setup( name='machine2human', version=m2h.__version__, packages=['m2h'], url='https://github.com/andrew000/machine2human', license='MIT License', author='AndrewKing', python_requires='>=3.6', description='Make machine more friendly to you! Convert seconds to a human string and back!', long_description=long_description, long_description_content_type="text/markdown", )
import React from 'react'; import { Container, Top, Logo, Title } from './styles'; import Icon from 'react-native-vector-icons/MaterialIcons'; import logo from '~/assets/Nubank_Logo.png'; export default function Header() { return ( <Container> <Top> <Logo source={logo} /> <Title>Felipão</Title> </Top> <Icon name="keyboard-arrow-down" size={20} color="#FFF" /> </Container> ); };
from datetime import datetime import socket import xmlrpclib from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.db import models from django.utils.translation import ugettext_lazy as _ class PingedURLManager(models.Manager): def process_pending(self): for item in self.filter(status=self.model.PENDING).select_related('server'): try: rpc = xmlrpclib.Server(item.server.url) reply = rpc.weblogUpdates.ping( item.weblogname, item.weblogurl, item.changesurl or item.weblogurl) item.status = reply['flerror'] and self.model.FAILED or self.model.SUCCESSFUL item.message = reply['message'] except socket.error, msg: item.status = self.model.ERROR item.message = u'Socket error' except xmlrpclib.ProtocolError, e: item.status = self.model.ERROR item.message = u'Protocol error: %s, %s, %s' % (e.errcode, e.errmsg, e.url) except xmlrpclib.Fault, e: item.status = self.model.ERROR item.message = e.faultString except Exception, e: item.status = self.model.ERROR item.message = u'Unknown error: %s' % (repr(e),) item.save() def for_object(self, obj): return self.filter( content_type=ContentType.objects.get_for_model(obj), object_id=obj.pk) def create_for_servers(self, **kwargs): for server in PingServer.objects.all(): self.create(server=server, **kwargs) class PingServer(models.Model): url = models.URLField(_('url'), verify_exists=False) def __unicode__(self): return self.url def delete(self): self.pingedurl_set.all().delete() super(PingServer, self).delete() class PingedURL(models.Model): PENDING = 1 FAILED = 2 SUCCESSFUL = 3 ERROR = 4 STATUS_CHOICES = ( (PENDING, _('pending')), (FAILED, _('failed')), (SUCCESSFUL, _('successful')), (ERROR, _('error')), ) created = models.DateTimeField(_('created'), default=datetime.now) server = models.ForeignKey(PingServer) content_type = models.ForeignKey(ContentType, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) content_object = generic.GenericForeignKey() weblogname = models.CharField(_('weblog name'), max_length=200) weblogurl = models.CharField(_('weblog URL'), max_length=200) changesurl = models.CharField(_('changes URL'), max_length=200, blank=True, default=u'') status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=PENDING) message = models.CharField(_('message'), max_length=200, blank=True, default=u'') class Meta: ordering = ['-created'] objects = PingedURLManager() def __unicode__(self): return self.changesurl or self.weblogurl
from ..abstract_command import AbstractModelCommand class Command(AbstractModelCommand): help = 'Creates membership of principal in role.' def add_command_arguments(self, parser): principal_parser = parser.add_mutually_exclusive_group(required=True) principal_parser.add_argument( '--principal-id', type=int, metavar='0', help='Integer identifier to select principal by.') principal_parser.add_argument( '--principal-uuid', type=str, metavar='"{00000000-0000-0000-0000-000000000000}"', help='UUID to select principal by.') principal_parser.add_argument( '--principal-email', type=str, metavar='"johndoe@example.com"', help='Email address to select principal by.') principal_parser.add_argument( '--principal-phone', type=str, metavar='"+1-541-754-3010"', help='Phone number to select principal by.') role_parser = parser.add_mutually_exclusive_group(required=True) role_parser.add_argument( '--role-id', type=int, metavar='0', help='Integer identifier to select role by.') role_parser.add_argument( '--role-uuid', type=str, metavar='"{00000000-0000-0000-0000-000000000000}"', help='UUID to select role by.') role_parser.add_argument( '--role-code', type=str, metavar='administrators', help='Code to select role by.') parser.add_argument( '--new-uuid', type=str, metavar='"{00000000-0000-0000-0000-000000000000}"', help='UUID of membership.') def handle_command(self, *args, **options): from ...models import Principal from ...models import PrincipalRoleMembership from ...models import Role from uuid import UUID from uuid import uuid4 role = self.get_object(Role.objects, options, 'role_', None) principal = self.get_object(Principal.objects, options, 'principal_', None) principal_role_membership = PrincipalRoleMembership() principal_role_membership.uuid = UUID(options['new_uuid']) if options['new_uuid'] else uuid4() principal_role_membership.principal = principal principal_role_membership.role = role principal_role_membership.save() return principal_role_membership
/** @file InterlockedDecrement function Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php. THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ /** Microsoft Visual Studio 7.1 Function Prototypes for I/O Intrinsics. **/ long _InterlockedDecrement( long * lpAddend ); #pragma intrinsic(_InterlockedDecrement) /** Performs an atomic decrement of an 32-bit unsigned integer. Performs an atomic decrement of the 32-bit unsigned integer specified by Value and returns the decrement value. The decrement operation must be performed using MP safe mechanisms. The state of the return value is not guaranteed to be MP safe. @param Value A pointer to the 32-bit value to decrement. @return The decrement value. **/ UINT32 EFIAPI InternalSyncDecrement ( IN UINT32 *Value ) { return _InterlockedDecrement (Value); }
def main(): horizontal = 0 depth = 0 aim = 0 with open("AoC-D2.txt") as f: directions = f.readlines() for line in directions: move = line.strip("\n").split() if move[0] == "forward": horizontal += int(move[1]) depth += aim * int(move[1]) elif move[0] == "up": aim -= int(move[1]) else: aim += int(move[1]) print(f"Final Position:\n" f"{horizontal} on the X-axis.\n" f"{depth} on the Y-axis.\n" f"The product is {horizontal * depth}.") if __name__ == "__main__": main()
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.lang['fi']={"editor":"Rikastekstieditori","editorPanel":"Rikastekstieditoripaneeli","common":{"editorHelp":"Paina ALT 0 nähdäksesi ohjeen","browseServer":"Selaa palvelinta","url":"Osoite","protocol":"Protokolla","upload":"Lisää tiedosto","uploadSubmit":"Lähetä palvelimelle","image":"Kuva","flash":"Flash-animaatio","form":"Lomake","checkbox":"Valintaruutu","radio":"Radiopainike","textField":"Tekstikenttä","textarea":"Tekstilaatikko","hiddenField":"Piilokenttä","button":"Painike","select":"Valintakenttä","imageButton":"Kuvapainike","notSet":"<ei asetettu>","id":"Tunniste","name":"Nimi","langDir":"Kielen suunta","langDirLtr":"Vasemmalta oikealle (LTR)","langDirRtl":"Oikealta vasemmalle (RTL)","langCode":"Kielikoodi","longDescr":"Pitkän kuvauksen URL","cssClass":"Tyyliluokat","advisoryTitle":"Avustava otsikko","cssStyle":"Tyyli","ok":"OK","cancel":"Peruuta","close":"Sulje","preview":"Esikatselu","resize":"Raahaa muuttaaksesi kokoa","generalTab":"Yleinen","advancedTab":"Lisäominaisuudet","validateNumberFailed":"Arvon pitää olla numero.","confirmNewPage":"Kaikki tallentamattomat muutokset tähän sisältöön menetetään. Oletko varma, että haluat ladata uuden sivun?","confirmCancel":"Jotkut asetuksista on muuttuneet. Oletko varma, että haluat sulkea valintaikkunan?","options":"Asetukset","target":"Kohde","targetNew":"Uusi ikkuna (_blank)","targetTop":"Päällimmäinen ikkuna (_top)","targetSelf":"Sama ikkuna (_self)","targetParent":"Ylemmän tason ikkuna (_parent)","langDirLTR":"Vasemmalta oikealle (LTR)","langDirRTL":"Oikealta vasemmalle (RTL)","styles":"Tyyli","cssClasses":"Tyylitiedoston luokat","width":"Leveys","height":"Korkeus","align":"Kohdistus","alignLeft":"Vasemmalle","alignRight":"Oikealle","alignCenter":"Keskelle","alignJustify":"Tasaa molemmat reunat","alignTop":"Ylös","alignMiddle":"Keskelle","alignBottom":"Alas","alignNone":"Ei asetettu","invalidValue":"Virheellinen arvo.","invalidHeight":"Korkeuden täytyy olla numero.","invalidWidth":"Leveyden täytyy olla numero.","invalidCssLength":"Kentän \"%1\" arvon täytyy olla positiivinen luku CSS mittayksikön (px, %, in, cm, mm, em, ex, pt tai pc) kanssa tai ilman.","invalidHtmlLength":"Kentän \"%1\" arvon täytyy olla positiivinen luku HTML mittayksikön (px tai %) kanssa tai ilman.","invalidInlineStyle":"Tyylille annetun arvon täytyy koostua yhdestä tai useammasta \"nimi : arvo\" parista, jotka ovat eroteltuna toisistaan puolipisteillä.","cssLengthTooltip":"Anna numeroarvo pikseleinä tai numeroarvo CSS mittayksikön kanssa (px, %, in, cm, mm, em, ex, pt, tai pc).","unavailable":"%1<span class=\"cke_accessibility\">, ei saatavissa</span>","keyboard":{"8":"Backspace","13":"Enter","16":"Shift","17":"Ctrl","18":"Alt","32":"Space","35":"End","36":"Home","46":"Delete","224":"Command"},"keyboardShortcut":"Keyboard shortcut"},"about":{"copy":"Copyright &copy; $1. Kaikki oikeuden pidätetään.","dlgTitle":"Tietoa CKEditorista","help":"Katso ohjeet: $1.","moreInfo":"Lisenssitiedot löytyvät kotisivuiltamme:","title":"Tietoa CKEditorista","userGuide":"CKEditorin käyttäjäopas"},"basicstyles":{"bold":"Lihavoitu","italic":"Kursivoitu","strike":"Yliviivattu","subscript":"Alaindeksi","superscript":"Yläindeksi","underline":"Alleviivattu"},"blockquote":{"toolbar":"Lainaus"},"clipboard":{"copy":"Kopioi","copyError":"Selaimesi turva-asetukset eivät salli editorin toteuttaa kopioimista. Käytä näppäimistöä kopioimiseen (Ctrl+C).","cut":"Leikkaa","cutError":"Selaimesi turva-asetukset eivät salli editorin toteuttaa leikkaamista. Käytä näppäimistöä leikkaamiseen (Ctrl+X).","paste":"Liitä","pasteArea":"Leikealue","pasteMsg":"Liitä painamalla (<STRONG>Ctrl+V</STRONG>) ja painamalla <STRONG>OK</STRONG>.","securityMsg":"Selaimesi turva-asetukset eivät salli editorin käyttää leikepöytää suoraan. Sinun pitää suorittaa liittäminen tässä ikkunassa.","title":"Liitä"},"contextmenu":{"options":"Pikavalikon ominaisuudet"},"button":{"selectedLabel":"%1 (Valittu)"},"toolbar":{"toolbarCollapse":"Kutista työkalupalkki","toolbarExpand":"Laajenna työkalupalkki","toolbarGroups":{"document":"Dokumentti","clipboard":"Leikepöytä/Kumoa","editing":"Muokkaus","forms":"Lomakkeet","basicstyles":"Perustyylit","paragraph":"Kappale","links":"Linkit","insert":"Lisää","styles":"Tyylit","colors":"Värit","tools":"Työkalut"},"toolbars":"Editorin työkalupalkit"},"elementspath":{"eleLabel":"Elementin polku","eleTitle":"%1 elementti"},"format":{"label":"Muotoilu","panelTitle":"Muotoilu","tag_address":"Osoite","tag_div":"Normaali (DIV)","tag_h1":"Otsikko 1","tag_h2":"Otsikko 2","tag_h3":"Otsikko 3","tag_h4":"Otsikko 4","tag_h5":"Otsikko 5","tag_h6":"Otsikko 6","tag_p":"Normaali","tag_pre":"Muotoiltu"},"horizontalrule":{"toolbar":"Lisää murtoviiva"},"image":{"alt":"Vaihtoehtoinen teksti","border":"Kehys","btnUpload":"Lähetä palvelimelle","button2Img":"Haluatko muuntaa valitun kuvanäppäimen kuvaksi?","hSpace":"Vaakatila","img2Button":"Haluatko muuntaa valitun kuvan kuvanäppäimeksi?","infoTab":"Kuvan tiedot","linkTab":"Linkki","lockRatio":"Lukitse suhteet","menu":"Kuvan ominaisuudet","resetSize":"Alkuperäinen koko","title":"Kuvan ominaisuudet","titleButton":"Kuvapainikkeen ominaisuudet","upload":"Lisää kuva","urlMissing":"Kuvan lähdeosoite puuttuu.","vSpace":"Pystytila","validateBorder":"Kehyksen täytyy olla kokonaisluku.","validateHSpace":"HSpace-määrityksen täytyy olla kokonaisluku.","validateVSpace":"VSpace-määrityksen täytyy olla kokonaisluku."},"indent":{"indent":"Suurenna sisennystä","outdent":"Pienennä sisennystä"},"fakeobjects":{"anchor":"Ankkuri","flash":"Flash animaatio","hiddenfield":"Piilokenttä","iframe":"IFrame-kehys","unknown":"Tuntematon objekti"},"link":{"acccessKey":"Pikanäppäin","advanced":"Lisäominaisuudet","advisoryContentType":"Avustava sisällön tyyppi","advisoryTitle":"Avustava otsikko","anchor":{"toolbar":"Lisää ankkuri/muokkaa ankkuria","menu":"Ankkurin ominaisuudet","title":"Ankkurin ominaisuudet","name":"Nimi","errorName":"Ankkurille on kirjoitettava nimi","remove":"Poista ankkuri"},"anchorId":"Ankkurin ID:n mukaan","anchorName":"Ankkurin nimen mukaan","charset":"Linkitetty kirjaimisto","cssClasses":"Tyyliluokat","download":"Force Download","displayText":"Display Text","emailAddress":"Sähköpostiosoite","emailBody":"Viesti","emailSubject":"Aihe","id":"Tunniste","info":"Linkin tiedot","langCode":"Kielen suunta","langDir":"Kielen suunta","langDirLTR":"Vasemmalta oikealle (LTR)","langDirRTL":"Oikealta vasemmalle (RTL)","menu":"Muokkaa linkkiä","name":"Nimi","noAnchors":"(Ei ankkureita tässä dokumentissa)","noEmail":"Kirjoita sähköpostiosoite","noUrl":"Linkille on kirjoitettava URL","other":"<muu>","popupDependent":"Riippuva (Netscape)","popupFeatures":"Popup ikkunan ominaisuudet","popupFullScreen":"Täysi ikkuna (IE)","popupLeft":"Vasemmalta (px)","popupLocationBar":"Osoiterivi","popupMenuBar":"Valikkorivi","popupResizable":"Venytettävä","popupScrollBars":"Vierityspalkit","popupStatusBar":"Tilarivi","popupToolbar":"Vakiopainikkeet","popupTop":"Ylhäältä (px)","rel":"Suhde","selectAnchor":"Valitse ankkuri","styles":"Tyyli","tabIndex":"Tabulaattori indeksi","target":"Kohde","targetFrame":"<kehys>","targetFrameName":"Kohdekehyksen nimi","targetPopup":"<popup ikkuna>","targetPopupName":"Popup ikkunan nimi","title":"Linkki","toAnchor":"Ankkuri tässä sivussa","toEmail":"Sähköposti","toUrl":"Osoite","toolbar":"Lisää linkki/muokkaa linkkiä","type":"Linkkityyppi","unlink":"Poista linkki","upload":"Lisää tiedosto"},"list":{"bulletedlist":"Luettelomerkit","numberedlist":"Numerointi"},"magicline":{"title":"Lisää kappale tähän."},"maximize":{"maximize":"Suurenna","minimize":"Pienennä"},"pastetext":{"button":"Liitä tekstinä","title":"Liitä tekstinä"},"pastefromword":{"confirmCleanup":"Liittämäsi teksti näyttäisi olevan Word-dokumentista. Haluatko siivota sen ennen liittämistä? (Suositus: Kyllä)","error":"Liitetyn tiedon siivoaminen ei onnistunut sisäisen virheen takia","title":"Liitä Word-dokumentista","toolbar":"Liitä Word-dokumentista"},"removeformat":{"toolbar":"Poista muotoilu"},"sourcearea":{"toolbar":"Koodi"},"specialchar":{"options":"Erikoismerkin ominaisuudet","title":"Valitse erikoismerkki","toolbar":"Lisää erikoismerkki"},"scayt":{"btn_about":"Tietoja oikoluvusta kirjoitetaessa","btn_dictionaries":"Sanakirjat","btn_disable":"Poista käytöstä oikoluku kirjoitetaessa","btn_enable":"Ota käyttöön oikoluku kirjoitettaessa","btn_langs":"Kielet","btn_options":"Asetukset","text_title":"Oikolue kirjoitettaessa"},"stylescombo":{"label":"Tyyli","panelTitle":"Muotoilujen tyylit","panelTitle1":"Lohkojen tyylit","panelTitle2":"Rivinsisäiset tyylit","panelTitle3":"Objektien tyylit"},"table":{"border":"Rajan paksuus","caption":"Otsikko","cell":{"menu":"Solu","insertBefore":"Lisää solu eteen","insertAfter":"Lisää solu perään","deleteCell":"Poista solut","merge":"Yhdistä solut","mergeRight":"Yhdistä oikealla olevan kanssa","mergeDown":"Yhdistä alla olevan kanssa","splitHorizontal":"Jaa solu vaakasuunnassa","splitVertical":"Jaa solu pystysuunnassa","title":"Solun ominaisuudet","cellType":"Solun tyyppi","rowSpan":"Rivin jatkuvuus","colSpan":"Solun jatkuvuus","wordWrap":"Rivitys","hAlign":"Horisontaali kohdistus","vAlign":"Vertikaali kohdistus","alignBaseline":"Alas (teksti)","bgColor":"Taustan väri","borderColor":"Reunan väri","data":"Data","header":"Ylätunniste","yes":"Kyllä","no":"Ei","invalidWidth":"Solun leveyden täytyy olla numero.","invalidHeight":"Solun korkeuden täytyy olla numero.","invalidRowSpan":"Rivin jatkuvuuden täytyy olla kokonaisluku.","invalidColSpan":"Solun jatkuvuuden täytyy olla kokonaisluku.","chooseColor":"Valitse"},"cellPad":"Solujen sisennys","cellSpace":"Solujen väli","column":{"menu":"Sarake","insertBefore":"Lisää sarake vasemmalle","insertAfter":"Lisää sarake oikealle","deleteColumn":"Poista sarakkeet"},"columns":"Sarakkeet","deleteTable":"Poista taulu","headers":"Ylätunnisteet","headersBoth":"Molemmat","headersColumn":"Ensimmäinen sarake","headersNone":"Ei","headersRow":"Ensimmäinen rivi","invalidBorder":"Reunan koon täytyy olla numero.","invalidCellPadding":"Solujen sisennyksen täytyy olla numero.","invalidCellSpacing":"Solujen välin täytyy olla numero.","invalidCols":"Sarakkeiden määrän täytyy olla suurempi kuin 0.","invalidHeight":"Taulun korkeuden täytyy olla numero.","invalidRows":"Rivien määrän täytyy olla suurempi kuin 0.","invalidWidth":"Taulun leveyden täytyy olla numero.","menu":"Taulun ominaisuudet","row":{"menu":"Rivi","insertBefore":"Lisää rivi yläpuolelle","insertAfter":"Lisää rivi alapuolelle","deleteRow":"Poista rivit"},"rows":"Rivit","summary":"Yhteenveto","title":"Taulun ominaisuudet","toolbar":"Taulu","widthPc":"prosenttia","widthPx":"pikseliä","widthUnit":"leveysyksikkö"},"undo":{"redo":"Toista","undo":"Kumoa"},"wsc":{"btnIgnore":"Jätä huomioimatta","btnIgnoreAll":"Jätä kaikki huomioimatta","btnReplace":"Korvaa","btnReplaceAll":"Korvaa kaikki","btnUndo":"Kumoa","changeTo":"Vaihda","errorLoading":"Virhe ladattaessa oikolukupalvelua isännältä: %s.","ieSpellDownload":"Oikeinkirjoituksen tarkistusta ei ole asennettu. Haluatko ladata sen nyt?","manyChanges":"Tarkistus valmis: %1 sanaa muutettiin","noChanges":"Tarkistus valmis: Yhtään sanaa ei muutettu","noMispell":"Tarkistus valmis: Ei virheitä","noSuggestions":"Ei ehdotuksia","notAvailable":"Valitettavasti oikoluku ei ole käytössä tällä hetkellä.","notInDic":"Ei sanakirjassa","oneChange":"Tarkistus valmis: Yksi sana muutettiin","progress":"Tarkistus käynnissä...","title":"Oikoluku","toolbar":"Tarkista oikeinkirjoitus"}};
new_npc_stats = { 'base_stats': { 'vit': 4, 'dex': 4, 'str': 4, 'int': 4, 'agility': 8, 'toughness': 9, }, 'stats': { 'max_hp': 'from vit', # vit*hp_per_vit + lvl*hp_per_lvl 'max_mana': 'from int?', 'armor': 'from str and toughness', 'magic_resistance': 'from toughness', # and int? 'speed': 'from dex and agility', 'dodge': 'from dex and speed', 'crit_chance': 'from dex', 'crit_dmg': 'from dex', }, 'storage': { 'equipped items': 'armor, weapons, ...', 'spell book': 'spells / abilities', 'potions': '', # in party? 'party': 'party instance' }, 'tracked_values': { 'ct': 1000, # when c reaches this, unit gets a turn 'c': 0, # holds current charge value - +speed each clock tick in battle 'status_effects': [], 'elemental_resistance': 0, # from items (and toughness?) 'hp': '', 'mana': '', } }
import plyj.parser as plyj class UnsupportedASTError(ValueError): pass class PrettyPretter: def __init__(self, indentation=4): self.out = None self.current_indent = None self.indentation_amount = indentation def print_tree(self, tree): self.out = '' self.current_indent = 0 self._print_tree(tree) return self.out def line_break(self): self.out += '\n' self.out += (self.indentation_amount * ' ') * self.current_indent def block(self, block): if isinstance(block, plyj.Block): block = block.statements if isinstance(block, list): self.out += ' {' self.current_indent += 1 for statement in block: if type(statement) != plyj.IfThenElse: self.line_break() skip_semicolon = self._print_tree(statement) if not skip_semicolon: self.out += ';' self.current_indent -= 1 self.line_break() self.out += '}' else: self.out += ' ' self._print_tree(block) self.out += ';' def semicolon_seperated(self, values): for arg in values: self._print_tree(arg) if arg != values[-1]: self.out += '; ' def comma_seperate(self, values): for arg in values: self._print_tree(arg) if arg != values[-1]: self.out += ', ' def _print_tree(self, tree, previous=None): if isinstance(tree, str): self.out += tree elif type(tree) == plyj.CompilationUnit: if tree.package_declaration != None: self._print_tree(tree.package_declaration) for import_dec in tree.import_declarations: self._print_tree(import_dec) for type_dec in tree.type_declarations: self._print_tree(type_dec) elif type(tree) == plyj.PackageDeclaration: self.out += 'package ' self._print_tree(tree.name) if tree.modifiers: raise NotImplemented('modifiers PackageDeclaration') self.out += ';' self.line_break() self.line_break() elif type(tree) == plyj.ImportDeclaration: if tree.on_demand: raise NotImplemented('no_demand ImportDeclaration') if tree.static: self.out += 'static ' self.out += 'import ' self._print_tree(tree.name) self.out += ';' self.line_break() elif type(tree) == plyj.ClassDeclaration: self.line_break() self.line_break() for modifier in tree.modifiers: self.out += modifier + ' ' self.out += 'class ' + tree.name if tree.type_parameters: self.out += '<' self.comma_seperate(tree.type_parameters) self.out += '>' if tree.extends: raise UnsupportedASTError('extends ClassDeclaration') if tree.implements: self.out += ' implements ' self.comma_seperate(tree.implements) self.out += ' ' self.out += ' {' self.current_indent += 1 self.line_break() for declaration in tree.body: self._print_tree(declaration) self.current_indent -= 1 self.line_break() self.out += '}' elif type(tree) == plyj.VariableDeclaration: for modifier in tree.modifiers: self.out += modifier + ' ' self._print_tree(tree.type) self.out += ' ' for declaration in tree.variable_declarators: self._print_tree(declaration) elif type(tree) == plyj.FieldDeclaration: self.line_break() for modifier in tree.modifiers: self.out += modifier + ' ' self._print_tree(tree.type) self.out += ' ' for declaration in tree.variable_declarators: self._print_tree(declaration) self.out += ';' self.line_break() elif type(tree) == plyj.Type: self._print_tree(tree.name) if tree.enclosed_in: raise UnsupportedASTError('enclosed_in Type') if tree.type_arguments: self.out += '<' if tree.type_arguments != 'diamond': for type_arg in tree.type_arguments: self._print_tree(type_arg) self.out += '>' if tree.dimensions: self.out += '[]' * tree.dimensions elif type(tree) == plyj.VariableDeclarator: self._print_tree(tree.variable) if tree.initializer: self.out += ' = ' self._print_tree(tree.initializer) elif type(tree) == plyj.Literal: self.out += tree.value elif type(tree) == plyj.Variable: self.out += tree.name elif type(tree) == plyj.Name: self.out += tree.value elif type(tree) == plyj.FormalParameter: self._print_tree(tree.type) self.out += ' ' if tree.vararg: self.out += '... ' self._print_tree(tree.variable) elif type(tree) == plyj.MethodDeclaration: self.line_break() self.line_break() for modifier in tree.modifiers: self._print_tree(modifier) self.out += ' ' self._print_tree(tree.return_type) self.out += ' ' + tree.name if tree.type_parameters: raise UnsupportedASTError('type_parameters MethodDeclaration') self.out += '(' self.comma_seperate(tree.parameters) self.out += ')' if tree.throws: raise UnsupportedASTError('throws MethodDeclaration') if tree.abstract: self.out += ';' else: self.block(tree.body) if tree.extended_dims: raise UnsupportedASTError('extended_dims ConstructorDeclaration') elif type(tree) == plyj.ConstructorDeclaration: self.line_break() for modifier in tree.modifiers: self._print_tree(modifier) self.out += ' ' self.out += tree.name self.out += '(' self.comma_seperate(tree.parameters) self.out += ')' if tree.throws: raise UnsupportedASTError('throws ConstructorDeclaration') self.block(tree.block) elif type(tree) == plyj.Assignment: self._print_tree(tree.lhs) self.out += ' ' + tree.operator + ' ' self._print_tree(tree.rhs) elif type(tree) == plyj.FieldAccess: self._print_tree(tree.target) self.out += '.' + tree.name elif type(tree) == plyj.Multiplicative or \ type(tree) == plyj.Additive or \ type(tree) == plyj.Equality or \ type(tree) == plyj.ConditionalOr or \ type(tree) == plyj.Relational: self.out += '(' self._print_tree(tree.lhs) self.out += ' ' + tree.operator + ' ' self._print_tree(tree.rhs) self.out += ')' elif type(tree) == plyj.InstanceCreation: self.out += 'new ' self._print_tree(tree.type) if tree.type_arguments: raise UnsupportedASTError('type_arguments InstanceCreation') self.out += '(' self.comma_seperate(tree.arguments) self.out += ')' elif type(tree) == plyj.MethodInvocation: if tree.target: self._print_tree(tree.target) self.out += '.' self.out += tree.name if tree.type_arguments: raise UnsupportedASTError('type_arguments MethodInvocation') self.out += '(' self.comma_seperate(tree.arguments) self.out += ')' elif type(tree) == plyj.IfThenElse: if not isinstance(previous, plyj.IfThenElse): self.line_break() else: self.out += ' ' self.out += 'if (' self._print_tree(tree.predicate) self.out += ')' self.block(tree.if_true) if tree.if_false: self.line_break() self.out += 'else' self._print_tree(tree.if_false) return True elif type(tree) == plyj.TypeParameter: self._print_tree(tree.name) if tree.extends: self.out += ' extends ' self.comma_seperate(tree.extends) elif type(tree) == plyj.Return: self.out += 'return' if tree.result: self.out += ' ' self._print_tree(tree.result) elif type(tree) == plyj.Throw: self.out += 'throw ' self._print_tree(tree.exception) elif type(tree) == plyj.Block: self.block(tree.statements) elif type(tree) == plyj.Cast: self.out += '((' self._print_tree(tree.target) self.out += ') ' self._print_tree(tree.expression) self.out += ')' elif type(tree) == plyj.DoWhile: self.out += 'do' self.block(tree.body) self.out += ' while (' self._print_tree(tree.predicate) self.out += ')' elif type(tree) == plyj.While: self.out += 'while (' self._print_tree(tree.predicate) self.out += ')' self.block(tree.body) return True elif type(tree) == plyj.ForEach: self.out += 'for (' self._print_tree(tree.type) self.out += ' ' self._print_tree(tree.variable) self.out += ' : ' self._print_tree(tree.iterable) self.out += ')' self._print_tree(tree.body) elif type(tree) == plyj.For: self.out += 'for (' self._print_tree(tree.init) self.out += '; ' self._print_tree(tree.predicate) self.out += '; ' self.semicolon_seperated(tree.update) self.out += ') ' self._print_tree(tree.body) return True elif type(tree) == plyj.ArrayCreation: self.out += 'new ' self._print_tree(tree.type) for dim in tree.dimensions: self.out += '[' self._print_tree(dim) self.out += ']' elif type(tree) == plyj.ArrayAccess: self._print_tree(tree.target) self.out += '[' self._print_tree(tree.index) self.out += ']' elif type(tree) == plyj.Unary: if tree.sign == 'x++': self._print_tree(tree.expression) self.out += '++' elif tree.sign == 'x--': self._print_tree(tree.expression) self.out += '--' elif tree.sign == '!': self.out += '!' self._print_tree(tree.expression) else: raise UnsupportedASTError(tree) elif type(tree) == plyj.Annotation: self.out += '@' self._print_tree(tree.name) if tree.single_member: self.out += '(' self._print_tree(tree.single_member) self.out += ')' elif tree.members: self.out += '(' self.comma_seperate(tree.members) self.out += ')' else: print self.out raise UnsupportedASTError(tree)
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019 IBM Corp. */ #include <io.h> #include <xscom.h> #include <npu3.h> #include <npu3-regs.h> #include <nvram.h> #include <interrupts.h> #include <xive.h> #define NPU3LOG(l, npu, fmt, a...) \ prlog(l, "NPU[%d:%d]: " fmt, (npu)->chip_id, (npu)->index, ##a) #define NPU3DBG(npu, fmt, a...) NPU3LOG(PR_DEBUG, npu, fmt, ##a) #define NPU3INF(npu, fmt, a...) NPU3LOG(PR_INFO, npu, fmt, ##a) #define NPU3ERR(npu, fmt, a...) NPU3LOG(PR_ERR, npu, fmt, ##a) #define NPU3DEVLOG(l, dev, fmt, a...) \ prlog(l, "NPU[%d:%d:%d]: " fmt, \ (dev)->npu->chip_id, \ (dev)->npu->index, \ (dev)->index, ##a) #define NPU3DEVDBG(dev, fmt, a...) NPU3DEVLOG(PR_DEBUG, dev, fmt, ##a) #define NPU3DEVINF(dev, fmt, a...) NPU3DEVLOG(PR_INFO, dev, fmt, ##a) #define NPU3DEVERR(dev, fmt, a...) NPU3DEVLOG(PR_ERR, dev, fmt, ##a) static void npu3_dt_create_link(struct dt_node *npu, uint32_t npu_index, uint32_t dev_index) { struct dt_node *link; uint32_t phy_lane_mask, ob_chiplet; link = dt_new_addr(npu, "link", dev_index); dt_add_property_string(link, "compatible", "ibm,npu-link"); dt_add_property_cells(link, "reg", dev_index); dt_add_property_cells(link, "ibm,npu-link-index", dev_index); switch (npu_index) { case 0: /* fall through */ case 2: ob_chiplet = npu_index ? 3 : 0; switch (dev_index) { case 0: phy_lane_mask = PPC_BITMASK32(0, 3); break; case 1: phy_lane_mask = PPC_BITMASK32(13, 16); break; case 2: phy_lane_mask = PPC_BITMASK32(7, 10); break; case 3: phy_lane_mask = PPC_BITMASK32(20, 23); break; } break; case 1: switch (dev_index) { case 0: ob_chiplet = 1; phy_lane_mask = PPC_BITMASK32(0, 3); break; case 1: ob_chiplet = 2; phy_lane_mask = PPC_BITMASK32(0, 3); break; case 2: ob_chiplet = 1; phy_lane_mask = PPC_BITMASK32(7, 10); break; case 3: ob_chiplet = 2; phy_lane_mask = PPC_BITMASK32(7, 10); break; } break; default: return; } dt_add_property_cells(link, "ibm,npu-phy", ob_chiplet); dt_add_property_cells(link, "ibm,npu-lane-mask", phy_lane_mask); } static void npu3_dt_create_npu(struct dt_node *xscom, uint32_t npu_index) { const uint32_t npu_base[] = { 0x5011000, 0x5011400, 0x3011c00 }; struct dt_node *npu; npu = dt_new_addr(xscom, "npu", npu_base[npu_index]); dt_add_property_cells(npu, "#size-cells", 0); dt_add_property_cells(npu, "#address-cells", 1); dt_add_property_cells(npu, "reg", npu_base[npu_index], 0x2c); dt_add_property_string(npu, "compatible", "ibm,power9-npu3"); dt_add_property_cells(npu, "ibm,npu-index", npu_index); for (uint32_t i = 0; i < NPU3_LINKS_PER_NPU; i++) npu3_dt_create_link(npu, npu_index, i); } /* This can be removed when/if we decide to use HDAT instead */ static bool npu3_dt_create(void) { struct proc_chip *chip = next_chip(NULL); struct dt_node *xscom; /* npu3 chips only */ if (proc_gen < proc_gen_p9 || chip->type == PROC_CHIP_P9_NIMBUS || chip->type == PROC_CHIP_P9_CUMULUS) return false; dt_for_each_compatible(dt_root, xscom, "ibm,xscom") for (uint32_t i = 0; i < 3; i++) npu3_dt_create_npu(xscom, i); return true; } static struct npu3 *npu3_create(struct dt_node *dn) { struct npu3 *npu; struct dt_node *link; struct npu3_dev *dev; char *path; uint32_t i; npu = zalloc(sizeof(*npu)); assert(npu); init_lock(&npu->lock); npu->dt_node = dn; npu->index = dt_prop_get_u32(dn, "ibm,npu-index"); npu->xscom_base = dt_get_address(dn, 0, NULL); npu->chip_id = dt_get_chip_id(dn); assert(get_chip(npu->chip_id)); dt_for_each_compatible(dn, link, "ibm,npu-link") { i = dt_prop_get_u32(link, "ibm,npu-link-index"); assert(i < NPU3_LINKS_PER_NPU); dev = &npu->devices[i]; dev->index = i; dev->npu = npu; dev->dn = link; dev->ob_chiplet = dt_prop_get_u32(link, "ibm,npu-phy"); dev->phy_lane_mask = dt_prop_get_u32(link, "ibm,npu-lane-mask"); dev->proc.status = NPU3_PROC_COMPLETE; }; path = dt_get_path(dn); NPU3INF(npu, "Found %s\n", path); NPU3INF(npu, "SCOM base: 0x%llx\n", npu->xscom_base); free(path); return npu; } struct npu3_dev *npu3_next_dev(struct npu3 *npu, struct npu3_dev *dev, enum npu3_dev_type type) { uint32_t i = 0; if (dev) i = dev->index + 1; for (; i < NPU3_LINKS_PER_NPU; i++) { dev = &npu->devices[i]; if (dev->type == type || type == NPU3_DEV_TYPE_ANY) return dev; } return NULL; } static void npu3_device_detect_fixup(struct npu3_dev *dev) { struct dt_node *dn = dev->dn; if (dev->type == NPU3_DEV_TYPE_NVLINK) { dt_add_property_strings(dn, "ibm,npu-link-type", "nvlink"); dev->link_speed = dt_prop_get_u32_def( dn, "nvidia,link-speed", 0xff); return; } NPU3DEVDBG(dev, "Link type unknown\n"); dt_add_property_strings(dn, "ibm,npu-link-type", "unknown"); } /* * We use the indirect method because it uses the same addresses as * the MMIO offsets (NPU RING) */ static void npu3_scom_sel(struct npu3 *npu, uint64_t reg, uint64_t size) { uint64_t val; val = SETFIELD(NPU3_MISC_DA_ADDR, 0ull, reg); val = SETFIELD(NPU3_MISC_DA_LEN, val, size); xscom_write(npu->chip_id, npu->xscom_base + NPU3_MISC_SCOM_IND_SCOM_ADDR, val); } static void npu3_scom_write(struct npu3 *npu, uint64_t reg, uint64_t size, uint64_t val) { npu3_scom_sel(npu, reg, size); xscom_write(npu->chip_id, npu->xscom_base + NPU3_MISC_SCOM_IND_SCOM_DATA, val); } static uint64_t npu3_scom_read(struct npu3 *npu, uint64_t reg, uint64_t size) { uint64_t val; npu3_scom_sel(npu, reg, size); xscom_read(npu->chip_id, npu->xscom_base + NPU3_MISC_SCOM_IND_SCOM_DATA, &val); return val; } void npu3_write(struct npu3 *npu, uint64_t reg, uint64_t val) { void *mmio = (void *)npu->regs[0]; if (mmio) out_be64(mmio + reg, val); else npu3_scom_write(npu, reg, NPU3_MISC_DA_LEN_8B, val); /* CQ_SM writes should be mirrored in all four blocks */ if (NPU3_REG_BLOCK(reg) != NPU3_BLOCK_CQ_SM(0)) return; for (uint32_t i = 1; i < 4; i++) npu3_write(npu, NPU3_BLOCK_CQ_SM(i) + NPU3_REG_OFFSET(reg), val); } uint64_t npu3_read(struct npu3 *npu, uint64_t reg) { void *mmio = (void *)npu->regs[0]; if (mmio) return in_be64(mmio + reg); return npu3_scom_read(npu, reg, NPU3_MISC_DA_LEN_8B); } void npu3_write_4b(struct npu3 *npu, uint64_t reg, uint32_t val) { void *mmio = (void *)npu->regs[0]; if (mmio) out_be32(mmio + reg, val); else npu3_scom_write(npu, reg, NPU3_MISC_DA_LEN_4B, (uint64_t)val << 32); if (NPU3_REG_BLOCK(reg) != NPU3_BLOCK_CQ_SM(0)) return; for (uint32_t i = 1; i < 4; i++) npu3_write_4b(npu, NPU3_BLOCK_CQ_SM(i) + NPU3_REG_OFFSET(reg), val); } uint32_t npu3_read_4b(struct npu3 *npu, uint64_t reg) { void *mmio = (void *)npu->regs[0]; if (mmio) return in_be32(mmio + reg); return npu3_scom_read(npu, reg, NPU3_MISC_DA_LEN_4B) >> 32; } static void npu3_misc_config(struct npu3 *npu) { struct npu3_dev *dev; uint32_t typemap = 0; uint64_t reg, val; npu3_for_each_nvlink_dev(dev, npu) typemap |= 0x10 >> dev->index; reg = NPU3_MCP_MISC_CFG0; val = npu3_read(npu, reg); val |= NPU3_MCP_MISC_CFG0_ENABLE_PBUS; val &= ~NPU3_MCP_MISC_CFG0_ENABLE_SNARF_CPM; val = SETFIELD(NPU3_MCP_MISC_CFG0_NVLINK_MODE, val, typemap); val = SETFIELD(NPU3_MCP_MISC_CFG0_OCAPI_MODE, val, ~typemap); npu3_write(npu, reg, val); reg = NPU3_SNP_MISC_CFG0; val = npu3_read(npu, reg); val |= NPU3_SNP_MISC_CFG0_ENABLE_PBUS; val = SETFIELD(NPU3_SNP_MISC_CFG0_NVLINK_MODE, val, typemap); val = SETFIELD(NPU3_SNP_MISC_CFG0_OCAPI_MODE, val, ~typemap); npu3_write(npu, reg, val); reg = NPU3_CTL_MISC_CFG2; val = npu3_read(npu, reg); val = SETFIELD(NPU3_CTL_MISC_CFG2_NVLINK_MODE, val, typemap); val = SETFIELD(NPU3_CTL_MISC_CFG2_OCAPI_MODE, val, ~typemap); npu3_write(npu, reg, val); reg = NPU3_DAT_MISC_CFG1; val = npu3_read(npu, reg); val = SETFIELD(NPU3_DAT_MISC_CFG1_NVLINK_MODE, val, typemap); val = SETFIELD(NPU3_DAT_MISC_CFG1_OCAPI_MODE, val, ~typemap); npu3_write(npu, reg, val); } static void npu3_assign_bars(struct npu3 *npu) { struct npu3_dev *dev; uint64_t addr, size, val; /* Global MMIO bar (per npu) */ phys_map_get(npu->chip_id, NPU_REGS, npu->index, &addr, &size); val = SETFIELD(NPU3_MMIO_BAR_ADDR, 0ull, addr >> 24); val |= NPU3_MMIO_BAR_ENABLE; npu3_write(npu, NPU3_MMIO_BAR, val); NPU3INF(npu, "MMIO base: 0x%016llx (%lldMB)\n", addr, size >> 20); npu->regs[0] = addr; npu->regs[1] = size; /* NTL bar (per device) */ npu3_for_each_dev(dev, npu) { phys_map_get(npu->chip_id, NPU_NTL, npu3_chip_dev_index(dev), &addr, &size); val = SETFIELD(NPU3_NTL_BAR_ADDR, 0ull, addr >> 16); val = SETFIELD(NPU3_NTL_BAR_SIZE, val, ilog2(size >> 16)); npu3_write(npu, NPU3_NTL_BAR(dev->index), val); dev->ntl_bar.addr = addr; dev->ntl_bar.size = size; } /* GENID bar (logically divided per device) */ phys_map_get(npu->chip_id, NPU_GENID, npu->index, &addr, NULL); val = SETFIELD(NPU3_GENID_BAR_ADDR, 0ull, addr >> 19); npu3_write(npu, NPU3_GENID_BAR, val); npu3_for_each_dev(dev, npu) { dev->genid_bar.addr = addr + (dev->index << 16); dev->genid_bar.size = 64 << 10; } } void npu3_dev_enable_bars(struct npu3_dev *dev, bool enable) { struct npu3 *npu = dev->npu; uint64_t reg, val; if (dev->ntl_bar.enable == enable) /* No state change */ return; dev->ntl_bar.enable = enable; dev->genid_bar.enable = enable; reg = NPU3_NTL_BAR(dev->index); val = npu3_read(npu, reg); val = SETFIELD(NPU3_NTL_BAR_ENABLE, val, enable); npu3_write(npu, reg, val); /* * Generation IDs are a single space in the hardware but we split them * per device. Only disable in hardware if every device has disabled. */ if (!enable) npu3_for_each_dev(dev, npu) if (dev->genid_bar.enable) return; reg = NPU3_GENID_BAR; val = npu3_read(npu, reg); val = SETFIELD(NPU3_GENID_BAR_ENABLE, val, enable); npu3_write(npu, reg, val); } static uint64_t npu3_ipi_attributes(struct irq_source *is, uint32_t isn) { struct npu3 *npu = is->data; uint32_t level = isn - npu->irq_base; /* TCE interrupt is used to detect a frozen PE */ if (level == 18) return IRQ_ATTR_TARGET_OPAL | IRQ_ATTR_TARGET_RARE | IRQ_ATTR_TYPE_MSI; return IRQ_ATTR_TARGET_LINUX; } static void npu3_ipi_interrupt(struct irq_source *is, uint32_t isn) { struct npu3 *npu = is->data; uint32_t level = isn - npu->irq_base; if (level != 18) { NPU3ERR(npu, "Received unknown interrupt %d\n", level); return; } opal_update_pending_evt(OPAL_EVENT_PCI_ERROR, OPAL_EVENT_PCI_ERROR); } #define NPU3_IRQ_LEVELS 60 static char *npu3_ipi_name(struct irq_source *is, uint32_t isn) { struct npu3 *npu = is->data; uint32_t level = isn - npu->irq_base; static const char *names[NPU3_IRQ_LEVELS] = { [0] = "NDL 0 Stall Event (brick 0)", [1] = "NDL 0 No-Stall Event (brick 0)", [2] = "NDL 1 Stall Event (brick 1)", [3] = "NDL 1 No-Stall Event (brick 1)", [4] = "NDL 2 Stall Event (brick 2)", [5] = "NDL 2 No-Stall Event (brick 2)", [6] = "NDL 3 Stall Event (brick 3)", [7] = "NDL 3 No-Stall Event (brick 3)", [8] = "NDL 4 Stall Event (brick 4)", [9] = "NDL 4 No-Stall Event (brick 4)", [10] = "NDL 5 Stall Event (brick 5)", [11] = "NDL 5 No-Stall Event (brick 5)", [12] = "NTL 0 Event", [13] = "NTL 1 Event", [14] = "NTL 2 Event", [15] = "NTL 3 Event", [16] = "NTL 4 Event", [17] = "NTL 5 Event", [18] = "TCE Event", [19] = "ATS Event", [20] = "CQ Event", [21] = "MISC Event", [41] = "Memory Controller Event", [42] = "NDL 6 Stall Event (brick 6)", [43] = "NDL 6 No-Stall Event (brick 6)", [44] = "NDL 7 Stall Event (brick 7)", [45] = "NDL 7 No-Stall Event (brick 7)", [46] = "NDL 8 Stall Event (brick 8)", [47] = "NDL 8 No-Stall Event (brick 8)", [48] = "NDL 9 Stall Event (brick 9)", [49] = "NDL 9 No-Stall Event (brick 9)", [50] = "NDL 10 Stall Event (brick 10)", [51] = "NDL 10 No-Stall Event (brick 10)", [52] = "NDL 11 Stall Event (brick 11)", [53] = "NDL 11 No-Stall Event (brick 11)", [54] = "NTL 6 Event", [55] = "NTL 7 Event", [56] = "NTL 8 Event", [57] = "NTL 9 Event", [58] = "NTL 10 Event", [59] = "NTL 11 Event", }; if (level >= NPU3_IRQ_LEVELS || !names[level]) return strdup("Unknown"); return strdup(names[level]); } static const struct irq_source_ops npu3_ipi_ops = { .attributes = npu3_ipi_attributes, .interrupt = npu3_ipi_interrupt, .name = npu3_ipi_name, }; static void npu3_setup_irqs(struct npu3 *npu) { uint64_t reg, val; uint32_t base; base = xive_alloc_ipi_irqs(npu->chip_id, NPU3_IRQ_LEVELS, 64); if (base == XIVE_IRQ_ERROR) { NPU3ERR(npu, "Failed to allocate interrupt sources\n"); return; } xive_register_ipi_source(base, NPU3_IRQ_LEVELS, npu, &npu3_ipi_ops); /* Set IPI configuration */ reg = NPU3_MISC_CFG; val = npu3_read(npu, reg); val = SETFIELD(NPU3_MISC_CFG_IPI_PS, val, NPU3_MISC_CFG_IPI_PS_64K); val = SETFIELD(NPU3_MISC_CFG_IPI_OS, val, NPU3_MISC_CFG_IPI_OS_AIX); npu3_write(npu, reg, val); /* Set IRQ base */ reg = NPU3_MISC_INT_BAR; val = SETFIELD(NPU3_MISC_INT_BAR_ADDR, 0ull, (uint64_t)xive_get_trigger_port(base) >> 12); npu3_write(npu, reg, val); npu->irq_base = base; } static void npu3_init(struct npu3 *npu) { struct npu3_dev *dev; platform.npu3_device_detect(npu); npu3_for_each_dev(dev, npu) npu3_device_detect_fixup(dev); npu3_misc_config(npu); npu3_assign_bars(npu); npu3_setup_irqs(npu); npu3_init_nvlink(npu); } void probe_npu3(void) { struct dt_node *dn; struct npu3 *npu; if (!npu3_dt_create()) return; if (!platform.npu3_device_detect) { prlog(PR_INFO, "NPU: Platform does not support NPU\n"); return; } dt_for_each_compatible(dt_root, dn, "ibm,power9-npu3") { npu = npu3_create(dn); npu3_init(npu); } }
import heapq import numpy as np from utils.vocab import Vocab class Huffman_node: """ Huffman node self.direction: the current node is left(0)/right(1) child of its parent node self.node: List of its left and right child self.freq: the Huffman weight value self.vector: context representation vector of this node """ def __init__(self, leftnode = None, rightnode = None, leaf = None, vector_dim = None): self.direction = None if leftnode is not None and rightnode is not None: assert isinstance(leftnode, Huffman_node) assert isinstance(rightnode, Huffman_node) leftnode.direction = 0 rightnode.direction = 1 self.node = [leftnode, rightnode] self.freq = leftnode.get_freq() + rightnode.get_freq() self.vector = np.random.uniform(-1, 1, (vector_dim)) else: assert leaf is not None self.node = leaf[0] self.freq = leaf[1] self.vector = None def __lt__(self, other): return self.freq < other.freq def get_node(self): return self.node def get_freq(self)-> int: return self.freq class Huffman_tree: """ Huffman tree self.path: Root Path Lists of every leaf node """ def __init__(self, vocab:Vocab, dim:int =4): self.vocab = vocab self.root = self.build_tree(self.vocab,dim) self.path = self.leafnode_path() def build_tree(self, vocab:Vocab, dim:int): """Construct the set of tree nodes""" node = list(map(lambda x:Huffman_node(leaf=x), vocab.token_freq)) heapq.heapify(node) while len(node)>1: node1 = heapq.heappop(node) node2 = heapq.heappop(node) heapq.heappush(node,Huffman_node(leftnode = node1, rightnode = node2, vector_dim=dim)) return node[0] def get_nodepath(self,target_id:int)->list: return self.path[target_id] def leafnode_path(self): """find the node path of every leaf and store""" stack_node = [] stack_path = [] path = {} stack_node.append(self.root) stack_path.append([self.root]) while len(stack_node)!=0: tmp_node = stack_node.pop() tmp_path = stack_path.pop() if isinstance(tmp_node.node,str): path[self.vocab.token_to_idx(tmp_node.node)] = tmp_path else: stack_node.append(tmp_node.node[1]) stack_node.append(tmp_node.node[0]) stack_path.append(tmp_path + [tmp_node.node[1]]) stack_path.append(tmp_path + [tmp_node.node[0]]) return path
// https://d3js.org/d3-force/ v3.0.0 Copyright 2010-2021 Mike Bostock !function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("d3-quadtree"),require("d3-dispatch"),require("d3-timer")):"function"==typeof define&&define.amd?define(["exports","d3-quadtree","d3-dispatch","d3-timer"],t):t((n="undefined"!=typeof globalThis?globalThis:n||self).d3=n.d3||{},n.d3,n.d3,n.d3)}(this,(function(n,t,e,r){"use strict";function i(n){return function(){return n}}function u(n){return 1e-6*(n()-.5)}function o(n){return n.x+n.vx}function f(n){return n.y+n.vy}function a(n){return n.index}function c(n,t){var e=n.get(t);if(!e)throw new Error("node not found: "+t);return e}const l=4294967296;function h(n){return n.x}function v(n){return n.y}var y=Math.PI*(3-Math.sqrt(5));n.forceCenter=function(n,t){var e,r=1;function i(){var i,u,o=e.length,f=0,a=0;for(i=0;i<o;++i)f+=(u=e[i]).x,a+=u.y;for(f=(f/o-n)*r,a=(a/o-t)*r,i=0;i<o;++i)(u=e[i]).x-=f,u.y-=a}return null==n&&(n=0),null==t&&(t=0),i.initialize=function(n){e=n},i.x=function(t){return arguments.length?(n=+t,i):n},i.y=function(n){return arguments.length?(t=+n,i):t},i.strength=function(n){return arguments.length?(r=+n,i):r},i},n.forceCollide=function(n){var e,r,a,c=1,l=1;function h(){for(var n,i,h,y,d,g,x,s=e.length,p=0;p<l;++p)for(i=t.quadtree(e,o,f).visitAfter(v),n=0;n<s;++n)h=e[n],g=r[h.index],x=g*g,y=h.x+h.vx,d=h.y+h.vy,i.visit(M);function M(n,t,e,r,i){var o=n.data,f=n.r,l=g+f;if(!o)return t>y+l||r<y-l||e>d+l||i<d-l;if(o.index>h.index){var v=y-o.x-o.vx,s=d-o.y-o.vy,p=v*v+s*s;p<l*l&&(0===v&&(p+=(v=u(a))*v),0===s&&(p+=(s=u(a))*s),p=(l-(p=Math.sqrt(p)))/p*c,h.vx+=(v*=p)*(l=(f*=f)/(x+f)),h.vy+=(s*=p)*l,o.vx-=v*(l=1-l),o.vy-=s*l)}}}function v(n){if(n.data)return n.r=r[n.data.index];for(var t=n.r=0;t<4;++t)n[t]&&n[t].r>n.r&&(n.r=n[t].r)}function y(){if(e){var t,i,u=e.length;for(r=new Array(u),t=0;t<u;++t)i=e[t],r[i.index]=+n(i,t,e)}}return"function"!=typeof n&&(n=i(null==n?1:+n)),h.initialize=function(n,t){e=n,a=t,y()},h.iterations=function(n){return arguments.length?(l=+n,h):l},h.strength=function(n){return arguments.length?(c=+n,h):c},h.radius=function(t){return arguments.length?(n="function"==typeof t?t:i(+t),y(),h):n},h},n.forceLink=function(n){var t,e,r,o,f,l,h=a,v=function(n){return 1/Math.min(o[n.source.index],o[n.target.index])},y=i(30),d=1;function g(r){for(var i=0,o=n.length;i<d;++i)for(var a,c,h,v,y,g,x,s=0;s<o;++s)c=(a=n[s]).source,v=(h=a.target).x+h.vx-c.x-c.vx||u(l),y=h.y+h.vy-c.y-c.vy||u(l),v*=g=((g=Math.sqrt(v*v+y*y))-e[s])/g*r*t[s],y*=g,h.vx-=v*(x=f[s]),h.vy-=y*x,c.vx+=v*(x=1-x),c.vy+=y*x}function x(){if(r){var i,u,a=r.length,l=n.length,v=new Map(r.map(((n,t)=>[h(n,t,r),n])));for(i=0,o=new Array(a);i<l;++i)(u=n[i]).index=i,"object"!=typeof u.source&&(u.source=c(v,u.source)),"object"!=typeof u.target&&(u.target=c(v,u.target)),o[u.source.index]=(o[u.source.index]||0)+1,o[u.target.index]=(o[u.target.index]||0)+1;for(i=0,f=new Array(l);i<l;++i)u=n[i],f[i]=o[u.source.index]/(o[u.source.index]+o[u.target.index]);t=new Array(l),s(),e=new Array(l),p()}}function s(){if(r)for(var e=0,i=n.length;e<i;++e)t[e]=+v(n[e],e,n)}function p(){if(r)for(var t=0,i=n.length;t<i;++t)e[t]=+y(n[t],t,n)}return null==n&&(n=[]),g.initialize=function(n,t){r=n,l=t,x()},g.links=function(t){return arguments.length?(n=t,x(),g):n},g.id=function(n){return arguments.length?(h=n,g):h},g.iterations=function(n){return arguments.length?(d=+n,g):d},g.strength=function(n){return arguments.length?(v="function"==typeof n?n:i(+n),s(),g):v},g.distance=function(n){return arguments.length?(y="function"==typeof n?n:i(+n),p(),g):y},g},n.forceManyBody=function(){var n,e,r,o,f,a=i(-30),c=1,l=1/0,y=.81;function d(r){var i,u=n.length,f=t.quadtree(n,h,v).visitAfter(x);for(o=r,i=0;i<u;++i)e=n[i],f.visit(s)}function g(){if(n){var t,e,r=n.length;for(f=new Array(r),t=0;t<r;++t)e=n[t],f[e.index]=+a(e,t,n)}}function x(n){var t,e,r,i,u,o=0,a=0;if(n.length){for(r=i=u=0;u<4;++u)(t=n[u])&&(e=Math.abs(t.value))&&(o+=t.value,a+=e,r+=e*t.x,i+=e*t.y);n.x=r/a,n.y=i/a}else{(t=n).x=t.data.x,t.y=t.data.y;do{o+=f[t.data.index]}while(t=t.next)}n.value=o}function s(n,t,i,a){if(!n.value)return!0;var h=n.x-e.x,v=n.y-e.y,d=a-t,g=h*h+v*v;if(d*d/y<g)return g<l&&(0===h&&(g+=(h=u(r))*h),0===v&&(g+=(v=u(r))*v),g<c&&(g=Math.sqrt(c*g)),e.vx+=h*n.value*o/g,e.vy+=v*n.value*o/g),!0;if(!(n.length||g>=l)){(n.data!==e||n.next)&&(0===h&&(g+=(h=u(r))*h),0===v&&(g+=(v=u(r))*v),g<c&&(g=Math.sqrt(c*g)));do{n.data!==e&&(d=f[n.data.index]*o/g,e.vx+=h*d,e.vy+=v*d)}while(n=n.next)}}return d.initialize=function(t,e){n=t,r=e,g()},d.strength=function(n){return arguments.length?(a="function"==typeof n?n:i(+n),g(),d):a},d.distanceMin=function(n){return arguments.length?(c=n*n,d):Math.sqrt(c)},d.distanceMax=function(n){return arguments.length?(l=n*n,d):Math.sqrt(l)},d.theta=function(n){return arguments.length?(y=n*n,d):Math.sqrt(y)},d},n.forceRadial=function(n,t,e){var r,u,o,f=i(.1);function a(n){for(var i=0,f=r.length;i<f;++i){var a=r[i],c=a.x-t||1e-6,l=a.y-e||1e-6,h=Math.sqrt(c*c+l*l),v=(o[i]-h)*u[i]*n/h;a.vx+=c*v,a.vy+=l*v}}function c(){if(r){var t,e=r.length;for(u=new Array(e),o=new Array(e),t=0;t<e;++t)o[t]=+n(r[t],t,r),u[t]=isNaN(o[t])?0:+f(r[t],t,r)}}return"function"!=typeof n&&(n=i(+n)),null==t&&(t=0),null==e&&(e=0),a.initialize=function(n){r=n,c()},a.strength=function(n){return arguments.length?(f="function"==typeof n?n:i(+n),c(),a):f},a.radius=function(t){return arguments.length?(n="function"==typeof t?t:i(+t),c(),a):n},a.x=function(n){return arguments.length?(t=+n,a):t},a.y=function(n){return arguments.length?(e=+n,a):e},a},n.forceSimulation=function(n){var t,i=1,u=.001,o=1-Math.pow(u,1/300),f=0,a=.6,c=new Map,h=r.timer(g),v=e.dispatch("tick","end"),d=function(){let n=1;return()=>(n=(1664525*n+1013904223)%l)/l}();function g(){x(),v.call("tick",t),i<u&&(h.stop(),v.call("end",t))}function x(e){var r,u,l=n.length;void 0===e&&(e=1);for(var h=0;h<e;++h)for(i+=(f-i)*o,c.forEach((function(n){n(i)})),r=0;r<l;++r)null==(u=n[r]).fx?u.x+=u.vx*=a:(u.x=u.fx,u.vx=0),null==u.fy?u.y+=u.vy*=a:(u.y=u.fy,u.vy=0);return t}function s(){for(var t,e=0,r=n.length;e<r;++e){if((t=n[e]).index=e,null!=t.fx&&(t.x=t.fx),null!=t.fy&&(t.y=t.fy),isNaN(t.x)||isNaN(t.y)){var i=10*Math.sqrt(.5+e),u=e*y;t.x=i*Math.cos(u),t.y=i*Math.sin(u)}(isNaN(t.vx)||isNaN(t.vy))&&(t.vx=t.vy=0)}}function p(t){return t.initialize&&t.initialize(n,d),t}return null==n&&(n=[]),s(),t={tick:x,restart:function(){return h.restart(g),t},stop:function(){return h.stop(),t},nodes:function(e){return arguments.length?(n=e,s(),c.forEach(p),t):n},alpha:function(n){return arguments.length?(i=+n,t):i},alphaMin:function(n){return arguments.length?(u=+n,t):u},alphaDecay:function(n){return arguments.length?(o=+n,t):+o},alphaTarget:function(n){return arguments.length?(f=+n,t):f},velocityDecay:function(n){return arguments.length?(a=1-n,t):1-a},randomSource:function(n){return arguments.length?(d=n,c.forEach(p),t):d},force:function(n,e){return arguments.length>1?(null==e?c.delete(n):c.set(n,p(e)),t):c.get(n)},find:function(t,e,r){var i,u,o,f,a,c=0,l=n.length;for(null==r?r=1/0:r*=r,c=0;c<l;++c)(o=(i=t-(f=n[c]).x)*i+(u=e-f.y)*u)<r&&(a=f,r=o);return a},on:function(n,e){return arguments.length>1?(v.on(n,e),t):v.on(n)}}},n.forceX=function(n){var t,e,r,u=i(.1);function o(n){for(var i,u=0,o=t.length;u<o;++u)(i=t[u]).vx+=(r[u]-i.x)*e[u]*n}function f(){if(t){var i,o=t.length;for(e=new Array(o),r=new Array(o),i=0;i<o;++i)e[i]=isNaN(r[i]=+n(t[i],i,t))?0:+u(t[i],i,t)}}return"function"!=typeof n&&(n=i(null==n?0:+n)),o.initialize=function(n){t=n,f()},o.strength=function(n){return arguments.length?(u="function"==typeof n?n:i(+n),f(),o):u},o.x=function(t){return arguments.length?(n="function"==typeof t?t:i(+t),f(),o):n},o},n.forceY=function(n){var t,e,r,u=i(.1);function o(n){for(var i,u=0,o=t.length;u<o;++u)(i=t[u]).vy+=(r[u]-i.y)*e[u]*n}function f(){if(t){var i,o=t.length;for(e=new Array(o),r=new Array(o),i=0;i<o;++i)e[i]=isNaN(r[i]=+n(t[i],i,t))?0:+u(t[i],i,t)}}return"function"!=typeof n&&(n=i(null==n?0:+n)),o.initialize=function(n){t=n,f()},o.strength=function(n){return arguments.length?(u="function"==typeof n?n:i(+n),f(),o):u},o.y=function(t){return arguments.length?(n="function"==typeof t?t:i(+t),f(),o):n},o},Object.defineProperty(n,"__esModule",{value:!0})}));
from discord import Member from sqlalchemy import Column, Integer, String, Boolean from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class JeevesUser(Base): """ A JeevesUser class that is also a sqlalchmey base. (This means it is OMR, automatically generated tables from the class definition) .. _discord.Member: https://discordpy.readthedocs.io/en/latest/api.html#discord.Member Parameters ----------- memberinstance : `discord.Member`_ The instance of the Member that we want to conver to JeevesUser. Attributes ----------- discordid : string A string representing the discord id. name : string The name of the member. points : int The amount of points the member has. leaugename : string The leauge name of the individual. runescapen : string The runescape name of the member. remindupd : bool A boolean indicating if the member wants to be remined of updates. """ __tablename__ = 'JeevesUser' id = Column(Integer, primary_key=True) discordid = Column(String) name = Column(String) points = Column(Integer) leaugename = Column(String) runescapen = Column(String) remindupd = Column(Boolean) def __init__(self,memberinstance): if not isinstance(memberinstance,Member): raise InvalidType(type(memberinstance),type(Member),"JeevesU init") self.discordid = memberinstance.id self.name = memberinstance.name self.points = 100 self.leaugename = None self.leaugeid = None self.runescapen = None #runescapename self.remindlupd = False #Message if new leauge patch def __eq__(self,other): """ An equal method. Raises ------- InvalidType If it is not a corresponding type. """ if(other == None): return False if not isinstance(other,JeevesUser): raise InvalidType(type(other),type(JeevesUser), "JU eq") return other.id == self.id def __ne__(self,other): """ An not equal method. Raises ------- InvalidType If it is not a corresponding type. """ return not self == other def __gt__(self,other): """ An greaterthan method. Raises ------- InvalidType If it is not a corresponding type. """ if not isinstance(other,JeevesUser): raise InvalidType(type(other),type(JeevesUser), "JU gt") return self.points > other.points def __lt__(self,other): """ An lessthan method. Raises ------- InvalidType If it is not a corresponding type. """ r return not self > other def __str__(self): """ A string method. """ return self.name def __repr__(self): """ A represent method. """ return "<JeevesUser (id={}, name={}, points={})>".format(\ self.id, self.name, self.points)
!function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r})},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=2)}([function(t,e){t.exports=function(t,e,n,r,i,o){var u,a=t=t||{},s=typeof t.default;"object"!==s&&"function"!==s||(u=t,a=t.default);var c,f="function"==typeof a?a.options:a;if(e&&(f.render=e.render,f.staticRenderFns=e.staticRenderFns,f._compiled=!0),n&&(f.functional=!0),i&&(f._scopeId=i),o?(c=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),r&&r.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(o)},f._ssrRegister=c):r&&(c=r),c){var l=f.functional,A=l?f.render:f.beforeCreate;l?(f._injectStyles=c,f.render=function(t,e){return c.call(e),A(t,e)}):f.beforeCreate=A?[].concat(A,c):[c]}return{esModule:u,exports:a,options:f}}},function(t,e,n){t.exports=n(9)},function(t,e,n){n(3),t.exports=n(22)},function(t,e,n){Nova.booting(function(t,e,r){t.component("index-armincms-belongs-to-many",n(4)),t.component("detail-armincms-belongs-to-many",n(7)),t.component("form-armincms-belongs-to-many",n(12))})},function(t,e,n){var r=n(0)(n(5),n(6),!1,null,null,null);t.exports=r.exports},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={props:["resourceName","field"]}},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("span",[t.field.value&&t.field.value.length?t._l(t.field.value,function(e,r){return n("router-link",{key:r,staticClass:"no-underline font-bold dim text-primary",attrs:{to:{name:"detail",params:{resourceName:e.name||t.field.resourceName,resourceId:e.id}}}},[t._v("\n "+t._s(e.text)+" "+t._s(t.field.value.length-r-1?" , ":"")+"\n ")])}):n("p",{attrs:{slote:"value"}},[t._v("—")])],2)},staticRenderFns:[]}},function(t,e,n){var r=n(0)(n(8),n(11),!1,null,null,null);t.exports=r.exports},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),i=n.n(r);e.default={props:["resource","resourceName","resourceId","field"],data:function(){return{display:!1,fields:[]}},methods:{displayPivots:function(t){this.display=t,this.loading=!1,this.getPivotFields()},getPivotFields:function(){var t,e=(t=i.a.mark(function t(e){var n=this;return i.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,Nova.request().get("/nova-api/armincms/"+this.resourceName+"/pivot-fields/"+this.field.resourceName,{params:{resourceId:this.resourceId,relatedId:this.display.id,pivotId:this.display.pivotId}}).then(function(t){var e=t.data;n.fields=e,_.each(n.fields,function(t){t.fill=function(){return""}})});case 2:case"end":return t.stop()}},t,this)}),function(){var e=t.apply(this,arguments);return new Promise(function(t,n){return function r(i,o){try{var u=e[i](o),a=u.value}catch(t){return void n(t)}if(!u.done)return Promise.resolve(a).then(function(t){r("next",t)},function(t){r("throw",t)});t(a)}("next")})});return function(t){return e.apply(this,arguments)}}(),resolveComponentName:function(t){return t.prefixComponent?"detail-"+t.component:t.component},handleClose:function(){this.display=null,this.$emit("close")}},computed:{}}},function(t,e,n){var r=function(){return this}()||Function("return this")(),i=r.regeneratorRuntime&&Object.getOwnPropertyNames(r).indexOf("regeneratorRuntime")>=0,o=i&&r.regeneratorRuntime;if(r.regeneratorRuntime=void 0,t.exports=n(10),i)r.regeneratorRuntime=o;else try{delete r.regeneratorRuntime}catch(t){r.regeneratorRuntime=void 0}},function(t,e){!function(e){"use strict";var n,r=Object.prototype,i=r.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},u=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",s=o.toStringTag||"@@toStringTag",c="object"==typeof t,f=e.regeneratorRuntime;if(f)c&&(t.exports=f);else{(f=e.regeneratorRuntime=c?t.exports:{}).wrap=_;var l="suspendedStart",A="suspendedYield",p="executing",d="completed",h={},v={};v[u]=function(){return this};var g=Object.getPrototypeOf,m=g&&g(g(k([])));m&&m!==r&&i.call(m,u)&&(v=m);var y=E.prototype=w.prototype=Object.create(v);x.prototype=y.constructor=E,E.constructor=x,E[s]=x.displayName="GeneratorFunction",f.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===x||"GeneratorFunction"===(e.displayName||e.name))},f.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,E):(t.__proto__=E,s in t||(t[s]="GeneratorFunction")),t.prototype=Object.create(y),t},f.awrap=function(t){return{__await:t}},C(B.prototype),B.prototype[a]=function(){return this},f.AsyncIterator=B,f.async=function(t,e,n,r){var i=new B(_(t,e,n,r));return f.isGeneratorFunction(e)?i:i.next().then(function(t){return t.done?t.value:i.next()})},C(y),y[s]="Generator",y[u]=function(){return this},y.toString=function(){return"[object Generator]"},f.keys=function(t){var e=[];for(var n in t)e.push(n);return e.reverse(),function n(){for(;e.length;){var r=e.pop();if(r in t)return n.value=r,n.done=!1,n}return n.done=!0,n}},f.values=k,O.prototype={constructor:O,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(S),!t)for(var e in this)"t"===e.charAt(0)&&i.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=n)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function r(r,i){return a.type="throw",a.arg=t,e.next=r,i&&(e.method="next",e.arg=n),!!i}for(var o=this.tryEntries.length-1;o>=0;--o){var u=this.tryEntries[o],a=u.completion;if("root"===u.tryLoc)return r("end");if(u.tryLoc<=this.prev){var s=i.call(u,"catchLoc"),c=i.call(u,"finallyLoc");if(s&&c){if(this.prev<u.catchLoc)return r(u.catchLoc,!0);if(this.prev<u.finallyLoc)return r(u.finallyLoc)}else if(s){if(this.prev<u.catchLoc)return r(u.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<u.finallyLoc)return r(u.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=e&&e<=o.finallyLoc&&(o=null);var u=o?o.completion:{};return u.type=t,u.arg=e,o?(this.method="next",this.next=o.finallyLoc,h):this.complete(u)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),h},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),S(n),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;S(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:k(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=n),h}}}function _(t,e,n,r){var i=e&&e.prototype instanceof w?e:w,o=Object.create(i.prototype),u=new O(r||[]);return o._invoke=function(t,e,n){var r=l;return function(i,o){if(r===p)throw new Error("Generator is already running");if(r===d){if("throw"===i)throw o;return T()}for(n.method=i,n.arg=o;;){var u=n.delegate;if(u){var a=j(u,n);if(a){if(a===h)continue;return a}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===l)throw r=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=p;var s=b(t,e,n);if("normal"===s.type){if(r=n.done?d:A,s.arg===h)continue;return{value:s.arg,done:n.done}}"throw"===s.type&&(r=d,n.method="throw",n.arg=s.arg)}}}(t,n,u),o}function b(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}function w(){}function x(){}function E(){}function C(t){["next","throw","return"].forEach(function(e){t[e]=function(t){return this._invoke(e,t)}})}function B(t){var e;this._invoke=function(n,r){function o(){return new Promise(function(e,o){!function e(n,r,o,u){var a=b(t[n],t,r);if("throw"!==a.type){var s=a.arg,c=s.value;return c&&"object"==typeof c&&i.call(c,"__await")?Promise.resolve(c.__await).then(function(t){e("next",t,o,u)},function(t){e("throw",t,o,u)}):Promise.resolve(c).then(function(t){s.value=t,o(s)},u)}u(a.arg)}(n,r,e,o)})}return e=e?e.then(o,o):o()}}function j(t,e){var r=t.iterator[e.method];if(r===n){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=n,j(t,e),"throw"===e.method))return h;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return h}var i=b(r,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,h;var o=i.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=n),e.delegate=null,h):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function R(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function S(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function O(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(R,this),this.reset(!0)}function k(t){if(t){var e=t[u];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,o=function e(){for(;++r<t.length;)if(i.call(t,r))return e.value=t[r],e.done=!1,e;return e.value=n,e.done=!0,e};return o.next=o}}return{next:T}}function T(){return{value:n,done:!0}}}(function(){return this}()||Function("return this")())},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("panel-item",{attrs:{field:t.field}},[t.field.value&&t.field.value.length?n("template",{slot:"value"},[t.field.pivots?n("span",t._l(t.field.value,function(e,r){return n("span",{key:e.id,staticClass:"no-underline font-bold dim text-primary cursor-pointer",attrs:{title:t.__(":resource Details",{resource:e.text})},on:{click:function(n){return t.displayPivots(e)}}},[t._v("\n "+t._s(e.text)+" "+t._s(t.field.value.length-r-1?" , ":"")+"\n ")])}),0):n("span",t._l(t.field.value,function(e,r){return n("router-link",{key:r,staticClass:"no-underline font-bold dim text-primary",attrs:{to:{name:"detail",params:{resourceName:e.name||t.field.resourceName,resourceId:e.id}},title:t.__("View")}},[t._v("\n "+t._s(e.text)+" "+t._s(t.field.value.length-r-1?" , ":"")+"\n ")])}),1),t._v(" "),t.field.pivots&&t.display?n("modal",{attrs:{role:"dialog"},on:{"modal-close":t.handleClose}},[n("loading-view",{attrs:{loading:t.loading}},[n("card",{class:"w-action-fields"},[n("form-heading-field",{staticClass:"mb-6 pt-6",attrs:{field:{asHtml:!0,value:t.display.text}}}),t._v(" "),n("div",{staticClass:"mb-6 py-3 px-6"},t._l(t.fields,function(e,r){return n("detail-"+e.component,{key:r,tag:"component",attrs:{"resource-name":t.resourceName,field:e,"via-resource":t.viaResource,"via-resource-id":t.viaResourceId,"via-relationship":t.viaRelationship}})}),1),t._v(" "),n("div",{staticClass:"px-6 py-3 flex"},[n("div",{staticClass:"flex items-center ml-auto"},[n("button",{staticClass:"btn btn-link dim cursor-pointer text-80 ml-auto mr-6",attrs:{type:"button"},on:{click:function(e){return e.preventDefault(),t.handleClose(e)}}},[t._v(t._s(t.__("Close")))]),t._v(" "),n("router-link",{staticClass:"no-underline font-bold dim text-primary",attrs:{to:{name:"detail",params:{resourceName:t.field.resourceName,resourceId:t.display.id}},title:t.__("View")}},[t._v("\n \t\t\t\t"+t._s(t.__(":resource Details",{resource:t.display.text}))+"\n\t\t\t\t\t\t\t ")])],1)])],1)],1)],1):t._e()],1):n("p",{attrs:{slot:"value"},slot:"value"},[t._v("—")])],2)},staticRenderFns:[]}},function(t,e,n){var r=n(0)(n(18),n(21),!1,function(t){n(13)},null,null);t.exports=r.exports},function(t,e,n){var r=n(14);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals);n(16)("a70556ba",r,!0,{})},function(t,e,n){(t.exports=n(15)(!1)).push([t.i,".vue-tags-input.ti-focus .ti-input{background-color:var(--white);outline:0;-webkit-box-shadow:0 0 0 3px var(--primary-50);box-shadow:0 0 0 3px var(--primary-50)}.vue-tags-input{max-width:100%!important}.ti-input{border-color:var(--60)!important;border-radius:.5rem!important;padding:2px!important}.ti-autocomplete{overflow-y:scroll;max-height:200px}.ti-autocomplete .ti-item{padding:5px}.ti-icon-close:hover,.ti-tag-center svg:hover polygon,.ti-tag-center svg:hover rect{fill:var(--black);color:var(--black)}.ti-tags .ti-tag{border-radius:8px!important;margin:3px!important}.ti-tags .ti-tag.ti-valid{background:var(--success)!important}.ti-autocomplete .ti-item.ti-selected-item{background:var(--info)!important}",""])},function(t,e){t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var n=function(t,e){var n=t[1]||"",r=t[3];if(!r)return n;if(e&&"function"==typeof btoa){var i=(u=r,"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(u))))+" */"),o=r.sources.map(function(t){return"/*# sourceURL="+r.sourceRoot+t+" */"});return[n].concat(o).concat([i]).join("\n")}var u;return[n].join("\n")}(e,t);return e[2]?"@media "+e[2]+"{"+n+"}":n}).join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},i=0;i<this.length;i++){var o=this[i][0];"number"==typeof o&&(r[o]=!0)}for(i=0;i<t.length;i++){var u=t[i];"number"==typeof u[0]&&r[u[0]]||(n&&!u[2]?u[2]=n:n&&(u[2]="("+u[2]+") and ("+n+")"),e.push(u))}},e}},function(t,e,n){var r="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!r)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var i=n(17),o={},u=r&&(document.head||document.getElementsByTagName("head")[0]),a=null,s=0,c=!1,f=function(){},l=null,A="data-vue-ssr-id",p="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());function d(t){for(var e=0;e<t.length;e++){var n=t[e],r=o[n.id];if(r){r.refs++;for(var i=0;i<r.parts.length;i++)r.parts[i](n.parts[i]);for(;i<n.parts.length;i++)r.parts.push(v(n.parts[i]));r.parts.length>n.parts.length&&(r.parts.length=n.parts.length)}else{var u=[];for(i=0;i<n.parts.length;i++)u.push(v(n.parts[i]));o[n.id]={id:n.id,refs:1,parts:u}}}}function h(){var t=document.createElement("style");return t.type="text/css",u.appendChild(t),t}function v(t){var e,n,r=document.querySelector("style["+A+'~="'+t.id+'"]');if(r){if(c)return f;r.parentNode.removeChild(r)}if(p){var i=s++;r=a||(a=h()),e=y.bind(null,r,i,!1),n=y.bind(null,r,i,!0)}else r=h(),e=function(t,e){var n=e.css,r=e.media,i=e.sourceMap;r&&t.setAttribute("media",r);l.ssrId&&t.setAttribute(A,e.id);i&&(n+="\n/*# sourceURL="+i.sources[0]+" */",n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */");if(t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}.bind(null,r),n=function(){r.parentNode.removeChild(r)};return e(t),function(r){if(r){if(r.css===t.css&&r.media===t.media&&r.sourceMap===t.sourceMap)return;e(t=r)}else n()}}t.exports=function(t,e,n,r){c=n,l=r||{};var u=i(t,e);return d(u),function(e){for(var n=[],r=0;r<u.length;r++){var a=u[r];(s=o[a.id]).refs--,n.push(s)}e?d(u=i(t,e)):u=[];for(r=0;r<n.length;r++){var s;if(0===(s=n[r]).refs){for(var c=0;c<s.parts.length;c++)s.parts[c]();delete o[s.id]}}}};var g,m=(g=[],function(t,e){return g[t]=e,g.filter(Boolean).join("\n")});function y(t,e,n,r){var i=n?"":r.css;if(t.styleSheet)t.styleSheet.cssText=m(e,i);else{var o=document.createTextNode(i),u=t.childNodes;u[e]&&t.removeChild(u[e]),u.length?t.insertBefore(o,u[e]):t.appendChild(o)}}},function(t,e){t.exports=function(t,e){for(var n=[],r={},i=0;i<e.length;i++){var o=e[i],u=o[0],a={id:t+":"+i,css:o[1],media:o[2],sourceMap:o[3]};r[u]?r[u].parts.push(a):n.push(r[u]={id:u,parts:[a]})}return n}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),i=n.n(r),o=n(19),u=(n.n(o),n(20)),a=(n.n(u),"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t});function s(t){return function(){var e=t.apply(this,arguments);return new Promise(function(t,n){return function r(i,o){try{var u=e[i](o),a=u.value}catch(t){return void n(t)}if(!u.done)return Promise.resolve(a).then(function(t){r("next",t)},function(t){r("throw",t)});t(a)}("next")})}}e.default={mixins:[o.FormField,o.HandlesValidationErrors],components:{VueTagsInput:u.VueTagsInput},props:["resourceName","resourceId","field"],data:function(){var t=this;return{tag:"",attachedResources:[],pivots:[],fields:[],search:"",loading:!1,validationErrors:new o.Errors,processingResource:null,resourceProcessor:null,cancelCallback:function(){return t.resetCallbak()},attachCallback:function(){return t.resetCallbak()},resetCallbak:function(){this.processingResource=null,this.resourceProcessor=null},processing:!1,availableResources:[],withTrashed:!1,softDeletes:!1,parentValue:""}},created:function(){this.field.searchable||this.getAvailableResources(),this.getAttachedResources(),this.field.parent_attribute&&this.watchParentComponents()},methods:{watchParentComponents:function(){var t=this;this.watchedComponents.forEach(function(e){var n="value";"belongs-to-field"===e.field.component&&(n="selectedResource"),"armincms-belongs-to-many"===e.field.component&&(n="attachedResources"),e.$watch(n,function(e){if(t.parentValue=e&&"selectedResource"==n?e.value:e,"attachedResources"===n){var r=e.map(function(t){return t.id});0===r.length&&(r=[0]),t.parentValue=r.join("-")}t.updateOptions()},{immediate:!0})})},isWatchingComponent:function(t){return void 0!==t.field&&t.field.attribute==this.field.parent_attribute},updateOptions:function(){var t=this;null!=this.parentValue&&""!=this.parentValue&&Nova.request().get(this.endpoint).then(function(e){var n=e.data;t.availableResources=n})},setInitialValue:function(){this.attachedResources=[]},fill:function(t){0==this.fillResources.length?t.append(this.field.attribute,this.fillResources):this.appendToForm(this.fillResources,t,this.field.attribute)},performSearch:function(t){var e=this;this.field.searchable&&(this.search=t,_.debounce(function(){e.search==t&&e.search.length>0&&e.getAvailableResources()},Nova.config.debounce)())},appendToForm:function(t,e,n){for(var r in t)"pivotAccessor"==r?this.mergeFormData(this.pivots[t[r]],e,n+this.wrap("pivots")):"object"==a(t[r])?this.appendToForm(t[r],e,n+this.wrap(r)):e.append(n+this.wrap(r),t[r])},mergeFormData:function(t,e,n){var r=!0,i=!1,o=void 0;try{for(var u,a=t.entries()[Symbol.iterator]();!(r=(u=a.next()).done);r=!0){var s=u.value;e.append(n+this.wrap(s[0]),s[1])}}catch(t){i=!0,o=t}finally{try{!r&&a.return&&a.return()}finally{if(i)throw o}}},wrap:function(t){return t.replace(/^([^\[]+)/,function(t){return"["+t+"]"})},handleChange:function(t){this.attachedResources=t},addingTag:function(t){console.log("adding tag:",t.tag.text),this.processTheResource(t.tag,t.addTag)},editingTag:function(t){console.log("editing tag:",t.tag.text),this.processTheResource(t.tag,t.editTag)},isDuplicate:function(t,e){return!this.field.duplicate&&t.map(function(t){return t.id}).indexOf(e.id)>=0},performEditTag:function(t){var e=this;this.field.pivots&&(this.cancelCallback=function(){t.performCancelEdit(t.index),e.attachCallback=e.cancelCallback=function(){}},this.attachCallback=function(){return t.performSaveEdit(t.index),e.attachCallback=e.cancelCallback=function(){},t.index},t.performOpenEdit(t.index))},attachTheResource:function(){var t=s(i.a.mark(function t(){var e;return i.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.validatePivotFields(this.processingResource);case 2:if(!t.sent){t.next=15;break}return t.next=5,this.resourceProcessor();case 5:return console.log("attached the resource:",this.processingResource.text),t.next=8,this.attachCallback();case 8:return e=t.sent,t.next=11,this.resetCallbak();case 11:e="number"==typeof e?e:this.attachedResources.length-1,this.pivots[e]=this.attachmentFormData,this.$set(this.attachedResources,e,_.tap(this.attachedResources[e],function(t){t.attached=!1,t.pivotAccessor=e})),this.processingModal=!1;case 15:case"end":return t.stop()}},t,this)}));return function(){return t.apply(this,arguments)}}(),validatePivotFields:function(){var t=s(i.a.mark(function t(e){return i.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!(this.fields.length>0)){t.next=10;break}return t.prev=1,t.next=4,this.validateRequest(e);case 4:t.next=10;break;case 6:return t.prev=6,t.t0=t.catch(1),422==t.t0.response.status&&(this.validationErrors=new o.Errors(t.t0.response.data.errors),Nova.error(this.__("There was a problem submitting the form."))),t.abrupt("return",!1);case 10:return t.abrupt("return",!0);case 11:case"end":return t.stop()}},t,this,[[1,6]])}));return function(e){return t.apply(this,arguments)}}(),validateRequest:function(t){return Nova.request().post("/nova-api/armincms/"+this.resourceName+"/pivots-validate/"+this.field.resourceName,this.attachmentFormData,{params:{field:this.field.attribute,resourceId:this.resourceId,relatedId:this.processingResource.id,editing:!0,editMode:t.attached?"update-attached":"attach"}})},processTheResource:function(){var t=s(i.a.mark(function t(e,n){return i.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(this.validationErrors=new o.Errors,this.loading=!0,this.processingResource=e,this.resourceProcessor=n,t.t0=this.field.pivots,!t.t0){t.next=8;break}return t.next=8,this.getPivotFields(e);case 8:this.processingModal=this.fields.length>0||this.attachTheResource(),this.loading=!1,console.log("processing resource:",this.processingResource.text);case 11:case"end":return t.stop()}},t,this)}));return function(e,n){return t.apply(this,arguments)}}(),triggerLoading:function(){this.loading=!this.loading},cancelProcessing:function(){this.processingModal=!1,console.log("canceled attachment:",this.processingResource.text),this.cancelCallback(),this.$emit("close"),this.resetCallbak()},getAvailableResources:function(){var t=this;Nova.request().get("/nova-api/armincms/"+this.resourceName+"/attachable/"+this.field.resourceName,{params:{search:this.search,field:this.field.attribute,resourceId:this.resourceId,withTrashed:this.field.withTrashed}}).then(function(e){var n=e.data;t.availableResources=n})},getAttachedResources:function(){var t=this;Nova.request().get("/nova-api/armincms/"+this.resourceName+"/attached/"+this.field.resourceName,{params:{field:this.field.attribute,resourceId:this.resourceId,withTrashed:this.field.withTrashed}}).then(function(e){var n=e.data;t.attachedResources=n})},createTag:function(t){return _.tap(Object(u.createTag)(t.text,this.attachedResources),function(e){e.attached=t.attached,e.id=t.id})},getPivotFields:function(){var t=s(i.a.mark(function t(e){var n=this;return i.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,Nova.request().get("/nova-api/armincms/"+this.resourceName+"/pivot-fields/"+this.field.resourceName,{params:{field:this.field.attribute,resourceId:this.resourceId,relatedId:this.processingResource.id,pivotId:this.processingResource.pivotId,editing:!0,editMode:e.attached?"update-attached":"attach"}}).then(function(t){var r=t.data;n.fields=r,_.each(n.fields,function(t){t.fill=function(){return""};var r=n.pivots[e.pivotAccessor]?n.pivots[e.pivotAccessor]:new FormData;r.has(t.attribute)&&(t.value=r.getAll(t.attribute))})});case 2:case"end":return t.stop()}},t,this)}));return function(e){return t.apply(this,arguments)}}()},computed:{watchedComponents:function(){var t=this;return this.field.parent_attribute?this.$parent.$children.filter(function(e){return t.isWatchingComponent(e)}):[]},endpoint:function(){return this.field.endpoint.replace("{resource-name}",this.resourceName).replace("{resource-id}",this.resourceId?this.resourceId:"").replace("{"+this.field.parent_attribute+"}",this.parentValue?this.parentValue:"")},filteredResources:function(){var t=this;return this.availableResources.filter(function(e){return 0===t.tag.length||e.text.match(t.tag)})},attachmentFormData:function(){var t=this;return _.tap(new FormData,function(e){_.each(t.fields,function(t){t.fill(e)})})},placeholder:function(){return this.field.placeholder||this.__("Choose an option")},fillResources:function(){return this.attachedResources.map(function(t){return delete t.text,delete t.tiClasses,t})}}}},function(t,e,n){var r;r=function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.i=function(t){return t},n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r})},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=40)}([function(t,e,n){"use strict";var r=n(39),i=n(152),o=Object.prototype.toString;function u(t){return"[object Array]"===o.call(t)}function a(t){return null!==t&&"object"==typeof t}function s(t){return"[object Function]"===o.call(t)}function c(t,e){if(null!==t&&void 0!==t)if("object"!=typeof t&&(t=[t]),u(t))for(var n=0,r=t.length;n<r;n++)e.call(null,t[n],n,t);else for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.call(null,t[i],i,t)}t.exports={isArray:u,isArrayBuffer:function(t){return"[object ArrayBuffer]"===o.call(t)},isBuffer:i,isFormData:function(t){return"undefined"!=typeof FormData&&t instanceof FormData},isArrayBufferView:function(t){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&t.buffer instanceof ArrayBuffer},isString:function(t){return"string"==typeof t},isNumber:function(t){return"number"==typeof t},isObject:a,isUndefined:function(t){return void 0===t},isDate:function(t){return"[object Date]"===o.call(t)},isFile:function(t){return"[object File]"===o.call(t)},isBlob:function(t){return"[object Blob]"===o.call(t)},isFunction:s,isStream:function(t){return a(t)&&s(t.pipe)},isURLSearchParams:function(t){return"undefined"!=typeof URLSearchParams&&t instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:c,merge:function t(){var e={};function n(n,r){"object"==typeof e[r]&&"object"==typeof n?e[r]=t(e[r],n):e[r]=n}for(var r=0,i=arguments.length;r<i;r++)c(arguments[r],n);return e},extend:function(t,e,n){return c(e,function(e,i){t[i]=n&&"function"==typeof e?r(e,n):e}),t},trim:function(t){return t.replace(/^\s*/,"").replace(/\s*$/,"")}}},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e,n){var r=n(53)("wks"),i=n(58),o=n(1).Symbol,u="function"==typeof o;(t.exports=function(t){return r[t]||(r[t]=u&&o[t]||(u?o:i)("Symbol."+t))}).store=r},function(t,e){var n=t.exports={version:"2.5.7"};"number"==typeof __e&&(__e=n)},function(t,e,n){var r=n(9);t.exports=function(t){if(!r(t))throw TypeError(t+" is not an object!");return t}},function(t,e,n){t.exports=!n(23)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(1),i=n(3),o=n(14),u=n(7),a=n(15),s=function(t,e,n){var c,f,l,A=t&s.F,p=t&s.G,d=t&s.S,h=t&s.P,v=t&s.B,g=t&s.W,m=p?i:i[e]||(i[e]={}),y=m.prototype,_=p?r:d?r[e]:(r[e]||{}).prototype;for(c in p&&(n=e),n)(f=!A&&_&&void 0!==_[c])&&a(m,c)||(l=f?_[c]:n[c],m[c]=p&&"function"!=typeof _[c]?n[c]:v&&f?o(l,r):g&&_[c]==l?function(t){var e=function(e,n,r){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,n)}return new t(e,n,r)}return t.apply(this,arguments)};return e.prototype=t.prototype,e}(l):h&&"function"==typeof l?o(Function.call,l):l,h&&((m.virtual||(m.virtual={}))[c]=l,t&s.R&&y&&!y[c]&&u(y,c,l)))};s.F=1,s.G=2,s.S=4,s.P=8,s.B=16,s.W=32,s.U=64,s.R=128,t.exports=s},function(t,e,n){var r=n(11),i=n(52);t.exports=n(5)?function(t,e,n){return r.f(t,e,i(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e){t.exports=function(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e){t.exports={}},function(t,e,n){var r=n(4),i=n(118),o=n(138),u=Object.defineProperty;e.f=n(5)?Object.defineProperty:function(t,e,n){if(r(t),e=o(e,!0),r(n),i)try{return u(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e,n){var r=n(12);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,i){return t.call(e,n,r,i)}}return function(){return t.apply(e,arguments)}}},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){var r=n(30),i=n(172),o=n(179),u="[object Null]",a="[object Undefined]",s=r?r.toStringTag:void 0;t.exports=function(t){return null==t?void 0===t?a:u:s&&s in Object(t)?i(t):o(t)}},function(t,e,n){var r=n(60),i="object"==typeof self&&self&&self.Object===Object&&self,o=r||i||Function("return this")();t.exports=o},function(t,e){t.exports=function(t){return null!=t&&"object"==typeof t}},function(t,e,n){"use strict";(function(e){var r=n(0),i=n(105),o={"Content-Type":"application/x-www-form-urlencoded"};function u(t,e){!r.isUndefined(t)&&r.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}var a,s={adapter:("undefined"!=typeof XMLHttpRequest?a=n(35):void 0!==e&&(a=n(35)),a),transformRequest:[function(t,e){return i(e,"Content-Type"),r.isFormData(t)||r.isArrayBuffer(t)||r.isBuffer(t)||r.isStream(t)||r.isFile(t)||r.isBlob(t)?t:r.isArrayBufferView(t)?t.buffer:r.isURLSearchParams(t)?(u(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):r.isObject(t)?(u(e,"application/json;charset=utf-8"),JSON.stringify(t)):t}],transformResponse:[function(t){if("string"==typeof t)try{t=JSON.parse(t)}catch(t){}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(t){return t>=200&&t<300}};s.headers={common:{Accept:"application/json, text/plain, */*"}},r.forEach(["delete","get","head"],function(t){s.headers[t]={}}),r.forEach(["post","put","patch"],function(t){s.headers[t]=r.merge(o)}),t.exports=s}).call(e,n(70))},function(t,e,n){"use strict";e.__esModule=!0;var r,i=n(109),o=(r=i)&&r.__esModule?r:{default:r};e.default=function(t,e,n){return e in t?(0,o.default)(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,n){var r=n(9),i=n(1).document,o=r(i)&&r(i.createElement);t.exports=function(t){return o?i.createElement(t):{}}},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e){t.exports=!0},function(t,e,n){"use strict";var r=n(12);t.exports.f=function(t){return new function(t){var e,n;this.promise=new t(function(t,r){if(void 0!==e||void 0!==n)throw TypeError("Bad Promise constructor");e=t,n=r}),this.resolve=r(e),this.reject=r(n)}(t)}},function(t,e,n){var r=n(11).f,i=n(15),o=n(2)("toStringTag");t.exports=function(t,e,n){t&&!i(t=n?t:t.prototype,o)&&r(t,o,{configurable:!0,value:e})}},function(t,e,n){var r=n(53)("keys"),i=n(58);t.exports=function(t){return r[t]||(r[t]=i(t))}},function(t,e){var n=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:n)(t)}},function(t,e,n){var r=n(47),i=n(21);t.exports=function(t){return r(i(t))}},function(t,e,n){var r=n(17).Symbol;t.exports=r},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.mapProps=void 0;var r,i=n(193),o=(r=i)&&r.__esModule?r:{default:r};var u={showHelpText:{type:Boolean,default:!1},shownViaNewRelationModal:{type:Boolean,default:!1},resourceId:{type:[Number,String]},resourceName:{type:String},field:{type:Object,required:!0},viaResource:{type:String,required:!1},viaResourceId:{type:[String,Number],required:!1},viaRelationship:{type:String,required:!1},shouldOverrideMeta:{type:Boolean,default:!1}};e.mapProps=function(t){return o.default.pick(u,t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=["1/2","1/3","2/3","1/4","3/4","1/5","2/5","3/5","4/5","1/6","5/6"]},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(150);Object.defineProperty(e,"default",{enumerable:!0,get:function(){return o(r).default}}),Object.defineProperty(e,"Form",{enumerable:!0,get:function(){return o(r).default}});var i=n(59);function o(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"Errors",{enumerable:!0,get:function(){return o(i).default}})},function(t,e,n){"use strict";(function(e){var r=n(0),i=n(97),o=n(100),u=n(106),a=n(104),s=n(38),c="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||n(99);t.exports=function(t){return new Promise(function(f,l){var A=t.data,p=t.headers;r.isFormData(A)&&delete p["Content-Type"];var d=new XMLHttpRequest,h="onreadystatechange",v=!1;if("test"===e.env.NODE_ENV||"undefined"==typeof window||!window.XDomainRequest||"withCredentials"in d||a(t.url)||(d=new window.XDomainRequest,h="onload",v=!0,d.onprogress=function(){},d.ontimeout=function(){}),t.auth){var g=t.auth.username||"",m=t.auth.password||"";p.Authorization="Basic "+c(g+":"+m)}if(d.open(t.method.toUpperCase(),o(t.url,t.params,t.paramsSerializer),!0),d.timeout=t.timeout,d[h]=function(){if(d&&(4===d.readyState||v)&&(0!==d.status||d.responseURL&&0===d.responseURL.indexOf("file:"))){var e="getAllResponseHeaders"in d?u(d.getAllResponseHeaders()):null,n={data:t.responseType&&"text"!==t.responseType?d.response:d.responseText,status:1223===d.status?204:d.status,statusText:1223===d.status?"No Content":d.statusText,headers:e,config:t,request:d};i(f,l,n),d=null}},d.onerror=function(){l(s("Network Error",t,null,d)),d=null},d.ontimeout=function(){l(s("timeout of "+t.timeout+"ms exceeded",t,"ECONNABORTED",d)),d=null},r.isStandardBrowserEnv()){var y=n(102),_=(t.withCredentials||a(t.url))&&t.xsrfCookieName?y.read(t.xsrfCookieName):void 0;_&&(p[t.xsrfHeaderName]=_)}if("setRequestHeader"in d&&r.forEach(p,function(t,e){void 0===A&&"content-type"===e.toLowerCase()?delete p[e]:d.setRequestHeader(e,t)}),t.withCredentials&&(d.withCredentials=!0),t.responseType)try{d.responseType=t.responseType}catch(e){if("json"!==t.responseType)throw e}"function"==typeof t.onDownloadProgress&&d.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&d.upload&&d.upload.addEventListener("progress",t.onUploadProgress),t.cancelToken&&t.cancelToken.promise.then(function(t){d&&(d.abort(),l(t),d=null)}),void 0===A&&(A=null),d.send(A)})}}).call(e,n(70))},function(t,e,n){"use strict";function r(t){this.message=t}r.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},r.prototype.__CANCEL__=!0,t.exports=r},function(t,e,n){"use strict";t.exports=function(t){return!(!t||!t.__CANCEL__)}},function(t,e,n){"use strict";var r=n(96);t.exports=function(t,e,n,i,o){var u=new Error(t);return r(u,e,n,i,o)}},function(t,e,n){"use strict";t.exports=function(t,e){return function(){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return t.apply(e,n)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.mapProps=e.CardSizes=e.SingularOrPlural=e.Minimum=e.Capitalize=e.Inflector=e.Errors=e.TogglesTrashed=e.PreventsFormAbandonment=e.PerPageable=e.PerformsSearches=e.Paginatable=e.InteractsWithResourceInformation=e.InteractsWithQueryString=e.InteractsWithDates=e.HasCards=e.HandlesValidationErrors=e.FormField=e.Filterable=e.Deletable=e.BehavesAsPanel=void 0;var r=E(n(72)),i=E(n(73)),o=E(n(74)),u=E(n(75)),a=E(n(76)),s=E(n(77)),c=E(n(78)),f=E(n(79)),l=E(n(80)),A=E(n(81)),p=E(n(83)),d=E(n(82)),h=E(n(84)),v=E(n(85)),g=E(n(89)),m=E(n(33)),y=E(n(86)),_=E(n(87)),b=n(34),w=E(n(88)),x=n(32);function E(t){return t&&t.__esModule?t:{default:t}}e.BehavesAsPanel=r.default,e.Deletable=i.default,e.Filterable=o.default,e.FormField=u.default,e.HandlesValidationErrors=a.default,e.HasCards=s.default,e.InteractsWithDates=c.default,e.InteractsWithQueryString=f.default,e.InteractsWithResourceInformation=l.default,e.Paginatable=A.default,e.PerformsSearches=p.default,e.PerPageable=d.default,e.PreventsFormAbandonment=h.default,e.TogglesTrashed=v.default,e.Errors=b.Errors,e.Inflector=g.default,e.Capitalize=y.default,e.Minimum=_.default,e.SingularOrPlural=w.default,e.CardSizes=m.default,e.mapProps=x.mapProps},function(t,e,n){t.exports={default:n(113),__esModule:!0}},function(t,e,n){"use strict";e.__esModule=!0;var r,i=n(41),o=(r=i)&&r.__esModule?r:{default:r};e.default=function(t){return function(){var e=t.apply(this,arguments);return new o.default(function(t,n){return function r(i,u){try{var a=e[i](u),s=a.value}catch(t){return void n(t)}if(!a.done)return o.default.resolve(s).then(function(t){r("next",t)},function(t){r("throw",t)});t(s)}("next")})}}},function(t,e,n){t.exports=n(199)},function(t,e,n){var r=n(13),i=n(2)("toStringTag"),o="Arguments"==r(function(){return arguments}());t.exports=function(t){var e,n,u;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(n=function(t,e){try{return t[e]}catch(t){}}(e=Object(t),i))?n:o?r(e):"Object"==(u=r(e))&&"function"==typeof e.callee?"Arguments":u}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,n){var r=n(1).document;t.exports=r&&r.documentElement},function(t,e,n){var r=n(13);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==r(t)?t.split(""):Object(t)}},function(t,e,n){"use strict";var r=n(24),i=n(6),o=n(134),u=n(7),a=n(10),s=n(122),c=n(26),f=n(130),l=n(2)("iterator"),A=!([].keys&&"next"in[].keys()),p=function(){return this};t.exports=function(t,e,n,d,h,v,g){s(n,e,d);var m,y,_,b=function(t){if(!A&&t in C)return C[t];switch(t){case"keys":case"values":return function(){return new n(this,t)}}return function(){return new n(this,t)}},w=e+" Iterator",x="values"==h,E=!1,C=t.prototype,B=C[l]||C["@@iterator"]||h&&C[h],j=B||b(h),R=h?x?b("entries"):j:void 0,S="Array"==e&&C.entries||B;if(S&&(_=f(S.call(new t)))!==Object.prototype&&_.next&&(c(_,w,!0),r||"function"==typeof _[l]||u(_,l,p)),x&&B&&"values"!==B.name&&(E=!0,j=function(){return B.call(this)}),r&&!g||!A&&!E&&C[l]||u(C,l,j),a[e]=j,a[w]=p,h)if(m={values:x?j:b("values"),keys:v?j:b("keys"),entries:R},g)for(y in m)y in C||o(C,y,m[y]);else i(i.P+i.F*(A||E),e,m);return m}},function(t,e,n){var r=n(131),i=n(45);t.exports=Object.keys||function(t){return r(t,i)}},function(t,e){t.exports=function(t){try{return{e:!1,v:t()}}catch(t){return{e:!0,v:t}}}},function(t,e,n){var r=n(4),i=n(9),o=n(25);t.exports=function(t,e){if(r(t),i(e)&&e.constructor===t)return e;var n=o.f(t);return(0,n.resolve)(e),n.promise}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){var r=n(3),i=n(1),o=i["__core-js_shared__"]||(i["__core-js_shared__"]={});(t.exports=function(t,e){return o[t]||(o[t]=void 0!==e?e:{})})("versions",[]).push({version:r.version,mode:n(24)?"pure":"global",copyright:"© 2018 Denis Pushkarev (zloirock.ru)"})},function(t,e,n){var r=n(4),i=n(12),o=n(2)("species");t.exports=function(t,e){var n,u=r(t).constructor;return void 0===u||void 0==(n=r(u)[o])?e:i(n)}},function(t,e,n){var r,i,o,u=n(14),a=n(119),s=n(46),c=n(22),f=n(1),l=f.process,A=f.setImmediate,p=f.clearImmediate,d=f.MessageChannel,h=f.Dispatch,v=0,g={},m=function(){var t=+this;if(g.hasOwnProperty(t)){var e=g[t];delete g[t],e()}},y=function(t){m.call(t.data)};A&&p||(A=function(t){for(var e=[],n=1;arguments.length>n;)e.push(arguments[n++]);return g[++v]=function(){a("function"==typeof t?t:Function(t),e)},r(v),v},p=function(t){delete g[t]},"process"==n(13)(l)?r=function(t){l.nextTick(u(m,t,1))}:h&&h.now?r=function(t){h.now(u(m,t,1))}:d?(o=(i=new d).port2,i.port1.onmessage=y,r=u(o.postMessage,o,1)):f.addEventListener&&"function"==typeof postMessage&&!f.importScripts?(r=function(t){f.postMessage(t+"","*")},f.addEventListener("message",y,!1)):r="onreadystatechange"in c("script")?function(t){s.appendChild(c("script")).onreadystatechange=function(){s.removeChild(this),m.call(t)}}:function(t){setTimeout(u(m,t,1),0)}),t.exports={set:A,clear:p}},function(t,e,n){var r=n(28),i=Math.min;t.exports=function(t){return t>0?i(r(t),9007199254740991):0}},function(t,e,n){var r=n(21);t.exports=function(t){return Object(r(t))}},function(t,e){var n=0,r=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++n+r).toString(36))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}();var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.record(e)}return r(t,[{key:"all",value:function(){return this.errors}},{key:"has",value:function(t){var e=this.errors.hasOwnProperty(t);e||(e=Object.keys(this.errors).filter(function(e){return e.startsWith(t+".")||e.startsWith(t+"[")}).length>0);return e}},{key:"first",value:function(t){return this.get(t)[0]}},{key:"get",value:function(t){return this.errors[t]||[]}},{key:"any",value:function(){return Object.keys(this.errors).length>0}},{key:"record",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.errors=t}},{key:"clear",value:function(t){if(t){var e=Object.assign({},this.errors);Object.keys(e).filter(function(e){return e===t||e.startsWith(t+".")||e.startsWith(t+"[")}).forEach(function(t){return delete e[t]}),this.errors=e}else this.errors={}}}]),t}();e.default=i},function(t,e,n){(function(e){var n="object"==typeof e&&e&&e.Object===Object&&e;t.exports=n}).call(e,n(71))},function(t,e){var n=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");t.exports=function(t){return n.test(t)}},function(t,e){var n=9007199254740991,r=/^(?:0|[1-9]\d*)$/;t.exports=function(t,e){var i=typeof t;return!!(e=null==e?n:e)&&("number"==i||"symbol"!=i&&r.test(t))&&t>-1&&t%1==0&&t<e}},function(t,e){t.exports=function(t,e){return t===e||t!=t&&e!=e}},function(t,e){t.exports=function(t){return t}},function(t,e){var n=Array.isArray;t.exports=n},function(t,e,n){var r=n(67),i=n(68);t.exports=function(t){return null!=t&&i(t.length)&&!r(t)}},function(t,e,n){var r=n(16),i=n(8),o="[object AsyncFunction]",u="[object Function]",a="[object GeneratorFunction]",s="[object Proxy]";t.exports=function(t){if(!i(t))return!1;var e=r(t);return e==u||e==a||e==o||e==s}},function(t,e){var n=9007199254740991;t.exports=function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=n}},function(t,e,n){var r=n(16),i=n(18),o="[object Symbol]";t.exports=function(t){return"symbol"==typeof t||i(t)&&r(t)==o}},function(t,e){var n,r,i=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function u(){throw new Error("clearTimeout has not been defined")}function a(t){if(n===setTimeout)return setTimeout(t,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(t){n=o}try{r="function"==typeof clearTimeout?clearTimeout:u}catch(t){r=u}}();var s,c=[],f=!1,l=-1;function A(){f&&s&&(f=!1,s.length?c=s.concat(c):l=-1,c.length&&p())}function p(){if(!f){var t=a(A);f=!0;for(var e=c.length;e;){for(s=c,c=[];++l<e;)s&&s[l].run();l=-1,e=c.length}s=null,f=!1,function(t){if(r===clearTimeout)return clearTimeout(t);if((r===u||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(t);try{r(t)}catch(e){try{return r.call(null,t)}catch(e){return r.call(this,t)}}}(t)}}function d(t,e){this.fun=t,this.array=e}function h(){}i.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];c.push(new d(t,e)),1!==c.length||f||a(p)},d.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=h,i.addListener=h,i.once=h,i.off=h,i.removeListener=h,i.removeAllListeners=h,i.emit=h,i.prependListener=h,i.prependOnceListener=h,i.listeners=function(t){return[]},i.binding=function(t){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(t){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={props:["resourceName","resourceId","resource","panel"],methods:{actionExecuted:function(){this.$emit("actionExecuted")}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(110),o=(r=i)&&r.__esModule?r:{default:r};function u(t){return _.map(t,function(t){return t.id.value})}e.default={methods:{openDeleteModal:function(){this.deleteModalOpen=!0},deleteResources:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return this.viaManyToMany?this.detachResources(t):Nova.request({url:"/nova-api/"+this.resourceName,method:"delete",params:(0,o.default)({},this.queryString,{resources:u(t)})}).then(n||function(){e.deleteModalOpen=!1,e.getResources()})},deleteSelectedResources:function(){this.deleteResources(this.selectedResources)},deleteAllMatchingResources:function(){var t=this;return this.viaManyToMany?this.detachAllMatchingResources():Nova.request({url:this.deleteAllMatchingResourcesEndpoint,method:"delete",params:(0,o.default)({},this.queryString,{resources:"all"})}).then(function(){t.deleteModalOpen=!1,t.getResources()})},detachResources:function(t){var e=this;return Nova.request({url:"/nova-api/"+this.resourceName+"/detach",method:"delete",params:(0,o.default)({},this.queryString,{resources:u(t)},{pivots:function(t){return _.filter(_.map(t,function(t){return t.id.pivotValue}))}(t)})}).then(function(){e.deleteModalOpen=!1,e.getResources()})},detachAllMatchingResources:function(){var t=this;return Nova.request({url:"/nova-api/"+this.resourceName+"/detach",method:"delete",params:(0,o.default)({},this.queryString,{resources:"all"})}).then(function(){t.deleteModalOpen=!1,t.getResources()})},forceDeleteResources:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return Nova.request({url:"/nova-api/"+this.resourceName+"/force",method:"delete",params:(0,o.default)({},this.queryString,{resources:u(t)})}).then(n||function(){e.deleteModalOpen=!1,e.getResources()})},forceDeleteSelectedResources:function(){this.forceDeleteResources(this.selectedResources)},forceDeleteAllMatchingResources:function(){var t=this;return Nova.request({url:this.forceDeleteSelectedResourcesEndpoint,method:"delete",params:(0,o.default)({},this.queryString,{resources:"all"})}).then(function(){t.deleteModalOpen=!1,t.getResources()})},restoreResources:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return Nova.request({url:"/nova-api/"+this.resourceName+"/restore",method:"put",params:(0,o.default)({},this.queryString,{resources:u(t)})}).then(n||function(){e.restoreModalOpen=!1,e.getResources()})},restoreSelectedResources:function(){this.restoreResources(this.selectedResources)},restoreAllMatchingResources:function(){var t=this;return Nova.request({url:this.restoreAllMatchingResourcesEndpoint,method:"put",params:(0,o.default)({},this.queryString,{resources:"all"})}).then(function(){t.restoreModalOpen=!1,t.getResources()})}},computed:{deleteAllMatchingResourcesEndpoint:function(){return this.lens?"/nova-api/"+this.resourceName+"/lens/"+this.lens:"/nova-api/"+this.resourceName},forceDeleteSelectedResourcesEndpoint:function(){return this.lens?"/nova-api/"+this.resourceName+"/lens/"+this.lens+"/force":"/nova-api/"+this.resourceName+"/force"},restoreAllMatchingResourcesEndpoint:function(){return this.lens?"/nova-api/"+this.resourceName+"/lens/"+this.lens+"/restore":"/nova-api/"+this.resourceName+"/restore"},queryString:function(){return{search:this.currentSearch,filters:this.encodedFilters,trashed:this.currentTrashed,viaResource:this.viaResource,viaResourceId:this.viaResourceId,viaRelationship:this.viaRelationship}}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=u(n(43)),i=u(n(20)),o=u(n(42));function u(t){return t&&t.__esModule?t:{default:t}}e.default={methods:{clearSelectedFilters:function(){var t=(0,o.default)(r.default.mark(function t(e){var n;return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!e){t.next=5;break}return t.next=3,this.$store.dispatch(this.resourceName+"/resetFilterState",{resourceName:this.resourceName,lens:e});case 3:t.next=7;break;case 5:return t.next=7,this.$store.dispatch(this.resourceName+"/resetFilterState",{resourceName:this.resourceName});case 7:this.updateQueryString((n={},(0,i.default)(n,this.pageParameter,1),(0,i.default)(n,this.filterParameter,""),n));case 8:case"end":return t.stop()}},t,this)}));return function(e){return t.apply(this,arguments)}}(),filterChanged:function(){var t;this.updateQueryString((t={},(0,i.default)(t,this.pageParameter,1),(0,i.default)(t,this.filterParameter,this.$store.getters[this.resourceName+"/currentEncodedFilters"]),t))},initializeFilters:function(){var t=(0,o.default)(r.default.mark(function t(e){return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return this.$store.commit(this.resourceName+"/clearFilters"),t.next=3,this.$store.dispatch(this.resourceName+"/fetchFilters",{resourceName:this.resourceName,viaResource:this.viaResource,viaResourceId:this.viaResourceId,viaRelationship:this.viaRelationship,lens:e});case 3:return t.next=5,this.initializeState(e);case 5:case"end":return t.stop()}},t,this)}));return function(e){return t.apply(this,arguments)}}(),initializeState:function(){var t=(0,o.default)(r.default.mark(function t(e){return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.initialEncodedFilters){t.next=5;break}return t.next=3,this.$store.dispatch(this.resourceName+"/initializeCurrentFilterValuesFromQueryString",this.initialEncodedFilters);case 3:t.next=7;break;case 5:return t.next=7,this.$store.dispatch(this.resourceName+"/resetFilterState",{resourceName:this.resourceName,lens:e});case 7:case"end":return t.stop()}},t,this)}));return function(e){return t.apply(this,arguments)}}()},computed:{filterParameter:function(){return this.resourceName+"_filter"}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(32);e.default={props:(0,r.mapProps)(["shownViaNewRelationModal","field","viaResource","viaResourceId","viaRelationship","resourceName","showHelpText"]),data:function(){return{value:""}},mounted:function(){var t=this;this.setInitialValue(),this.field.fill=this.fill,Nova.$on(this.field.attribute+"-value",function(e){t.value=e})},destroyed:function(){Nova.$off(this.field.attribute+"-value")},methods:{setInitialValue:function(){this.value=void 0!==this.field.value&&null!==this.field.value?this.field.value:""},fill:function(t){t.append(this.field.attribute,String(this.value))},handleChange:function(t){this.value=t.target.value,this.field&&Nova.$emit(this.field.attribute+"-change",this.value)}},computed:{isReadonly:function(){return this.field.readonly||_.get(this.field,"extraAttributes.readonly")}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(34);e.default={props:{errors:{default:function(){return new r.Errors}}},data:function(){return{errorClass:"border-danger"}},computed:{errorClasses:function(){return this.hasError?[this.errorClass]:[]},fieldAttribute:function(){return this.field.attribute},validationKey:function(){return this.field.validationKey},hasError:function(){return this.errors.has(this.validationKey)},firstError:function(){if(this.hasError)return this.errors.first(this.validationKey)}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=u(n(43)),i=u(n(42)),o=u(n(33));function u(t){return t&&t.__esModule?t:{default:t}}e.default={props:{loadCards:{type:Boolean,default:!0}},data:function(){return{cards:[]}},created:function(){this.fetchCards()},watch:{cardsEndpoint:function(){this.fetchCards()}},methods:{fetchCards:function(){var t=(0,i.default)(r.default.mark(function t(){var e,n;return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.loadCards){t.next=6;break}return t.next=3,Nova.request().get(this.cardsEndpoint,{params:this.extraCardParams});case 3:e=t.sent,n=e.data,this.cards=n;case 6:case"end":return t.stop()}},t,this)}));return function(){return t.apply(this,arguments)}}()},computed:{shouldShowCards:function(){return this.cards.length>0},smallCards:function(){return _.filter(this.cards,function(t){return-1!==o.default.indexOf(t.width)})},largeCards:function(){return _.filter(this.cards,function(t){return"full"==t.width})},extraCardParams:function(){return null}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={methods:{toAppTimezone:function(t){return t?moment.tz(t,this.userTimezone).clone().tz(Nova.config.timezone).format("YYYY-MM-DD HH:mm:ss"):t},fromAppTimezone:function(t){return t?moment.tz(t,Nova.config.timezone).clone().tz(this.userTimezone).format("YYYY-MM-DD HH:mm:ss"):t},localizeDateTimeField:function(t){if(!t.value)return t.value;var e=moment.tz(t.value,Nova.config.timezone).clone().tz(this.userTimezone);return t.format?e.format(t.format):this.usesTwelveHourTime?e.format("YYYY-MM-DD h:mm:ss A"):e.format("YYYY-MM-DD HH:mm:ss")},localizeDateField:function(t){if(!t.value)return t.value;var e=moment.tz(t.value,Nova.config.timezone).clone().tz(this.userTimezone);return t.format?e.format(t.format):e.format("YYYY-MM-DD")}},computed:{userTimezone:function(){return Nova.config.userTimezone?Nova.config.userTimezone:moment.tz.guess()},usesTwelveHourTime:function(){return _.endsWith((new Date).toLocaleString(),"AM")||_.endsWith((new Date).toLocaleString(),"PM")}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(188),o=(r=i)&&r.__esModule?r:{default:r};e.default={methods:{updateQueryString:function(t){this.$router.push({query:(0,o.default)(t,this.$route.query)}).catch(function(t){if("NavigationDuplicated"!=t.name)throw t})}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={computed:{resourceInformation:function(){var t=this;return _.find(Nova.config.resources,function(e){return e.uriKey==t.resourceName})},viaResourceInformation:function(){var t=this;if(this.viaResource)return _.find(Nova.config.resources,function(e){return e.uriKey==t.viaResource})},authorizedToCreate:function(){return this.resourceInformation.authorizedToCreate}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(20),o=(r=i)&&r.__esModule?r:{default:r};e.default={methods:{selectPreviousPage:function(){this.updateQueryString((0,o.default)({},this.pageParameter,this.currentPage-1))},selectNextPage:function(){this.updateQueryString((0,o.default)({},this.pageParameter,this.currentPage+1))}},computed:{currentPage:function(){return parseInt(this.$route.query[this.pageParameter]||1)}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(20),o=(r=i)&&r.__esModule?r:{default:r};e.default={data:function(){return{perPage:25}},methods:{initializePerPageFromQueryString:function(){this.perPage=this.currentPerPage},perPageChanged:function(){this.updateQueryString((0,o.default)({},this.perPageParameter,this.perPage))}},computed:{currentPerPage:function(){return this.$route.query[this.perPageParameter]||25}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(187),o=(r=i)&&r.__esModule?r:{default:r};e.default={data:function(){return{search:"",selectedResource:"",availableResources:[]}},methods:{selectResource:function(t){this.selectedResource=t,this.field&&Nova.$emit(this.field.attribute+"-change",this.selectedResource.value)},handleSearchCleared:function(){this.availableResources=[]},clearSelection:function(){this.selectedResource="",this.availableResources=[],this.field&&Nova.$emit(this.field.attribute+"-change",null)},performSearch:function(t){var e=this;this.search=t;var n=t.trim();""!=n&&this.debouncer(function(){e.getAvailableResources(n)},500)},debouncer:(0,o.default)(function(t){return t()},500)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={beforeRouteLeave:function(t,e,n){this.canLeave?n():window.confirm(this.__("Do you really want to leave? You have unsaved changes."))?n():n(!1)},data:function(){return{canLeave:!0}},methods:{updateFormStatus:function(){this.canLeave=!1}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={data:function(){return{withTrashed:!1}},methods:{toggleWithTrashed:function(){this.withTrashed=!this.withTrashed},enableWithTrashed:function(){this.withTrashed=!0},disableWithTrashed:function(){this.withTrashed=!1}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,o.default)(t)};var r,i=n(198),o=(r=i)&&r.__esModule?r:{default:r}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(41),o=(r=i)&&r.__esModule?r:{default:r};e.default=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100;return o.default.all([t,new o.default(function(t){setTimeout(function(){return t()},e)})]).then(function(t){return t[0]})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){if(null==t.match(/^(.*)[A-Za-zÀ-ÖØ-öø-ÿ]$/))return t;if(t>1||0==t)return r.Inflector.pluralize(e);return r.Inflector.singularize(e)};var r=n(40)},function(t,e,n){"use strict";var r={uncountableWords:["equipment","information","rice","money","species","series","fish","sheep","moose","deer","news"],pluralRules:[[new RegExp("(m)an$","gi"),"$1en"],[new RegExp("(pe)rson$","gi"),"$1ople"],[new RegExp("(child)$","gi"),"$1ren"],[new RegExp("^(ox)$","gi"),"$1en"],[new RegExp("(ax|test)is$","gi"),"$1es"],[new RegExp("(octop|vir)us$","gi"),"$1i"],[new RegExp("(alias|status)$","gi"),"$1es"],[new RegExp("(bu)s$","gi"),"$1ses"],[new RegExp("(buffal|tomat|potat)o$","gi"),"$1oes"],[new RegExp("([ti])um$","gi"),"$1a"],[new RegExp("sis$","gi"),"ses"],[new RegExp("(?:([^f])fe|([lr])f)$","gi"),"$1$2ves"],[new RegExp("(hive)$","gi"),"$1s"],[new RegExp("([^aeiouy]|qu)y$","gi"),"$1ies"],[new RegExp("(x|ch|ss|sh)$","gi"),"$1es"],[new RegExp("(matr|vert|ind)ix|ex$","gi"),"$1ices"],[new RegExp("([m|l])ouse$","gi"),"$1ice"],[new RegExp("(quiz)$","gi"),"$1zes"],[new RegExp("s$","gi"),"s"],[new RegExp("$","gi"),"s"]],singularRules:[[new RegExp("(m)en$","gi"),"$1an"],[new RegExp("(pe)ople$","gi"),"$1rson"],[new RegExp("(child)ren$","gi"),"$1"],[new RegExp("([ti])a$","gi"),"$1um"],[new RegExp("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$","gi"),"$1$2sis"],[new RegExp("(hive)s$","gi"),"$1"],[new RegExp("(tive)s$","gi"),"$1"],[new RegExp("(curve)s$","gi"),"$1"],[new RegExp("([lr])ves$","gi"),"$1f"],[new RegExp("([^fo])ves$","gi"),"$1fe"],[new RegExp("([^aeiouy]|qu)ies$","gi"),"$1y"],[new RegExp("(s)eries$","gi"),"$1eries"],[new RegExp("(m)ovies$","gi"),"$1ovie"],[new RegExp("(x|ch|ss|sh)es$","gi"),"$1"],[new RegExp("([m|l])ice$","gi"),"$1ouse"],[new RegExp("(bus)es$","gi"),"$1"],[new RegExp("(o)es$","gi"),"$1"],[new RegExp("(shoe)s$","gi"),"$1"],[new RegExp("(cris|ax|test)es$","gi"),"$1is"],[new RegExp("(octop|vir)i$","gi"),"$1us"],[new RegExp("(alias|status)es$","gi"),"$1"],[new RegExp("^(ox)en","gi"),"$1"],[new RegExp("(vert|ind)ices$","gi"),"$1ex"],[new RegExp("(matr)ices$","gi"),"$1ix"],[new RegExp("(quiz)zes$","gi"),"$1"],[new RegExp("s$","gi"),""]],nonTitlecasedWords:["and","or","nor","a","an","the","so","but","to","of","at","by","from","into","on","onto","off","out","in","over","with","for"],idSuffix:new RegExp("(_ids|_id)$","g"),underbar:new RegExp("_","g"),spaceOrUnderbar:new RegExp("[ _]","g"),uppercase:new RegExp("([A-Z])","g"),underbarPrefix:new RegExp("^_"),applyRules:function(t,e,n,r){if(r)t=r;else if(!(n.indexOf(t.toLowerCase())>-1))for(var i=0;i<e.length;i++)if(t.match(e[i][0])){t=t.replace(e[i][0],e[i][1]);break}return t},pluralize:function(t,e){return this.applyRules(t,this.pluralRules,this.uncountableWords,e)},singularize:function(t,e){return this.applyRules(t,this.singularRules,this.uncountableWords,e)},camelize:function(t,e){for(var n=t.split("/"),r=0;r<n.length;r++){for(var i=n[r].split("_"),o=e&&r+1===n.length?1:0;o<i.length;o++)i[o]=i[o].charAt(0).toUpperCase()+i[o].substring(1);n[r]=i.join("")}(t=n.join("::"),!0===e)&&(t=t.charAt(0).toLowerCase()+t.slice(1));return t},underscore:function(t){for(var e=t.split("::"),n=0;n<e.length;n++)e[n]=e[n].replace(this.uppercase,"_$1"),e[n]=e[n].replace(this.underbarPrefix,"");return t=e.join("/").toLowerCase()},humanize:function(t,e){return t=(t=(t=t.toLowerCase()).replace(this.idSuffix,"")).replace(this.underbar," "),e||(t=this.capitalize(t)),t},capitalize:function(t){return t=(t=t.toLowerCase()).substring(0,1).toUpperCase()+t.substring(1)},dasherize:function(t){return t=t.replace(this.spaceOrUnderbar,"-")},camel2words:function(t,e){!0===e?(t=this.camelize(t),t=this.underscore(t)):t=t.toLowerCase();for(var n=(t=t.replace(this.underbar," ")).split(" "),r=0;r<n.length;r++){for(var i=n[r].split("-"),o=0;o<i.length;o++)this.nonTitlecasedWords.indexOf(i[o].toLowerCase())<0&&(i[o]=this.capitalize(i[o]));n[r]=i.join("-")}return t=(t=n.join(" ")).substring(0,1).toUpperCase()+t.substring(1)},demodulize:function(t){var e=t.split("::");return t=e[e.length-1]},tableize:function(t){return t=this.pluralize(this.underscore(t))},classify:function(t){return t=this.singularize(this.camelize(t))},foreignKey:function(t,e){return t=this.underscore(this.demodulize(t))+(e?"":"_")+"id"},ordinalize:function(t){for(var e=t.split(" "),n=0;n<e.length;n++){if(NaN===parseInt(e[n])){var r=e[n].substring(e[n].length-2),i=e[n].substring(e[n].length-1),o="th";"11"!=r&&"12"!=r&&"13"!=r&&("1"===i?o="st":"2"===i?o="nd":"3"===i&&(o="rd")),e[n]+=o}}return t=e.join(" ")}};t.exports=r},function(t,e,n){t.exports=n(91)},function(t,e,n){"use strict";var r=n(0),i=n(39),o=n(93),u=n(19);function a(t){var e=new o(t),n=i(o.prototype.request,e);return r.extend(n,o.prototype,e),r.extend(n,e),n}var s=a(u);s.Axios=o,s.create=function(t){return a(r.merge(u,t))},s.Cancel=n(36),s.CancelToken=n(92),s.isCancel=n(37),s.all=function(t){return Promise.all(t)},s.spread=n(107),t.exports=s,t.exports.default=s},function(t,e,n){"use strict";var r=n(36);function i(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise(function(t){e=t});var n=this;t(function(t){n.reason||(n.reason=new r(t),e(n.reason))})}i.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},i.source=function(){var t;return{token:new i(function(e){t=e}),cancel:t}},t.exports=i},function(t,e,n){"use strict";var r=n(19),i=n(0),o=n(94),u=n(95);function a(t){this.defaults=t,this.interceptors={request:new o,response:new o}}a.prototype.request=function(t){"string"==typeof t&&(t=i.merge({url:arguments[0]},arguments[1])),(t=i.merge(r,{method:"get"},this.defaults,t)).method=t.method.toLowerCase();var e=[u,void 0],n=Promise.resolve(t);for(this.interceptors.request.forEach(function(t){e.unshift(t.fulfilled,t.rejected)}),this.interceptors.response.forEach(function(t){e.push(t.fulfilled,t.rejected)});e.length;)n=n.then(e.shift(),e.shift());return n},i.forEach(["delete","get","head","options"],function(t){a.prototype[t]=function(e,n){return this.request(i.merge(n||{},{method:t,url:e}))}}),i.forEach(["post","put","patch"],function(t){a.prototype[t]=function(e,n,r){return this.request(i.merge(r||{},{method:t,url:e,data:n}))}}),t.exports=a},function(t,e,n){"use strict";var r=n(0);function i(){this.handlers=[]}i.prototype.use=function(t,e){return this.handlers.push({fulfilled:t,rejected:e}),this.handlers.length-1},i.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)},i.prototype.forEach=function(t){r.forEach(this.handlers,function(e){null!==e&&t(e)})},t.exports=i},function(t,e,n){"use strict";var r=n(0),i=n(98),o=n(37),u=n(19),a=n(103),s=n(101);function c(t){t.cancelToken&&t.cancelToken.throwIfRequested()}t.exports=function(t){return c(t),t.baseURL&&!a(t.url)&&(t.url=s(t.baseURL,t.url)),t.headers=t.headers||{},t.data=i(t.data,t.headers,t.transformRequest),t.headers=r.merge(t.headers.common||{},t.headers[t.method]||{},t.headers||{}),r.forEach(["delete","get","head","post","put","patch","common"],function(e){delete t.headers[e]}),(t.adapter||u.adapter)(t).then(function(e){return c(t),e.data=i(e.data,e.headers,t.transformResponse),e},function(e){return o(e)||(c(t),e&&e.response&&(e.response.data=i(e.response.data,e.response.headers,t.transformResponse))),Promise.reject(e)})}},function(t,e,n){"use strict";t.exports=function(t,e,n,r,i){return t.config=e,n&&(t.code=n),t.request=r,t.response=i,t}},function(t,e,n){"use strict";var r=n(38);t.exports=function(t,e,n){var i=n.config.validateStatus;n.status&&i&&!i(n.status)?e(r("Request failed with status code "+n.status,n.config,null,n.request,n)):t(n)}},function(t,e,n){"use strict";var r=n(0);t.exports=function(t,e,n){return r.forEach(n,function(n){t=n(t,e)}),t}},function(t,e,n){"use strict";var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function i(){this.message="String contains an invalid character"}i.prototype=new Error,i.prototype.code=5,i.prototype.name="InvalidCharacterError",t.exports=function(t){for(var e,n,o=String(t),u="",a=0,s=r;o.charAt(0|a)||(s="=",a%1);u+=s.charAt(63&e>>8-a%1*8)){if((n=o.charCodeAt(a+=.75))>255)throw new i;e=e<<8|n}return u}},function(t,e,n){"use strict";var r=n(0);function i(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}t.exports=function(t,e,n){if(!e)return t;var o;if(n)o=n(e);else if(r.isURLSearchParams(e))o=e.toString();else{var u=[];r.forEach(e,function(t,e){null!==t&&void 0!==t&&(r.isArray(t)?e+="[]":t=[t],r.forEach(t,function(t){r.isDate(t)?t=t.toISOString():r.isObject(t)&&(t=JSON.stringify(t)),u.push(i(e)+"="+i(t))}))}),o=u.join("&")}return o&&(t+=(-1===t.indexOf("?")?"?":"&")+o),t}},function(t,e,n){"use strict";t.exports=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}},function(t,e,n){"use strict";var r=n(0);t.exports=r.isStandardBrowserEnv()?{write:function(t,e,n,i,o,u){var a=[];a.push(t+"="+encodeURIComponent(e)),r.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),r.isString(i)&&a.push("path="+i),r.isString(o)&&a.push("domain="+o),!0===u&&a.push("secure"),document.cookie=a.join("; ")},read:function(t){var e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(t){this.write(t,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}},function(t,e,n){"use strict";t.exports=function(t){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(t)}},function(t,e,n){"use strict";var r=n(0);t.exports=r.isStandardBrowserEnv()?function(){var t,e=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function i(t){var r=t;return e&&(n.setAttribute("href",r),r=n.href),n.setAttribute("href",r),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return t=i(window.location.href),function(e){var n=r.isString(e)?i(e):e;return n.protocol===t.protocol&&n.host===t.host}}():function(){return!0}},function(t,e,n){"use strict";var r=n(0);t.exports=function(t,e){r.forEach(t,function(n,r){r!==e&&r.toUpperCase()===e.toUpperCase()&&(t[e]=n,delete t[r])})}},function(t,e,n){"use strict";var r=n(0),i=["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"];t.exports=function(t){var e,n,o,u={};return t?(r.forEach(t.split("\n"),function(t){if(o=t.indexOf(":"),e=r.trim(t.substr(0,o)).toLowerCase(),n=r.trim(t.substr(o+1)),e){if(u[e]&&i.indexOf(e)>=0)return;u[e]="set-cookie"===e?(u[e]?u[e]:[]).concat([n]):u[e]?u[e]+", "+n:n}}),u):u}},function(t,e,n){"use strict";t.exports=function(t){return function(e){return t.apply(null,e)}}},function(t,e,n){t.exports={default:n(111),__esModule:!0}},function(t,e,n){t.exports={default:n(112),__esModule:!0}},function(t,e,n){"use strict";e.__esModule=!0;var r,i=n(108),o=(r=i)&&r.__esModule?r:{default:r};e.default=o.default||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}},function(t,e,n){n(142),t.exports=n(3).Object.assign},function(t,e,n){n(143);var r=n(3).Object;t.exports=function(t,e,n){return r.defineProperty(t,e,n)}},function(t,e,n){n(144),n(146),n(149),n(145),n(147),n(148),t.exports=n(3).Promise},function(t,e){t.exports=function(){}},function(t,e){t.exports=function(t,e,n,r){if(!(t instanceof e)||void 0!==r&&r in t)throw TypeError(n+": incorrect invocation!");return t}},function(t,e,n){var r=n(29),i=n(56),o=n(137);t.exports=function(t){return function(e,n,u){var a,s=r(e),c=i(s.length),f=o(u,c);if(t&&n!=n){for(;c>f;)if((a=s[f++])!=a)return!0}else for(;c>f;f++)if((t||f in s)&&s[f]===n)return t||f||0;return!t&&-1}}},function(t,e,n){var r=n(14),i=n(121),o=n(120),u=n(4),a=n(56),s=n(140),c={},f={};(e=t.exports=function(t,e,n,l,A){var p,d,h,v,g=A?function(){return t}:s(t),m=r(n,l,e?2:1),y=0;if("function"!=typeof g)throw TypeError(t+" is not iterable!");if(o(g)){for(p=a(t.length);p>y;y++)if((v=e?m(u(d=t[y])[0],d[1]):m(t[y]))===c||v===f)return v}else for(h=g.call(t);!(d=h.next()).done;)if((v=i(h,m,d.value,e))===c||v===f)return v}).BREAK=c,e.RETURN=f},function(t,e,n){t.exports=!n(5)&&!n(23)(function(){return 7!=Object.defineProperty(n(22)("div"),"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t,e,n){var r=void 0===n;switch(e.length){case 0:return r?t():t.call(n);case 1:return r?t(e[0]):t.call(n,e[0]);case 2:return r?t(e[0],e[1]):t.call(n,e[0],e[1]);case 3:return r?t(e[0],e[1],e[2]):t.call(n,e[0],e[1],e[2]);case 4:return r?t(e[0],e[1],e[2],e[3]):t.call(n,e[0],e[1],e[2],e[3])}return t.apply(n,e)}},function(t,e,n){var r=n(10),i=n(2)("iterator"),o=Array.prototype;t.exports=function(t){return void 0!==t&&(r.Array===t||o[i]===t)}},function(t,e,n){var r=n(4);t.exports=function(t,e,n,i){try{return i?e(r(n)[0],n[1]):e(n)}catch(e){var o=t.return;throw void 0!==o&&r(o.call(t)),e}}},function(t,e,n){"use strict";var r=n(127),i=n(52),o=n(26),u={};n(7)(u,n(2)("iterator"),function(){return this}),t.exports=function(t,e,n){t.prototype=r(u,{next:i(1,n)}),o(t,e+" Iterator")}},function(t,e,n){var r=n(2)("iterator"),i=!1;try{var o=[7][r]();o.return=function(){i=!0},Array.from(o,function(){throw 2})}catch(t){}t.exports=function(t,e){if(!e&&!i)return!1;var n=!1;try{var o=[7],u=o[r]();u.next=function(){return{done:n=!0}},o[r]=function(){return u},t(o)}catch(t){}return n}},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e,n){var r=n(1),i=n(55).set,o=r.MutationObserver||r.WebKitMutationObserver,u=r.process,a=r.Promise,s="process"==n(13)(u);t.exports=function(){var t,e,n,c=function(){var r,i;for(s&&(r=u.domain)&&r.exit();t;){i=t.fn,t=t.next;try{i()}catch(r){throw t?n():e=void 0,r}}e=void 0,r&&r.enter()};if(s)n=function(){u.nextTick(c)};else if(!o||r.navigator&&r.navigator.standalone)if(a&&a.resolve){var f=a.resolve(void 0);n=function(){f.then(c)}}else n=function(){i.call(r,c)};else{var l=!0,A=document.createTextNode("");new o(c).observe(A,{characterData:!0}),n=function(){A.data=l=!l}}return function(r){var i={fn:r,next:void 0};e&&(e.next=i),t||(t=i,n()),e=i}}},function(t,e,n){"use strict";var r=n(49),i=n(129),o=n(132),u=n(57),a=n(47),s=Object.assign;t.exports=!s||n(23)(function(){var t={},e={},n=Symbol(),r="abcdefghijklmnopqrst";return t[n]=7,r.split("").forEach(function(t){e[t]=t}),7!=s({},t)[n]||Object.keys(s({},e)).join("")!=r})?function(t,e){for(var n=u(t),s=arguments.length,c=1,f=i.f,l=o.f;s>c;)for(var A,p=a(arguments[c++]),d=f?r(p).concat(f(p)):r(p),h=d.length,v=0;h>v;)l.call(p,A=d[v++])&&(n[A]=p[A]);return n}:s},function(t,e,n){var r=n(4),i=n(128),o=n(45),u=n(27)("IE_PROTO"),a=function(){},s=function(){var t,e=n(22)("iframe"),r=o.length;for(e.style.display="none",n(46).appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write("<script>document.F=Object<\/script>"),t.close(),s=t.F;r--;)delete s.prototype[o[r]];return s()};t.exports=Object.create||function(t,e){var n;return null!==t?(a.prototype=r(t),n=new a,a.prototype=null,n[u]=t):n=s(),void 0===e?n:i(n,e)}},function(t,e,n){var r=n(11),i=n(4),o=n(49);t.exports=n(5)?Object.defineProperties:function(t,e){i(t);for(var n,u=o(e),a=u.length,s=0;a>s;)r.f(t,n=u[s++],e[n]);return t}},function(t,e){e.f=Object.getOwnPropertySymbols},function(t,e,n){var r=n(15),i=n(57),o=n(27)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=i(t),r(t,o)?t[o]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?u:null}},function(t,e,n){var r=n(15),i=n(29),o=n(116)(!1),u=n(27)("IE_PROTO");t.exports=function(t,e){var n,a=i(t),s=0,c=[];for(n in a)n!=u&&r(a,n)&&c.push(n);for(;e.length>s;)r(a,n=e[s++])&&(~o(c,n)||c.push(n));return c}},function(t,e){e.f={}.propertyIsEnumerable},function(t,e,n){var r=n(7);t.exports=function(t,e,n){for(var i in e)n&&t[i]?t[i]=e[i]:r(t,i,e[i]);return t}},function(t,e,n){t.exports=n(7)},function(t,e,n){"use strict";var r=n(1),i=n(3),o=n(11),u=n(5),a=n(2)("species");t.exports=function(t){var e="function"==typeof i[t]?i[t]:r[t];u&&e&&!e[a]&&o.f(e,a,{configurable:!0,get:function(){return this}})}},function(t,e,n){var r=n(28),i=n(21);t.exports=function(t){return function(e,n){var o,u,a=String(i(e)),s=r(n),c=a.length;return s<0||s>=c?t?"":void 0:(o=a.charCodeAt(s))<55296||o>56319||s+1===c||(u=a.charCodeAt(s+1))<56320||u>57343?t?a.charAt(s):o:t?a.slice(s,s+2):u-56320+(o-55296<<10)+65536}}},function(t,e,n){var r=n(28),i=Math.max,o=Math.min;t.exports=function(t,e){return(t=r(t))<0?i(t+e,0):o(t,e)}},function(t,e,n){var r=n(9);t.exports=function(t,e){if(!r(t))return t;var n,i;if(e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;if("function"==typeof(n=t.valueOf)&&!r(i=n.call(t)))return i;if(!e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;throw TypeError("Can't convert object to primitive value")}},function(t,e,n){var r=n(1).navigator;t.exports=r&&r.userAgent||""},function(t,e,n){var r=n(44),i=n(2)("iterator"),o=n(10);t.exports=n(3).getIteratorMethod=function(t){if(void 0!=t)return t[i]||t["@@iterator"]||o[r(t)]}},function(t,e,n){"use strict";var r=n(114),i=n(124),o=n(10),u=n(29);t.exports=n(48)(Array,"Array",function(t,e){this._t=u(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,n=this._i++;return!t||n>=t.length?(this._t=void 0,i(1)):i(0,"keys"==e?n:"values"==e?t[n]:[n,t[n]])},"values"),o.Arguments=o.Array,r("keys"),r("values"),r("entries")},function(t,e,n){var r=n(6);r(r.S+r.F,"Object",{assign:n(126)})},function(t,e,n){var r=n(6);r(r.S+r.F*!n(5),"Object",{defineProperty:n(11).f})},function(t,e){},function(t,e,n){"use strict";var r,i,o,u,a=n(24),s=n(1),c=n(14),f=n(44),l=n(6),A=n(9),p=n(12),d=n(115),h=n(117),v=n(54),g=n(55).set,m=n(125)(),y=n(25),_=n(50),b=n(139),w=n(51),x=s.TypeError,E=s.process,C=E&&E.versions,B=C&&C.v8||"",j=s.Promise,R="process"==f(E),S=function(){},O=i=y.f,k=!!function(){try{var t=j.resolve(1),e=(t.constructor={})[n(2)("species")]=function(t){t(S,S)};return(R||"function"==typeof PromiseRejectionEvent)&&t.then(S)instanceof e&&0!==B.indexOf("6.6")&&-1===b.indexOf("Chrome/66")}catch(t){}}(),T=function(t){var e;return!(!A(t)||"function"!=typeof(e=t.then))&&e},P=function(t,e){if(!t._n){t._n=!0;var n=t._c;m(function(){for(var r=t._v,i=1==t._s,o=0,u=function(e){var n,o,u,a=i?e.ok:e.fail,s=e.resolve,c=e.reject,f=e.domain;try{a?(i||(2==t._h&&N(t),t._h=1),!0===a?n=r:(f&&f.enter(),n=a(r),f&&(f.exit(),u=!0)),n===e.promise?c(x("Promise-chain cycle")):(o=T(n))?o.call(n,s,c):s(n)):c(r)}catch(t){f&&!u&&f.exit(),c(t)}};n.length>o;)u(n[o++]);t._c=[],t._n=!1,e&&!t._h&&I(t)})}},I=function(t){g.call(s,function(){var e,n,r,i=t._v,o=M(t);if(o&&(e=_(function(){R?E.emit("unhandledRejection",i,t):(n=s.onunhandledrejection)?n({promise:t,reason:i}):(r=s.console)&&r.error&&r.error("Unhandled promise rejection",i)}),t._h=R||M(t)?2:1),t._a=void 0,o&&e.e)throw e.v})},M=function(t){return 1!==t._h&&0===(t._a||t._c).length},N=function(t){g.call(s,function(){var e;R?E.emit("rejectionHandled",t):(e=s.onrejectionhandled)&&e({promise:t,reason:t._v})})},D=function(t){var e=this;e._d||(e._d=!0,(e=e._w||e)._v=t,e._s=2,e._a||(e._a=e._c.slice()),P(e,!0))},$=function(t){var e,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===t)throw x("Promise can't be resolved itself");(e=T(t))?m(function(){var r={_w:n,_d:!1};try{e.call(t,c($,r,1),c(D,r,1))}catch(t){D.call(r,t)}}):(n._v=t,n._s=1,P(n,!1))}catch(t){D.call({_w:n,_d:!1},t)}}};k||(j=function(t){d(this,j,"Promise","_h"),p(t),r.call(this);try{t(c($,this,1),c(D,this,1))}catch(t){D.call(this,t)}},(r=function(t){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1}).prototype=n(133)(j.prototype,{then:function(t,e){var n=O(v(this,j));return n.ok="function"!=typeof t||t,n.fail="function"==typeof e&&e,n.domain=R?E.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&P(this,!1),n.promise},catch:function(t){return this.then(void 0,t)}}),o=function(){var t=new r;this.promise=t,this.resolve=c($,t,1),this.reject=c(D,t,1)},y.f=O=function(t){return t===j||t===u?new o(t):i(t)}),l(l.G+l.W+l.F*!k,{Promise:j}),n(26)(j,"Promise"),n(135)("Promise"),u=n(3).Promise,l(l.S+l.F*!k,"Promise",{reject:function(t){var e=O(this);return(0,e.reject)(t),e.promise}}),l(l.S+l.F*(a||!k),"Promise",{resolve:function(t){return w(a&&this===u?j:this,t)}}),l(l.S+l.F*!(k&&n(123)(function(t){j.all(t).catch(S)})),"Promise",{all:function(t){var e=this,n=O(e),r=n.resolve,i=n.reject,o=_(function(){var n=[],o=0,u=1;h(t,!1,function(t){var a=o++,s=!1;n.push(void 0),u++,e.resolve(t).then(function(t){s||(s=!0,n[a]=t,--u||r(n))},i)}),--u||r(n)});return o.e&&i(o.v),n.promise},race:function(t){var e=this,n=O(e),r=n.reject,i=_(function(){h(t,!1,function(t){e.resolve(t).then(n.resolve,r)})});return i.e&&r(i.v),n.promise}})},function(t,e,n){"use strict";var r=n(136)(!0);n(48)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,n=this._i;return n>=e.length?{value:void 0,done:!0}:(t=r(e,n),this._i+=t.length,{value:t,done:!1})})},function(t,e,n){"use strict";var r=n(6),i=n(3),o=n(1),u=n(54),a=n(51);r(r.P+r.R,"Promise",{finally:function(t){var e=u(this,i.Promise||o.Promise),n="function"==typeof t;return this.then(n?function(n){return a(e,t()).then(function(){return n})}:t,n?function(n){return a(e,t()).then(function(){throw n})}:t)}})},function(t,e,n){"use strict";var r=n(6),i=n(25),o=n(50);r(r.S,"Promise",{try:function(t){var e=i.f(this),n=o(t);return(n.e?e.reject:e.resolve)(n.v),e.promise}})},function(t,e,n){n(141);for(var r=n(1),i=n(7),o=n(10),u=n(2)("toStringTag"),a="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),s=0;s<a.length;s++){var c=a[s],f=r[c],l=f&&f.prototype;l&&!l[u]&&i(l,u,c),o[c]=o.Array}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(59),u=(r=o)&&r.__esModule?r:{default:r},a=n(151);var s=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.processing=!1,this.successful=!1,this.withData(e).withOptions(n).withErrors({})}return i(t,[{key:"withData",value:function(t){for(var e in(0,a.isArray)(t)&&(t=t.reduce(function(t,e){return t[e]="",t},{})),this.setInitialValues(t),this.errors=new u.default,this.processing=!1,this.successful=!1,t)(0,a.guardAgainstReservedFieldName)(e),this[e]=t[e];return this}},{key:"withErrors",value:function(t){return this.errors=new u.default(t),this}},{key:"withOptions",value:function(t){if(this.__options={resetOnSuccess:!0},t.hasOwnProperty("resetOnSuccess")&&(this.__options.resetOnSuccess=t.resetOnSuccess),t.hasOwnProperty("onSuccess")&&(this.onSuccess=t.onSuccess),t.hasOwnProperty("onFail")&&(this.onFail=t.onFail),this.__http=t.http||window.axios||n(90),!this.__http)throw new Error("No http library provided. Either pass an http option, or install axios.");return this}},{key:"data",value:function(){var t={};for(var e in this.initial)t[e]=this[e];return t}},{key:"only",value:function(t){var e=this;return t.reduce(function(t,n){return t[n]=e[n],t},{})}},{key:"reset",value:function(){(0,a.merge)(this,this.initial),this.errors.clear()}},{key:"setInitialValues",value:function(t){this.initial={},(0,a.merge)(this.initial,t)}},{key:"populate",value:function(t){var e=this;return Object.keys(t).forEach(function(n){var r,i,o;(0,a.guardAgainstReservedFieldName)(n),e.hasOwnProperty(n)&&(0,a.merge)(e,(r={},i=n,o=t[n],i in r?Object.defineProperty(r,i,{value:o,enumerable:!0,configurable:!0,writable:!0}):r[i]=o,r))}),this}},{key:"clear",value:function(){for(var t in this.initial)this[t]="";this.errors.clear()}},{key:"post",value:function(t){return this.submit("post",t)}},{key:"put",value:function(t){return this.submit("put",t)}},{key:"patch",value:function(t){return this.submit("patch",t)}},{key:"delete",value:function(t){return this.submit("delete",t)}},{key:"submit",value:function(t,e){var n=this;return this.__validateRequestType(t),this.errors.clear(),this.processing=!0,this.successful=!1,new Promise(function(r,i){n.__http[t](e,n.hasFiles()?(0,a.objectToFormData)(n.data()):n.data()).then(function(t){n.processing=!1,n.onSuccess(t.data),r(t.data)}).catch(function(t){n.processing=!1,n.onFail(t),i(t)})})}},{key:"hasFiles",value:function(){for(var t in this.initial)if(this[t]instanceof File||this[t]instanceof FileList)return!0;return!1}},{key:"onSuccess",value:function(t){this.successful=!0,this.__options.resetOnSuccess&&this.reset()}},{key:"onFail",value:function(t){this.successful=!1,t.response&&t.response.data.errors&&this.errors.record(t.response.data.errors)}},{key:"hasError",value:function(t){return this.errors.has(t)}},{key:"getError",value:function(t){return this.errors.first(t)}},{key:"getErrors",value:function(t){return this.errors.get(t)}},{key:"__validateRequestType",value:function(t){var e=["get","delete","head","post","put","patch"];if(-1===e.indexOf(t))throw new Error("`"+t+"` is not a valid request type, must be one of: `"+e.join("`, `")+"`.")}}],[{key:"create",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return(new t).withData(e)}}]),t}();e.default=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};e.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)},e.guardAgainstReservedFieldName=function(t){if(-1!==i.indexOf(t))throw new Error("Field name "+t+" isn't allowed to be used in a Form or Errors instance.")},e.merge=function(t,e){for(var n in e)t[n]=o(e[n])},e.cloneDeep=o,e.objectToFormData=u;var i=e.reservedFieldNames=["__http","__options","__validateRequestType","clear","data","delete","errors","getError","getErrors","hasError","initial","onFail","only","onSuccess","patch","populate","post","processing","successful","put","reset","submit","withData","withErrors","withOptions"];function o(t){if(null===t)return null;if(Array.isArray(t))return[].concat(function(t){if(Array.isArray(t)){for(var e=0,n=Array(t.length);e<t.length;e++)n[e]=t[e];return n}return Array.from(t)}(t));if("object"===(void 0===t?"undefined":r(t))){var e={};for(var n in t)e[n]=o(t[n]);return e}return t}function u(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new FormData,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;for(var r in t)s(e,a(n,r),t[r]);return e}function a(t,e){return t?t+"["+e+"]":e}function s(t,e,n){return n instanceof Date?t.append(e,n.toISOString()):n instanceof File?t.append(e,n,n.name):"object"!==(void 0===n?"undefined":r(n))?t.append(e,n):void u(n,t,e)}},function(t,e){function n(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}t.exports=function(t){return null!=t&&(n(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&n(t.slice(0,0))}(t)||!!t._isBuffer)}},function(t,e){t.exports=function(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}},function(t,e,n){var r=n(164),i=n(189),o=n(65),u=n(190),a=n(62),s=n(191),c=Object.prototype.hasOwnProperty;t.exports=function(t,e){var n=o(t),f=!n&&i(t),l=!n&&!f&&u(t),A=!n&&!f&&!l&&s(t),p=n||f||l||A,d=p?r(t.length,String):[],h=d.length;for(var v in t)!e&&!c.call(t,v)||p&&("length"==v||l&&("offset"==v||"parent"==v)||A&&("buffer"==v||"byteLength"==v||"byteOffset"==v)||a(v,h))||d.push(v);return d}},function(t,e){t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,i=Array(r);++n<r;)i[n]=e(t[n],n,t);return i}},function(t,e){t.exports=function(t){return t.split("")}},function(t,e,n){var r=n(16),i=n(18),o="[object Arguments]";t.exports=function(t){return i(t)&&r(t)==o}},function(t,e,n){var r=n(67),i=n(175),o=n(8),u=n(184),a=/^\[object .+?Constructor\]$/,s=Function.prototype,c=Object.prototype,f=s.toString,l=c.hasOwnProperty,A=RegExp("^"+f.call(l).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=function(t){return!(!o(t)||i(t))&&(r(t)?A:a).test(u(t))}},function(t,e,n){var r=n(16),i=n(68),o=n(18),u={};u["[object Float32Array]"]=u["[object Float64Array]"]=u["[object Int8Array]"]=u["[object Int16Array]"]=u["[object Int32Array]"]=u["[object Uint8Array]"]=u["[object Uint8ClampedArray]"]=u["[object Uint16Array]"]=u["[object Uint32Array]"]=!0,u["[object Arguments]"]=u["[object Array]"]=u["[object ArrayBuffer]"]=u["[object Boolean]"]=u["[object DataView]"]=u["[object Date]"]=u["[object Error]"]=u["[object Function]"]=u["[object Map]"]=u["[object Number]"]=u["[object Object]"]=u["[object RegExp]"]=u["[object Set]"]=u["[object String]"]=u["[object WeakMap]"]=!1,t.exports=function(t){return o(t)&&i(t.length)&&!!u[r(t)]}},function(t,e,n){var r=n(8),i=n(176),o=n(177),u=Object.prototype.hasOwnProperty;t.exports=function(t){if(!r(t))return o(t);var e=i(t),n=[];for(var a in t)("constructor"!=a||!e&&u.call(t,a))&&n.push(a);return n}},function(t,e,n){var r=n(64),i=n(180),o=n(181);t.exports=function(t,e){return o(i(t,e,r),t+"")}},function(t,e,n){var r=n(186),i=n(170),o=n(64),u=i?function(t,e){return i(t,"toString",{configurable:!0,enumerable:!1,value:r(e),writable:!0})}:o;t.exports=u},function(t,e){t.exports=function(t,e,n){var r=-1,i=t.length;e<0&&(e=-e>i?0:i+e),(n=n>i?i:n)<0&&(n+=i),i=e>n?0:n-e>>>0,e>>>=0;for(var o=Array(i);++r<i;)o[r]=t[r+e];return o}},function(t,e){t.exports=function(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}},function(t,e,n){var r=n(30),i=n(155),o=n(65),u=n(69),a=1/0,s=r?r.prototype:void 0,c=s?s.toString:void 0;t.exports=function t(e){if("string"==typeof e)return e;if(o(e))return i(e,t)+"";if(u(e))return c?c.call(e):"";var n=e+"";return"0"==n&&1/e==-a?"-0":n}},function(t,e){t.exports=function(t){return function(e){return t(e)}}},function(t,e,n){var r=n(163);t.exports=function(t,e,n){var i=t.length;return n=void 0===n?i:n,!e&&n>=i?t:r(t,e,n)}},function(t,e,n){var r=n(17)["__core-js_shared__"];t.exports=r},function(t,e,n){var r=n(167),i=n(61),o=n(183),u=n(197);t.exports=function(t){return function(e){e=u(e);var n=i(e)?o(e):void 0,a=n?n[0]:e.charAt(0),s=n?r(n,1).join(""):e.slice(1);return a[t]()+s}}},function(t,e,n){var r=n(171),i=function(){try{var t=r(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();t.exports=i},function(t,e,n){var r=n(158),i=n(173);t.exports=function(t,e){var n=i(t,e);return r(n)?n:void 0}},function(t,e,n){var r=n(30),i=Object.prototype,o=i.hasOwnProperty,u=i.toString,a=r?r.toStringTag:void 0;t.exports=function(t){var e=o.call(t,a),n=t[a];try{t[a]=void 0;var r=!0}catch(t){}var i=u.call(t);return r&&(e?t[a]=n:delete t[a]),i}},function(t,e){t.exports=function(t,e){return null==t?void 0:t[e]}},function(t,e,n){var r=n(63),i=n(66),o=n(62),u=n(8);t.exports=function(t,e,n){if(!u(n))return!1;var a=typeof e;return!!("number"==a?i(n)&&o(e,n.length):"string"==a&&e in n)&&r(n[e],t)}},function(t,e,n){var r,i=n(168),o=(r=/[^.]+$/.exec(i&&i.keys&&i.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";t.exports=function(t){return!!o&&o in t}},function(t,e){var n=Object.prototype;t.exports=function(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||n)}},function(t,e){t.exports=function(t){var e=[];if(null!=t)for(var n in Object(t))e.push(n);return e}},function(t,e,n){(function(t){var r=n(60),i="object"==typeof e&&e&&!e.nodeType&&e,o=i&&"object"==typeof t&&t&&!t.nodeType&&t,u=o&&o.exports===i&&r.process,a=function(){try{var t=o&&o.require&&o.require("util").types;return t||u&&u.binding&&u.binding("util")}catch(t){}}();t.exports=a}).call(e,n(31)(t))},function(t,e){var n=Object.prototype.toString;t.exports=function(t){return n.call(t)}},function(t,e,n){var r=n(153),i=Math.max;t.exports=function(t,e,n){return e=i(void 0===e?t.length-1:e,0),function(){for(var o=arguments,u=-1,a=i(o.length-e,0),s=Array(a);++u<a;)s[u]=o[e+u];u=-1;for(var c=Array(e+1);++u<e;)c[u]=o[u];return c[e]=n(s),r(t,this,c)}}},function(t,e,n){var r=n(162),i=n(182)(r);t.exports=i},function(t,e){var n=800,r=16,i=Date.now;t.exports=function(t){var e=0,o=0;return function(){var u=i(),a=r-(u-o);if(o=u,a>0){if(++e>=n)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}},function(t,e,n){var r=n(156),i=n(61),o=n(185);t.exports=function(t){return i(t)?o(t):r(t)}},function(t,e){var n=Function.prototype.toString;t.exports=function(t){if(null!=t){try{return n.call(t)}catch(t){}try{return t+""}catch(t){}}return""}},function(t,e){var n="[\\ud800-\\udfff]",r="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",i="\\ud83c[\\udffb-\\udfff]",o="[^\\ud800-\\udfff]",u="(?:\\ud83c[\\udde6-\\uddff]){2}",a="[\\ud800-\\udbff][\\udc00-\\udfff]",s="(?:"+r+"|"+i+")"+"?",c="[\\ufe0e\\ufe0f]?"+s+("(?:\\u200d(?:"+[o,u,a].join("|")+")[\\ufe0e\\ufe0f]?"+s+")*"),f="(?:"+[o+r+"?",r,u,a,n].join("|")+")",l=RegExp(i+"(?="+i+")|"+f+c,"g");t.exports=function(t){return t.match(l)||[]}},function(t,e){t.exports=function(t){return function(){return t}}},function(t,e,n){var r=n(8),i=n(194),o=n(196),u="Expected a function",a=Math.max,s=Math.min;t.exports=function(t,e,n){var c,f,l,A,p,d,h=0,v=!1,g=!1,m=!0;if("function"!=typeof t)throw new TypeError(u);function y(e){var n=c,r=f;return c=f=void 0,h=e,A=t.apply(r,n)}function _(t){var n=t-d;return void 0===d||n>=e||n<0||g&&t-h>=l}function b(){var t=i();if(_(t))return w(t);p=setTimeout(b,function(t){var n=e-(t-d);return g?s(n,l-(t-h)):n}(t))}function w(t){return p=void 0,m&&c?y(t):(c=f=void 0,A)}function x(){var t=i(),n=_(t);if(c=arguments,f=this,d=t,n){if(void 0===p)return function(t){return h=t,p=setTimeout(b,e),v?y(t):A}(d);if(g)return clearTimeout(p),p=setTimeout(b,e),y(d)}return void 0===p&&(p=setTimeout(b,e)),A}return e=o(e)||0,r(n)&&(v=!!n.leading,l=(g="maxWait"in n)?a(o(n.maxWait)||0,e):l,m="trailing"in n?!!n.trailing:m),x.cancel=function(){void 0!==p&&clearTimeout(p),h=0,c=d=f=p=void 0},x.flush=function(){return void 0===p?A:w(i())},x}},function(t,e,n){var r=n(161),i=n(63),o=n(174),u=n(192),a=Object.prototype,s=a.hasOwnProperty,c=r(function(t,e){t=Object(t);var n=-1,r=e.length,c=r>2?e[2]:void 0;for(c&&o(e[0],e[1],c)&&(r=1);++n<r;)for(var f=e[n],l=u(f),A=-1,p=l.length;++A<p;){var d=l[A],h=t[d];(void 0===h||i(h,a[d])&&!s.call(t,d))&&(t[d]=f[d])}return t});t.exports=c},function(t,e,n){var r=n(157),i=n(18),o=Object.prototype,u=o.hasOwnProperty,a=o.propertyIsEnumerable,s=r(function(){return arguments}())?r:function(t){return i(t)&&u.call(t,"callee")&&!a.call(t,"callee")};t.exports=s},function(t,e,n){(function(t){var r=n(17),i=n(195),o="object"==typeof e&&e&&!e.nodeType&&e,u=o&&"object"==typeof t&&t&&!t.nodeType&&t,a=u&&u.exports===o?r.Buffer:void 0,s=(a?a.isBuffer:void 0)||i;t.exports=s}).call(e,n(31)(t))},function(t,e,n){var r=n(159),i=n(166),o=n(178),u=o&&o.isTypedArray,a=u?i(u):r;t.exports=a},function(t,e,n){var r=n(154),i=n(160),o=n(66);t.exports=function(t){return o(t)?r(t,!0):i(t)}},function(t,e,n){(function(t,r){var i;(function(){var o,u=200,a="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",c="__lodash_hash_undefined__",f=500,l="__lodash_placeholder__",A=1,p=2,d=4,h=1,v=2,g=1,m=2,y=4,_=8,b=16,w=32,x=64,E=128,C=256,B=512,j=30,R="...",S=800,O=16,k=1,T=2,P=1/0,I=9007199254740991,M=1.7976931348623157e308,N=NaN,D=4294967295,$=D-1,F=D>>>1,L=[["ary",E],["bind",g],["bindKey",m],["curry",_],["curryRight",b],["flip",B],["partial",w],["partialRight",x],["rearg",C]],z="[object Arguments]",Q="[object Array]",G="[object AsyncFunction]",U="[object Boolean]",Y="[object Date]",W="[object DOMException]",q="[object Error]",H="[object Function]",V="[object GeneratorFunction]",Z="[object Map]",J="[object Number]",K="[object Null]",X="[object Object]",tt="[object Proxy]",et="[object RegExp]",nt="[object Set]",rt="[object String]",it="[object Symbol]",ot="[object Undefined]",ut="[object WeakMap]",at="[object WeakSet]",st="[object ArrayBuffer]",ct="[object DataView]",ft="[object Float32Array]",lt="[object Float64Array]",At="[object Int8Array]",pt="[object Int16Array]",dt="[object Int32Array]",ht="[object Uint8Array]",vt="[object Uint8ClampedArray]",gt="[object Uint16Array]",mt="[object Uint32Array]",yt=/\b__p \+= '';/g,_t=/\b(__p \+=) '' \+/g,bt=/(__e\(.*?\)|\b__t\)) \+\n'';/g,wt=/&(?:amp|lt|gt|quot|#39);/g,xt=/[&<>"']/g,Et=RegExp(wt.source),Ct=RegExp(xt.source),Bt=/<%-([\s\S]+?)%>/g,jt=/<%([\s\S]+?)%>/g,Rt=/<%=([\s\S]+?)%>/g,St=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ot=/^\w*$/,kt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Tt=/[\\^$.*+?()[\]{}|]/g,Pt=RegExp(Tt.source),It=/^\s+|\s+$/g,Mt=/^\s+/,Nt=/\s+$/,Dt=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,$t=/\{\n\/\* \[wrapped with (.+)\] \*/,Ft=/,? & /,Lt=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,zt=/\\(\\)?/g,Qt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Gt=/\w*$/,Ut=/^[-+]0x[0-9a-f]+$/i,Yt=/^0b[01]+$/i,Wt=/^\[object .+?Constructor\]$/,qt=/^0o[0-7]+$/i,Ht=/^(?:0|[1-9]\d*)$/,Vt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Zt=/($^)/,Jt=/['\n\r\u2028\u2029\\]/g,Kt="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Xt="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",te="[\\ud800-\\udfff]",ee="["+Xt+"]",ne="["+Kt+"]",re="\\d+",ie="[\\u2700-\\u27bf]",oe="[a-z\\xdf-\\xf6\\xf8-\\xff]",ue="[^\\ud800-\\udfff"+Xt+re+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",ae="\\ud83c[\\udffb-\\udfff]",se="[^\\ud800-\\udfff]",ce="(?:\\ud83c[\\udde6-\\uddff]){2}",fe="[\\ud800-\\udbff][\\udc00-\\udfff]",le="[A-Z\\xc0-\\xd6\\xd8-\\xde]",Ae="(?:"+oe+"|"+ue+")",pe="(?:"+le+"|"+ue+")",de="(?:"+ne+"|"+ae+")"+"?",he="[\\ufe0e\\ufe0f]?"+de+("(?:\\u200d(?:"+[se,ce,fe].join("|")+")[\\ufe0e\\ufe0f]?"+de+")*"),ve="(?:"+[ie,ce,fe].join("|")+")"+he,ge="(?:"+[se+ne+"?",ne,ce,fe,te].join("|")+")",me=RegExp("['’]","g"),ye=RegExp(ne,"g"),_e=RegExp(ae+"(?="+ae+")|"+ge+he,"g"),be=RegExp([le+"?"+oe+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[ee,le,"$"].join("|")+")",pe+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[ee,le+Ae,"$"].join("|")+")",le+"?"+Ae+"+(?:['’](?:d|ll|m|re|s|t|ve))?",le+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",re,ve].join("|"),"g"),we=RegExp("[\\u200d\\ud800-\\udfff"+Kt+"\\ufe0e\\ufe0f]"),xe=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Ee=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Ce=-1,Be={};Be[ft]=Be[lt]=Be[At]=Be[pt]=Be[dt]=Be[ht]=Be[vt]=Be[gt]=Be[mt]=!0,Be[z]=Be[Q]=Be[st]=Be[U]=Be[ct]=Be[Y]=Be[q]=Be[H]=Be[Z]=Be[J]=Be[X]=Be[et]=Be[nt]=Be[rt]=Be[ut]=!1;var je={};je[z]=je[Q]=je[st]=je[ct]=je[U]=je[Y]=je[ft]=je[lt]=je[At]=je[pt]=je[dt]=je[Z]=je[J]=je[X]=je[et]=je[nt]=je[rt]=je[it]=je[ht]=je[vt]=je[gt]=je[mt]=!0,je[q]=je[H]=je[ut]=!1;var Re={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Se=parseFloat,Oe=parseInt,ke="object"==typeof t&&t&&t.Object===Object&&t,Te="object"==typeof self&&self&&self.Object===Object&&self,Pe=ke||Te||Function("return this")(),Ie="object"==typeof e&&e&&!e.nodeType&&e,Me=Ie&&"object"==typeof r&&r&&!r.nodeType&&r,Ne=Me&&Me.exports===Ie,De=Ne&&ke.process,$e=function(){try{var t=Me&&Me.require&&Me.require("util").types;return t||De&&De.binding&&De.binding("util")}catch(t){}}(),Fe=$e&&$e.isArrayBuffer,Le=$e&&$e.isDate,ze=$e&&$e.isMap,Qe=$e&&$e.isRegExp,Ge=$e&&$e.isSet,Ue=$e&&$e.isTypedArray;function Ye(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function We(t,e,n,r){for(var i=-1,o=null==t?0:t.length;++i<o;){var u=t[i];e(r,u,n(u),t)}return r}function qe(t,e){for(var n=-1,r=null==t?0:t.length;++n<r&&!1!==e(t[n],n,t););return t}function He(t,e){for(var n=null==t?0:t.length;n--&&!1!==e(t[n],n,t););return t}function Ve(t,e){for(var n=-1,r=null==t?0:t.length;++n<r;)if(!e(t[n],n,t))return!1;return!0}function Ze(t,e){for(var n=-1,r=null==t?0:t.length,i=0,o=[];++n<r;){var u=t[n];e(u,n,t)&&(o[i++]=u)}return o}function Je(t,e){return!!(null==t?0:t.length)&&sn(t,e,0)>-1}function Ke(t,e,n){for(var r=-1,i=null==t?0:t.length;++r<i;)if(n(e,t[r]))return!0;return!1}function Xe(t,e){for(var n=-1,r=null==t?0:t.length,i=Array(r);++n<r;)i[n]=e(t[n],n,t);return i}function tn(t,e){for(var n=-1,r=e.length,i=t.length;++n<r;)t[i+n]=e[n];return t}function en(t,e,n,r){var i=-1,o=null==t?0:t.length;for(r&&o&&(n=t[++i]);++i<o;)n=e(n,t[i],i,t);return n}function nn(t,e,n,r){var i=null==t?0:t.length;for(r&&i&&(n=t[--i]);i--;)n=e(n,t[i],i,t);return n}function rn(t,e){for(var n=-1,r=null==t?0:t.length;++n<r;)if(e(t[n],n,t))return!0;return!1}var on=An("length");function un(t,e,n){var r;return n(t,function(t,n,i){if(e(t,n,i))return r=n,!1}),r}function an(t,e,n,r){for(var i=t.length,o=n+(r?1:-1);r?o--:++o<i;)if(e(t[o],o,t))return o;return-1}function sn(t,e,n){return e==e?function(t,e,n){var r=n-1,i=t.length;for(;++r<i;)if(t[r]===e)return r;return-1}(t,e,n):an(t,fn,n)}function cn(t,e,n,r){for(var i=n-1,o=t.length;++i<o;)if(r(t[i],e))return i;return-1}function fn(t){return t!=t}function ln(t,e){var n=null==t?0:t.length;return n?hn(t,e)/n:N}function An(t){return function(e){return null==e?o:e[t]}}function pn(t){return function(e){return null==t?o:t[e]}}function dn(t,e,n,r,i){return i(t,function(t,i,o){n=r?(r=!1,t):e(n,t,i,o)}),n}function hn(t,e){for(var n,r=-1,i=t.length;++r<i;){var u=e(t[r]);u!==o&&(n=n===o?u:n+u)}return n}function vn(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}function gn(t){return function(e){return t(e)}}function mn(t,e){return Xe(e,function(e){return t[e]})}function yn(t,e){return t.has(e)}function _n(t,e){for(var n=-1,r=t.length;++n<r&&sn(e,t[n],0)>-1;);return n}function bn(t,e){for(var n=t.length;n--&&sn(e,t[n],0)>-1;);return n}var wn=pn({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),xn=pn({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function En(t){return"\\"+Re[t]}function Cn(t){return we.test(t)}function Bn(t){var e=-1,n=Array(t.size);return t.forEach(function(t,r){n[++e]=[r,t]}),n}function jn(t,e){return function(n){return t(e(n))}}function Rn(t,e){for(var n=-1,r=t.length,i=0,o=[];++n<r;){var u=t[n];u!==e&&u!==l||(t[n]=l,o[i++]=n)}return o}function Sn(t){var e=-1,n=Array(t.size);return t.forEach(function(t){n[++e]=t}),n}function On(t){var e=-1,n=Array(t.size);return t.forEach(function(t){n[++e]=[t,t]}),n}function kn(t){return Cn(t)?function(t){var e=_e.lastIndex=0;for(;_e.test(t);)++e;return e}(t):on(t)}function Tn(t){return Cn(t)?function(t){return t.match(_e)||[]}(t):function(t){return t.split("")}(t)}var Pn=pn({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"});var In=function t(e){var n,r=(e=null==e?Pe:In.defaults(Pe.Object(),e,In.pick(Pe,Ee))).Array,i=e.Date,Kt=e.Error,Xt=e.Function,te=e.Math,ee=e.Object,ne=e.RegExp,re=e.String,ie=e.TypeError,oe=r.prototype,ue=Xt.prototype,ae=ee.prototype,se=e["__core-js_shared__"],ce=ue.toString,fe=ae.hasOwnProperty,le=0,Ae=(n=/[^.]+$/.exec(se&&se.keys&&se.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"",pe=ae.toString,de=ce.call(ee),he=Pe._,ve=ne("^"+ce.call(fe).replace(Tt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ge=Ne?e.Buffer:o,_e=e.Symbol,we=e.Uint8Array,Re=ge?ge.allocUnsafe:o,ke=jn(ee.getPrototypeOf,ee),Te=ee.create,Ie=ae.propertyIsEnumerable,Me=oe.splice,De=_e?_e.isConcatSpreadable:o,$e=_e?_e.iterator:o,on=_e?_e.toStringTag:o,pn=function(){try{var t=Fo(ee,"defineProperty");return t({},"",{}),t}catch(t){}}(),Mn=e.clearTimeout!==Pe.clearTimeout&&e.clearTimeout,Nn=i&&i.now!==Pe.Date.now&&i.now,Dn=e.setTimeout!==Pe.setTimeout&&e.setTimeout,$n=te.ceil,Fn=te.floor,Ln=ee.getOwnPropertySymbols,zn=ge?ge.isBuffer:o,Qn=e.isFinite,Gn=oe.join,Un=jn(ee.keys,ee),Yn=te.max,Wn=te.min,qn=i.now,Hn=e.parseInt,Vn=te.random,Zn=oe.reverse,Jn=Fo(e,"DataView"),Kn=Fo(e,"Map"),Xn=Fo(e,"Promise"),tr=Fo(e,"Set"),er=Fo(e,"WeakMap"),nr=Fo(ee,"create"),rr=er&&new er,ir={},or=lu(Jn),ur=lu(Kn),ar=lu(Xn),sr=lu(tr),cr=lu(er),fr=_e?_e.prototype:o,lr=fr?fr.valueOf:o,Ar=fr?fr.toString:o;function pr(t){if(Ra(t)&&!ga(t)&&!(t instanceof gr)){if(t instanceof vr)return t;if(fe.call(t,"__wrapped__"))return Au(t)}return new vr(t)}var dr=function(){function t(){}return function(e){if(!ja(e))return{};if(Te)return Te(e);t.prototype=e;var n=new t;return t.prototype=o,n}}();function hr(){}function vr(t,e){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!e,this.__index__=0,this.__values__=o}function gr(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=D,this.__views__=[]}function mr(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function yr(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function _r(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function br(t){var e=-1,n=null==t?0:t.length;for(this.__data__=new _r;++e<n;)this.add(t[e])}function wr(t){var e=this.__data__=new yr(t);this.size=e.size}function xr(t,e){var n=ga(t),r=!n&&va(t),i=!n&&!r&&ba(t),o=!n&&!r&&!i&&Na(t),u=n||r||i||o,a=u?vn(t.length,re):[],s=a.length;for(var c in t)!e&&!fe.call(t,c)||u&&("length"==c||i&&("offset"==c||"parent"==c)||o&&("buffer"==c||"byteLength"==c||"byteOffset"==c)||Wo(c,s))||a.push(c);return a}function Er(t){var e=t.length;return e?t[bi(0,e-1)]:o}function Cr(t,e){return su(no(t),Ir(e,0,t.length))}function Br(t){return su(no(t))}function jr(t,e,n){(n===o||pa(t[e],n))&&(n!==o||e in t)||Tr(t,e,n)}function Rr(t,e,n){var r=t[e];fe.call(t,e)&&pa(r,n)&&(n!==o||e in t)||Tr(t,e,n)}function Sr(t,e){for(var n=t.length;n--;)if(pa(t[n][0],e))return n;return-1}function Or(t,e,n,r){return Fr(t,function(t,i,o){e(r,t,n(t),o)}),r}function kr(t,e){return t&&ro(e,is(e),t)}function Tr(t,e,n){"__proto__"==e&&pn?pn(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}function Pr(t,e){for(var n=-1,i=e.length,u=r(i),a=null==t;++n<i;)u[n]=a?o:Xa(t,e[n]);return u}function Ir(t,e,n){return t==t&&(n!==o&&(t=t<=n?t:n),e!==o&&(t=t>=e?t:e)),t}function Mr(t,e,n,r,i,u){var a,s=e&A,c=e&p,f=e&d;if(n&&(a=i?n(t,r,i,u):n(t)),a!==o)return a;if(!ja(t))return t;var l=ga(t);if(l){if(a=function(t){var e=t.length,n=new t.constructor(e);return e&&"string"==typeof t[0]&&fe.call(t,"index")&&(n.index=t.index,n.input=t.input),n}(t),!s)return no(t,a)}else{var h=Qo(t),v=h==H||h==V;if(ba(t))return Zi(t,s);if(h==X||h==z||v&&!i){if(a=c||v?{}:Uo(t),!s)return c?function(t,e){return ro(t,zo(t),e)}(t,function(t,e){return t&&ro(e,os(e),t)}(a,t)):function(t,e){return ro(t,Lo(t),e)}(t,kr(a,t))}else{if(!je[h])return i?t:{};a=function(t,e,n){var r,i,o,u=t.constructor;switch(e){case st:return Ji(t);case U:case Y:return new u(+t);case ct:return function(t,e){var n=e?Ji(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}(t,n);case ft:case lt:case At:case pt:case dt:case ht:case vt:case gt:case mt:return Ki(t,n);case Z:return new u;case J:case rt:return new u(t);case et:return(o=new(i=t).constructor(i.source,Gt.exec(i))).lastIndex=i.lastIndex,o;case nt:return new u;case it:return r=t,lr?ee(lr.call(r)):{}}}(t,h,s)}}u||(u=new wr);var g=u.get(t);if(g)return g;u.set(t,a),Pa(t)?t.forEach(function(r){a.add(Mr(r,e,n,r,t,u))}):Sa(t)&&t.forEach(function(r,i){a.set(i,Mr(r,e,n,i,t,u))});var m=l?o:(f?c?To:ko:c?os:is)(t);return qe(m||t,function(r,i){m&&(r=t[i=r]),Rr(a,i,Mr(r,e,n,i,t,u))}),a}function Nr(t,e,n){var r=n.length;if(null==t)return!r;for(t=ee(t);r--;){var i=n[r],u=e[i],a=t[i];if(a===o&&!(i in t)||!u(a))return!1}return!0}function Dr(t,e,n){if("function"!=typeof t)throw new ie(s);return iu(function(){t.apply(o,n)},e)}function $r(t,e,n,r){var i=-1,o=Je,a=!0,s=t.length,c=[],f=e.length;if(!s)return c;n&&(e=Xe(e,gn(n))),r?(o=Ke,a=!1):e.length>=u&&(o=yn,a=!1,e=new br(e));t:for(;++i<s;){var l=t[i],A=null==n?l:n(l);if(l=r||0!==l?l:0,a&&A==A){for(var p=f;p--;)if(e[p]===A)continue t;c.push(l)}else o(e,A,r)||c.push(l)}return c}pr.templateSettings={escape:Bt,evaluate:jt,interpolate:Rt,variable:"",imports:{_:pr}},pr.prototype=hr.prototype,pr.prototype.constructor=pr,vr.prototype=dr(hr.prototype),vr.prototype.constructor=vr,gr.prototype=dr(hr.prototype),gr.prototype.constructor=gr,mr.prototype.clear=function(){this.__data__=nr?nr(null):{},this.size=0},mr.prototype.delete=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e},mr.prototype.get=function(t){var e=this.__data__;if(nr){var n=e[t];return n===c?o:n}return fe.call(e,t)?e[t]:o},mr.prototype.has=function(t){var e=this.__data__;return nr?e[t]!==o:fe.call(e,t)},mr.prototype.set=function(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=nr&&e===o?c:e,this},yr.prototype.clear=function(){this.__data__=[],this.size=0},yr.prototype.delete=function(t){var e=this.__data__,n=Sr(e,t);return!(n<0||(n==e.length-1?e.pop():Me.call(e,n,1),--this.size,0))},yr.prototype.get=function(t){var e=this.__data__,n=Sr(e,t);return n<0?o:e[n][1]},yr.prototype.has=function(t){return Sr(this.__data__,t)>-1},yr.prototype.set=function(t,e){var n=this.__data__,r=Sr(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this},_r.prototype.clear=function(){this.size=0,this.__data__={hash:new mr,map:new(Kn||yr),string:new mr}},_r.prototype.delete=function(t){var e=Do(this,t).delete(t);return this.size-=e?1:0,e},_r.prototype.get=function(t){return Do(this,t).get(t)},_r.prototype.has=function(t){return Do(this,t).has(t)},_r.prototype.set=function(t,e){var n=Do(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this},br.prototype.add=br.prototype.push=function(t){return this.__data__.set(t,c),this},br.prototype.has=function(t){return this.__data__.has(t)},wr.prototype.clear=function(){this.__data__=new yr,this.size=0},wr.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},wr.prototype.get=function(t){return this.__data__.get(t)},wr.prototype.has=function(t){return this.__data__.has(t)},wr.prototype.set=function(t,e){var n=this.__data__;if(n instanceof yr){var r=n.__data__;if(!Kn||r.length<u-1)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new _r(r)}return n.set(t,e),this.size=n.size,this};var Fr=uo(qr),Lr=uo(Hr,!0);function zr(t,e){var n=!0;return Fr(t,function(t,r,i){return n=!!e(t,r,i)}),n}function Qr(t,e,n){for(var r=-1,i=t.length;++r<i;){var u=t[r],a=e(u);if(null!=a&&(s===o?a==a&&!Ma(a):n(a,s)))var s=a,c=u}return c}function Gr(t,e){var n=[];return Fr(t,function(t,r,i){e(t,r,i)&&n.push(t)}),n}function Ur(t,e,n,r,i){var o=-1,u=t.length;for(n||(n=Yo),i||(i=[]);++o<u;){var a=t[o];e>0&&n(a)?e>1?Ur(a,e-1,n,r,i):tn(i,a):r||(i[i.length]=a)}return i}var Yr=ao(),Wr=ao(!0);function qr(t,e){return t&&Yr(t,e,is)}function Hr(t,e){return t&&Wr(t,e,is)}function Vr(t,e){return Ze(e,function(e){return Ea(t[e])})}function Zr(t,e){for(var n=0,r=(e=Wi(e,t)).length;null!=t&&n<r;)t=t[fu(e[n++])];return n&&n==r?t:o}function Jr(t,e,n){var r=e(t);return ga(t)?r:tn(r,n(t))}function Kr(t){return null==t?t===o?ot:K:on&&on in ee(t)?function(t){var e=fe.call(t,on),n=t[on];try{t[on]=o;var r=!0}catch(t){}var i=pe.call(t);return r&&(e?t[on]=n:delete t[on]),i}(t):function(t){return pe.call(t)}(t)}function Xr(t,e){return t>e}function ti(t,e){return null!=t&&fe.call(t,e)}function ei(t,e){return null!=t&&e in ee(t)}function ni(t,e,n){for(var i=n?Ke:Je,u=t[0].length,a=t.length,s=a,c=r(a),f=1/0,l=[];s--;){var A=t[s];s&&e&&(A=Xe(A,gn(e))),f=Wn(A.length,f),c[s]=!n&&(e||u>=120&&A.length>=120)?new br(s&&A):o}A=t[0];var p=-1,d=c[0];t:for(;++p<u&&l.length<f;){var h=A[p],v=e?e(h):h;if(h=n||0!==h?h:0,!(d?yn(d,v):i(l,v,n))){for(s=a;--s;){var g=c[s];if(!(g?yn(g,v):i(t[s],v,n)))continue t}d&&d.push(v),l.push(h)}}return l}function ri(t,e,n){var r=null==(t=eu(t,e=Wi(e,t)))?t:t[fu(xu(e))];return null==r?o:Ye(r,t,n)}function ii(t){return Ra(t)&&Kr(t)==z}function oi(t,e,n,r,i){return t===e||(null==t||null==e||!Ra(t)&&!Ra(e)?t!=t&&e!=e:function(t,e,n,r,i,u){var a=ga(t),s=ga(e),c=a?Q:Qo(t),f=s?Q:Qo(e),l=(c=c==z?X:c)==X,A=(f=f==z?X:f)==X,p=c==f;if(p&&ba(t)){if(!ba(e))return!1;a=!0,l=!1}if(p&&!l)return u||(u=new wr),a||Na(t)?So(t,e,n,r,i,u):function(t,e,n,r,i,o,u){switch(n){case ct:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case st:return!(t.byteLength!=e.byteLength||!o(new we(t),new we(e)));case U:case Y:case J:return pa(+t,+e);case q:return t.name==e.name&&t.message==e.message;case et:case rt:return t==e+"";case Z:var a=Bn;case nt:var s=r&h;if(a||(a=Sn),t.size!=e.size&&!s)return!1;var c=u.get(t);if(c)return c==e;r|=v,u.set(t,e);var f=So(a(t),a(e),r,i,o,u);return u.delete(t),f;case it:if(lr)return lr.call(t)==lr.call(e)}return!1}(t,e,c,n,r,i,u);if(!(n&h)){var d=l&&fe.call(t,"__wrapped__"),g=A&&fe.call(e,"__wrapped__");if(d||g){var m=d?t.value():t,y=g?e.value():e;return u||(u=new wr),i(m,y,n,r,u)}}return!!p&&(u||(u=new wr),function(t,e,n,r,i,u){var a=n&h,s=ko(t),c=s.length,f=ko(e).length;if(c!=f&&!a)return!1;for(var l=c;l--;){var A=s[l];if(!(a?A in e:fe.call(e,A)))return!1}var p=u.get(t),d=u.get(e);if(p&&d)return p==e&&d==t;var v=!0;u.set(t,e),u.set(e,t);for(var g=a;++l<c;){A=s[l];var m=t[A],y=e[A];if(r)var _=a?r(y,m,A,e,t,u):r(m,y,A,t,e,u);if(!(_===o?m===y||i(m,y,n,r,u):_)){v=!1;break}g||(g="constructor"==A)}if(v&&!g){var b=t.constructor,w=e.constructor;b!=w&&"constructor"in t&&"constructor"in e&&!("function"==typeof b&&b instanceof b&&"function"==typeof w&&w instanceof w)&&(v=!1)}return u.delete(t),u.delete(e),v}(t,e,n,r,i,u))}(t,e,n,r,oi,i))}function ui(t,e,n,r){var i=n.length,u=i,a=!r;if(null==t)return!u;for(t=ee(t);i--;){var s=n[i];if(a&&s[2]?s[1]!==t[s[0]]:!(s[0]in t))return!1}for(;++i<u;){var c=(s=n[i])[0],f=t[c],l=s[1];if(a&&s[2]){if(f===o&&!(c in t))return!1}else{var A=new wr;if(r)var p=r(f,l,c,t,e,A);if(!(p===o?oi(l,f,h|v,r,A):p))return!1}}return!0}function ai(t){return!(!ja(t)||Ae&&Ae in t)&&(Ea(t)?ve:Wt).test(lu(t))}function si(t){return"function"==typeof t?t:null==t?Os:"object"==typeof t?ga(t)?di(t[0],t[1]):pi(t):Fs(t)}function ci(t){if(!Jo(t))return Un(t);var e=[];for(var n in ee(t))fe.call(t,n)&&"constructor"!=n&&e.push(n);return e}function fi(t){if(!ja(t))return function(t){var e=[];if(null!=t)for(var n in ee(t))e.push(n);return e}(t);var e=Jo(t),n=[];for(var r in t)("constructor"!=r||!e&&fe.call(t,r))&&n.push(r);return n}function li(t,e){return t<e}function Ai(t,e){var n=-1,i=ya(t)?r(t.length):[];return Fr(t,function(t,r,o){i[++n]=e(t,r,o)}),i}function pi(t){var e=$o(t);return 1==e.length&&e[0][2]?Xo(e[0][0],e[0][1]):function(n){return n===t||ui(n,t,e)}}function di(t,e){return Ho(t)&&Ko(e)?Xo(fu(t),e):function(n){var r=Xa(n,t);return r===o&&r===e?ts(n,t):oi(e,r,h|v)}}function hi(t,e,n,r,i){t!==e&&Yr(e,function(u,a){if(i||(i=new wr),ja(u))!function(t,e,n,r,i,u,a){var s=nu(t,n),c=nu(e,n),f=a.get(c);if(f)jr(t,n,f);else{var l=u?u(s,c,n+"",t,e,a):o,A=l===o;if(A){var p=ga(c),d=!p&&ba(c),h=!p&&!d&&Na(c);l=c,p||d||h?ga(s)?l=s:_a(s)?l=no(s):d?(A=!1,l=Zi(c,!0)):h?(A=!1,l=Ki(c,!0)):l=[]:ka(c)||va(c)?(l=s,va(s)?l=Ua(s):ja(s)&&!Ea(s)||(l=Uo(c))):A=!1}A&&(a.set(c,l),i(l,c,r,u,a),a.delete(c)),jr(t,n,l)}}(t,e,a,n,hi,r,i);else{var s=r?r(nu(t,a),u,a+"",t,e,i):o;s===o&&(s=u),jr(t,a,s)}},os)}function vi(t,e){var n=t.length;if(n)return Wo(e+=e<0?n:0,n)?t[e]:o}function gi(t,e,n){var r=-1;return e=Xe(e=e.length?Xe(e,function(t){return ga(t)?function(e){return Zr(e,1===t.length?t[0]:t)}:t}):[Os],gn(No())),function(t,e){var n=t.length;for(t.sort(e);n--;)t[n]=t[n].value;return t}(Ai(t,function(t,n,i){return{criteria:Xe(e,function(e){return e(t)}),index:++r,value:t}}),function(t,e){return function(t,e,n){for(var r=-1,i=t.criteria,o=e.criteria,u=i.length,a=n.length;++r<u;){var s=Xi(i[r],o[r]);if(s){if(r>=a)return s;var c=n[r];return s*("desc"==c?-1:1)}}return t.index-e.index}(t,e,n)})}function mi(t,e,n){for(var r=-1,i=e.length,o={};++r<i;){var u=e[r],a=Zr(t,u);n(a,u)&&Bi(o,Wi(u,t),a)}return o}function yi(t,e,n,r){var i=r?cn:sn,o=-1,u=e.length,a=t;for(t===e&&(e=no(e)),n&&(a=Xe(t,gn(n)));++o<u;)for(var s=0,c=e[o],f=n?n(c):c;(s=i(a,f,s,r))>-1;)a!==t&&Me.call(a,s,1),Me.call(t,s,1);return t}function _i(t,e){for(var n=t?e.length:0,r=n-1;n--;){var i=e[n];if(n==r||i!==o){var o=i;Wo(i)?Me.call(t,i,1):$i(t,i)}}return t}function bi(t,e){return t+Fn(Vn()*(e-t+1))}function wi(t,e){var n="";if(!t||e<1||e>I)return n;do{e%2&&(n+=t),(e=Fn(e/2))&&(t+=t)}while(e);return n}function xi(t,e){return ou(tu(t,e,Os),t+"")}function Ei(t){return Er(ps(t))}function Ci(t,e){var n=ps(t);return su(n,Ir(e,0,n.length))}function Bi(t,e,n,r){if(!ja(t))return t;for(var i=-1,u=(e=Wi(e,t)).length,a=u-1,s=t;null!=s&&++i<u;){var c=fu(e[i]),f=n;if("__proto__"===c||"constructor"===c||"prototype"===c)return t;if(i!=a){var l=s[c];(f=r?r(l,c,s):o)===o&&(f=ja(l)?l:Wo(e[i+1])?[]:{})}Rr(s,c,f),s=s[c]}return t}var ji=rr?function(t,e){return rr.set(t,e),t}:Os,Ri=pn?function(t,e){return pn(t,"toString",{configurable:!0,enumerable:!1,value:js(e),writable:!0})}:Os;function Si(t){return su(ps(t))}function Oi(t,e,n){var i=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(n=n>o?o:n)<0&&(n+=o),o=e>n?0:n-e>>>0,e>>>=0;for(var u=r(o);++i<o;)u[i]=t[i+e];return u}function ki(t,e){var n;return Fr(t,function(t,r,i){return!(n=e(t,r,i))}),!!n}function Ti(t,e,n){var r=0,i=null==t?r:t.length;if("number"==typeof e&&e==e&&i<=F){for(;r<i;){var o=r+i>>>1,u=t[o];null!==u&&!Ma(u)&&(n?u<=e:u<e)?r=o+1:i=o}return i}return Pi(t,e,Os,n)}function Pi(t,e,n,r){var i=0,u=null==t?0:t.length;if(0===u)return 0;for(var a=(e=n(e))!=e,s=null===e,c=Ma(e),f=e===o;i<u;){var l=Fn((i+u)/2),A=n(t[l]),p=A!==o,d=null===A,h=A==A,v=Ma(A);if(a)var g=r||h;else g=f?h&&(r||p):s?h&&p&&(r||!d):c?h&&p&&!d&&(r||!v):!d&&!v&&(r?A<=e:A<e);g?i=l+1:u=l}return Wn(u,$)}function Ii(t,e){for(var n=-1,r=t.length,i=0,o=[];++n<r;){var u=t[n],a=e?e(u):u;if(!n||!pa(a,s)){var s=a;o[i++]=0===u?0:u}}return o}function Mi(t){return"number"==typeof t?t:Ma(t)?N:+t}function Ni(t){if("string"==typeof t)return t;if(ga(t))return Xe(t,Ni)+"";if(Ma(t))return Ar?Ar.call(t):"";var e=t+"";return"0"==e&&1/t==-P?"-0":e}function Di(t,e,n){var r=-1,i=Je,o=t.length,a=!0,s=[],c=s;if(n)a=!1,i=Ke;else if(o>=u){var f=e?null:xo(t);if(f)return Sn(f);a=!1,i=yn,c=new br}else c=e?[]:s;t:for(;++r<o;){var l=t[r],A=e?e(l):l;if(l=n||0!==l?l:0,a&&A==A){for(var p=c.length;p--;)if(c[p]===A)continue t;e&&c.push(A),s.push(l)}else i(c,A,n)||(c!==s&&c.push(A),s.push(l))}return s}function $i(t,e){return null==(t=eu(t,e=Wi(e,t)))||delete t[fu(xu(e))]}function Fi(t,e,n,r){return Bi(t,e,n(Zr(t,e)),r)}function Li(t,e,n,r){for(var i=t.length,o=r?i:-1;(r?o--:++o<i)&&e(t[o],o,t););return n?Oi(t,r?0:o,r?o+1:i):Oi(t,r?o+1:0,r?i:o)}function zi(t,e){var n=t;return n instanceof gr&&(n=n.value()),en(e,function(t,e){return e.func.apply(e.thisArg,tn([t],e.args))},n)}function Qi(t,e,n){var i=t.length;if(i<2)return i?Di(t[0]):[];for(var o=-1,u=r(i);++o<i;)for(var a=t[o],s=-1;++s<i;)s!=o&&(u[o]=$r(u[o]||a,t[s],e,n));return Di(Ur(u,1),e,n)}function Gi(t,e,n){for(var r=-1,i=t.length,u=e.length,a={};++r<i;){var s=r<u?e[r]:o;n(a,t[r],s)}return a}function Ui(t){return _a(t)?t:[]}function Yi(t){return"function"==typeof t?t:Os}function Wi(t,e){return ga(t)?t:Ho(t,e)?[t]:cu(Ya(t))}var qi=xi;function Hi(t,e,n){var r=t.length;return n=n===o?r:n,!e&&n>=r?t:Oi(t,e,n)}var Vi=Mn||function(t){return Pe.clearTimeout(t)};function Zi(t,e){if(e)return t.slice();var n=t.length,r=Re?Re(n):new t.constructor(n);return t.copy(r),r}function Ji(t){var e=new t.constructor(t.byteLength);return new we(e).set(new we(t)),e}function Ki(t,e){var n=e?Ji(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}function Xi(t,e){if(t!==e){var n=t!==o,r=null===t,i=t==t,u=Ma(t),a=e!==o,s=null===e,c=e==e,f=Ma(e);if(!s&&!f&&!u&&t>e||u&&a&&c&&!s&&!f||r&&a&&c||!n&&c||!i)return 1;if(!r&&!u&&!f&&t<e||f&&n&&i&&!r&&!u||s&&n&&i||!a&&i||!c)return-1}return 0}function to(t,e,n,i){for(var o=-1,u=t.length,a=n.length,s=-1,c=e.length,f=Yn(u-a,0),l=r(c+f),A=!i;++s<c;)l[s]=e[s];for(;++o<a;)(A||o<u)&&(l[n[o]]=t[o]);for(;f--;)l[s++]=t[o++];return l}function eo(t,e,n,i){for(var o=-1,u=t.length,a=-1,s=n.length,c=-1,f=e.length,l=Yn(u-s,0),A=r(l+f),p=!i;++o<l;)A[o]=t[o];for(var d=o;++c<f;)A[d+c]=e[c];for(;++a<s;)(p||o<u)&&(A[d+n[a]]=t[o++]);return A}function no(t,e){var n=-1,i=t.length;for(e||(e=r(i));++n<i;)e[n]=t[n];return e}function ro(t,e,n,r){var i=!n;n||(n={});for(var u=-1,a=e.length;++u<a;){var s=e[u],c=r?r(n[s],t[s],s,n,t):o;c===o&&(c=t[s]),i?Tr(n,s,c):Rr(n,s,c)}return n}function io(t,e){return function(n,r){var i=ga(n)?We:Or,o=e?e():{};return i(n,t,No(r,2),o)}}function oo(t){return xi(function(e,n){var r=-1,i=n.length,u=i>1?n[i-1]:o,a=i>2?n[2]:o;for(u=t.length>3&&"function"==typeof u?(i--,u):o,a&&qo(n[0],n[1],a)&&(u=i<3?o:u,i=1),e=ee(e);++r<i;){var s=n[r];s&&t(e,s,r,u)}return e})}function uo(t,e){return function(n,r){if(null==n)return n;if(!ya(n))return t(n,r);for(var i=n.length,o=e?i:-1,u=ee(n);(e?o--:++o<i)&&!1!==r(u[o],o,u););return n}}function ao(t){return function(e,n,r){for(var i=-1,o=ee(e),u=r(e),a=u.length;a--;){var s=u[t?a:++i];if(!1===n(o[s],s,o))break}return e}}function so(t){return function(e){var n=Cn(e=Ya(e))?Tn(e):o,r=n?n[0]:e.charAt(0),i=n?Hi(n,1).join(""):e.slice(1);return r[t]()+i}}function co(t){return function(e){return en(Es(vs(e).replace(me,"")),t,"")}}function fo(t){return function(){var e=arguments;switch(e.length){case 0:return new t;case 1:return new t(e[0]);case 2:return new t(e[0],e[1]);case 3:return new t(e[0],e[1],e[2]);case 4:return new t(e[0],e[1],e[2],e[3]);case 5:return new t(e[0],e[1],e[2],e[3],e[4]);case 6:return new t(e[0],e[1],e[2],e[3],e[4],e[5]);case 7:return new t(e[0],e[1],e[2],e[3],e[4],e[5],e[6])}var n=dr(t.prototype),r=t.apply(n,e);return ja(r)?r:n}}function lo(t){return function(e,n,r){var i=ee(e);if(!ya(e)){var u=No(n,3);e=is(e),n=function(t){return u(i[t],t,i)}}var a=t(e,n,r);return a>-1?i[u?e[a]:a]:o}}function Ao(t){return Oo(function(e){var n=e.length,r=n,i=vr.prototype.thru;for(t&&e.reverse();r--;){var u=e[r];if("function"!=typeof u)throw new ie(s);if(i&&!a&&"wrapper"==Io(u))var a=new vr([],!0)}for(r=a?r:n;++r<n;){var c=Io(u=e[r]),f="wrapper"==c?Po(u):o;a=f&&Vo(f[0])&&f[1]==(E|_|w|C)&&!f[4].length&&1==f[9]?a[Io(f[0])].apply(a,f[3]):1==u.length&&Vo(u)?a[c]():a.thru(u)}return function(){var t=arguments,r=t[0];if(a&&1==t.length&&ga(r))return a.plant(r).value();for(var i=0,o=n?e[i].apply(this,t):r;++i<n;)o=e[i].call(this,o);return o}})}function po(t,e,n,i,u,a,s,c,f,l){var A=e&E,p=e&g,d=e&m,h=e&(_|b),v=e&B,y=d?o:fo(t);return function g(){for(var m=arguments.length,_=r(m),b=m;b--;)_[b]=arguments[b];if(h)var w=Mo(g),x=function(t,e){for(var n=t.length,r=0;n--;)t[n]===e&&++r;return r}(_,w);if(i&&(_=to(_,i,u,h)),a&&(_=eo(_,a,s,h)),m-=x,h&&m<l){var E=Rn(_,w);return bo(t,e,po,g.placeholder,n,_,E,c,f,l-m)}var C=p?n:this,B=d?C[t]:t;return m=_.length,c?_=function(t,e){for(var n=t.length,r=Wn(e.length,n),i=no(t);r--;){var u=e[r];t[r]=Wo(u,n)?i[u]:o}return t}(_,c):v&&m>1&&_.reverse(),A&&f<m&&(_.length=f),this&&this!==Pe&&this instanceof g&&(B=y||fo(B)),B.apply(C,_)}}function ho(t,e){return function(n,r){return function(t,e,n,r){return qr(t,function(t,i,o){e(r,n(t),i,o)}),r}(n,t,e(r),{})}}function vo(t,e){return function(n,r){var i;if(n===o&&r===o)return e;if(n!==o&&(i=n),r!==o){if(i===o)return r;"string"==typeof n||"string"==typeof r?(n=Ni(n),r=Ni(r)):(n=Mi(n),r=Mi(r)),i=t(n,r)}return i}}function go(t){return Oo(function(e){return e=Xe(e,gn(No())),xi(function(n){var r=this;return t(e,function(t){return Ye(t,r,n)})})})}function mo(t,e){var n=(e=e===o?" ":Ni(e)).length;if(n<2)return n?wi(e,t):e;var r=wi(e,$n(t/kn(e)));return Cn(e)?Hi(Tn(r),0,t).join(""):r.slice(0,t)}function yo(t){return function(e,n,i){return i&&"number"!=typeof i&&qo(e,n,i)&&(n=i=o),e=La(e),n===o?(n=e,e=0):n=La(n),function(t,e,n,i){for(var o=-1,u=Yn($n((e-t)/(n||1)),0),a=r(u);u--;)a[i?u:++o]=t,t+=n;return a}(e,n,i=i===o?e<n?1:-1:La(i),t)}}function _o(t){return function(e,n){return"string"==typeof e&&"string"==typeof n||(e=Ga(e),n=Ga(n)),t(e,n)}}function bo(t,e,n,r,i,u,a,s,c,f){var l=e&_;e|=l?w:x,(e&=~(l?x:w))&y||(e&=~(g|m));var A=[t,e,i,l?u:o,l?a:o,l?o:u,l?o:a,s,c,f],p=n.apply(o,A);return Vo(t)&&ru(p,A),p.placeholder=r,uu(p,t,e)}function wo(t){var e=te[t];return function(t,n){if(t=Ga(t),(n=null==n?0:Wn(za(n),292))&&Qn(t)){var r=(Ya(t)+"e").split("e");return+((r=(Ya(e(r[0]+"e"+(+r[1]+n)))+"e").split("e"))[0]+"e"+(+r[1]-n))}return e(t)}}var xo=tr&&1/Sn(new tr([,-0]))[1]==P?function(t){return new tr(t)}:Ms;function Eo(t){return function(e){var n=Qo(e);return n==Z?Bn(e):n==nt?On(e):function(t,e){return Xe(e,function(e){return[e,t[e]]})}(e,t(e))}}function Co(t,e,n,i,u,a,c,f){var A=e&m;if(!A&&"function"!=typeof t)throw new ie(s);var p=i?i.length:0;if(p||(e&=~(w|x),i=u=o),c=c===o?c:Yn(za(c),0),f=f===o?f:za(f),p-=u?u.length:0,e&x){var d=i,h=u;i=u=o}var v=A?o:Po(t),B=[t,e,n,i,u,d,h,a,c,f];if(v&&function(t,e){var n=t[1],r=e[1],i=n|r,o=i<(g|m|E),u=r==E&&n==_||r==E&&n==C&&t[7].length<=e[8]||r==(E|C)&&e[7].length<=e[8]&&n==_;if(!o&&!u)return t;r&g&&(t[2]=e[2],i|=n&g?0:y);var a=e[3];if(a){var s=t[3];t[3]=s?to(s,a,e[4]):a,t[4]=s?Rn(t[3],l):e[4]}(a=e[5])&&(s=t[5],t[5]=s?eo(s,a,e[6]):a,t[6]=s?Rn(t[5],l):e[6]),(a=e[7])&&(t[7]=a),r&E&&(t[8]=null==t[8]?e[8]:Wn(t[8],e[8])),null==t[9]&&(t[9]=e[9]),t[0]=e[0],t[1]=i}(B,v),t=B[0],e=B[1],n=B[2],i=B[3],u=B[4],!(f=B[9]=B[9]===o?A?0:t.length:Yn(B[9]-p,0))&&e&(_|b)&&(e&=~(_|b)),e&&e!=g)j=e==_||e==b?function(t,e,n){var i=fo(t);return function u(){for(var a=arguments.length,s=r(a),c=a,f=Mo(u);c--;)s[c]=arguments[c];var l=a<3&&s[0]!==f&&s[a-1]!==f?[]:Rn(s,f);return(a-=l.length)<n?bo(t,e,po,u.placeholder,o,s,l,o,o,n-a):Ye(this&&this!==Pe&&this instanceof u?i:t,this,s)}}(t,e,f):e!=w&&e!=(g|w)||u.length?po.apply(o,B):function(t,e,n,i){var o=e&g,u=fo(t);return function e(){for(var a=-1,s=arguments.length,c=-1,f=i.length,l=r(f+s),A=this&&this!==Pe&&this instanceof e?u:t;++c<f;)l[c]=i[c];for(;s--;)l[c++]=arguments[++a];return Ye(A,o?n:this,l)}}(t,e,n,i);else var j=function(t,e,n){var r=e&g,i=fo(t);return function e(){return(this&&this!==Pe&&this instanceof e?i:t).apply(r?n:this,arguments)}}(t,e,n);return uu((v?ji:ru)(j,B),t,e)}function Bo(t,e,n,r){return t===o||pa(t,ae[n])&&!fe.call(r,n)?e:t}function jo(t,e,n,r,i,u){return ja(t)&&ja(e)&&(u.set(e,t),hi(t,e,o,jo,u),u.delete(e)),t}function Ro(t){return ka(t)?o:t}function So(t,e,n,r,i,u){var a=n&h,s=t.length,c=e.length;if(s!=c&&!(a&&c>s))return!1;var f=u.get(t),l=u.get(e);if(f&&l)return f==e&&l==t;var A=-1,p=!0,d=n&v?new br:o;for(u.set(t,e),u.set(e,t);++A<s;){var g=t[A],m=e[A];if(r)var y=a?r(m,g,A,e,t,u):r(g,m,A,t,e,u);if(y!==o){if(y)continue;p=!1;break}if(d){if(!rn(e,function(t,e){if(!yn(d,e)&&(g===t||i(g,t,n,r,u)))return d.push(e)})){p=!1;break}}else if(g!==m&&!i(g,m,n,r,u)){p=!1;break}}return u.delete(t),u.delete(e),p}function Oo(t){return ou(tu(t,o,mu),t+"")}function ko(t){return Jr(t,is,Lo)}function To(t){return Jr(t,os,zo)}var Po=rr?function(t){return rr.get(t)}:Ms;function Io(t){for(var e=t.name+"",n=ir[e],r=fe.call(ir,e)?n.length:0;r--;){var i=n[r],o=i.func;if(null==o||o==t)return i.name}return e}function Mo(t){return(fe.call(pr,"placeholder")?pr:t).placeholder}function No(){var t=pr.iteratee||ks;return t=t===ks?si:t,arguments.length?t(arguments[0],arguments[1]):t}function Do(t,e){var n,r,i=t.__data__;return("string"==(r=typeof(n=e))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==n:null===n)?i["string"==typeof e?"string":"hash"]:i.map}function $o(t){for(var e=is(t),n=e.length;n--;){var r=e[n],i=t[r];e[n]=[r,i,Ko(i)]}return e}function Fo(t,e){var n=function(t,e){return null==t?o:t[e]}(t,e);return ai(n)?n:o}var Lo=Ln?function(t){return null==t?[]:(t=ee(t),Ze(Ln(t),function(e){return Ie.call(t,e)}))}:Qs,zo=Ln?function(t){for(var e=[];t;)tn(e,Lo(t)),t=ke(t);return e}:Qs,Qo=Kr;function Go(t,e,n){for(var r=-1,i=(e=Wi(e,t)).length,o=!1;++r<i;){var u=fu(e[r]);if(!(o=null!=t&&n(t,u)))break;t=t[u]}return o||++r!=i?o:!!(i=null==t?0:t.length)&&Ba(i)&&Wo(u,i)&&(ga(t)||va(t))}function Uo(t){return"function"!=typeof t.constructor||Jo(t)?{}:dr(ke(t))}function Yo(t){return ga(t)||va(t)||!!(De&&t&&t[De])}function Wo(t,e){var n=typeof t;return!!(e=null==e?I:e)&&("number"==n||"symbol"!=n&&Ht.test(t))&&t>-1&&t%1==0&&t<e}function qo(t,e,n){if(!ja(n))return!1;var r=typeof e;return!!("number"==r?ya(n)&&Wo(e,n.length):"string"==r&&e in n)&&pa(n[e],t)}function Ho(t,e){if(ga(t))return!1;var n=typeof t;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=t&&!Ma(t))||Ot.test(t)||!St.test(t)||null!=e&&t in ee(e)}function Vo(t){var e=Io(t),n=pr[e];if("function"!=typeof n||!(e in gr.prototype))return!1;if(t===n)return!0;var r=Po(n);return!!r&&t===r[0]}(Jn&&Qo(new Jn(new ArrayBuffer(1)))!=ct||Kn&&Qo(new Kn)!=Z||Xn&&"[object Promise]"!=Qo(Xn.resolve())||tr&&Qo(new tr)!=nt||er&&Qo(new er)!=ut)&&(Qo=function(t){var e=Kr(t),n=e==X?t.constructor:o,r=n?lu(n):"";if(r)switch(r){case or:return ct;case ur:return Z;case ar:return"[object Promise]";case sr:return nt;case cr:return ut}return e});var Zo=se?Ea:Gs;function Jo(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||ae)}function Ko(t){return t==t&&!ja(t)}function Xo(t,e){return function(n){return null!=n&&n[t]===e&&(e!==o||t in ee(n))}}function tu(t,e,n){return e=Yn(e===o?t.length-1:e,0),function(){for(var i=arguments,o=-1,u=Yn(i.length-e,0),a=r(u);++o<u;)a[o]=i[e+o];o=-1;for(var s=r(e+1);++o<e;)s[o]=i[o];return s[e]=n(a),Ye(t,this,s)}}function eu(t,e){return e.length<2?t:Zr(t,Oi(e,0,-1))}function nu(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ru=au(ji),iu=Dn||function(t,e){return Pe.setTimeout(t,e)},ou=au(Ri);function uu(t,e,n){var r=e+"";return ou(t,function(t,e){var n=e.length;if(!n)return t;var r=n-1;return e[r]=(n>1?"& ":"")+e[r],e=e.join(n>2?", ":" "),t.replace(Dt,"{\n/* [wrapped with "+e+"] */\n")}(r,function(t,e){return qe(L,function(n){var r="_."+n[0];e&n[1]&&!Je(t,r)&&t.push(r)}),t.sort()}(function(t){var e=t.match($t);return e?e[1].split(Ft):[]}(r),n)))}function au(t){var e=0,n=0;return function(){var r=qn(),i=O-(r-n);if(n=r,i>0){if(++e>=S)return arguments[0]}else e=0;return t.apply(o,arguments)}}function su(t,e){var n=-1,r=t.length,i=r-1;for(e=e===o?r:e;++n<e;){var u=bi(n,i),a=t[u];t[u]=t[n],t[n]=a}return t.length=e,t}var cu=function(t){var e=aa(t,function(t){return n.size===f&&n.clear(),t}),n=e.cache;return e}(function(t){var e=[];return 46===t.charCodeAt(0)&&e.push(""),t.replace(kt,function(t,n,r,i){e.push(r?i.replace(zt,"$1"):n||t)}),e});function fu(t){if("string"==typeof t||Ma(t))return t;var e=t+"";return"0"==e&&1/t==-P?"-0":e}function lu(t){if(null!=t){try{return ce.call(t)}catch(t){}try{return t+""}catch(t){}}return""}function Au(t){if(t instanceof gr)return t.clone();var e=new vr(t.__wrapped__,t.__chain__);return e.__actions__=no(t.__actions__),e.__index__=t.__index__,e.__values__=t.__values__,e}var pu=xi(function(t,e){return _a(t)?$r(t,Ur(e,1,_a,!0)):[]}),du=xi(function(t,e){var n=xu(e);return _a(n)&&(n=o),_a(t)?$r(t,Ur(e,1,_a,!0),No(n,2)):[]}),hu=xi(function(t,e){var n=xu(e);return _a(n)&&(n=o),_a(t)?$r(t,Ur(e,1,_a,!0),o,n):[]});function vu(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=null==n?0:za(n);return i<0&&(i=Yn(r+i,0)),an(t,No(e,3),i)}function gu(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=r-1;return n!==o&&(i=za(n),i=n<0?Yn(r+i,0):Wn(i,r-1)),an(t,No(e,3),i,!0)}function mu(t){return null!=t&&t.length?Ur(t,1):[]}function yu(t){return t&&t.length?t[0]:o}var _u=xi(function(t){var e=Xe(t,Ui);return e.length&&e[0]===t[0]?ni(e):[]}),bu=xi(function(t){var e=xu(t),n=Xe(t,Ui);return e===xu(n)?e=o:n.pop(),n.length&&n[0]===t[0]?ni(n,No(e,2)):[]}),wu=xi(function(t){var e=xu(t),n=Xe(t,Ui);return(e="function"==typeof e?e:o)&&n.pop(),n.length&&n[0]===t[0]?ni(n,o,e):[]});function xu(t){var e=null==t?0:t.length;return e?t[e-1]:o}var Eu=xi(Cu);function Cu(t,e){return t&&t.length&&e&&e.length?yi(t,e):t}var Bu=Oo(function(t,e){var n=null==t?0:t.length,r=Pr(t,e);return _i(t,Xe(e,function(t){return Wo(t,n)?+t:t}).sort(Xi)),r});function ju(t){return null==t?t:Zn.call(t)}var Ru=xi(function(t){return Di(Ur(t,1,_a,!0))}),Su=xi(function(t){var e=xu(t);return _a(e)&&(e=o),Di(Ur(t,1,_a,!0),No(e,2))}),Ou=xi(function(t){var e=xu(t);return e="function"==typeof e?e:o,Di(Ur(t,1,_a,!0),o,e)});function ku(t){if(!t||!t.length)return[];var e=0;return t=Ze(t,function(t){if(_a(t))return e=Yn(t.length,e),!0}),vn(e,function(e){return Xe(t,An(e))})}function Tu(t,e){if(!t||!t.length)return[];var n=ku(t);return null==e?n:Xe(n,function(t){return Ye(e,o,t)})}var Pu=xi(function(t,e){return _a(t)?$r(t,e):[]}),Iu=xi(function(t){return Qi(Ze(t,_a))}),Mu=xi(function(t){var e=xu(t);return _a(e)&&(e=o),Qi(Ze(t,_a),No(e,2))}),Nu=xi(function(t){var e=xu(t);return e="function"==typeof e?e:o,Qi(Ze(t,_a),o,e)}),Du=xi(ku);var $u=xi(function(t){var e=t.length,n=e>1?t[e-1]:o;return Tu(t,n="function"==typeof n?(t.pop(),n):o)});function Fu(t){var e=pr(t);return e.__chain__=!0,e}function Lu(t,e){return e(t)}var zu=Oo(function(t){var e=t.length,n=e?t[0]:0,r=this.__wrapped__,i=function(e){return Pr(e,t)};return!(e>1||this.__actions__.length)&&r instanceof gr&&Wo(n)?((r=r.slice(n,+n+(e?1:0))).__actions__.push({func:Lu,args:[i],thisArg:o}),new vr(r,this.__chain__).thru(function(t){return e&&!t.length&&t.push(o),t})):this.thru(i)});var Qu=io(function(t,e,n){fe.call(t,n)?++t[n]:Tr(t,n,1)});var Gu=lo(vu),Uu=lo(gu);function Yu(t,e){return(ga(t)?qe:Fr)(t,No(e,3))}function Wu(t,e){return(ga(t)?He:Lr)(t,No(e,3))}var qu=io(function(t,e,n){fe.call(t,n)?t[n].push(e):Tr(t,n,[e])});var Hu=xi(function(t,e,n){var i=-1,o="function"==typeof e,u=ya(t)?r(t.length):[];return Fr(t,function(t){u[++i]=o?Ye(e,t,n):ri(t,e,n)}),u}),Vu=io(function(t,e,n){Tr(t,n,e)});function Zu(t,e){return(ga(t)?Xe:Ai)(t,No(e,3))}var Ju=io(function(t,e,n){t[n?0:1].push(e)},function(){return[[],[]]});var Ku=xi(function(t,e){if(null==t)return[];var n=e.length;return n>1&&qo(t,e[0],e[1])?e=[]:n>2&&qo(e[0],e[1],e[2])&&(e=[e[0]]),gi(t,Ur(e,1),[])}),Xu=Nn||function(){return Pe.Date.now()};function ta(t,e,n){return e=n?o:e,e=t&&null==e?t.length:e,Co(t,E,o,o,o,o,e)}function ea(t,e){var n;if("function"!=typeof e)throw new ie(s);return t=za(t),function(){return--t>0&&(n=e.apply(this,arguments)),t<=1&&(e=o),n}}var na=xi(function(t,e,n){var r=g;if(n.length){var i=Rn(n,Mo(na));r|=w}return Co(t,r,e,n,i)}),ra=xi(function(t,e,n){var r=g|m;if(n.length){var i=Rn(n,Mo(ra));r|=w}return Co(e,r,t,n,i)});function ia(t,e,n){var r,i,u,a,c,f,l=0,A=!1,p=!1,d=!0;if("function"!=typeof t)throw new ie(s);function h(e){var n=r,u=i;return r=i=o,l=e,a=t.apply(u,n)}function v(t){var n=t-f;return f===o||n>=e||n<0||p&&t-l>=u}function g(){var t=Xu();if(v(t))return m(t);c=iu(g,function(t){var n=e-(t-f);return p?Wn(n,u-(t-l)):n}(t))}function m(t){return c=o,d&&r?h(t):(r=i=o,a)}function y(){var t=Xu(),n=v(t);if(r=arguments,i=this,f=t,n){if(c===o)return function(t){return l=t,c=iu(g,e),A?h(t):a}(f);if(p)return Vi(c),c=iu(g,e),h(f)}return c===o&&(c=iu(g,e)),a}return e=Ga(e)||0,ja(n)&&(A=!!n.leading,u=(p="maxWait"in n)?Yn(Ga(n.maxWait)||0,e):u,d="trailing"in n?!!n.trailing:d),y.cancel=function(){c!==o&&Vi(c),l=0,r=f=i=c=o},y.flush=function(){return c===o?a:m(Xu())},y}var oa=xi(function(t,e){return Dr(t,1,e)}),ua=xi(function(t,e,n){return Dr(t,Ga(e)||0,n)});function aa(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new ie(s);var n=function(){var r=arguments,i=e?e.apply(this,r):r[0],o=n.cache;if(o.has(i))return o.get(i);var u=t.apply(this,r);return n.cache=o.set(i,u)||o,u};return n.cache=new(aa.Cache||_r),n}function sa(t){if("function"!=typeof t)throw new ie(s);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}aa.Cache=_r;var ca=qi(function(t,e){var n=(e=1==e.length&&ga(e[0])?Xe(e[0],gn(No())):Xe(Ur(e,1),gn(No()))).length;return xi(function(r){for(var i=-1,o=Wn(r.length,n);++i<o;)r[i]=e[i].call(this,r[i]);return Ye(t,this,r)})}),fa=xi(function(t,e){var n=Rn(e,Mo(fa));return Co(t,w,o,e,n)}),la=xi(function(t,e){var n=Rn(e,Mo(la));return Co(t,x,o,e,n)}),Aa=Oo(function(t,e){return Co(t,C,o,o,o,e)});function pa(t,e){return t===e||t!=t&&e!=e}var da=_o(Xr),ha=_o(function(t,e){return t>=e}),va=ii(function(){return arguments}())?ii:function(t){return Ra(t)&&fe.call(t,"callee")&&!Ie.call(t,"callee")},ga=r.isArray,ma=Fe?gn(Fe):function(t){return Ra(t)&&Kr(t)==st};function ya(t){return null!=t&&Ba(t.length)&&!Ea(t)}function _a(t){return Ra(t)&&ya(t)}var ba=zn||Gs,wa=Le?gn(Le):function(t){return Ra(t)&&Kr(t)==Y};function xa(t){if(!Ra(t))return!1;var e=Kr(t);return e==q||e==W||"string"==typeof t.message&&"string"==typeof t.name&&!ka(t)}function Ea(t){if(!ja(t))return!1;var e=Kr(t);return e==H||e==V||e==G||e==tt}function Ca(t){return"number"==typeof t&&t==za(t)}function Ba(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=I}function ja(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function Ra(t){return null!=t&&"object"==typeof t}var Sa=ze?gn(ze):function(t){return Ra(t)&&Qo(t)==Z};function Oa(t){return"number"==typeof t||Ra(t)&&Kr(t)==J}function ka(t){if(!Ra(t)||Kr(t)!=X)return!1;var e=ke(t);if(null===e)return!0;var n=fe.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&ce.call(n)==de}var Ta=Qe?gn(Qe):function(t){return Ra(t)&&Kr(t)==et};var Pa=Ge?gn(Ge):function(t){return Ra(t)&&Qo(t)==nt};function Ia(t){return"string"==typeof t||!ga(t)&&Ra(t)&&Kr(t)==rt}function Ma(t){return"symbol"==typeof t||Ra(t)&&Kr(t)==it}var Na=Ue?gn(Ue):function(t){return Ra(t)&&Ba(t.length)&&!!Be[Kr(t)]};var Da=_o(li),$a=_o(function(t,e){return t<=e});function Fa(t){if(!t)return[];if(ya(t))return Ia(t)?Tn(t):no(t);if($e&&t[$e])return function(t){for(var e,n=[];!(e=t.next()).done;)n.push(e.value);return n}(t[$e]());var e=Qo(t);return(e==Z?Bn:e==nt?Sn:ps)(t)}function La(t){return t?(t=Ga(t))===P||t===-P?(t<0?-1:1)*M:t==t?t:0:0===t?t:0}function za(t){var e=La(t),n=e%1;return e==e?n?e-n:e:0}function Qa(t){return t?Ir(za(t),0,D):0}function Ga(t){if("number"==typeof t)return t;if(Ma(t))return N;if(ja(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=ja(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(It,"");var n=Yt.test(t);return n||qt.test(t)?Oe(t.slice(2),n?2:8):Ut.test(t)?N:+t}function Ua(t){return ro(t,os(t))}function Ya(t){return null==t?"":Ni(t)}var Wa=oo(function(t,e){if(Jo(e)||ya(e))ro(e,is(e),t);else for(var n in e)fe.call(e,n)&&Rr(t,n,e[n])}),qa=oo(function(t,e){ro(e,os(e),t)}),Ha=oo(function(t,e,n,r){ro(e,os(e),t,r)}),Va=oo(function(t,e,n,r){ro(e,is(e),t,r)}),Za=Oo(Pr);var Ja=xi(function(t,e){t=ee(t);var n=-1,r=e.length,i=r>2?e[2]:o;for(i&&qo(e[0],e[1],i)&&(r=1);++n<r;)for(var u=e[n],a=os(u),s=-1,c=a.length;++s<c;){var f=a[s],l=t[f];(l===o||pa(l,ae[f])&&!fe.call(t,f))&&(t[f]=u[f])}return t}),Ka=xi(function(t){return t.push(o,jo),Ye(as,o,t)});function Xa(t,e,n){var r=null==t?o:Zr(t,e);return r===o?n:r}function ts(t,e){return null!=t&&Go(t,e,ei)}var es=ho(function(t,e,n){null!=e&&"function"!=typeof e.toString&&(e=pe.call(e)),t[e]=n},js(Os)),ns=ho(function(t,e,n){null!=e&&"function"!=typeof e.toString&&(e=pe.call(e)),fe.call(t,e)?t[e].push(n):t[e]=[n]},No),rs=xi(ri);function is(t){return ya(t)?xr(t):ci(t)}function os(t){return ya(t)?xr(t,!0):fi(t)}var us=oo(function(t,e,n){hi(t,e,n)}),as=oo(function(t,e,n,r){hi(t,e,n,r)}),ss=Oo(function(t,e){var n={};if(null==t)return n;var r=!1;e=Xe(e,function(e){return e=Wi(e,t),r||(r=e.length>1),e}),ro(t,To(t),n),r&&(n=Mr(n,A|p|d,Ro));for(var i=e.length;i--;)$i(n,e[i]);return n});var cs=Oo(function(t,e){return null==t?{}:function(t,e){return mi(t,e,function(e,n){return ts(t,n)})}(t,e)});function fs(t,e){if(null==t)return{};var n=Xe(To(t),function(t){return[t]});return e=No(e),mi(t,n,function(t,n){return e(t,n[0])})}var ls=Eo(is),As=Eo(os);function ps(t){return null==t?[]:mn(t,is(t))}var ds=co(function(t,e,n){return e=e.toLowerCase(),t+(n?hs(e):e)});function hs(t){return xs(Ya(t).toLowerCase())}function vs(t){return(t=Ya(t))&&t.replace(Vt,wn).replace(ye,"")}var gs=co(function(t,e,n){return t+(n?"-":"")+e.toLowerCase()}),ms=co(function(t,e,n){return t+(n?" ":"")+e.toLowerCase()}),ys=so("toLowerCase");var _s=co(function(t,e,n){return t+(n?"_":"")+e.toLowerCase()});var bs=co(function(t,e,n){return t+(n?" ":"")+xs(e)});var ws=co(function(t,e,n){return t+(n?" ":"")+e.toUpperCase()}),xs=so("toUpperCase");function Es(t,e,n){return t=Ya(t),(e=n?o:e)===o?function(t){return xe.test(t)}(t)?function(t){return t.match(be)||[]}(t):function(t){return t.match(Lt)||[]}(t):t.match(e)||[]}var Cs=xi(function(t,e){try{return Ye(t,o,e)}catch(t){return xa(t)?t:new Kt(t)}}),Bs=Oo(function(t,e){return qe(e,function(e){e=fu(e),Tr(t,e,na(t[e],t))}),t});function js(t){return function(){return t}}var Rs=Ao(),Ss=Ao(!0);function Os(t){return t}function ks(t){return si("function"==typeof t?t:Mr(t,A))}var Ts=xi(function(t,e){return function(n){return ri(n,t,e)}}),Ps=xi(function(t,e){return function(n){return ri(t,n,e)}});function Is(t,e,n){var r=is(e),i=Vr(e,r);null!=n||ja(e)&&(i.length||!r.length)||(n=e,e=t,t=this,i=Vr(e,is(e)));var o=!(ja(n)&&"chain"in n&&!n.chain),u=Ea(t);return qe(i,function(n){var r=e[n];t[n]=r,u&&(t.prototype[n]=function(){var e=this.__chain__;if(o||e){var n=t(this.__wrapped__);return(n.__actions__=no(this.__actions__)).push({func:r,args:arguments,thisArg:t}),n.__chain__=e,n}return r.apply(t,tn([this.value()],arguments))})}),t}function Ms(){}var Ns=go(Xe),Ds=go(Ve),$s=go(rn);function Fs(t){return Ho(t)?An(fu(t)):function(t){return function(e){return Zr(e,t)}}(t)}var Ls=yo(),zs=yo(!0);function Qs(){return[]}function Gs(){return!1}var Us=vo(function(t,e){return t+e},0),Ys=wo("ceil"),Ws=vo(function(t,e){return t/e},1),qs=wo("floor");var Hs,Vs=vo(function(t,e){return t*e},1),Zs=wo("round"),Js=vo(function(t,e){return t-e},0);return pr.after=function(t,e){if("function"!=typeof e)throw new ie(s);return t=za(t),function(){if(--t<1)return e.apply(this,arguments)}},pr.ary=ta,pr.assign=Wa,pr.assignIn=qa,pr.assignInWith=Ha,pr.assignWith=Va,pr.at=Za,pr.before=ea,pr.bind=na,pr.bindAll=Bs,pr.bindKey=ra,pr.castArray=function(){if(!arguments.length)return[];var t=arguments[0];return ga(t)?t:[t]},pr.chain=Fu,pr.chunk=function(t,e,n){e=(n?qo(t,e,n):e===o)?1:Yn(za(e),0);var i=null==t?0:t.length;if(!i||e<1)return[];for(var u=0,a=0,s=r($n(i/e));u<i;)s[a++]=Oi(t,u,u+=e);return s},pr.compact=function(t){for(var e=-1,n=null==t?0:t.length,r=0,i=[];++e<n;){var o=t[e];o&&(i[r++]=o)}return i},pr.concat=function(){var t=arguments.length;if(!t)return[];for(var e=r(t-1),n=arguments[0],i=t;i--;)e[i-1]=arguments[i];return tn(ga(n)?no(n):[n],Ur(e,1))},pr.cond=function(t){var e=null==t?0:t.length,n=No();return t=e?Xe(t,function(t){if("function"!=typeof t[1])throw new ie(s);return[n(t[0]),t[1]]}):[],xi(function(n){for(var r=-1;++r<e;){var i=t[r];if(Ye(i[0],this,n))return Ye(i[1],this,n)}})},pr.conforms=function(t){return function(t){var e=is(t);return function(n){return Nr(n,t,e)}}(Mr(t,A))},pr.constant=js,pr.countBy=Qu,pr.create=function(t,e){var n=dr(t);return null==e?n:kr(n,e)},pr.curry=function t(e,n,r){var i=Co(e,_,o,o,o,o,o,n=r?o:n);return i.placeholder=t.placeholder,i},pr.curryRight=function t(e,n,r){var i=Co(e,b,o,o,o,o,o,n=r?o:n);return i.placeholder=t.placeholder,i},pr.debounce=ia,pr.defaults=Ja,pr.defaultsDeep=Ka,pr.defer=oa,pr.delay=ua,pr.difference=pu,pr.differenceBy=du,pr.differenceWith=hu,pr.drop=function(t,e,n){var r=null==t?0:t.length;return r?Oi(t,(e=n||e===o?1:za(e))<0?0:e,r):[]},pr.dropRight=function(t,e,n){var r=null==t?0:t.length;return r?Oi(t,0,(e=r-(e=n||e===o?1:za(e)))<0?0:e):[]},pr.dropRightWhile=function(t,e){return t&&t.length?Li(t,No(e,3),!0,!0):[]},pr.dropWhile=function(t,e){return t&&t.length?Li(t,No(e,3),!0):[]},pr.fill=function(t,e,n,r){var i=null==t?0:t.length;return i?(n&&"number"!=typeof n&&qo(t,e,n)&&(n=0,r=i),function(t,e,n,r){var i=t.length;for((n=za(n))<0&&(n=-n>i?0:i+n),(r=r===o||r>i?i:za(r))<0&&(r+=i),r=n>r?0:Qa(r);n<r;)t[n++]=e;return t}(t,e,n,r)):[]},pr.filter=function(t,e){return(ga(t)?Ze:Gr)(t,No(e,3))},pr.flatMap=function(t,e){return Ur(Zu(t,e),1)},pr.flatMapDeep=function(t,e){return Ur(Zu(t,e),P)},pr.flatMapDepth=function(t,e,n){return n=n===o?1:za(n),Ur(Zu(t,e),n)},pr.flatten=mu,pr.flattenDeep=function(t){return null!=t&&t.length?Ur(t,P):[]},pr.flattenDepth=function(t,e){return null!=t&&t.length?Ur(t,e=e===o?1:za(e)):[]},pr.flip=function(t){return Co(t,B)},pr.flow=Rs,pr.flowRight=Ss,pr.fromPairs=function(t){for(var e=-1,n=null==t?0:t.length,r={};++e<n;){var i=t[e];r[i[0]]=i[1]}return r},pr.functions=function(t){return null==t?[]:Vr(t,is(t))},pr.functionsIn=function(t){return null==t?[]:Vr(t,os(t))},pr.groupBy=qu,pr.initial=function(t){return null!=t&&t.length?Oi(t,0,-1):[]},pr.intersection=_u,pr.intersectionBy=bu,pr.intersectionWith=wu,pr.invert=es,pr.invertBy=ns,pr.invokeMap=Hu,pr.iteratee=ks,pr.keyBy=Vu,pr.keys=is,pr.keysIn=os,pr.map=Zu,pr.mapKeys=function(t,e){var n={};return e=No(e,3),qr(t,function(t,r,i){Tr(n,e(t,r,i),t)}),n},pr.mapValues=function(t,e){var n={};return e=No(e,3),qr(t,function(t,r,i){Tr(n,r,e(t,r,i))}),n},pr.matches=function(t){return pi(Mr(t,A))},pr.matchesProperty=function(t,e){return di(t,Mr(e,A))},pr.memoize=aa,pr.merge=us,pr.mergeWith=as,pr.method=Ts,pr.methodOf=Ps,pr.mixin=Is,pr.negate=sa,pr.nthArg=function(t){return t=za(t),xi(function(e){return vi(e,t)})},pr.omit=ss,pr.omitBy=function(t,e){return fs(t,sa(No(e)))},pr.once=function(t){return ea(2,t)},pr.orderBy=function(t,e,n,r){return null==t?[]:(ga(e)||(e=null==e?[]:[e]),ga(n=r?o:n)||(n=null==n?[]:[n]),gi(t,e,n))},pr.over=Ns,pr.overArgs=ca,pr.overEvery=Ds,pr.overSome=$s,pr.partial=fa,pr.partialRight=la,pr.partition=Ju,pr.pick=cs,pr.pickBy=fs,pr.property=Fs,pr.propertyOf=function(t){return function(e){return null==t?o:Zr(t,e)}},pr.pull=Eu,pr.pullAll=Cu,pr.pullAllBy=function(t,e,n){return t&&t.length&&e&&e.length?yi(t,e,No(n,2)):t},pr.pullAllWith=function(t,e,n){return t&&t.length&&e&&e.length?yi(t,e,o,n):t},pr.pullAt=Bu,pr.range=Ls,pr.rangeRight=zs,pr.rearg=Aa,pr.reject=function(t,e){return(ga(t)?Ze:Gr)(t,sa(No(e,3)))},pr.remove=function(t,e){var n=[];if(!t||!t.length)return n;var r=-1,i=[],o=t.length;for(e=No(e,3);++r<o;){var u=t[r];e(u,r,t)&&(n.push(u),i.push(r))}return _i(t,i),n},pr.rest=function(t,e){if("function"!=typeof t)throw new ie(s);return xi(t,e=e===o?e:za(e))},pr.reverse=ju,pr.sampleSize=function(t,e,n){return e=(n?qo(t,e,n):e===o)?1:za(e),(ga(t)?Cr:Ci)(t,e)},pr.set=function(t,e,n){return null==t?t:Bi(t,e,n)},pr.setWith=function(t,e,n,r){return r="function"==typeof r?r:o,null==t?t:Bi(t,e,n,r)},pr.shuffle=function(t){return(ga(t)?Br:Si)(t)},pr.slice=function(t,e,n){var r=null==t?0:t.length;return r?(n&&"number"!=typeof n&&qo(t,e,n)?(e=0,n=r):(e=null==e?0:za(e),n=n===o?r:za(n)),Oi(t,e,n)):[]},pr.sortBy=Ku,pr.sortedUniq=function(t){return t&&t.length?Ii(t):[]},pr.sortedUniqBy=function(t,e){return t&&t.length?Ii(t,No(e,2)):[]},pr.split=function(t,e,n){return n&&"number"!=typeof n&&qo(t,e,n)&&(e=n=o),(n=n===o?D:n>>>0)?(t=Ya(t))&&("string"==typeof e||null!=e&&!Ta(e))&&!(e=Ni(e))&&Cn(t)?Hi(Tn(t),0,n):t.split(e,n):[]},pr.spread=function(t,e){if("function"!=typeof t)throw new ie(s);return e=null==e?0:Yn(za(e),0),xi(function(n){var r=n[e],i=Hi(n,0,e);return r&&tn(i,r),Ye(t,this,i)})},pr.tail=function(t){var e=null==t?0:t.length;return e?Oi(t,1,e):[]},pr.take=function(t,e,n){return t&&t.length?Oi(t,0,(e=n||e===o?1:za(e))<0?0:e):[]},pr.takeRight=function(t,e,n){var r=null==t?0:t.length;return r?Oi(t,(e=r-(e=n||e===o?1:za(e)))<0?0:e,r):[]},pr.takeRightWhile=function(t,e){return t&&t.length?Li(t,No(e,3),!1,!0):[]},pr.takeWhile=function(t,e){return t&&t.length?Li(t,No(e,3)):[]},pr.tap=function(t,e){return e(t),t},pr.throttle=function(t,e,n){var r=!0,i=!0;if("function"!=typeof t)throw new ie(s);return ja(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),ia(t,e,{leading:r,maxWait:e,trailing:i})},pr.thru=Lu,pr.toArray=Fa,pr.toPairs=ls,pr.toPairsIn=As,pr.toPath=function(t){return ga(t)?Xe(t,fu):Ma(t)?[t]:no(cu(Ya(t)))},pr.toPlainObject=Ua,pr.transform=function(t,e,n){var r=ga(t),i=r||ba(t)||Na(t);if(e=No(e,4),null==n){var o=t&&t.constructor;n=i?r?new o:[]:ja(t)&&Ea(o)?dr(ke(t)):{}}return(i?qe:qr)(t,function(t,r,i){return e(n,t,r,i)}),n},pr.unary=function(t){return ta(t,1)},pr.union=Ru,pr.unionBy=Su,pr.unionWith=Ou,pr.uniq=function(t){return t&&t.length?Di(t):[]},pr.uniqBy=function(t,e){return t&&t.length?Di(t,No(e,2)):[]},pr.uniqWith=function(t,e){return e="function"==typeof e?e:o,t&&t.length?Di(t,o,e):[]},pr.unset=function(t,e){return null==t||$i(t,e)},pr.unzip=ku,pr.unzipWith=Tu,pr.update=function(t,e,n){return null==t?t:Fi(t,e,Yi(n))},pr.updateWith=function(t,e,n,r){return r="function"==typeof r?r:o,null==t?t:Fi(t,e,Yi(n),r)},pr.values=ps,pr.valuesIn=function(t){return null==t?[]:mn(t,os(t))},pr.without=Pu,pr.words=Es,pr.wrap=function(t,e){return fa(Yi(e),t)},pr.xor=Iu,pr.xorBy=Mu,pr.xorWith=Nu,pr.zip=Du,pr.zipObject=function(t,e){return Gi(t||[],e||[],Rr)},pr.zipObjectDeep=function(t,e){return Gi(t||[],e||[],Bi)},pr.zipWith=$u,pr.entries=ls,pr.entriesIn=As,pr.extend=qa,pr.extendWith=Ha,Is(pr,pr),pr.add=Us,pr.attempt=Cs,pr.camelCase=ds,pr.capitalize=hs,pr.ceil=Ys,pr.clamp=function(t,e,n){return n===o&&(n=e,e=o),n!==o&&(n=(n=Ga(n))==n?n:0),e!==o&&(e=(e=Ga(e))==e?e:0),Ir(Ga(t),e,n)},pr.clone=function(t){return Mr(t,d)},pr.cloneDeep=function(t){return Mr(t,A|d)},pr.cloneDeepWith=function(t,e){return Mr(t,A|d,e="function"==typeof e?e:o)},pr.cloneWith=function(t,e){return Mr(t,d,e="function"==typeof e?e:o)},pr.conformsTo=function(t,e){return null==e||Nr(t,e,is(e))},pr.deburr=vs,pr.defaultTo=function(t,e){return null==t||t!=t?e:t},pr.divide=Ws,pr.endsWith=function(t,e,n){t=Ya(t),e=Ni(e);var r=t.length,i=n=n===o?r:Ir(za(n),0,r);return(n-=e.length)>=0&&t.slice(n,i)==e},pr.eq=pa,pr.escape=function(t){return(t=Ya(t))&&Ct.test(t)?t.replace(xt,xn):t},pr.escapeRegExp=function(t){return(t=Ya(t))&&Pt.test(t)?t.replace(Tt,"\\$&"):t},pr.every=function(t,e,n){var r=ga(t)?Ve:zr;return n&&qo(t,e,n)&&(e=o),r(t,No(e,3))},pr.find=Gu,pr.findIndex=vu,pr.findKey=function(t,e){return un(t,No(e,3),qr)},pr.findLast=Uu,pr.findLastIndex=gu,pr.findLastKey=function(t,e){return un(t,No(e,3),Hr)},pr.floor=qs,pr.forEach=Yu,pr.forEachRight=Wu,pr.forIn=function(t,e){return null==t?t:Yr(t,No(e,3),os)},pr.forInRight=function(t,e){return null==t?t:Wr(t,No(e,3),os)},pr.forOwn=function(t,e){return t&&qr(t,No(e,3))},pr.forOwnRight=function(t,e){return t&&Hr(t,No(e,3))},pr.get=Xa,pr.gt=da,pr.gte=ha,pr.has=function(t,e){return null!=t&&Go(t,e,ti)},pr.hasIn=ts,pr.head=yu,pr.identity=Os,pr.includes=function(t,e,n,r){t=ya(t)?t:ps(t),n=n&&!r?za(n):0;var i=t.length;return n<0&&(n=Yn(i+n,0)),Ia(t)?n<=i&&t.indexOf(e,n)>-1:!!i&&sn(t,e,n)>-1},pr.indexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=null==n?0:za(n);return i<0&&(i=Yn(r+i,0)),sn(t,e,i)},pr.inRange=function(t,e,n){return e=La(e),n===o?(n=e,e=0):n=La(n),function(t,e,n){return t>=Wn(e,n)&&t<Yn(e,n)}(t=Ga(t),e,n)},pr.invoke=rs,pr.isArguments=va,pr.isArray=ga,pr.isArrayBuffer=ma,pr.isArrayLike=ya,pr.isArrayLikeObject=_a,pr.isBoolean=function(t){return!0===t||!1===t||Ra(t)&&Kr(t)==U},pr.isBuffer=ba,pr.isDate=wa,pr.isElement=function(t){return Ra(t)&&1===t.nodeType&&!ka(t)},pr.isEmpty=function(t){if(null==t)return!0;if(ya(t)&&(ga(t)||"string"==typeof t||"function"==typeof t.splice||ba(t)||Na(t)||va(t)))return!t.length;var e=Qo(t);if(e==Z||e==nt)return!t.size;if(Jo(t))return!ci(t).length;for(var n in t)if(fe.call(t,n))return!1;return!0},pr.isEqual=function(t,e){return oi(t,e)},pr.isEqualWith=function(t,e,n){var r=(n="function"==typeof n?n:o)?n(t,e):o;return r===o?oi(t,e,o,n):!!r},pr.isError=xa,pr.isFinite=function(t){return"number"==typeof t&&Qn(t)},pr.isFunction=Ea,pr.isInteger=Ca,pr.isLength=Ba,pr.isMap=Sa,pr.isMatch=function(t,e){return t===e||ui(t,e,$o(e))},pr.isMatchWith=function(t,e,n){return n="function"==typeof n?n:o,ui(t,e,$o(e),n)},pr.isNaN=function(t){return Oa(t)&&t!=+t},pr.isNative=function(t){if(Zo(t))throw new Kt(a);return ai(t)},pr.isNil=function(t){return null==t},pr.isNull=function(t){return null===t},pr.isNumber=Oa,pr.isObject=ja,pr.isObjectLike=Ra,pr.isPlainObject=ka,pr.isRegExp=Ta,pr.isSafeInteger=function(t){return Ca(t)&&t>=-I&&t<=I},pr.isSet=Pa,pr.isString=Ia,pr.isSymbol=Ma,pr.isTypedArray=Na,pr.isUndefined=function(t){return t===o},pr.isWeakMap=function(t){return Ra(t)&&Qo(t)==ut},pr.isWeakSet=function(t){return Ra(t)&&Kr(t)==at},pr.join=function(t,e){return null==t?"":Gn.call(t,e)},pr.kebabCase=gs,pr.last=xu,pr.lastIndexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=r;return n!==o&&(i=(i=za(n))<0?Yn(r+i,0):Wn(i,r-1)),e==e?function(t,e,n){for(var r=n+1;r--;)if(t[r]===e)return r;return r}(t,e,i):an(t,fn,i,!0)},pr.lowerCase=ms,pr.lowerFirst=ys,pr.lt=Da,pr.lte=$a,pr.max=function(t){return t&&t.length?Qr(t,Os,Xr):o},pr.maxBy=function(t,e){return t&&t.length?Qr(t,No(e,2),Xr):o},pr.mean=function(t){return ln(t,Os)},pr.meanBy=function(t,e){return ln(t,No(e,2))},pr.min=function(t){return t&&t.length?Qr(t,Os,li):o},pr.minBy=function(t,e){return t&&t.length?Qr(t,No(e,2),li):o},pr.stubArray=Qs,pr.stubFalse=Gs,pr.stubObject=function(){return{}},pr.stubString=function(){return""},pr.stubTrue=function(){return!0},pr.multiply=Vs,pr.nth=function(t,e){return t&&t.length?vi(t,za(e)):o},pr.noConflict=function(){return Pe._===this&&(Pe._=he),this},pr.noop=Ms,pr.now=Xu,pr.pad=function(t,e,n){t=Ya(t);var r=(e=za(e))?kn(t):0;if(!e||r>=e)return t;var i=(e-r)/2;return mo(Fn(i),n)+t+mo($n(i),n)},pr.padEnd=function(t,e,n){t=Ya(t);var r=(e=za(e))?kn(t):0;return e&&r<e?t+mo(e-r,n):t},pr.padStart=function(t,e,n){t=Ya(t);var r=(e=za(e))?kn(t):0;return e&&r<e?mo(e-r,n)+t:t},pr.parseInt=function(t,e,n){return n||null==e?e=0:e&&(e=+e),Hn(Ya(t).replace(Mt,""),e||0)},pr.random=function(t,e,n){if(n&&"boolean"!=typeof n&&qo(t,e,n)&&(e=n=o),n===o&&("boolean"==typeof e?(n=e,e=o):"boolean"==typeof t&&(n=t,t=o)),t===o&&e===o?(t=0,e=1):(t=La(t),e===o?(e=t,t=0):e=La(e)),t>e){var r=t;t=e,e=r}if(n||t%1||e%1){var i=Vn();return Wn(t+i*(e-t+Se("1e-"+((i+"").length-1))),e)}return bi(t,e)},pr.reduce=function(t,e,n){var r=ga(t)?en:dn,i=arguments.length<3;return r(t,No(e,4),n,i,Fr)},pr.reduceRight=function(t,e,n){var r=ga(t)?nn:dn,i=arguments.length<3;return r(t,No(e,4),n,i,Lr)},pr.repeat=function(t,e,n){return e=(n?qo(t,e,n):e===o)?1:za(e),wi(Ya(t),e)},pr.replace=function(){var t=arguments,e=Ya(t[0]);return t.length<3?e:e.replace(t[1],t[2])},pr.result=function(t,e,n){var r=-1,i=(e=Wi(e,t)).length;for(i||(i=1,t=o);++r<i;){var u=null==t?o:t[fu(e[r])];u===o&&(r=i,u=n),t=Ea(u)?u.call(t):u}return t},pr.round=Zs,pr.runInContext=t,pr.sample=function(t){return(ga(t)?Er:Ei)(t)},pr.size=function(t){if(null==t)return 0;if(ya(t))return Ia(t)?kn(t):t.length;var e=Qo(t);return e==Z||e==nt?t.size:ci(t).length},pr.snakeCase=_s,pr.some=function(t,e,n){var r=ga(t)?rn:ki;return n&&qo(t,e,n)&&(e=o),r(t,No(e,3))},pr.sortedIndex=function(t,e){return Ti(t,e)},pr.sortedIndexBy=function(t,e,n){return Pi(t,e,No(n,2))},pr.sortedIndexOf=function(t,e){var n=null==t?0:t.length;if(n){var r=Ti(t,e);if(r<n&&pa(t[r],e))return r}return-1},pr.sortedLastIndex=function(t,e){return Ti(t,e,!0)},pr.sortedLastIndexBy=function(t,e,n){return Pi(t,e,No(n,2),!0)},pr.sortedLastIndexOf=function(t,e){if(null!=t&&t.length){var n=Ti(t,e,!0)-1;if(pa(t[n],e))return n}return-1},pr.startCase=bs,pr.startsWith=function(t,e,n){return t=Ya(t),n=null==n?0:Ir(za(n),0,t.length),e=Ni(e),t.slice(n,n+e.length)==e},pr.subtract=Js,pr.sum=function(t){return t&&t.length?hn(t,Os):0},pr.sumBy=function(t,e){return t&&t.length?hn(t,No(e,2)):0},pr.template=function(t,e,n){var r=pr.templateSettings;n&&qo(t,e,n)&&(e=o),t=Ya(t),e=Ha({},e,r,Bo);var i,u,a=Ha({},e.imports,r.imports,Bo),s=is(a),c=mn(a,s),f=0,l=e.interpolate||Zt,A="__p += '",p=ne((e.escape||Zt).source+"|"+l.source+"|"+(l===Rt?Qt:Zt).source+"|"+(e.evaluate||Zt).source+"|$","g"),d="//# sourceURL="+(fe.call(e,"sourceURL")?(e.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Ce+"]")+"\n";t.replace(p,function(e,n,r,o,a,s){return r||(r=o),A+=t.slice(f,s).replace(Jt,En),n&&(i=!0,A+="' +\n__e("+n+") +\n'"),a&&(u=!0,A+="';\n"+a+";\n__p += '"),r&&(A+="' +\n((__t = ("+r+")) == null ? '' : __t) +\n'"),f=s+e.length,e}),A+="';\n";var h=fe.call(e,"variable")&&e.variable;h||(A="with (obj) {\n"+A+"\n}\n"),A=(u?A.replace(yt,""):A).replace(_t,"$1").replace(bt,"$1;"),A="function("+(h||"obj")+") {\n"+(h?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(i?", __e = _.escape":"")+(u?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+A+"return __p\n}";var v=Cs(function(){return Xt(s,d+"return "+A).apply(o,c)});if(v.source=A,xa(v))throw v;return v},pr.times=function(t,e){if((t=za(t))<1||t>I)return[];var n=D,r=Wn(t,D);e=No(e),t-=D;for(var i=vn(r,e);++n<t;)e(n);return i},pr.toFinite=La,pr.toInteger=za,pr.toLength=Qa,pr.toLower=function(t){return Ya(t).toLowerCase()},pr.toNumber=Ga,pr.toSafeInteger=function(t){return t?Ir(za(t),-I,I):0===t?t:0},pr.toString=Ya,pr.toUpper=function(t){return Ya(t).toUpperCase()},pr.trim=function(t,e,n){if((t=Ya(t))&&(n||e===o))return t.replace(It,"");if(!t||!(e=Ni(e)))return t;var r=Tn(t),i=Tn(e);return Hi(r,_n(r,i),bn(r,i)+1).join("")},pr.trimEnd=function(t,e,n){if((t=Ya(t))&&(n||e===o))return t.replace(Nt,"");if(!t||!(e=Ni(e)))return t;var r=Tn(t);return Hi(r,0,bn(r,Tn(e))+1).join("")},pr.trimStart=function(t,e,n){if((t=Ya(t))&&(n||e===o))return t.replace(Mt,"");if(!t||!(e=Ni(e)))return t;var r=Tn(t);return Hi(r,_n(r,Tn(e))).join("")},pr.truncate=function(t,e){var n=j,r=R;if(ja(e)){var i="separator"in e?e.separator:i;n="length"in e?za(e.length):n,r="omission"in e?Ni(e.omission):r}var u=(t=Ya(t)).length;if(Cn(t)){var a=Tn(t);u=a.length}if(n>=u)return t;var s=n-kn(r);if(s<1)return r;var c=a?Hi(a,0,s).join(""):t.slice(0,s);if(i===o)return c+r;if(a&&(s+=c.length-s),Ta(i)){if(t.slice(s).search(i)){var f,l=c;for(i.global||(i=ne(i.source,Ya(Gt.exec(i))+"g")),i.lastIndex=0;f=i.exec(l);)var A=f.index;c=c.slice(0,A===o?s:A)}}else if(t.indexOf(Ni(i),s)!=s){var p=c.lastIndexOf(i);p>-1&&(c=c.slice(0,p))}return c+r},pr.unescape=function(t){return(t=Ya(t))&&Et.test(t)?t.replace(wt,Pn):t},pr.uniqueId=function(t){var e=++le;return Ya(t)+e},pr.upperCase=ws,pr.upperFirst=xs,pr.each=Yu,pr.eachRight=Wu,pr.first=yu,Is(pr,(Hs={},qr(pr,function(t,e){fe.call(pr.prototype,e)||(Hs[e]=t)}),Hs),{chain:!1}),pr.VERSION="4.17.19",qe(["bind","bindKey","curry","curryRight","partial","partialRight"],function(t){pr[t].placeholder=pr}),qe(["drop","take"],function(t,e){gr.prototype[t]=function(n){n=n===o?1:Yn(za(n),0);var r=this.__filtered__&&!e?new gr(this):this.clone();return r.__filtered__?r.__takeCount__=Wn(n,r.__takeCount__):r.__views__.push({size:Wn(n,D),type:t+(r.__dir__<0?"Right":"")}),r},gr.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()}}),qe(["filter","map","takeWhile"],function(t,e){var n=e+1,r=n==k||3==n;gr.prototype[t]=function(t){var e=this.clone();return e.__iteratees__.push({iteratee:No(t,3),type:n}),e.__filtered__=e.__filtered__||r,e}}),qe(["head","last"],function(t,e){var n="take"+(e?"Right":"");gr.prototype[t]=function(){return this[n](1).value()[0]}}),qe(["initial","tail"],function(t,e){var n="drop"+(e?"":"Right");gr.prototype[t]=function(){return this.__filtered__?new gr(this):this[n](1)}}),gr.prototype.compact=function(){return this.filter(Os)},gr.prototype.find=function(t){return this.filter(t).head()},gr.prototype.findLast=function(t){return this.reverse().find(t)},gr.prototype.invokeMap=xi(function(t,e){return"function"==typeof t?new gr(this):this.map(function(n){return ri(n,t,e)})}),gr.prototype.reject=function(t){return this.filter(sa(No(t)))},gr.prototype.slice=function(t,e){t=za(t);var n=this;return n.__filtered__&&(t>0||e<0)?new gr(n):(t<0?n=n.takeRight(-t):t&&(n=n.drop(t)),e!==o&&(n=(e=za(e))<0?n.dropRight(-e):n.take(e-t)),n)},gr.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},gr.prototype.toArray=function(){return this.take(D)},qr(gr.prototype,function(t,e){var n=/^(?:filter|find|map|reject)|While$/.test(e),r=/^(?:head|last)$/.test(e),i=pr[r?"take"+("last"==e?"Right":""):e],u=r||/^find/.test(e);i&&(pr.prototype[e]=function(){var e=this.__wrapped__,a=r?[1]:arguments,s=e instanceof gr,c=a[0],f=s||ga(e),l=function(t){var e=i.apply(pr,tn([t],a));return r&&A?e[0]:e};f&&n&&"function"==typeof c&&1!=c.length&&(s=f=!1);var A=this.__chain__,p=!!this.__actions__.length,d=u&&!A,h=s&&!p;if(!u&&f){e=h?e:new gr(this);var v=t.apply(e,a);return v.__actions__.push({func:Lu,args:[l],thisArg:o}),new vr(v,A)}return d&&h?t.apply(this,a):(v=this.thru(l),d?r?v.value()[0]:v.value():v)})}),qe(["pop","push","shift","sort","splice","unshift"],function(t){var e=oe[t],n=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",r=/^(?:pop|shift)$/.test(t);pr.prototype[t]=function(){var t=arguments;if(r&&!this.__chain__){var i=this.value();return e.apply(ga(i)?i:[],t)}return this[n](function(n){return e.apply(ga(n)?n:[],t)})}}),qr(gr.prototype,function(t,e){var n=pr[e];if(n){var r=n.name+"";fe.call(ir,r)||(ir[r]=[]),ir[r].push({name:e,func:n})}}),ir[po(o,m).name]=[{name:"wrapper",func:o}],gr.prototype.clone=function(){var t=new gr(this.__wrapped__);return t.__actions__=no(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=no(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=no(this.__views__),t},gr.prototype.reverse=function(){if(this.__filtered__){var t=new gr(this);t.__dir__=-1,t.__filtered__=!0}else(t=this.clone()).__dir__*=-1;return t},gr.prototype.value=function(){var t=this.__wrapped__.value(),e=this.__dir__,n=ga(t),r=e<0,i=n?t.length:0,o=function(t,e,n){for(var r=-1,i=n.length;++r<i;){var o=n[r],u=o.size;switch(o.type){case"drop":t+=u;break;case"dropRight":e-=u;break;case"take":e=Wn(e,t+u);break;case"takeRight":t=Yn(t,e-u)}}return{start:t,end:e}}(0,i,this.__views__),u=o.start,a=o.end,s=a-u,c=r?a:u-1,f=this.__iteratees__,l=f.length,A=0,p=Wn(s,this.__takeCount__);if(!n||!r&&i==s&&p==s)return zi(t,this.__actions__);var d=[];t:for(;s--&&A<p;){for(var h=-1,v=t[c+=e];++h<l;){var g=f[h],m=g.iteratee,y=g.type,_=m(v);if(y==T)v=_;else if(!_){if(y==k)continue t;break t}}d[A++]=v}return d},pr.prototype.at=zu,pr.prototype.chain=function(){return Fu(this)},pr.prototype.commit=function(){return new vr(this.value(),this.__chain__)},pr.prototype.next=function(){this.__values__===o&&(this.__values__=Fa(this.value()));var t=this.__index__>=this.__values__.length;return{done:t,value:t?o:this.__values__[this.__index__++]}},pr.prototype.plant=function(t){for(var e,n=this;n instanceof hr;){var r=Au(n);r.__index__=0,r.__values__=o,e?i.__wrapped__=r:e=r;var i=r;n=n.__wrapped__}return i.__wrapped__=t,e},pr.prototype.reverse=function(){var t=this.__wrapped__;if(t instanceof gr){var e=t;return this.__actions__.length&&(e=new gr(this)),(e=e.reverse()).__actions__.push({func:Lu,args:[ju],thisArg:o}),new vr(e,this.__chain__)}return this.thru(ju)},pr.prototype.toJSON=pr.prototype.valueOf=pr.prototype.value=function(){return zi(this.__wrapped__,this.__actions__)},pr.prototype.first=pr.prototype.head,$e&&(pr.prototype[$e]=function(){return this}),pr}();Pe._=In,(i=function(){return In}.call(e,n,e,r))===o||(r.exports=i)}).call(this)}).call(e,n(71),n(31)(t))},function(t,e,n){var r=n(17);t.exports=function(){return r.Date.now()}},function(t,e){t.exports=function(){return!1}},function(t,e,n){var r=n(8),i=n(69),o=NaN,u=/^\s+|\s+$/g,a=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,c=/^0o[0-7]+$/i,f=parseInt;t.exports=function(t){if("number"==typeof t)return t;if(i(t))return o;if(r(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=r(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(u,"");var n=s.test(t);return n||c.test(t)?f(t.slice(2),n?2:8):a.test(t)?o:+t}},function(t,e,n){var r=n(165);t.exports=function(t){return null==t?"":r(t)}},function(t,e,n){var r=n(169)("toUpperCase");t.exports=r},function(t,e,n){var r=function(){return this}()||Function("return this")(),i=r.regeneratorRuntime&&Object.getOwnPropertyNames(r).indexOf("regeneratorRuntime")>=0,o=i&&r.regeneratorRuntime;if(r.regeneratorRuntime=void 0,t.exports=n(200),i)r.regeneratorRuntime=o;else try{delete r.regeneratorRuntime}catch(t){r.regeneratorRuntime=void 0}},function(t,e){!function(e){"use strict";var n,r=Object.prototype,i=r.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},u=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",s=o.toStringTag||"@@toStringTag",c="object"==typeof t,f=e.regeneratorRuntime;if(f)c&&(t.exports=f);else{(f=e.regeneratorRuntime=c?t.exports:{}).wrap=_;var l="suspendedStart",A="suspendedYield",p="executing",d="completed",h={},v={};v[u]=function(){return this};var g=Object.getPrototypeOf,m=g&&g(g(k([])));m&&m!==r&&i.call(m,u)&&(v=m);var y=E.prototype=w.prototype=Object.create(v);x.prototype=y.constructor=E,E.constructor=x,E[s]=x.displayName="GeneratorFunction",f.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===x||"GeneratorFunction"===(e.displayName||e.name))},f.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,E):(t.__proto__=E,s in t||(t[s]="GeneratorFunction")),t.prototype=Object.create(y),t},f.awrap=function(t){return{__await:t}},C(B.prototype),B.prototype[a]=function(){return this},f.AsyncIterator=B,f.async=function(t,e,n,r){var i=new B(_(t,e,n,r));return f.isGeneratorFunction(e)?i:i.next().then(function(t){return t.done?t.value:i.next()})},C(y),y[s]="Generator",y[u]=function(){return this},y.toString=function(){return"[object Generator]"},f.keys=function(t){var e=[];for(var n in t)e.push(n);return e.reverse(),function n(){for(;e.length;){var r=e.pop();if(r in t)return n.value=r,n.done=!1,n}return n.done=!0,n}},f.values=k,O.prototype={constructor:O,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(S),!t)for(var e in this)"t"===e.charAt(0)&&i.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=n)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function r(r,i){return a.type="throw",a.arg=t,e.next=r,i&&(e.method="next",e.arg=n),!!i}for(var o=this.tryEntries.length-1;o>=0;--o){var u=this.tryEntries[o],a=u.completion;if("root"===u.tryLoc)return r("end");if(u.tryLoc<=this.prev){var s=i.call(u,"catchLoc"),c=i.call(u,"finallyLoc");if(s&&c){if(this.prev<u.catchLoc)return r(u.catchLoc,!0);if(this.prev<u.finallyLoc)return r(u.finallyLoc)}else if(s){if(this.prev<u.catchLoc)return r(u.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<u.finallyLoc)return r(u.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=e&&e<=o.finallyLoc&&(o=null);var u=o?o.completion:{};return u.type=t,u.arg=e,o?(this.method="next",this.next=o.finallyLoc,h):this.complete(u)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),h},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),S(n),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;S(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:k(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=n),h}}}function _(t,e,n,r){var i=e&&e.prototype instanceof w?e:w,o=Object.create(i.prototype),u=new O(r||[]);return o._invoke=function(t,e,n){var r=l;return function(i,o){if(r===p)throw new Error("Generator is already running");if(r===d){if("throw"===i)throw o;return T()}for(n.method=i,n.arg=o;;){var u=n.delegate;if(u){var a=j(u,n);if(a){if(a===h)continue;return a}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===l)throw r=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=p;var s=b(t,e,n);if("normal"===s.type){if(r=n.done?d:A,s.arg===h)continue;return{value:s.arg,done:n.done}}"throw"===s.type&&(r=d,n.method="throw",n.arg=s.arg)}}}(t,n,u),o}function b(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}function w(){}function x(){}function E(){}function C(t){["next","throw","return"].forEach(function(e){t[e]=function(t){return this._invoke(e,t)}})}function B(t){var e;this._invoke=function(n,r){function o(){return new Promise(function(e,o){!function e(n,r,o,u){var a=b(t[n],t,r);if("throw"!==a.type){var s=a.arg,c=s.value;return c&&"object"==typeof c&&i.call(c,"__await")?Promise.resolve(c.__await).then(function(t){e("next",t,o,u)},function(t){e("throw",t,o,u)}):Promise.resolve(c).then(function(t){s.value=t,o(s)},u)}u(a.arg)}(n,r,e,o)})}return e=e?e.then(o,o):o()}}function j(t,e){var r=t.iterator[e.method];if(r===n){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=n,j(t,e),"throw"===e.method))return h;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return h}var i=b(r,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,h;var o=i.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=n),e.delegate=null,h):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function R(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function S(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function O(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(R,this),this.reset(!0)}function k(t){if(t){var e=t[u];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,o=function e(){for(;++r<t.length;)if(i.call(t,r))return e.value=t[r],e.done=!1,e;return e.value=n,e.done=!0,e};return o.next=o}}return{next:T}}function T(){return{value:n,done:!0}}}(function(){return this}()||Function("return this")())}])},t.exports=r()},function(t,e,n){var r;window,r=function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="/dist/",n(n.s=6)}([function(t,e,n){var r=n(8);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals),(0,n(4).default)("7ec05f6c",r,!1,{})},function(t,e,n){var r=n(10);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals),(0,n(4).default)("3453d19d",r,!1,{})},function(t,e,n){"use strict";t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var n=function(t,e){var n,r=t[1]||"",i=t[3];if(!i)return r;if(e&&"function"==typeof btoa){var o=(n=i,"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(n))))+" */"),u=i.sources.map(function(t){return"/*# sourceURL="+i.sourceRoot+t+" */"});return[r].concat(u).concat([o]).join("\n")}return[r].join("\n")}(e,t);return e[2]?"@media "+e[2]+"{"+n+"}":n}).join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},i=0;i<this.length;i++){var o=this[i][0];null!=o&&(r[o]=!0)}for(i=0;i<t.length;i++){var u=t[i];null!=u[0]&&r[u[0]]||(n&&!u[2]?u[2]=n:n&&(u[2]="("+u[2]+") and ("+n+")"),e.push(u))}},e}},function(t,e){t.exports="data:application/vnd.ms-fontobject;base64,aAUAAMQEAAABAAIAAAAAAAAAAAAAAAAAAAABAJABAAAAAExQAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAUdPJHwAAAAAAAAAAAAAAAAAAAAAAAA4AaQBjAG8AbQBvAG8AbgAAAA4AUgBlAGcAdQBsAGEAcgAAABYAVgBlAHIAcwBpAG8AbgAgADEALgAwAAAADgBpAGMAbwBtAG8AbwBuAAAAAAAAAQAAAAsAgAADADBPUy8yDxIFrAAAALwAAABgY21hcBdW0okAAAEcAAAAVGdhc3AAAAAQAAABcAAAAAhnbHlmpZ+jMAAAAXgAAAD8aGVhZA/FmAgAAAJ0AAAANmhoZWEHgAPIAAACrAAAACRobXR4EgABvgAAAtAAAAAcbG9jYQCSAOIAAALsAAAAEG1heHAACQAfAAAC/AAAACBuYW1lmUoJ+wAAAxwAAAGGcG9zdAADAAAAAASkAAAAIAADA4ABkAAFAAACmQLMAAAAjwKZAswAAAHrADMBCQAAAAAAAAAAAAAAAAAAAAEQAAAAAAAAAAAAAAAAAAAAAEAAAOkCA8D/wABAA8AAQAAAAAEAAAAAAAAAAAAAACAAAAAAAAMAAAADAAAAHAABAAMAAAAcAAMAAQAAABwABAA4AAAACgAIAAIAAgABACDpAv/9//8AAAAAACDpAP/9//8AAf/jFwQAAwABAAAAAAAAAAAAAAABAAH//wAPAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAEAVgEBA74CgQAcAAABMhceARcWFwcmJy4BJyYjIgYHFyERFzY3PgE3NgIWSkNDbykpF2QQIB9VMzQ5P3AtnP6AmB0iIkspKAJVFxhSODlCIDMrKz4REislmgGAmhkVFBwICAABANYAgQMqAtUACwAAAQcXBycHJzcnNxc3Ayru7jzu7jzu7jzu7gKZ7u487u487u487u4AAQCSAIEDgAK9AAUAACUBFwEnNwGAAcQ8/gDuPPkBxDz+AO48AAAAAAEAAAAAAAAfydNRXw889QALBAAAAAAA1nUqGwAAAADWdSobAAAAAAO+AtUAAAAIAAIAAAAAAAAAAQAAA8D/wAAABAAAAAAAA74AAQAAAAAAAAAAAAAAAAAAAAcEAAAAAAAAAAAAAAACAAAABAAAVgQAANYEAACSAAAAAAAKABQAHgBQAGoAfgABAAAABwAdAAEAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAADgCuAAEAAAAAAAEABwAAAAEAAAAAAAIABwBgAAEAAAAAAAMABwA2AAEAAAAAAAQABwB1AAEAAAAAAAUACwAVAAEAAAAAAAYABwBLAAEAAAAAAAoAGgCKAAMAAQQJAAEADgAHAAMAAQQJAAIADgBnAAMAAQQJAAMADgA9AAMAAQQJAAQADgB8AAMAAQQJAAUAFgAgAAMAAQQJAAYADgBSAAMAAQQJAAoANACkaWNvbW9vbgBpAGMAbwBtAG8AbwBuVmVyc2lvbiAxLjAAVgBlAHIAcwBpAG8AbgAgADEALgAwaWNvbW9vbgBpAGMAbwBtAG8AbwBuaWNvbW9vbgBpAGMAbwBtAG8AbwBuUmVndWxhcgBSAGUAZwB1AGwAYQByaWNvbW9vbgBpAGMAbwBtAG8AbwBuRm9udCBnZW5lcmF0ZWQgYnkgSWNvTW9vbi4ARgBvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAASQBjAG8ATQBvAG8AbgAuAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="},function(t,e,n){"use strict";function r(t,e){for(var n=[],r={},i=0;i<e.length;i++){var o=e[i],u=o[0],a={id:t+":"+i,css:o[1],media:o[2],sourceMap:o[3]};r[u]?r[u].parts.push(a):n.push(r[u]={id:u,parts:[a]})}return n}n.r(e),n.d(e,"default",function(){return d});var i="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!i)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var o={},u=i&&(document.head||document.getElementsByTagName("head")[0]),a=null,s=0,c=!1,f=function(){},l=null,A="data-vue-ssr-id",p="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());function d(t,e,n,i){c=n,l=i||{};var u=r(t,e);return h(u),function(e){for(var n=[],i=0;i<u.length;i++){var a=u[i];(s=o[a.id]).refs--,n.push(s)}for(e?h(u=r(t,e)):u=[],i=0;i<n.length;i++){var s;if(0===(s=n[i]).refs){for(var c=0;c<s.parts.length;c++)s.parts[c]();delete o[s.id]}}}}function h(t){for(var e=0;e<t.length;e++){var n=t[e],r=o[n.id];if(r){r.refs++;for(var i=0;i<r.parts.length;i++)r.parts[i](n.parts[i]);for(;i<n.parts.length;i++)r.parts.push(g(n.parts[i]));r.parts.length>n.parts.length&&(r.parts.length=n.parts.length)}else{var u=[];for(i=0;i<n.parts.length;i++)u.push(g(n.parts[i]));o[n.id]={id:n.id,refs:1,parts:u}}}}function v(){var t=document.createElement("style");return t.type="text/css",u.appendChild(t),t}function g(t){var e,n,r=document.querySelector("style["+A+'~="'+t.id+'"]');if(r){if(c)return f;r.parentNode.removeChild(r)}if(p){var i=s++;r=a||(a=v()),e=_.bind(null,r,i,!1),n=_.bind(null,r,i,!0)}else r=v(),e=function(t,e){var n=e.css,r=e.media,i=e.sourceMap;if(r&&t.setAttribute("media",r),l.ssrId&&t.setAttribute(A,e.id),i&&(n+="\n/*# sourceURL="+i.sources[0]+" */",n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */"),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}.bind(null,r),n=function(){r.parentNode.removeChild(r)};return e(t),function(r){if(r){if(r.css===t.css&&r.media===t.media&&r.sourceMap===t.sourceMap)return;e(t=r)}else n()}}var m,y=(m=[],function(t,e){return m[t]=e,m.filter(Boolean).join("\n")});function _(t,e,n,r){var i=n?"":r.css;if(t.styleSheet)t.styleSheet.cssText=y(e,i);else{var o=document.createTextNode(i),u=t.childNodes;u[e]&&t.removeChild(u[e]),u.length?t.insertBefore(o,u[e]):t.appendChild(o)}}},function(t,e,n){"use strict";var r=Array.isArray,i=Object.keys,o=Object.prototype.hasOwnProperty;t.exports=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){var u,a,s,c=r(e),f=r(n);if(c&&f){if((a=e.length)!=n.length)return!1;for(u=a;0!=u--;)if(!t(e[u],n[u]))return!1;return!0}if(c!=f)return!1;var l=e instanceof Date,A=n instanceof Date;if(l!=A)return!1;if(l&&A)return e.getTime()==n.getTime();var p=e instanceof RegExp,d=n instanceof RegExp;if(p!=d)return!1;if(p&&d)return e.toString()==n.toString();var h=i(e);if((a=h.length)!==i(n).length)return!1;for(u=a;0!=u--;)if(!o.call(n,h[u]))return!1;for(u=a;0!=u--;)if(!t(e[s=h[u]],n[s]))return!1;return!0}return e!=e&&n!=n}},function(t,e,n){t.exports=n(14)},function(t,e,n){"use strict";var r=n(0);n.n(r).a},function(t,e,n){(t.exports=n(2)(!0)).push([t.i,".ti-tag-input[data-v-108f4f13] {\n background-color: transparent;\n color: inherit;\n border: none;\n padding: 0px;\n margin: 0px;\n display: flex;\n top: 0px;\n position: absolute;\n width: 100%;\n line-height: inherit;\n}\n.ti-tag-input[data-v-108f4f13]::-ms-clear {\n display: none;\n}\ninput[data-v-108f4f13]:focus {\n outline: none;\n}\ninput[disabled][data-v-108f4f13] {\n background-color: transparent;\n}\n","",{version:3,sources:["C:/Users/johan/dev/vue-tags-input/vue-tags-input/C:/Users/johan/dev/vue-tags-input/vue-tags-input/tag-input.vue"],names:[],mappings:"AAAA;EACE,8BAA8B;EAC9B,eAAe;EACf,aAAa;EACb,aAAa;EACb,YAAY;EACZ,cAAc;EACd,SAAS;EACT,mBAAmB;EACnB,YAAY;EACZ,qBAAqB;CAAE;AAEzB;EACE,cAAc;CAAE;AAElB;EACE,cAAc;CAAE;AAElB;EACE,8BAA8B;CAAE",file:"tag-input.vue?vue&type=style&index=0&id=108f4f13&lang=css&scoped=true&",sourcesContent:[".ti-tag-input {\n background-color: transparent;\n color: inherit;\n border: none;\n padding: 0px;\n margin: 0px;\n display: flex;\n top: 0px;\n position: absolute;\n width: 100%;\n line-height: inherit; }\n\n.ti-tag-input::-ms-clear {\n display: none; }\n\ninput:focus {\n outline: none; }\n\ninput[disabled] {\n background-color: transparent; }\n"],sourceRoot:""}])},function(t,e,n){"use strict";var r=n(1);n.n(r).a},function(t,e,n){e=t.exports=n(2)(!0);var r=n(11),i=r(n(3)),o=r(n(3)+"#iefix"),u=r(n(12)),a=r(n(13));e.push([t.i,"@font-face {\n font-family: 'icomoon';\n src: url("+i+");\n src: url("+o+') format("embedded-opentype"), url('+u+') format("truetype"), url('+a+') format("woff");\n font-weight: normal;\n font-style: normal;\n}\n[class^="ti-icon-"][data-v-61d92e31], [class*=" ti-icon-"][data-v-61d92e31] {\n font-family: \'icomoon\' !important;\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n.ti-icon-check[data-v-61d92e31]:before {\n content: "\\e902";\n}\n.ti-icon-close[data-v-61d92e31]:before {\n content: "\\e901";\n}\n.ti-icon-undo[data-v-61d92e31]:before {\n content: "\\e900";\n}\nul[data-v-61d92e31] {\n margin: 0px;\n padding: 0px;\n list-style-type: none;\n}\n*[data-v-61d92e31], *[data-v-61d92e31]:before, *[data-v-61d92e31]:after {\n box-sizing: border-box;\n}\ninput[data-v-61d92e31]:focus {\n outline: none;\n}\ninput[disabled][data-v-61d92e31] {\n background-color: transparent;\n}\n.vue-tags-input[data-v-61d92e31] {\n max-width: 450px;\n position: relative;\n background-color: #fff;\n}\ndiv.vue-tags-input.disabled[data-v-61d92e31] {\n opacity: 0.5;\n}\ndiv.vue-tags-input.disabled *[data-v-61d92e31] {\n cursor: default;\n}\n.ti-input[data-v-61d92e31] {\n border: 1px solid #ccc;\n display: flex;\n padding: 4px;\n flex-wrap: wrap;\n}\n.ti-tags[data-v-61d92e31] {\n display: flex;\n flex-wrap: wrap;\n width: 100%;\n line-height: 1em;\n}\n.ti-tag[data-v-61d92e31] {\n background-color: #5C6BC0;\n color: #fff;\n border-radius: 2px;\n display: flex;\n padding: 3px 5px;\n margin: 2px;\n font-size: .85em;\n}\n.ti-tag[data-v-61d92e31]:focus {\n outline: none;\n}\n.ti-tag .ti-content[data-v-61d92e31] {\n display: flex;\n align-items: center;\n}\n.ti-tag .ti-tag-center[data-v-61d92e31] {\n position: relative;\n}\n.ti-tag span[data-v-61d92e31] {\n line-height: .85em;\n}\n.ti-tag span.ti-hidden[data-v-61d92e31] {\n padding-left: 14px;\n visibility: hidden;\n height: 0px;\n white-space: pre;\n}\n.ti-tag .ti-actions[data-v-61d92e31] {\n margin-left: 2px;\n display: flex;\n align-items: center;\n font-size: 1.15em;\n}\n.ti-tag .ti-actions i[data-v-61d92e31] {\n cursor: pointer;\n}\n.ti-tag[data-v-61d92e31]:last-child {\n margin-right: 4px;\n}\n.ti-tag.ti-invalid[data-v-61d92e31], .ti-tag.ti-tag.ti-deletion-mark[data-v-61d92e31] {\n background-color: #e54d42;\n}\n.ti-new-tag-input-wrapper[data-v-61d92e31] {\n display: flex;\n flex: 1 0 auto;\n padding: 3px 5px;\n margin: 2px;\n font-size: .85em;\n}\n.ti-new-tag-input-wrapper input[data-v-61d92e31] {\n flex: 1 0 auto;\n min-width: 100px;\n border: none;\n padding: 0px;\n margin: 0px;\n}\n.ti-new-tag-input[data-v-61d92e31] {\n line-height: initial;\n}\n.ti-autocomplete[data-v-61d92e31] {\n border: 1px solid #ccc;\n border-top: none;\n position: absolute;\n width: 100%;\n background-color: #fff;\n z-index: 20;\n}\n.ti-item > div[data-v-61d92e31] {\n cursor: pointer;\n padding: 3px 6px;\n width: 100%;\n}\n.ti-selected-item[data-v-61d92e31] {\n background-color: #5C6BC0;\n color: #fff;\n}\n',"",{version:3,sources:["C:/Users/johan/dev/vue-tags-input/vue-tags-input/C:/Users/johan/dev/vue-tags-input/vue-tags-input/vue-tags-input.scss"],names:[],mappings:"AAAA;EACE,uBAAuB;EACvB,mCAA8C;EAC9C,+JAAuM;EACvM,oBAAoB;EACpB,mBAAmB;CAAE;AAEvB;EACE,kCAAkC;EAClC,YAAY;EACZ,mBAAmB;EACnB,oBAAoB;EACpB,qBAAqB;EACrB,qBAAqB;EACrB,eAAe;EACf,oCAAoC;EACpC,mCAAmC;CAAE;AAEvC;EACE,iBAAiB;CAAE;AAErB;EACE,iBAAiB;CAAE;AAErB;EACE,iBAAiB;CAAE;AAErB;EACE,YAAY;EACZ,aAAa;EACb,sBAAsB;CAAE;AAE1B;EACE,uBAAuB;CAAE;AAE3B;EACE,cAAc;CAAE;AAElB;EACE,8BAA8B;CAAE;AAElC;EACE,iBAAiB;EACjB,mBAAmB;EACnB,uBAAuB;CAAE;AAE3B;EACE,aAAa;CAAE;AACf;IACE,gBAAgB;CAAE;AAEtB;EACE,uBAAuB;EACvB,cAAc;EACd,aAAa;EACb,gBAAgB;CAAE;AAEpB;EACE,cAAc;EACd,gBAAgB;EAChB,YAAY;EACZ,iBAAiB;CAAE;AAErB;EACE,0BAA0B;EAC1B,YAAY;EACZ,mBAAmB;EACnB,cAAc;EACd,iBAAiB;EACjB,YAAY;EACZ,iBAAiB;CAAE;AACnB;IACE,cAAc;CAAE;AAClB;IACE,cAAc;IACd,oBAAoB;CAAE;AACxB;IACE,mBAAmB;CAAE;AACvB;IACE,mBAAmB;CAAE;AACvB;IACE,mBAAmB;IACnB,mBAAmB;IACnB,YAAY;IACZ,iBAAiB;CAAE;AACrB;IACE,iBAAiB;IACjB,cAAc;IACd,oBAAoB;IACpB,kBAAkB;CAAE;AACpB;MACE,gBAAgB;CAAE;AACtB;IACE,kBAAkB;CAAE;AACtB;IACE,0BAA0B;CAAE;AAEhC;EACE,cAAc;EACd,eAAe;EACf,iBAAiB;EACjB,YAAY;EACZ,iBAAiB;CAAE;AACnB;IACE,eAAe;IACf,iBAAiB;IACjB,aAAa;IACb,aAAa;IACb,YAAY;CAAE;AAElB;EACE,qBAAqB;CAAE;AAEzB;EACE,uBAAuB;EACvB,iBAAiB;EACjB,mBAAmB;EACnB,YAAY;EACZ,uBAAuB;EACvB,YAAY;CAAE;AAEhB;EACE,gBAAgB;EAChB,iBAAiB;EACjB,YAAY;CAAE;AAEhB;EACE,0BAA0B;EAC1B,YAAY;CAAE",file:"vue-tags-input.scss?vue&type=style&index=0&id=61d92e31&lang=scss&scoped=true&",sourcesContent:['@font-face {\n font-family: \'icomoon\';\n src: url("./assets/fonts/icomoon.eot?7grlse");\n src: url("./assets/fonts/icomoon.eot?7grlse#iefix") format("embedded-opentype"), url("./assets/fonts/icomoon.ttf?7grlse") format("truetype"), url("./assets/fonts/icomoon.woff?7grlse") format("woff");\n font-weight: normal;\n font-style: normal; }\n\n[class^="ti-icon-"], [class*=" ti-icon-"] {\n font-family: \'icomoon\' !important;\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale; }\n\n.ti-icon-check:before {\n content: "\\e902"; }\n\n.ti-icon-close:before {\n content: "\\e901"; }\n\n.ti-icon-undo:before {\n content: "\\e900"; }\n\nul {\n margin: 0px;\n padding: 0px;\n list-style-type: none; }\n\n*, *:before, *:after {\n box-sizing: border-box; }\n\ninput:focus {\n outline: none; }\n\ninput[disabled] {\n background-color: transparent; }\n\n.vue-tags-input {\n max-width: 450px;\n position: relative;\n background-color: #fff; }\n\ndiv.vue-tags-input.disabled {\n opacity: 0.5; }\n div.vue-tags-input.disabled * {\n cursor: default; }\n\n.ti-input {\n border: 1px solid #ccc;\n display: flex;\n padding: 4px;\n flex-wrap: wrap; }\n\n.ti-tags {\n display: flex;\n flex-wrap: wrap;\n width: 100%;\n line-height: 1em; }\n\n.ti-tag {\n background-color: #5C6BC0;\n color: #fff;\n border-radius: 2px;\n display: flex;\n padding: 3px 5px;\n margin: 2px;\n font-size: .85em; }\n .ti-tag:focus {\n outline: none; }\n .ti-tag .ti-content {\n display: flex;\n align-items: center; }\n .ti-tag .ti-tag-center {\n position: relative; }\n .ti-tag span {\n line-height: .85em; }\n .ti-tag span.ti-hidden {\n padding-left: 14px;\n visibility: hidden;\n height: 0px;\n white-space: pre; }\n .ti-tag .ti-actions {\n margin-left: 2px;\n display: flex;\n align-items: center;\n font-size: 1.15em; }\n .ti-tag .ti-actions i {\n cursor: pointer; }\n .ti-tag:last-child {\n margin-right: 4px; }\n .ti-tag.ti-invalid, .ti-tag.ti-tag.ti-deletion-mark {\n background-color: #e54d42; }\n\n.ti-new-tag-input-wrapper {\n display: flex;\n flex: 1 0 auto;\n padding: 3px 5px;\n margin: 2px;\n font-size: .85em; }\n .ti-new-tag-input-wrapper input {\n flex: 1 0 auto;\n min-width: 100px;\n border: none;\n padding: 0px;\n margin: 0px; }\n\n.ti-new-tag-input {\n line-height: initial; }\n\n.ti-autocomplete {\n border: 1px solid #ccc;\n border-top: none;\n position: absolute;\n width: 100%;\n background-color: #fff;\n z-index: 20; }\n\n.ti-item > div {\n cursor: pointer;\n padding: 3px 6px;\n width: 100%; }\n\n.ti-selected-item {\n background-color: #5C6BC0;\n color: #fff; }\n'],sourceRoot:""}])},function(t,e,n){"use strict";t.exports=function(t){return"string"!=typeof t?t:(/^['"].*['"]$/.test(t)&&(t=t.slice(1,-1)),/["'() \t\n]/.test(t)?'"'+t.replace(/"/g,'\\"').replace(/\n/g,"\\n")+'"':t)}},function(t,e){t.exports="data:font/ttf;base64,AAEAAAALAIAAAwAwT1MvMg8SBawAAAC8AAAAYGNtYXAXVtKJAAABHAAAAFRnYXNwAAAAEAAAAXAAAAAIZ2x5ZqWfozAAAAF4AAAA/GhlYWQPxZgIAAACdAAAADZoaGVhB4ADyAAAAqwAAAAkaG10eBIAAb4AAALQAAAAHGxvY2EAkgDiAAAC7AAAABBtYXhwAAkAHwAAAvwAAAAgbmFtZZlKCfsAAAMcAAABhnBvc3QAAwAAAAAEpAAAACAAAwOAAZAABQAAApkCzAAAAI8CmQLMAAAB6wAzAQkAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAAADpAgPA/8AAQAPAAEAAAAABAAAAAAAAAAAAAAAgAAAAAAADAAAAAwAAABwAAQADAAAAHAADAAEAAAAcAAQAOAAAAAoACAACAAIAAQAg6QL//f//AAAAAAAg6QD//f//AAH/4xcEAAMAAQAAAAAAAAAAAAAAAQAB//8ADwABAAAAAAAAAAAAAgAANzkBAAAAAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAAAAAAAAAAIAADc5AQAAAAABAFYBAQO+AoEAHAAAATIXHgEXFhcHJicuAScmIyIGBxchERc2Nz4BNzYCFkpDQ28pKRdkECAfVTM0OT9wLZz+gJgdIiJLKSgCVRcYUjg5QiAzKys+ERIrJZoBgJoZFRQcCAgAAQDWAIEDKgLVAAsAAAEHFwcnByc3JzcXNwMq7u487u487u487u4Cme7uPO7uPO7uPO7uAAEAkgCBA4ACvQAFAAAlARcBJzcBgAHEPP4A7jz5AcQ8/gDuPAAAAAABAAAAAAAAH8nTUV8PPPUACwQAAAAAANZ1KhsAAAAA1nUqGwAAAAADvgLVAAAACAACAAAAAAAAAAEAAAPA/8AAAAQAAAAAAAO+AAEAAAAAAAAAAAAAAAAAAAAHBAAAAAAAAAAAAAAAAgAAAAQAAFYEAADWBAAAkgAAAAAACgAUAB4AUABqAH4AAQAAAAcAHQABAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAA4ArgABAAAAAAABAAcAAAABAAAAAAACAAcAYAABAAAAAAADAAcANgABAAAAAAAEAAcAdQABAAAAAAAFAAsAFQABAAAAAAAGAAcASwABAAAAAAAKABoAigADAAEECQABAA4ABwADAAEECQACAA4AZwADAAEECQADAA4APQADAAEECQAEAA4AfAADAAEECQAFABYAIAADAAEECQAGAA4AUgADAAEECQAKADQApGljb21vb24AaQBjAG8AbQBvAG8AblZlcnNpb24gMS4wAFYAZQByAHMAaQBvAG4AIAAxAC4AMGljb21vb24AaQBjAG8AbQBvAG8Abmljb21vb24AaQBjAG8AbQBvAG8AblJlZ3VsYXIAUgBlAGcAdQBsAGEAcmljb21vb24AaQBjAG8AbQBvAG8AbkZvbnQgZ2VuZXJhdGVkIGJ5IEljb01vb24uAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAEkAYwBvAE0AbwBvAG4ALgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},function(t,e){t.exports="data:font/woff;base64,d09GRgABAAAAAAUQAAsAAAAABMQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABCAAAAGAAAABgDxIFrGNtYXAAAAFoAAAAVAAAAFQXVtKJZ2FzcAAAAbwAAAAIAAAACAAAABBnbHlmAAABxAAAAPwAAAD8pZ+jMGhlYWQAAALAAAAANgAAADYPxZgIaGhlYQAAAvgAAAAkAAAAJAeAA8hobXR4AAADHAAAABwAAAAcEgABvmxvY2EAAAM4AAAAEAAAABAAkgDibWF4cAAAA0gAAAAgAAAAIAAJAB9uYW1lAAADaAAAAYYAAAGGmUoJ+3Bvc3QAAATwAAAAIAAAACAAAwAAAAMDgAGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAA6QIDwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEADgAAAAKAAgAAgACAAEAIOkC//3//wAAAAAAIOkA//3//wAB/+MXBAADAAEAAAAAAAAAAAAAAAEAAf//AA8AAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAEAAAAAAAAAAAACAAA3OQEAAAAAAQBWAQEDvgKBABwAAAEyFx4BFxYXByYnLgEnJiMiBgcXIREXNjc+ATc2AhZKQ0NvKSkXZBAgH1UzNDk/cC2c/oCYHSIiSykoAlUXGFI4OUIgMysrPhESKyWaAYCaGRUUHAgIAAEA1gCBAyoC1QALAAABBxcHJwcnNyc3FzcDKu7uPO7uPO7uPO7uApnu7jzu7jzu7jzu7gABAJIAgQOAAr0ABQAAJQEXASc3AYABxDz+AO48+QHEPP4A7jwAAAAAAQAAAAAAAB/J01FfDzz1AAsEAAAAAADWdSobAAAAANZ1KhsAAAAAA74C1QAAAAgAAgAAAAAAAAABAAADwP/AAAAEAAAAAAADvgABAAAAAAAAAAAAAAAAAAAABwQAAAAAAAAAAAAAAAIAAAAEAABWBAAA1gQAAJIAAAAAAAoAFAAeAFAAagB+AAEAAAAHAB0AAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAOAK4AAQAAAAAAAQAHAAAAAQAAAAAAAgAHAGAAAQAAAAAAAwAHADYAAQAAAAAABAAHAHUAAQAAAAAABQALABUAAQAAAAAABgAHAEsAAQAAAAAACgAaAIoAAwABBAkAAQAOAAcAAwABBAkAAgAOAGcAAwABBAkAAwAOAD0AAwABBAkABAAOAHwAAwABBAkABQAWACAAAwABBAkABgAOAFIAAwABBAkACgA0AKRpY29tb29uAGkAYwBvAG0AbwBvAG5WZXJzaW9uIDEuMABWAGUAcgBzAGkAbwBuACAAMQAuADBpY29tb29uAGkAYwBvAG0AbwBvAG5pY29tb29uAGkAYwBvAG0AbwBvAG5SZWd1bGFyAFIAZQBnAHUAbABhAHJpY29tb29uAGkAYwBvAG0AbwBvAG5Gb250IGdlbmVyYXRlZCBieSBJY29Nb29uLgBGAG8AbgB0ACAAZwBlAG4AZQByAGEAdABlAGQAIABiAHkAIABJAGMAbwBNAG8AbwBuAC4AAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},function(t,e,n){"use strict";n.r(e);var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"vue-tags-input",class:[{"ti-disabled":t.disabled},{"ti-focus":t.focused}]},[n("div",{staticClass:"ti-input"},[t.tagsCopy?n("ul",{staticClass:"ti-tags"},[t._l(t.tagsCopy,function(e,r){return n("li",{key:r,staticClass:"ti-tag",class:[{"ti-editing":t.tagsEditStatus[r]},e.tiClasses,e.classes,{"ti-deletion-mark":t.isMarked(r)}],style:e.style,attrs:{tabindex:"0"},on:{click:function(n){return t.$emit("tag-clicked",{tag:e,index:r})}}},[n("div",{staticClass:"ti-content"},[t.$scopedSlots["tag-left"]?n("div",{staticClass:"ti-tag-left"},[t._t("tag-left",null,{tag:e,index:r,edit:t.tagsEditStatus[r],performSaveEdit:t.performSaveTag,performDelete:t.performDeleteTag,performCancelEdit:t.cancelEdit,performOpenEdit:t.performEditTag,deletionMark:t.isMarked(r)})],2):t._e(),t._v(" "),n("div",{ref:"tagCenter",refInFor:!0,staticClass:"ti-tag-center"},[t.$scopedSlots["tag-center"]?t._e():n("span",{class:{"ti-hidden":t.tagsEditStatus[r]},on:{click:function(e){return t.performEditTag(r)}}},[t._v(t._s(e.text))]),t._v(" "),t.$scopedSlots["tag-center"]?t._e():n("tag-input",{attrs:{scope:{edit:t.tagsEditStatus[r],maxlength:t.maxlength,tag:e,index:r,validateTag:t.createChangedTag,performCancelEdit:t.cancelEdit,performSaveEdit:t.performSaveTag}}}),t._v(" "),t._t("tag-center",null,{tag:e,index:r,maxlength:t.maxlength,edit:t.tagsEditStatus[r],performSaveEdit:t.performSaveTag,performDelete:t.performDeleteTag,performCancelEdit:t.cancelEdit,validateTag:t.createChangedTag,performOpenEdit:t.performEditTag,deletionMark:t.isMarked(r)})],2),t._v(" "),t.$scopedSlots["tag-right"]?n("div",{staticClass:"ti-tag-right"},[t._t("tag-right",null,{tag:e,index:r,edit:t.tagsEditStatus[r],performSaveEdit:t.performSaveTag,performDelete:t.performDeleteTag,performCancelEdit:t.cancelEdit,performOpenEdit:t.performEditTag,deletionMark:t.isMarked(r)})],2):t._e()]),t._v(" "),n("div",{staticClass:"ti-actions"},[t.$scopedSlots["tag-actions"]?t._e():n("i",{directives:[{name:"show",rawName:"v-show",value:t.tagsEditStatus[r],expression:"tagsEditStatus[index]"}],staticClass:"ti-icon-undo",on:{click:function(e){return t.cancelEdit(r)}}}),t._v(" "),t.$scopedSlots["tag-actions"]?t._e():n("i",{directives:[{name:"show",rawName:"v-show",value:!t.tagsEditStatus[r],expression:"!tagsEditStatus[index]"}],staticClass:"ti-icon-close",on:{click:function(e){return t.performDeleteTag(r)}}}),t._v(" "),t.$scopedSlots["tag-actions"]?t._t("tag-actions",null,{tag:e,index:r,edit:t.tagsEditStatus[r],performSaveEdit:t.performSaveTag,performDelete:t.performDeleteTag,performCancelEdit:t.cancelEdit,performOpenEdit:t.performEditTag,deletionMark:t.isMarked(r)}):t._e()],2)])}),t._v(" "),n("li",{staticClass:"ti-new-tag-input-wrapper"},[n("input",t._b({ref:"newTagInput",staticClass:"ti-new-tag-input",class:[t.createClasses(t.newTag,t.tags,t.validation,t.isDuplicate)],attrs:{placeholder:t.placeholder,maxlength:t.maxlength,disabled:t.disabled,type:"text",size:"1"},domProps:{value:t.newTag},on:{keydown:[function(e){return t.performAddTags(t.filteredAutocompleteItems[t.selectedItem]||t.newTag,e)},function(e){return e.type.indexOf("key")||8===e.keyCode?t.invokeDelete(e):null},function(e){return e.type.indexOf("key")||38===e.keyCode?t.selectItem(e,"before"):null},function(e){return e.type.indexOf("key")||40===e.keyCode?t.selectItem(e,"after"):null}],paste:t.addTagsFromPaste,input:t.updateNewTag,blur:function(e){return t.$emit("blur",e)},focus:function(e){t.focused=!0,t.$emit("focus",e)},click:function(e){!t.addOnlyFromAutocomplete&&(t.selectedItem=null)}}},"input",t.$attrs,!1))])],2):t._e()]),t._v(" "),t._t("between-elements"),t._v(" "),t.autocompleteOpen?n("div",{staticClass:"ti-autocomplete",on:{mouseout:function(e){t.selectedItem=null}}},[t._t("autocomplete-header"),t._v(" "),n("ul",t._l(t.filteredAutocompleteItems,function(e,r){return n("li",{key:r,staticClass:"ti-item",class:[e.tiClasses,e.classes,{"ti-selected-item":t.isSelected(r)}],style:e.style,on:{mouseover:function(e){!t.disabled&&(t.selectedItem=r)}}},[t.$scopedSlots["autocomplete-item"]?t._t("autocomplete-item",null,{item:e,index:r,performAdd:function(e){return t.performAddTags(e,void 0,"autocomplete")},selected:t.isSelected(r)}):n("div",{on:{click:function(n){return t.performAddTags(e,void 0,"autocomplete")}}},[t._v("\n "+t._s(e.text)+"\n ")])],2)}),0),t._v(" "),t._t("autocomplete-footer")],2):t._e()],2)};r._withStripped=!0;var i=n(5),o=n.n(i),u=function(t){return JSON.parse(JSON.stringify(t))},a=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3?arguments[3]:void 0;void 0===t.text&&(t={text:t});var i=function(t,e){return n.filter(function(e){var n=t.text;return"string"==typeof e.rule?!new RegExp(e.rule).test(n):e.rule instanceof RegExp?!e.rule.test(n):"[object Function]"==={}.toString.call(e.rule)?e.rule(t):void 0}).map(function(t){return t.classes})}(t),o=function(t,e){for(var n=0;n<t.length;){if(e(t[n]))return n;n++}return-1}(e,function(e){return e===t}),a=u(e),s=-1!==o?a.splice(o,1)[0]:u(t);return(r?r(a,s):-1!==a.map(function(t){return t.text}).indexOf(s.text))&&i.push("ti-duplicate"),0===i.length?i.push("ti-valid"):i.push("ti-invalid"),i},s=function(t){void 0===t.text&&(t={text:t});for(var e=u(t),n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return e.tiClasses=a.apply(void 0,[t].concat(r)),e},c=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return t.map(function(e){return s.apply(void 0,[e,t].concat(n))})},f=function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.scope.edit?n("input",{directives:[{name:"model",rawName:"v-model",value:t.scope.tag.text,expression:"scope.tag.text"}],staticClass:"ti-tag-input",attrs:{maxlength:t.scope.maxlength,type:"text",size:"1"},domProps:{value:t.scope.tag.text},on:{input:[function(e){e.target.composing||t.$set(t.scope.tag,"text",e.target.value)},function(e){return t.scope.validateTag(t.scope.index,e)}],blur:function(e){return t.scope.performCancelEdit(t.scope.index)},keydown:function(e){return t.scope.performSaveEdit(t.scope.index,e)}}}):t._e()};f._withStripped=!0;var l={name:"TagInput",props:{scope:{type:Object}}};function A(t,e,n,r,i,o,u,a){var s,c="function"==typeof t?t.options:t;if(e&&(c.render=e,c.staticRenderFns=n,c._compiled=!0),r&&(c.functional=!0),o&&(c._scopeId="data-v-"+o),u?(s=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),i&&i.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(u)},c._ssrRegister=s):i&&(s=a?function(){i.call(this,this.$root.$options.shadowRoot)}:i),s)if(c.functional){c._injectStyles=s;var f=c.render;c.render=function(t,e){return s.call(e),f(t,e)}}else{var l=c.beforeCreate;c.beforeCreate=l?[].concat(l,s):[s]}return{exports:t,options:c}}n(7);var p=A(l,f,[],!1,null,"108f4f13",null);p.options.__file="vue-tags-input/tag-input.vue";var d=p.exports,h=function(t){return!t.some(function(t){var e=!t.text;e&&console.warn('Missing property "text"',t);var n=!1;return t.classes&&(n="string"!=typeof t.classes),n&&console.warn('Property "classes" must be type of string',t),e||n})},v=function(t){return!t.some(function(t){if("number"==typeof t){var e=isFinite(t)&&Math.floor(t)===t;return e||console.warn("Only numerics are allowed for this prop. Found:",t),!e}if("string"==typeof t){var n=/\W|[a-z]|!\d/i.test(t);return n||console.warn("Only alpha strings are allowed for this prop. Found:",t),!n}return console.warn("Only numeric and string values are allowed. Found:",t),!1})},g={value:{type:String,default:"",required:!0},tags:{type:Array,default:function(){return[]},validator:h},autocompleteItems:{type:Array,default:function(){return[]},validator:h},allowEditTags:{type:Boolean,default:!1},autocompleteFilterDuplicates:{default:!0,type:Boolean},addOnlyFromAutocomplete:{type:Boolean,default:!1},autocompleteMinLength:{type:Number,default:1},autocompleteAlwaysOpen:{type:Boolean,default:!1},disabled:{type:Boolean,default:!1},placeholder:{type:String,default:"Add Tag"},addOnKey:{type:Array,default:function(){return[13]},validator:v},saveOnKey:{type:Array,default:function(){return[13]},validator:v},maxTags:{type:Number},maxlength:{type:Number},validation:{type:Array,default:function(){return[]},validator:function(t){return!t.some(function(t){var e=!t.rule;e&&console.warn('Property "rule" is missing',t);var n=t.rule&&("string"==typeof t.rule||t.rule instanceof RegExp||"[object Function]"==={}.toString.call(t.rule));n||console.warn("A rule must be type of string, RegExp or function. Found:",JSON.stringify(t.rule));var r=!t.classes;r&&console.warn('Property "classes" is missing',t);var i=t.type&&"string"!=typeof t.type;return i&&console.warn('Property "type" must be type of string. Found:',t),!n||e||r||i})}},separators:{type:Array,default:function(){return[";"]},validator:function(t){return!t.some(function(t){var e="string"!=typeof t;return e&&console.warn("Separators must be type of string. Found:",t),e})}},avoidAddingDuplicates:{type:Boolean,default:!0},addOnBlur:{type:Boolean,default:!0},isDuplicate:{type:Function,default:null},addFromPaste:{type:Boolean,default:!0},deleteOnBackspace:{default:!0,type:Boolean}};function m(t){return(m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var y={name:"VueTagsInput",components:{TagInput:d},props:g,data:function(){return{newTag:null,tagsCopy:null,tagsEditStatus:null,deletionMark:null,deletionMarkTime:null,selectedItem:null,focused:null}},computed:{autocompleteOpen:function(){return!!this.autocompleteAlwaysOpen||null!==this.newTag&&this.newTag.length>=this.autocompleteMinLength&&this.filteredAutocompleteItems.length>0&&this.focused},filteredAutocompleteItems:function(){var t=this,e=this.autocompleteItems.map(function(e){return s(e,t.tags,t.validation,t.isDuplicate)});return this.autocompleteFilterDuplicates?e.filter(this.duplicateFilter):e}},methods:{createClasses:a,getSelectedIndex:function(t){var e=this.filteredAutocompleteItems,n=this.selectedItem,r=e.length-1;if(0!==e.length)return null===n?0:"before"===t&&0===n?r:"after"===t&&n===r?0:"after"===t?n+1:n-1},selectDefaultItem:function(){this.addOnlyFromAutocomplete&&this.filteredAutocompleteItems.length>0?this.selectedItem=0:this.selectedItem=null},selectItem:function(t,e){t.preventDefault(),this.selectedItem=this.getSelectedIndex(e)},isSelected:function(t){return this.selectedItem===t},isMarked:function(t){return this.deletionMark===t},invokeDelete:function(){var t=this;if(this.deleteOnBackspace&&!(this.newTag.length>0)){var e=this.tagsCopy.length-1;null===this.deletionMark?(this.deletionMarkTime=setTimeout(function(){return t.deletionMark=null},1e3),this.deletionMark=e):this.performDeleteTag(e)}},addTagsFromPaste:function(){var t=this;this.addFromPaste&&setTimeout(function(){return t.performAddTags(t.newTag)},10)},performEditTag:function(t){var e=this;this.allowEditTags&&(this._events["before-editing-tag"]||this.editTag(t),this.$emit("before-editing-tag",{index:t,tag:this.tagsCopy[t],editTag:function(){return e.editTag(t)}}))},editTag:function(t){this.allowEditTags&&(this.toggleEditMode(t),this.focus(t))},toggleEditMode:function(t){this.allowEditTags&&!this.disabled&&this.$set(this.tagsEditStatus,t,!this.tagsEditStatus[t])},createChangedTag:function(t,e){var n=this.tagsCopy[t];n.text=e?e.target.value:this.tagsCopy[t].text,this.$set(this.tagsCopy,t,s(n,this.tagsCopy,this.validation,this.isDuplicate))},focus:function(t){var e=this;this.$nextTick(function(){var n=e.$refs.tagCenter[t].querySelector("input.ti-tag-input");n&&n.focus()})},quote:function(t){return t.replace(/([()[{*+.$^\\|?])/g,"\\$1")},cancelEdit:function(t){this.tags[t]&&(this.tagsCopy[t]=u(s(this.tags[t],this.tags,this.validation,this.isDuplicate)),this.$set(this.tagsEditStatus,t,!1))},hasForbiddingAddRule:function(t){var e=this;return t.some(function(t){var n=e.validation.find(function(e){return t===e.classes});return!!n&&n.disableAdd})},createTagTexts:function(t){var e=this,n=new RegExp(this.separators.map(function(t){return e.quote(t)}).join("|"));return t.split(n).map(function(t){return{text:t}})},performDeleteTag:function(t){var e=this;this._events["before-deleting-tag"]||this.deleteTag(t),this.$emit("before-deleting-tag",{index:t,tag:this.tagsCopy[t],deleteTag:function(){return e.deleteTag(t)}})},deleteTag:function(t){this.disabled||(this.deletionMark=null,clearTimeout(this.deletionMarkTime),this.tagsCopy.splice(t,1),this._events["update:tags"]&&this.$emit("update:tags",this.tagsCopy),this.$emit("tags-changed",this.tagsCopy))},noTriggerKey:function(t,e){var n=-1!==this[e].indexOf(t.keyCode)||-1!==this[e].indexOf(t.key);return n&&t.preventDefault(),!n},performAddTags:function(t,e,n){var r=this;if(!(this.disabled||e&&this.noTriggerKey(e,"addOnKey"))){var i=[];"object"===m(t)&&(i=[t]),"string"==typeof t&&(i=this.createTagTexts(t)),(i=i.filter(function(t){return t.text.trim().length>0})).forEach(function(t){t=s(t,r.tags,r.validation,r.isDuplicate),r._events["before-adding-tag"]||r.addTag(t,n),r.$emit("before-adding-tag",{tag:t,addTag:function(){return r.addTag(t,n)}})})}},duplicateFilter:function(t){return this.isDuplicate?!this.isDuplicate(this.tagsCopy,t):!this.tagsCopy.find(function(e){return e.text===t.text})},addTag:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"new-tag-input",r=this.filteredAutocompleteItems.map(function(t){return t.text});this.addOnlyFromAutocomplete&&-1===r.indexOf(t.text)||this.$nextTick(function(){return e.maxTags&&e.maxTags<=e.tagsCopy.length?e.$emit("max-tags-reached",t):e.avoidAddingDuplicates&&!e.duplicateFilter(t)?e.$emit("adding-duplicate",t):void(e.hasForbiddingAddRule(t.tiClasses)||(e.$emit("input",""),e.tagsCopy.push(t),e._events["update:tags"]&&e.$emit("update:tags",e.tagsCopy),"autocomplete"===n&&e.$refs.newTagInput.focus(),e.$emit("tags-changed",e.tagsCopy)))})},performSaveTag:function(t,e){var n=this,r=this.tagsCopy[t];this.disabled||e&&this.noTriggerKey(e,"addOnKey")||0!==r.text.trim().length&&(this._events["before-saving-tag"]||this.saveTag(t,r),this.$emit("before-saving-tag",{index:t,tag:r,saveTag:function(){return n.saveTag(t,r)}}))},saveTag:function(t,e){if(this.avoidAddingDuplicates){var n=u(this.tagsCopy),r=n.splice(t,1)[0];if(this.isDuplicate?this.isDuplicate(n,r):-1!==n.map(function(t){return t.text}).indexOf(r.text))return this.$emit("saving-duplicate",e)}this.hasForbiddingAddRule(e.tiClasses)||(this.$set(this.tagsCopy,t,e),this.toggleEditMode(t),this._events["update:tags"]&&this.$emit("update:tags",this.tagsCopy),this.$emit("tags-changed",this.tagsCopy))},tagsEqual:function(){var t=this;return!this.tagsCopy.some(function(e,n){return!o()(e,t.tags[n])})},updateNewTag:function(t){var e=t.target.value;this.newTag=e,this.$emit("input",e)},initTags:function(){this.tagsCopy=c(this.tags,this.validation,this.isDuplicate),this.tagsEditStatus=u(this.tags).map(function(){return!1}),this._events["update:tags"]&&!this.tagsEqual()&&this.$emit("update:tags",this.tagsCopy)},blurred:function(t){this.$el.contains(t.target)||this.$el.contains(document.activeElement)||(this.addOnBlur&&this.focused&&this.performAddTags(this.newTag),this.focused=!1)}},watch:{value:function(t){this.addOnlyFromAutocomplete||(this.selectedItem=null),this.newTag=t},tags:{handler:function(){this.initTags()},deep:!0},autocompleteOpen:"selectDefaultItem"},created:function(){this.newTag=this.value,this.initTags()},mounted:function(){this.selectDefaultItem(),document.addEventListener("click",this.blurred)},destroyed:function(){document.removeEventListener("click",this.blurred)}},_=(n(9),A(y,r,[],!1,null,"61d92e31",null));_.options.__file="vue-tags-input/vue-tags-input.vue";var b=_.exports;n.d(e,"VueTagsInput",function(){return b}),n.d(e,"createClasses",function(){return a}),n.d(e,"createTag",function(){return s}),n.d(e,"createTags",function(){return c}),n.d(e,"TagInput",function(){return d}),b.install=function(t){return t.component(b.name,b)},"undefined"!=typeof window&&window.Vue&&window.Vue.use(b),e.default=b}])},t.exports=r()},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("default-field",{attrs:{field:t.field,errors:t.errors}},[n("template",{slot:"field"},[n("vue-tags-input",{attrs:{tags:t.attachedResources,"autocomplete-min-length":0,"add-only-from-autocomplete":!0,"add-from-paste":!1,"add-on-blur":!1,"allow-edit-tags":!0,placeholder:t.placeholder,"is-duplicate":t.isDuplicate,"autocomplete-items":t.filteredResources,"avoid-adding-duplicates":!t.field.duplicate},on:{input:t.performSearch,"before-adding-tag":t.addingTag,"before-editing-tag":t.editingTag,"tags-changed":function(e){return t.attachedResources=e}},scopedSlots:t._u([{key:"tag-center",fn:function(e){return n("div",{},[n("span",{on:{click:function(n){return t.performEditTag(e)}}},[t._v("\n "+t._s(e.tag.text)+"\n\n "),t.field.pivots?n("svg",{staticStyle:{cursor:"pointer"},attrs:{xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",viewBox:"0 0 347 347",width:"15px"}},[n("polygon",{attrs:{fill:"#fff",points:"284.212,0 231.967,51.722 295.706,115.461 347.429,63.216"}}),t._v(" "),n("polygon",{attrs:{fill:"#fff",points:"0,347.429 85.682,319.216 28.212,261.747"}}),t._v(" "),n("rect",{attrs:{fill:"#fff",x:"115.322",y:"56.259",width:"90.14",height:"261.554",transform:"matrix(-0.7071 -0.7071 0.7071 -0.7071 141.551 432.7058)"}})]):t._e()])])}}]),model:{value:t.tag,callback:function(e){t.tag=e},expression:"tag"}}),t._v(" "),t.processingResource?n("modal",{attrs:{role:"dialog"},on:{"modal-close":t.cancelProcessing}},[n("form",{staticClass:"bg-white rounded-lg shadow-lg overflow-hidden",class:"w-action-fields",attrs:{autocomplete:"off",name:t.field.attribute,id:t.field.attribute},on:{submit:function(e){return e.preventDefault(),e.stopPropagation(),t.attachTheResource(e)}}},[n("form-heading-field",{staticClass:"mb-6",attrs:{field:{asHtml:!0,value:t.processingResource.attached?t.__("Update :resource",{resource:t.processingResource.text}):t.__("Attach :resource",{resource:t.processingResource.text})}}}),t._v(" "),n("p",{staticClass:"text-80 px-8 my-1"},[n("loading-view",{attrs:{loading:t.loading}},[n("card",t._l(t.fields,function(e){return n("div",[n("form-"+e.component,{tag:"component",attrs:{"resource-name":t.resourceName,field:e,errors:t.validationErrors,"via-resource":t.viaResource,"via-resource-id":t.viaResourceId,"via-relationship":t.viaRelationship}})],1)}),0),t._v(" "),n("div",{staticClass:"px-6 py-3 flex"},[n("div",{staticClass:"flex items-center ml-auto"},[n("button",{staticClass:"btn btn-link dim cursor-pointer text-80 ml-auto mr-6",attrs:{dusk:"cancel-attach-button",type:"button"},on:{click:function(e){return e.preventDefault(),t.cancelProcessing(e)}}},[t._v("\n "+t._s(t.__("Cancel Attaching"))+"\n ")]),t._v(" "),n("progress-button",{ref:"attachButton",staticClass:"btn btn-default",class:"btn-primary",attrs:{dusk:"confirm-attach-button",type:"submit",disabled:t.processing,processing:t.processing,form:t.field.attribute}},[t._v("\n "+t._s(t.__("Attach Resource"))+"\n ")])],1)])],1)],1)],1)]):t._e()],1)],2)},staticRenderFns:[]}},function(t,e){}]);
const Post = require('../models/postModel.js') const formidable = require('formidable') const fs = require ('fs') const _ = require("lodash") exports.postById = (req,res,next,id)=>{ Post.findById(id) .populate("postedBy", "_id name") .exec((err,post) =>{ if(err || !post){ return res.status(400).json({ error:err }) } req.post =post next() }) } exports.getPost = (req,res) =>{ const posts = Post.find() .populate("postedBy","_id name") .select("_id title body") // to select only things we want to see .then ((posts)=> { res.status(200).json({posts}) }) .catch(err => console.log(colors.red(err))) } // creating a new post exports.createPost = (req,res,next) =>{ let form = new formidable.IncomingForm() form.keepExtensions = true form.parse(req,(err,fields,files)=>{ if (err){ return res.status(400).json({ error:"Image cannot be uploaded" }) } let post = new Post(fields) req.profile.hashed_password = undefined; req.profile.salt = undefined; post.postedBy = req.profile if(files.photo){ post.photo.data = fs.readFileSync(file.photo.path) post.photo.contentType = files.photo.type } post.save((err,result) =>{ if(err){ res.status(400).json({error:err}) } res.json(result) }) }) } exports.postByUser = (req, res)=>{ Post.find({postedBy: req.profile._id}) .populate("postedBy","_id name") // since it is in another model so we use populate .sort("_created")// new post will appear first .exec((err,posts)=>{ if(err){ return res.status(400).json({ error:err }) } res.json({posts}) }) } exports.isPoster = (req,res,next) =>{ var isPoster = req.post && req.auth && req.post.postedBy._id == req.auth._id if(!isPoster){ return res.status(403).json({ error:"user is Not authorized " }) } next() } exports.updatePost = (req,res,next) =>{ let post = req.post post = _.extend(post,req.body) post.updated = Date.now() post.save(err =>{ if (err){ return res.status(400).json({ error:err }) } res.json(post) }) } exports.deletePost = (req,res)=>{ let post = req.post post.remove((err,post)=>{ if(err){ return res.status(400).json({ error:err }) } res.json({ message:"Post Deleted successfully" }) }) }
# This script allows you to define the turntable kinematics accoding to your KUKA KRC robot controller # Modify the values according to the Machine data definition # Define the name of your turntable in RoboDK (name in the RoboDK tree) # Make sure the joint sense is set to [1,1] (do not invert axes) turntable_name = "Positioner" # KUKA values to model a 2 axis turntable # ROOT_POINT: The ROOT Point is the position of the turntable with respect to the robot # This value is not required to model the turntable, # however, it represents the location of the turntable base with respect to the robot base ROOT_POSE = [20.903679, 1929.991330, 209.270615, 0.905965, -0.140198, -179.285088] #ROOT_POSE = None # Set to None to skip placing the turntable # Enter the position of axis 1 with respect to the turntable ROOT point # Variable: $ET1_TA1KR ROOT_2_E1 = [0, 0, 0, 0, 90, 0] # Enter the position of axis 2 with respect to axis 1 # KUKA SRC Variable: $ET1_TA2A1 E1_2_E2 = [75.581, 2.737, -5.883, 90.42, 89.373, 89.674] # Enter the position of the turntable flange with respect to axis 2 # KUKA SRC Variable: $ET1_TFLA3 E2_2_Flange = [0, 0, 0, -90, 0.117, -179.898] # Enter the position of the measurement point and flange # Note: this value is not used # KUKA SRC Variable: $ET1_TPINFL Measurement_Point = [-850.078, 0, 0, 0, 0, 0] #------------------------------------------------------------------------- #------------------------------------------------------------------------- #------------------------------------------------------------------------- #------------------------------------------------------------------------- #------------------------------------------------------------------------- from robodk.robolink import * from robodk.robomath import * import math # Calculate poses pose_2_e1 = KUKA_2_Pose(ROOT_2_E1) pose_2_e2 = KUKA_2_Pose(E1_2_E2) pose_2_flange = KUKA_2_Pose(E2_2_Flange) flange_2_point = KUKA_2_Pose(Measurement_Point) #flange_Z = Measurement_Point[2] #flange_angle_rad = math.atan2(Measurement_Point[1],Measurement_Point[0]) #flange_angle_deg = flange_angle_rad*180/pi #flange_pose = transl(0,0,flange_Z) * rotz(flange_angle_rad) #flange_pose_str = "transl(0,0,%.6f)*rotz(%.6f)" % (flange_Z, flange_angle_deg) # Function to simulate the forward kinematics of a 2 axis mechanism given linking poses # (simulation according to KUKA controller) def FK_Turntable(ax12): pose_fk = pose_2_e1 * rotz(ax12[0] * pi / 180) * pose_2_e2 * rotz(ax12[1] * pi / 180) * pose_2_flange return pose_fk # Start the RoboDK API RDK = Robolink() # Retrieve the turntable object in RoboDK turntable = RDK.Item(turntable_name, ITEM_TYPE_ROBOT) if not turntable.Valid(): print("Turntable does not exist: " + turntable_name) quit() # Simulate a list of points (moving axis 1 and 2 independently) joints = [] # List of joints to test points_kuka = [] # points according to KUKA kinematics points_robodk = [] # points according to RoboDK kinematics range_axis = [-90, -60, -30, 0, 30, 60, 90] for ax1 in range_axis: joints.append([ax1, 0]) for ax2 in range_axis: joints.append([0, ax2]) print("List of points according to KUKA Kinematics (mm):") for j in joints: pose_fk_kuka = FK_Turntable(j) * flange_2_point xyz_kuka = pose_fk_kuka.Pos() x, y, z = xyz_kuka print("%.3f, %.3f, %.3f" % (x, y, z)) points_kuka.append(xyz_kuka) print("\n\nUpdating turntable kinematics...") # This operation can be done manually using the UI: # Utilities-Calibrate Reference (if a turntable is provided as a robot and we calibrate using points) pose_flange, stats = RDK.CalibrateReference(points_kuka, CALIBRATE_TURNTABLE_2X, False, turntable) #---------------------------------------------------------------------------- # Important: RoboDK does not add a flange rotation, so we need to calculate it turntable.setParam("KinematicsPoseTool", "transl(0,0,0)") # this is redundant (the pose should already be eye(4)) joints_ref = [0, 0] pose_fk_robodk = turntable.SolveFK(joints_ref) pose_fk_kuka = FK_Turntable(joints_ref) flange_pose_rdk = invH(pose_fk_robodk) * pose_fk_kuka #flange_pose = transl(0,0,flange_Z) * rotz(flange_angle_rad) #flange_pose_str = "transl(0,0,%.6f)*rotz(%.6f)" % (flange_Z, flange_angle_deg) x, y, z, w, p, r = Pose_2_TxyzRxyz(flange_pose_rdk) flange_pose_str = "transl(%.6f,%.6f,%.6f)*rotx(%.6f)*roty(%.6f)*rotz(%.6f)" % (x, y, z, w * 180 / pi, p * 180 / pi, r * 180 / pi) turntable.setParam("KinematicsPoseTool", flange_pose_str) #print(pose_flange) #print("\nStatistics:") #print(stats) print("\nList of poinst according to RoboDK kinematics (mm):") for i in range(len(joints)): jnts = joints[i] pose_fk = turntable.SolveFK(jnts) * flange_2_point xyz_robodk = pose_fk.Pos() points_robodk.append(xyz_robodk) x, y, z = xyz_robodk print("%.3f, %.3f, %.3f" % (x, y, z)) print("\nErrors (KUKA vs. RoboDK) (mm):") max_error = -1 for i in range(len(joints)): jnts = joints[i] xyz_kuka = points_kuka[i] xyz_robodk = points_robodk[i] # Calculate error vector error = subs3(xyz_kuka, xyz_robodk) ex, ey, ez = error e_mm = norm(error) if e_mm > max_error: max_error = e_mm print("%.3f -> [%.3f, %.3f, %.3f]" % (e_mm, ex, ey, ez)) # Update the ROOT coordinate system, if provided if ROOT_POSE is not None: print("\nTrying to update root pose") root_frame = turntable.Parent() if root_frame.type != ITEM_TYPE_FRAME: RDK.ShowMessage("Place your positionner on a reference frame") quit() # retrieve the robot base: robot_base = root_frame.Parent() if robot_base.type != ITEM_TYPE_FRAME: RDK.ShowMessage("Place the reference of your positionner directly attached to the robot base") quit() robot_base_childs = robot_base.Childs() if len(robot_base_childs) > 0 and robot_base_childs[0].type == ITEM_TYPE_ROBOT: pose_root = KUKA_2_Pose(ROOT_POSE) root_frame.setPose(pose_root) print("Root pose updated to: " + str(ROOT_POSE)) else: RDK.ShowMessage("Place the reference of your positionner directly attached to the robot base (the robot must be attached to the robot base)") quit() else: print("\nMake sure to manually update the root pose (turntable base coordinate system)") # Done! if max_error < 1e-3: print("\nCompleted successfully!\n\n") else: print("\nCompleted with errors (%.3f mm)\n\n" % max_error) quit() #----------------------------------------------------- #----------------------------------------------------- #----------------------------------------------------- #----------------------------------------------------- #----------------------------------------------------- #----------------------------------------------------- # Example to create a 2 axis turntable using the API robot_name = 'Turntable 2x' # Joint values joints_build = [0, 0] joints_home = [0, 0] lower_limits = [-120, -360] upper_limits = [120, 360] parameters = [] # Define the joint sense (set to +1 or -1 for each axis (+1 is used as a reference for the ABB IRB120 robot) joints_senses = [+1, +1] base_pose = eye(4) tool_pose = eye(4) # Retrieve all your items from RoboDK (they should be previously loaded manually or using the API's command RDK.AddFile()) DOFs = len(joints_build) list_objects = [] for i in range(DOFs + 1): itm = None if i == 0: itm = RDK.Item(robot_name + ' Base', ITEM_TYPE_OBJECT) else: itm = RDK.Item(robot_name + ' ' + str(i), ITEM_TYPE_OBJECT) list_objects.append(itm) # Create the robot/mechanism turntable = RDK.BuildMechanism(MAKE_ROBOT_2R, list_objects, parameters, joints_build, joints_home, joints_senses, lower_limits, upper_limits, base_pose, tool_pose, robot_name) if not turntable.Valid(): print("Failed to create the robot. Check input values.") quit() else: print("Robot/mechanism created: " + turntable.Name())
let userEmail = 'abs123l' let password ='1234' let userChecker = function(myString){ if ((myString.includes(123)) && (myString.length > 6)) { return true } else { return false } } console.log(userChecker(userEmail)); let passChecker = function(pass){ if ((pass.includes(1234)) && (pass.length > 8)) { return true } else { return false } }
/** @file */ /* * Copyright (c) 2019, Cisco Systems, Inc. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://github.com/cisco/libacvp/LICENSE */ #include "ut_common.h" #include "acvp_lcl.h" ACVP_CTX *ctx; static char filename[] = "filename"; static char value[] = "same"; char *test_server = "demo.acvts.nist.gov"; char *api_context = "acvp/"; char *path_segment = "acvp/v1/"; char *uri = "login"; int port = 443; ACVP_RESULT rv; static void setup(void) { setup_empty_ctx(&ctx); } static void setup_full_ctx(void) { setup_empty_ctx(&ctx); rv = acvp_cap_sym_cipher_enable(ctx, ACVP_AES_GCM, &dummy_handler_success); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_set_prereq(ctx, ACVP_AES_GCM, ACVP_PREREQ_AES, value); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_set_prereq(ctx, ACVP_AES_GCM, ACVP_PREREQ_DRBG, value); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_sym_cipher_set_parm(ctx, ACVP_AES_GCM, ACVP_SYM_CIPH_PARM_DIR, ACVP_SYM_CIPH_DIR_BOTH); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_sym_cipher_set_parm(ctx, ACVP_AES_GCM, ACVP_SYM_CIPH_PARM_KO, ACVP_SYM_CIPH_KO_NA); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_sym_cipher_set_parm(ctx, ACVP_AES_GCM, ACVP_SYM_CIPH_PARM_IVGEN_SRC, ACVP_SYM_CIPH_IVGEN_SRC_INT); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_sym_cipher_set_parm(ctx, ACVP_AES_GCM, ACVP_SYM_CIPH_PARM_IVGEN_MODE, ACVP_SYM_CIPH_IVGEN_MODE_821); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_sym_cipher_set_parm(ctx, ACVP_AES_GCM, ACVP_SYM_CIPH_KEYLEN, 128); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_sym_cipher_set_parm(ctx, ACVP_AES_GCM, ACVP_SYM_CIPH_TAGLEN, 96); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_sym_cipher_set_parm(ctx, ACVP_AES_GCM, ACVP_SYM_CIPH_IVLEN, 96); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_sym_cipher_set_parm(ctx, ACVP_AES_GCM, ACVP_SYM_CIPH_PTLEN, 0); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_sym_cipher_set_parm(ctx, ACVP_AES_GCM, ACVP_SYM_CIPH_AADLEN, 0); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_hash_enable(ctx, ACVP_HASH_SHA1, &dummy_handler_success); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_cmac_enable(ctx, ACVP_CMAC_AES, &dummy_handler_success); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_cmac_set_parm(ctx, ACVP_CMAC_AES, ACVP_CMAC_MACLEN, 128); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_cmac_set_parm(ctx, ACVP_CMAC_AES, ACVP_CMAC_KEYLEN, 128); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_cmac_set_parm(ctx, ACVP_CMAC_AES, ACVP_CMAC_DIRECTION_GEN, 1); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_hmac_enable(ctx, ACVP_HMAC_SHA1, &dummy_handler_success); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kdf135_tls_enable(ctx, &dummy_handler_success); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_set_prereq(ctx, ACVP_KDF135_TLS, ACVP_PREREQ_SHA, value); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_set_prereq(ctx, ACVP_KDF135_TLS, ACVP_PREREQ_HMAC, value); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kdf135_tls_set_parm(ctx, ACVP_KDF135_TLS, ACVP_KDF135_TLS12, ACVP_SHA256 | ACVP_SHA384 | ACVP_SHA512); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kas_ecc_enable(ctx, ACVP_KAS_ECC_CDH, &dummy_handler_success); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kas_ecc_set_prereq(ctx, ACVP_KAS_ECC_CDH, ACVP_KAS_ECC_MODE_CDH, ACVP_PREREQ_ECDSA, value); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kas_ecc_set_parm(ctx, ACVP_KAS_ECC_CDH, ACVP_KAS_ECC_MODE_CDH, ACVP_KAS_ECC_FUNCTION, ACVP_KAS_ECC_FUNC_PARTIAL); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kas_ecc_set_parm(ctx, ACVP_KAS_ECC_CDH, ACVP_KAS_ECC_MODE_CDH, ACVP_KAS_ECC_CURVE, ACVP_EC_CURVE_P224); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kas_ffc_enable(ctx, ACVP_KAS_FFC_COMP, &dummy_handler_success); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kas_ffc_set_prereq(ctx, ACVP_KAS_FFC_COMP, ACVP_KAS_FFC_MODE_COMPONENT, ACVP_PREREQ_HMAC, value); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kas_ffc_set_parm(ctx, ACVP_KAS_FFC_COMP, ACVP_KAS_FFC_MODE_COMPONENT, ACVP_KAS_FFC_FUNCTION, ACVP_KAS_FFC_FUNC_DPGEN); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kas_ffc_set_parm(ctx, ACVP_KAS_FFC_COMP, ACVP_KAS_FFC_MODE_COMPONENT, ACVP_KAS_FFC_FUNCTION, ACVP_KAS_FFC_FUNC_DPVAL); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kas_ffc_set_scheme(ctx, ACVP_KAS_FFC_COMP, ACVP_KAS_FFC_MODE_COMPONENT, ACVP_KAS_FFC_DH_EPHEMERAL, ACVP_KAS_FFC_ROLE, ACVP_KAS_FFC_ROLE_INITIATOR); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kas_ffc_set_scheme(ctx, ACVP_KAS_FFC_COMP, ACVP_KAS_FFC_MODE_COMPONENT, ACVP_KAS_FFC_DH_EPHEMERAL, ACVP_KAS_FFC_KDF, ACVP_KAS_FFC_NOKDFNOKC); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_kas_ffc_set_scheme(ctx, ACVP_KAS_FFC_COMP, ACVP_KAS_FFC_MODE_COMPONENT, ACVP_KAS_FFC_DH_EPHEMERAL, ACVP_KAS_FFC_FB, ACVP_SHA224); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_dsa_enable(ctx, ACVP_DSA_PQGGEN, &dummy_handler_success); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_set_prereq(ctx, ACVP_DSA_PQGGEN, ACVP_PREREQ_SHA, value); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_dsa_set_parm(ctx, ACVP_DSA_PQGGEN, ACVP_DSA_MODE_PQGGEN, ACVP_DSA_GENPQ, ACVP_DSA_PROBABLE); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_dsa_set_parm(ctx, ACVP_DSA_PQGGEN, ACVP_DSA_MODE_PQGGEN, ACVP_DSA_LN2048_224, ACVP_SHA224); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_dsa_set_parm(ctx, ACVP_DSA_PQGGEN, ACVP_DSA_MODE_PQGGEN, ACVP_DSA_GENG, ACVP_DSA_CANONICAL); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_rsa_sig_enable(ctx, ACVP_RSA_SIGGEN, &dummy_handler_success); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_rsa_siggen_set_type(ctx, ACVP_RSA_SIG_TYPE_X931); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_rsa_siggen_set_mod_parm(ctx, ACVP_RSA_SIG_TYPE_X931, 2048, ACVP_SHA256, 0); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_ecdsa_enable(ctx, ACVP_ECDSA_KEYGEN, &dummy_handler_success); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_set_prereq(ctx, ACVP_ECDSA_KEYGEN, ACVP_PREREQ_SHA, value); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_set_prereq(ctx, ACVP_ECDSA_KEYGEN, ACVP_PREREQ_DRBG, value); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_ecdsa_set_parm(ctx, ACVP_ECDSA_KEYGEN, ACVP_ECDSA_CURVE, ACVP_EC_CURVE_P224); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_ecdsa_set_parm(ctx, ACVP_ECDSA_KEYGEN, ACVP_ECDSA_SECRET_GEN, ACVP_ECDSA_SECRET_GEN_TEST_CAND); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_drbg_enable(ctx, ACVP_HASHDRBG, &dummy_handler_success); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_drbg_set_parm(ctx, ACVP_HASHDRBG, ACVP_DRBG_SHA_1, ACVP_DRBG_DER_FUNC_ENABLED, 0); cr_assert(rv == ACVP_SUCCESS); rv = acvp_cap_set_prereq(ctx, ACVP_HASHDRBG, ACVP_PREREQ_SHA, value); cr_assert(rv == ACVP_SUCCESS); } static void teardown(void) { if (ctx) teardown_ctx(&ctx); } static ACVP_RESULT dummy_totp_success(char **token, int token_max) { strncpy(*token, "test", 4); return ACVP_SUCCESS; } static ACVP_RESULT dummy_totp_overflow(char **token, int token_max) { memset(*token, 'a', 129); return ACVP_SUCCESS; } /* * This test sets up a new test session with good params */ Test(CREATE_CTX, good) { rv = acvp_create_test_session(&ctx, &progress, ACVP_LOG_LVL_STATUS); cr_assert(rv == ACVP_SUCCESS); teardown_ctx(&ctx); ctx = NULL; rv = acvp_create_test_session(&ctx, &progress, ACVP_LOG_LVL_ERR); cr_assert(rv == ACVP_SUCCESS); teardown_ctx(&ctx); ctx = NULL; rv = acvp_create_test_session(&ctx, &progress, ACVP_LOG_LVL_WARN); cr_assert(rv == ACVP_SUCCESS); teardown_ctx(&ctx); ctx = NULL; rv = acvp_create_test_session(&ctx, &progress, ACVP_LOG_LVL_INFO); cr_assert(rv == ACVP_SUCCESS); teardown_ctx(&ctx); ctx = NULL; rv = acvp_create_test_session(&ctx, &progress, ACVP_LOG_LVL_VERBOSE); cr_assert(rv == ACVP_SUCCESS); teardown_ctx(&ctx); ctx = NULL; rv = acvp_create_test_session(&ctx, &progress, 0); cr_assert(rv == ACVP_SUCCESS); teardown_ctx(&ctx); ctx = NULL; rv = acvp_create_test_session(&ctx, NULL, ACVP_LOG_LVL_VERBOSE); cr_assert(rv == ACVP_SUCCESS); teardown_ctx(&ctx); ctx = NULL; } /* * This test sets up a new test session with non-null ctx */ Test(CREATE_CTX, dup_ctx) { ACVP_CTX *ctx = NULL; rv = acvp_create_test_session(&ctx, &progress, ACVP_LOG_LVL_VERBOSE); cr_assert(rv == ACVP_SUCCESS); rv = acvp_create_test_session(&ctx, &progress, ACVP_LOG_LVL_VERBOSE); cr_assert(rv == ACVP_DUPLICATE_CTX); teardown_ctx(&ctx); } /* * This test sets up a new test session with null ctx */ Test(CREATE_CTX, null_ctx) { rv = acvp_create_test_session(NULL, &progress, ACVP_LOG_LVL_STATUS); cr_assert(rv == ACVP_INVALID_ARG); cr_assert(ctx == NULL); } /* * This test sets 2fa cb */ Test(SET_SESSION_PARAMS, good_2fa, .init = setup, .fini = teardown) { rv = acvp_set_2fa_callback(ctx, &dummy_totp_success); cr_assert(rv == ACVP_SUCCESS); } /* * This test sets 2fa cb with null params */ Test(SET_SESSION_PARAMS, null_params_2fa, .init = setup, .fini = teardown) { rv = acvp_set_2fa_callback(ctx, NULL); cr_assert(rv == ACVP_MISSING_ARG); rv = acvp_set_2fa_callback(NULL, &dummy_totp_success); cr_assert(rv == ACVP_NO_CTX); } /* * This test sets json filename */ Test(SET_SESSION_PARAMS, set_input_json_good, .init = setup, .fini = teardown) { rv = acvp_set_json_filename(ctx, filename); cr_assert(rv == ACVP_SUCCESS); } /* * This test sets json filename - null params */ Test(SET_SESSION_PARAMS, set_input_json_null_params, .init = setup, .fini = teardown) { rv = acvp_set_json_filename(NULL, filename); cr_assert(rv == ACVP_NO_CTX); rv = acvp_set_json_filename(ctx, NULL); cr_assert(rv == ACVP_MISSING_ARG); } /* * This test sets server info */ Test(SET_SESSION_PARAMS, set_server_good, .init = setup, .fini = teardown) { rv = acvp_set_server(ctx, "for test", 1111); cr_assert(rv == ACVP_SUCCESS); } /* * This test sets server info with NULL params */ Test(SET_SESSION_PARAMS, set_server_null_params, .init = setup, .fini = teardown) { rv = acvp_set_server(NULL, "for test", 1111); cr_assert(rv == ACVP_NO_CTX); rv = acvp_set_server(ctx, NULL, 1111); cr_assert(rv == ACVP_INVALID_ARG); rv = acvp_set_server(ctx, "for test", -1); cr_assert(rv == ACVP_INVALID_ARG); } /* * This test sets server info with long params */ Test(SET_SESSION_PARAMS, set_server_overflow, .init = setup, .fini = teardown) { char long_str[1000]; int i; for (i = 0; i < 999; i++) { long_str[i] = 'a'; } long_str[999] = '\0'; rv = acvp_set_server(ctx, long_str, -1); cr_assert(rv == ACVP_INVALID_ARG); } /* * This test sets path_segment info */ Test(SET_SESSION_PARAMS, set_path_segment_good, .init = setup, .fini = teardown) { rv = acvp_set_path_segment(ctx, "for test"); cr_assert(rv == ACVP_SUCCESS); } /* * This test sets path_segment info with NULL params */ Test(SET_SESSION_PARAMS, set_path_segment_null_params, .init = setup, .fini = teardown) { rv = acvp_set_path_segment(NULL, "for test"); cr_assert(rv == ACVP_NO_CTX); rv = acvp_set_path_segment(ctx, NULL); cr_assert(rv == ACVP_INVALID_ARG); } /* * This test sets path_segment info with long params */ Test(SET_SESSION_PARAMS, set_path_segment_overflow, .init = setup, .fini = teardown) { char long_str[1000]; int i; for (i = 0; i < 999; i++) { long_str[i] = 'a'; } long_str[999] = '\0'; rv = acvp_set_path_segment(ctx, long_str); cr_assert(rv == ACVP_INVALID_ARG); } /* * This test sets cacerts info */ Test(SET_SESSION_PARAMS, set_cacerts_good, .init = setup, .fini = teardown) { rv = acvp_set_cacerts(ctx, "for test"); cr_assert(rv == ACVP_SUCCESS); } /* * This test sets cacerts info with NULL params */ Test(SET_SESSION_PARAMS, set_cacerts_null_params, .init = setup, .fini = teardown) { rv = acvp_set_cacerts(NULL, "for test"); cr_assert(rv == ACVP_NO_CTX); rv = acvp_set_cacerts(ctx, NULL); cr_assert(rv == ACVP_MISSING_ARG); } /* * This test sets cacerts info with long params */ Test(SET_SESSION_PARAMS, set_cacerts_overflow, .init = setup, .fini = teardown) { char long_str[1000]; int i; for (i = 0; i < 999; i++) { long_str[i] = 'a'; } long_str[999] = '\0'; rv = acvp_set_cacerts(ctx, long_str); cr_assert(rv == ACVP_INVALID_ARG); } /* * This test sets cert_key info */ Test(SET_SESSION_PARAMS, set_cert_key_good, .init = setup, .fini = teardown) { rv = acvp_set_certkey(ctx, "for test", "for test"); cr_assert(rv == ACVP_SUCCESS); } /* * This test sets cert_key info with NULL params */ Test(SET_SESSION_PARAMS, set_cert_key_null_params, .init = setup, .fini = teardown) { rv = acvp_set_certkey(NULL, "for test", "for test"); cr_assert(rv == ACVP_NO_CTX); rv = acvp_set_certkey(ctx, NULL, "for test"); cr_assert(rv == ACVP_MISSING_ARG); rv = acvp_set_certkey(ctx, "for test", NULL); cr_assert(rv == ACVP_MISSING_ARG); } /* * This test sets cert_key info with long params */ Test(SET_SESSION_PARAMS, set_cert_key_overflow, .init = setup, .fini = teardown) { char long_str[1000]; int i; for (i = 0; i < 999; i++) { long_str[i] = 'a'; } long_str[999] = '\0'; rv = acvp_set_certkey(ctx, long_str, "for test"); cr_assert(rv == ACVP_INVALID_ARG); rv = acvp_set_certkey(ctx, "for test", long_str); cr_assert(rv == ACVP_INVALID_ARG); } /* * This test marks as sample */ Test(SET_SESSION_PARAMS, mark_as_sample_good, .init = setup, .fini = teardown) { rv = acvp_mark_as_sample(ctx); cr_assert(rv == ACVP_SUCCESS); } /* * This test marks as sample with null ctx */ Test(SET_SESSION_PARAMS, mark_as_sample_null_ctx, .init = setup, .fini = teardown) { rv = acvp_mark_as_sample(NULL); cr_assert(rv == ACVP_NO_CTX); } /* * This test frees ctx */ Test(FREE_TEST_SESSION, good, .init = setup) { rv = acvp_free_test_session(ctx); cr_assert(rv == ACVP_SUCCESS); } /* * This test frees ctx - should still succeed */ Test(FREE_TEST_SESSION, null_ctx, .init = setup) { free(ctx); /* it got allocated in setup */ ctx = NULL; rv = acvp_free_test_session(ctx); cr_assert(rv == ACVP_SUCCESS); } /* * This test frees ctx - should still succeed */ Test(FREE_TEST_SESSION, good_full, .init = setup_full_ctx) { rv = acvp_free_test_session(ctx); cr_assert(rv == ACVP_SUCCESS); } /* * Calls run with missing path segment */ Test(RUN, missing_path, .init = setup_full_ctx, .fini = teardown) { rv = acvp_set_server(ctx, test_server, port); cr_assert(rv == ACVP_SUCCESS); rv = acvp_set_api_context(ctx, api_context); cr_assert(rv == ACVP_SUCCESS); rv = acvp_set_server(ctx, test_server, port); cr_assert(rv == ACVP_SUCCESS); rv = acvp_set_2fa_callback(ctx, &totp); cr_assert(rv == ACVP_SUCCESS); rv = acvp_run(ctx, 0); cr_assert(rv == ACVP_MISSING_ARG); } /* * Calls run with good values * transport fail is exptected - we made it through the register * API successfully to try to send the registration. that part * will fail - no actual connection to server here. * This expects ACVP_TRANSPORT_FAIL because refresh sends * but we don't receive HTTP_OK */ Test(RUN, good, .init = setup_full_ctx, .fini = teardown) { rv = acvp_set_server(ctx, test_server, port); cr_assert(rv == ACVP_SUCCESS); rv = acvp_set_api_context(ctx, api_context); cr_assert(rv == ACVP_SUCCESS); rv = acvp_set_path_segment(ctx, path_segment); cr_assert(rv == ACVP_SUCCESS); rv = acvp_set_server(ctx, test_server, port); cr_assert(rv == ACVP_SUCCESS); rv = acvp_set_2fa_callback(ctx, &totp); cr_assert(rv == ACVP_SUCCESS); rv = acvp_run(ctx, 0); cr_assert(rv == ACVP_TRANSPORT_FAIL); } /* * This calls run with an overflow totp that will get * triggered in build_login */ Test(RUN, bad_totp_cb, .init = setup_full_ctx, .fini = teardown) { rv = acvp_set_2fa_callback(ctx, &dummy_totp_overflow); cr_assert(rv == ACVP_SUCCESS); rv = acvp_run(ctx, 0); cr_assert(rv == ACVP_INVALID_ARG); } /* * This calls run without adding totp callback - we expect * transport fail because we should make it through the rest * of the register api, but fail because we aren't going to be * able to successfully connect to NIST */ Test(RUN, good_without_totp, .init = setup_full_ctx, .fini = teardown) { rv = acvp_run(ctx, 0); cr_assert(rv == ACVP_MISSING_ARG); } /* * Run with null ctx */ Test(RUN, null_ctx, .fini = teardown) { rv = acvp_run(NULL, 0); cr_assert(rv == ACVP_NO_CTX); } /* * Check test results with empty ctx */ Test(CHECK_RESULTS, no_vs_list, .init = setup, .fini = teardown) { rv = acvp_check_test_results(ctx); cr_assert(rv == ACVP_MISSING_ARG); } /* * Process tests with full ctx - should return ACVP_MISSING_ARG for * now, at least until mock server is set up (because we didn't receive * any vectors to load in) */ Test(PROCESS_TESTS, good, .init = setup_full_ctx, .fini = teardown) { rv = acvp_process_tests(ctx); cr_assert(rv == ACVP_MISSING_ARG); } /* * process tests with null ctx */ Test(PROCESS_TESTS, null_ctx, .fini = teardown) { rv = acvp_process_tests(NULL); cr_assert(rv == ACVP_NO_CTX); } /* * process tests with empty ctx */ Test(PROCESS_TESTS, no_vs_list, .init = setup, .fini = teardown) { rv = acvp_process_tests(ctx); cr_assert(rv == ACVP_MISSING_ARG); } Test(GET_LIBRARY_VERSION, good) { char *version = acvp_version(); cr_assert(version != NULL); cr_assert(strlen(version) > 0); } Test(GET_PROTOCOL_VERSION, good) { char *version = acvp_protocol_version(); cr_assert(version != NULL); cr_assert(strlen(version) > 0); } /* * calls acvp_refresh with good params, didn't add totp callback */ Test(REFRESH, good_without_totp, .init = setup_full_ctx, .fini = teardown) { rv = acvp_set_server(ctx, test_server, port); cr_assert(rv == ACVP_SUCCESS); rv = acvp_set_path_segment(ctx, path_segment); cr_assert(rv == ACVP_SUCCESS); rv = acvp_refresh(ctx); cr_assert(rv == ACVP_TRANSPORT_FAIL); } /* * calls acvp_refresh with null ctx */ Test(REFRESH, null_ctx, .fini = teardown) { rv = acvp_refresh(NULL); cr_assert(rv == ACVP_NO_CTX); } /* * calls acvp_refresh with good params * This expects ACVP_TRANSPORT_FAIL because refresh sends * but we don't receive HTTP_OK */ Test(REFRESH, good_with_totp, .init = setup_full_ctx, .fini = teardown) { rv = acvp_set_server(ctx, test_server, port); cr_assert(rv == ACVP_SUCCESS); rv = acvp_set_api_context(ctx, api_context); cr_assert(rv == ACVP_SUCCESS); rv = acvp_set_path_segment(ctx, path_segment); cr_assert(rv == ACVP_SUCCESS); rv = acvp_set_2fa_callback(ctx, &totp); cr_assert(rv == ACVP_SUCCESS); rv = acvp_refresh(ctx); cr_assert(rv == ACVP_TRANSPORT_FAIL); } /* * Good tests - should still pass even if ctx is null */ Test(FREE_CTX, good, .init = setup_full_ctx) { rv = acvp_free_test_session(ctx); cr_assert(rv == ACVP_SUCCESS); ctx = NULL; rv = acvp_free_test_session(ctx); cr_assert(rv == ACVP_SUCCESS); }
var provider; import configuration from 'torii/configuration'; var originalConfiguration = configuration.providers['mock-oauth1']; import BaseProvider from 'torii/providers/oauth1'; var providerName = 'mock-oauth1'; var Provider = BaseProvider.extend({ name: providerName, baseUrl: 'http://example.com', redirectUri: 'http://foo' }); module('MockOauth1Provider (oauth1 subclass) - Unit', { setup: function(){ configuration.providers['mock-oauth1'] = {}; provider = Provider.create(); }, teardown: function(){ Ember.run(provider, 'destroy'); configuration.providers[providerName] = originalConfiguration; } }); test("Provider requires a requestTokenUri", function(){ configuration.providers[providerName] = {}; throws(function(){ provider.buildRequestTokenUrl(); }, /Expected configuration value providers.mock-oauth1.requestTokenUri to be defined!/); }); test("buildRequestTokenUrl generates a URL with required config", function(){ configuration.providers[providerName] = { requestTokenUri: 'http://expectedUrl.com' }; equal(provider.buildRequestTokenUrl(), 'http://expectedUrl.com', 'generates the correct URL'); });
#2. download train data and test data import urllib.request import pandas as pd #download naver movie review data->ratings_train.txt & retings_test.txt urllib.request.urlretrieve("https://raw.githubusercontent.com/e9t/nsmc/master/ratings_train.txt", filename="ratings_train.txt") urllib.request.urlretrieve("https://raw.githubusercontent.com/e9t/nsmc/master/ratings_test.txt", filename="ratings_test.txt") train_df=pd.read_table('ratings_train.txt') test_df=pd.read_table('ratings_test.txt') print(train_df.head()) print(test_df.head())#id: not needed data, document: movie review, label: good or not print('Amount of training data samples: {}'.format(len(train_df))) print('Amount of test data samples: {}'.format(len(train_df))) print() #3. set field(torchtext.legacy.data) from torchtext.legacy import data from konlpy.tag import Mecab tokenizer=Mecab()#ERROR
from Locations.Lobby import Lobby location = Lobby() print("The girl ran away through the door.") while True: com = location.get_input() location.process_command(com)
var exists = require('101/exists') var toArray = require('toarray') module.exports = copyListeners function copyListeners (src, dst, events) { var events = exists(events) ? toArray(events) : Object.keys(src._events) events.forEach(function (event) { listeners = src.listeners(event) listeners.forEach(function (listener) { dst.on(event, listener) }) }) }
import json import os input_list = ["../../data/origin.json", "../../data/origin2.json"] output_path = "../../data/document/all.json" def format_content(content, id=0): pos = [] for a in range(0, len(content)): if content[a] == "\n\n": pos.append(a) p1 = 1 while pos[p1] - pos[p1 - 1] <= 2: p1 += 1 p2 = len(pos) - 1 while pos[p2] - pos[p2 - 1] <= 2: p2 -= 1 content = content[pos[p1]:pos[p2]] res = [] for x in content: if x.find("\n") == -1: res.append(x.strip()) return "".join(res) if __name__ == "__main__": result = [] for input_path in input_list: data = json.load(open(input_path, "r", encoding="utf8")) print(len(data["term"])) for item in data["term"]: temp = { "content": format_content(item["content"][0]["content"], item["termID"]), "label": [], "id": item["termID"] } for x in item["result"][0]["answer"]: temp["label"].append(x["value"][0]) temp["label"] = list(set(temp["label"])) result.append(temp) json.dump(result, open(output_path, "w", encoding="utf8"), indent=2, ensure_ascii=False, sort_keys=True)
# # Copyright (c) 2022 Airbyte, Inc., all rights reserved. # from typing import Any, MutableMapping from airbyte_cdk.models import SyncMode from airbyte_cdk.sources.streams import Stream def read_incremental(stream_instance: Stream, stream_state: MutableMapping[str, Any]): res = [] if stream_state and "state" in dir(stream_instance): stream_instance.state = stream_state slices = stream_instance.stream_slices(sync_mode=SyncMode.incremental, stream_state=stream_state) for slice in slices: records = stream_instance.read_records(sync_mode=SyncMode.incremental, stream_slice=slice, stream_state=stream_state) for record in records: stream_state = stream_instance.get_updated_state(stream_state, record) res.append(record) return res, stream_state def read_full_refresh(stream_instance: Stream): records = [] slices = stream_instance.stream_slices(sync_mode=SyncMode.full_refresh) for slice in slices: records.extend(list(stream_instance.read_records(stream_slice=slice, sync_mode=SyncMode.full_refresh))) return records
/* CF3 Copyright (c) 2015 ishiura-lab. Released under the MIT license. https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md */ #include<stdio.h> #include<stdint.h> #include<stdlib.h> #include"test1.h" uint8_t x1 = 1U; static int32_t x15 = 59; static volatile int32_t x19 = INT32_MIN; int32_t x29 = -21; uint64_t x31 = UINT64_MAX; int8_t x35 = -1; int32_t x37 = INT32_MIN; uint64_t x39 = UINT64_MAX; int32_t t8 = -113; uint8_t x43 = 28U; int32_t t9 = -84245; uint32_t x45 = UINT32_MAX; volatile uint8_t x47 = 49U; static int8_t x50 = INT8_MAX; uint64_t x54 = UINT64_MAX; int64_t x58 = 715991425LL; int8_t x60 = INT8_MIN; int64_t x73 = -888520LL; int8_t x75 = -1; int16_t x78 = INT16_MAX; static int32_t x80 = INT32_MIN; volatile int16_t x86 = INT16_MAX; int16_t x87 = INT16_MIN; uint64_t x91 = UINT64_MAX; int32_t t19 = -33915455; volatile uint8_t x94 = 1U; int32_t t21 = -7; static int8_t x101 = -31; static int8_t x103 = -31; volatile int32_t t24 = -202262; int32_t t27 = -188; int64_t x129 = 19LL; int16_t x130 = 3; int64_t x132 = -16854249022494LL; int32_t t28 = -1; static int16_t x136 = INT16_MAX; volatile int32_t t29 = 37; static int8_t x140 = INT8_MAX; volatile uint64_t x150 = 24LLU; static int32_t x157 = -6; volatile int32_t x168 = 222085; static uint64_t x169 = 792LLU; static volatile int32_t x172 = -2038; uint8_t x179 = UINT8_MAX; int64_t x205 = -1LL; volatile int32_t x206 = -441971827; int8_t x214 = -6; int8_t x215 = INT8_MAX; volatile int64_t x216 = INT64_MIN; int8_t x219 = INT8_MIN; int8_t x223 = 32; volatile int32_t t46 = 679512368; uint64_t x225 = 8646807LLU; uint32_t x226 = UINT32_MAX; int32_t x235 = -1; volatile int32_t x236 = -1; int8_t x239 = -2; int64_t x240 = -1LL; int8_t x248 = INT8_MIN; uint32_t x251 = 167U; uint16_t x254 = UINT16_MAX; volatile int32_t t54 = -618088830; int32_t x262 = INT32_MIN; volatile int16_t x267 = INT16_MIN; static volatile int8_t x288 = -1; int16_t x292 = 449; int64_t x297 = INT64_MAX; static uint64_t x302 = UINT64_MAX; volatile int32_t t63 = -1; uint16_t x311 = UINT16_MAX; static int16_t x319 = INT16_MAX; volatile int8_t x320 = -3; int32_t x329 = INT32_MIN; volatile int32_t t69 = 180233510; volatile int64_t x344 = INT64_MIN; static int32_t x354 = -1; uint32_t x356 = 17120529U; static volatile uint32_t x365 = 6389U; volatile int16_t x369 = INT16_MAX; volatile int8_t x377 = INT8_MAX; volatile int32_t t80 = 0; static volatile int32_t t81 = 7972; volatile int16_t x391 = -1; static int8_t x395 = INT8_MIN; int8_t x406 = INT8_MIN; int32_t x411 = -1516; int8_t x413 = 1; volatile int32_t t88 = 2; int32_t x417 = INT32_MAX; volatile int8_t x418 = -1; uint64_t x424 = 930901LLU; static volatile int32_t t90 = 851275; uint32_t x430 = UINT32_MAX; int32_t x438 = -113292367; volatile int16_t x444 = -1; uint64_t x455 = UINT64_MAX; static int32_t x457 = INT32_MIN; volatile int16_t x462 = INT16_MIN; static int16_t x475 = 2632; uint8_t x478 = 0U; int16_t x480 = INT16_MIN; volatile uint16_t x487 = 628U; uint32_t x488 = 6524U; uint16_t x489 = UINT16_MAX; int8_t x495 = -1; uint64_t x497 = 12LLU; static int32_t t109 = 62273; volatile int32_t x502 = INT32_MIN; int8_t x512 = INT8_MAX; volatile int8_t x520 = 6; int16_t x523 = -1; volatile int32_t t114 = -90936; uint32_t x525 = 2U; int16_t x526 = INT16_MAX; int32_t x539 = -121108722; static int32_t x543 = INT32_MIN; volatile int16_t x545 = -1; uint8_t x546 = UINT8_MAX; uint32_t x552 = UINT32_MAX; volatile int32_t t121 = -650504835; int32_t x553 = -1594; static uint8_t x555 = 35U; uint64_t x557 = 1859570641744958LLU; uint8_t x560 = 1U; volatile int32_t x565 = 1354976; int32_t x570 = -56; uint64_t x577 = 283234578753233177LLU; int8_t x582 = 0; int64_t x586 = -34045789462LL; uint32_t x593 = 131U; int64_t x602 = INT64_MIN; uint64_t x605 = 142491722LLU; uint16_t x606 = UINT16_MAX; volatile uint32_t x608 = 436432U; int16_t x613 = -261; volatile int32_t x615 = -1; uint8_t x619 = UINT8_MAX; uint32_t x621 = 1876U; volatile uint64_t x622 = UINT64_MAX; uint16_t x628 = 93U; static int8_t x632 = INT8_MIN; volatile int16_t x642 = INT16_MAX; int32_t x650 = INT32_MIN; volatile int32_t t143 = 1128945; int64_t x656 = 121LL; int32_t x659 = 12222383; static int32_t t145 = -421569; static int16_t x671 = INT16_MIN; static uint8_t x675 = 60U; int32_t x678 = -1; int8_t x680 = -1; uint8_t x682 = 10U; uint32_t x690 = 15U; int32_t x694 = -83335490; int16_t x704 = INT16_MIN; int64_t x706 = INT64_MIN; static uint32_t x708 = 8U; uint16_t x709 = 2148U; static int16_t x710 = INT16_MIN; int8_t x711 = INT8_MIN; int64_t x715 = -993191457798663204LL; int32_t x718 = -1; uint32_t x720 = 32U; uint64_t x727 = UINT64_MAX; int32_t t160 = 8761216; uint64_t x729 = 634120988326024LLU; int32_t t161 = -198456601; volatile int32_t t163 = 801; uint16_t x753 = UINT16_MAX; static int16_t x754 = -1; static uint32_t x757 = 52685U; int8_t x776 = INT8_MIN; volatile uint8_t x778 = 4U; volatile int32_t t172 = 8096; int32_t x787 = INT32_MAX; int64_t x794 = 1215339364LL; static int8_t x796 = INT8_MIN; int32_t x802 = -1; int8_t x803 = INT8_MIN; int64_t x804 = INT64_MAX; volatile int32_t t178 = -1784791; volatile int8_t x816 = -53; uint16_t x819 = 6U; volatile int32_t x822 = INT32_MAX; int8_t x823 = -1; uint32_t x828 = UINT32_MAX; int64_t x835 = -1LL; uint8_t x837 = 0U; volatile int8_t x838 = INT8_MIN; static int32_t t187 = -20957; volatile int64_t x856 = -1LL; volatile uint64_t x858 = 3137844LLU; int8_t x859 = INT8_MIN; static volatile int32_t t191 = -2648289; volatile int32_t t193 = -1386; static volatile int8_t x878 = INT8_MAX; int32_t t194 = -233997331; uint8_t x889 = UINT8_MAX; static int32_t x891 = -5271; void f0(void) { uint8_t x2 = 51U; int64_t x3 = 43928975692LL; static int16_t x4 = -1; static volatile int32_t t0 = -97885120; t0 = (x1>((x2+x3)%x4)); if (t0 != 1) { NG(); } else { ; } } void f1(void) { int64_t x5 = -1LL; int8_t x6 = 29; uint32_t x7 = UINT32_MAX; int16_t x8 = -10; static volatile int32_t t1 = -1; t1 = (x5>((x6+x7)%x8)); if (t1 != 0) { NG(); } else { ; } } void f2(void) { uint32_t x13 = 340750441U; int16_t x14 = INT16_MIN; uint16_t x16 = UINT16_MAX; int32_t t2 = 5509; t2 = (x13>((x14+x15)%x16)); if (t2 != 0) { NG(); } else { ; } } void f3(void) { int16_t x17 = INT16_MIN; int32_t x18 = 4040990; int32_t x20 = INT32_MIN; int32_t t3 = 63; t3 = (x17>((x18+x19)%x20)); if (t3 != 1) { NG(); } else { ; } } void f4(void) { uint64_t x21 = UINT64_MAX; int64_t x22 = INT64_MAX; int8_t x23 = -1; volatile uint32_t x24 = UINT32_MAX; static int32_t t4 = -149893634; t4 = (x21>((x22+x23)%x24)); if (t4 != 1) { NG(); } else { ; } } void f5(void) { int32_t x25 = INT32_MAX; uint8_t x26 = 1U; volatile int64_t x27 = -1LL; int32_t x28 = 22811; static volatile int32_t t5 = -3382; t5 = (x25>((x26+x27)%x28)); if (t5 != 1) { NG(); } else { ; } } void f6(void) { int16_t x30 = INT16_MIN; static volatile uint64_t x32 = 2002481307929877731LLU; static volatile int32_t t6 = -135795531; t6 = (x29>((x30+x31)%x32)); if (t6 != 1) { NG(); } else { ; } } void f7(void) { static int8_t x33 = INT8_MIN; int8_t x34 = INT8_MIN; static uint32_t x36 = 875U; static int32_t t7 = 1; t7 = (x33>((x34+x35)%x36)); if (t7 != 1) { NG(); } else { ; } } void f8(void) { int8_t x38 = -13; static uint16_t x40 = 6U; t8 = (x37>((x38+x39)%x40)); if (t8 != 1) { NG(); } else { ; } } void f9(void) { int64_t x41 = 4126929410452042913LL; static volatile int16_t x42 = INT16_MIN; int64_t x44 = INT64_MIN; t9 = (x41>((x42+x43)%x44)); if (t9 != 1) { NG(); } else { ; } } void f10(void) { int8_t x46 = 2; int64_t x48 = 18624826773492584LL; volatile int32_t t10 = 1819; t10 = (x45>((x46+x47)%x48)); if (t10 != 1) { NG(); } else { ; } } void f11(void) { volatile int32_t x49 = INT32_MAX; int64_t x51 = -185245066949470LL; static uint16_t x52 = 2U; static int32_t t11 = 120719; t11 = (x49>((x50+x51)%x52)); if (t11 != 1) { NG(); } else { ; } } void f12(void) { int32_t x53 = INT32_MAX; int64_t x55 = INT64_MIN; uint32_t x56 = 62U; int32_t t12 = -8; t12 = (x53>((x54+x55)%x56)); if (t12 != 1) { NG(); } else { ; } } void f13(void) { uint8_t x57 = 89U; uint64_t x59 = 150LLU; int32_t t13 = -487; t13 = (x57>((x58+x59)%x60)); if (t13 != 0) { NG(); } else { ; } } void f14(void) { int64_t x69 = INT64_MIN; static int8_t x70 = INT8_MAX; int16_t x71 = 893; uint8_t x72 = 3U; int32_t t14 = 1268; t14 = (x69>((x70+x71)%x72)); if (t14 != 0) { NG(); } else { ; } } void f15(void) { int8_t x74 = 0; int64_t x76 = INT64_MIN; volatile int32_t t15 = 18680780; t15 = (x73>((x74+x75)%x76)); if (t15 != 0) { NG(); } else { ; } } void f16(void) { int32_t x77 = -1; int16_t x79 = -1; volatile int32_t t16 = 119551901; t16 = (x77>((x78+x79)%x80)); if (t16 != 0) { NG(); } else { ; } } void f17(void) { int8_t x81 = INT8_MIN; volatile uint32_t x82 = 702776U; int64_t x83 = INT64_MIN; volatile uint32_t x84 = 607U; static int32_t t17 = -14626; t17 = (x81>((x82+x83)%x84)); if (t17 != 0) { NG(); } else { ; } } void f18(void) { uint16_t x85 = 63U; uint64_t x88 = UINT64_MAX; int32_t t18 = 22; t18 = (x85>((x86+x87)%x88)); if (t18 != 1) { NG(); } else { ; } } void f19(void) { volatile uint16_t x89 = 405U; static uint16_t x90 = UINT16_MAX; int8_t x92 = -1; t19 = (x89>((x90+x91)%x92)); if (t19 != 0) { NG(); } else { ; } } void f20(void) { volatile int64_t x93 = INT64_MAX; int16_t x95 = INT16_MAX; int32_t x96 = INT32_MIN; volatile int32_t t20 = 3; t20 = (x93>((x94+x95)%x96)); if (t20 != 1) { NG(); } else { ; } } void f21(void) { static uint64_t x97 = 490734LLU; int32_t x98 = 69494; uint16_t x99 = UINT16_MAX; static int32_t x100 = INT32_MAX; t21 = (x97>((x98+x99)%x100)); if (t21 != 1) { NG(); } else { ; } } void f22(void) { volatile uint32_t x102 = 175U; static int8_t x104 = INT8_MAX; static volatile int32_t t22 = 1196; t22 = (x101>((x102+x103)%x104)); if (t22 != 1) { NG(); } else { ; } } void f23(void) { uint8_t x109 = UINT8_MAX; int16_t x110 = INT16_MIN; int32_t x111 = 92231; int8_t x112 = INT8_MIN; int32_t t23 = 212466059; t23 = (x109>((x110+x111)%x112)); if (t23 != 1) { NG(); } else { ; } } void f24(void) { int32_t x113 = 1444; int8_t x114 = -14; int8_t x115 = INT8_MIN; volatile uint8_t x116 = UINT8_MAX; t24 = (x113>((x114+x115)%x116)); if (t24 != 1) { NG(); } else { ; } } void f25(void) { int32_t x117 = INT32_MIN; volatile uint16_t x118 = UINT16_MAX; uint16_t x119 = UINT16_MAX; int64_t x120 = INT64_MIN; volatile int32_t t25 = -539; t25 = (x117>((x118+x119)%x120)); if (t25 != 0) { NG(); } else { ; } } void f26(void) { uint8_t x121 = UINT8_MAX; volatile int32_t x122 = 0; int64_t x123 = INT64_MIN; static int64_t x124 = INT64_MAX; volatile int32_t t26 = -179537; t26 = (x121>((x122+x123)%x124)); if (t26 != 1) { NG(); } else { ; } } void f27(void) { volatile uint16_t x125 = 1751U; uint16_t x126 = 234U; int8_t x127 = INT8_MIN; uint8_t x128 = 3U; t27 = (x125>((x126+x127)%x128)); if (t27 != 1) { NG(); } else { ; } } void f28(void) { volatile int8_t x131 = INT8_MAX; t28 = (x129>((x130+x131)%x132)); if (t28 != 0) { NG(); } else { ; } } void f29(void) { int16_t x133 = -1; volatile int32_t x134 = 2667004; int32_t x135 = 11897613; t29 = (x133>((x134+x135)%x136)); if (t29 != 0) { NG(); } else { ; } } void f30(void) { static volatile int32_t x137 = -1; int32_t x138 = INT32_MIN; static uint16_t x139 = 2U; int32_t t30 = -11; t30 = (x137>((x138+x139)%x140)); if (t30 != 1) { NG(); } else { ; } } void f31(void) { uint8_t x145 = 97U; uint32_t x146 = 1814U; int64_t x147 = INT64_MIN; int16_t x148 = -1; static int32_t t31 = -206323; t31 = (x145>((x146+x147)%x148)); if (t31 != 1) { NG(); } else { ; } } void f32(void) { int32_t x149 = INT32_MIN; uint32_t x151 = UINT32_MAX; int16_t x152 = -1; static volatile int32_t t32 = 1049072; t32 = (x149>((x150+x151)%x152)); if (t32 != 1) { NG(); } else { ; } } void f33(void) { int32_t x153 = INT32_MIN; uint16_t x154 = 45U; static uint16_t x155 = 1599U; volatile int64_t x156 = INT64_MAX; int32_t t33 = 502; t33 = (x153>((x154+x155)%x156)); if (t33 != 0) { NG(); } else { ; } } void f34(void) { int64_t x158 = 746107745692LL; int8_t x159 = INT8_MIN; int64_t x160 = 1316875029757LL; volatile int32_t t34 = -114442; t34 = (x157>((x158+x159)%x160)); if (t34 != 0) { NG(); } else { ; } } void f35(void) { uint64_t x161 = 328393542053027523LLU; static int32_t x162 = INT32_MAX; int32_t x163 = -1; static int8_t x164 = INT8_MIN; volatile int32_t t35 = 2265237; t35 = (x161>((x162+x163)%x164)); if (t35 != 1) { NG(); } else { ; } } void f36(void) { volatile uint8_t x165 = 5U; int16_t x166 = INT16_MIN; int8_t x167 = -1; volatile int32_t t36 = -3902482; t36 = (x165>((x166+x167)%x168)); if (t36 != 1) { NG(); } else { ; } } void f37(void) { uint32_t x170 = UINT32_MAX; int16_t x171 = 1; int32_t t37 = -258216007; t37 = (x169>((x170+x171)%x172)); if (t37 != 1) { NG(); } else { ; } } void f38(void) { int8_t x177 = INT8_MIN; int16_t x178 = -14; volatile int32_t x180 = INT32_MAX; volatile int32_t t38 = 18720318; t38 = (x177>((x178+x179)%x180)); if (t38 != 0) { NG(); } else { ; } } void f39(void) { static uint32_t x185 = UINT32_MAX; int64_t x186 = 6LL; int64_t x187 = 8059590533LL; volatile uint16_t x188 = 1U; int32_t t39 = 9919027; t39 = (x185>((x186+x187)%x188)); if (t39 != 1) { NG(); } else { ; } } void f40(void) { int8_t x189 = -2; static int16_t x190 = INT16_MIN; uint16_t x191 = 9228U; int32_t x192 = -1; static int32_t t40 = 794; t40 = (x189>((x190+x191)%x192)); if (t40 != 0) { NG(); } else { ; } } void f41(void) { int8_t x197 = -1; volatile int16_t x198 = INT16_MIN; volatile uint64_t x199 = UINT64_MAX; volatile int16_t x200 = 876; int32_t t41 = -221421; t41 = (x197>((x198+x199)%x200)); if (t41 != 1) { NG(); } else { ; } } void f42(void) { int16_t x207 = INT16_MAX; static volatile uint64_t x208 = 1475085347049907LLU; static int32_t t42 = -5205908; t42 = (x205>((x206+x207)%x208)); if (t42 != 1) { NG(); } else { ; } } void f43(void) { uint8_t x209 = 1U; static int64_t x210 = 14938745543LL; volatile uint16_t x211 = UINT16_MAX; volatile int32_t x212 = 4693; int32_t t43 = -9; t43 = (x209>((x210+x211)%x212)); if (t43 != 0) { NG(); } else { ; } } void f44(void) { int32_t x213 = INT32_MIN; int32_t t44 = 1073532927; t44 = (x213>((x214+x215)%x216)); if (t44 != 0) { NG(); } else { ; } } void f45(void) { int8_t x217 = INT8_MAX; int64_t x218 = INT64_MAX; uint64_t x220 = 749199151030762310LLU; static int32_t t45 = 46424; t45 = (x217>((x218+x219)%x220)); if (t45 != 0) { NG(); } else { ; } } void f46(void) { volatile uint32_t x221 = 31778U; static int64_t x222 = INT64_MIN; int8_t x224 = INT8_MIN; t46 = (x221>((x222+x223)%x224)); if (t46 != 1) { NG(); } else { ; } } void f47(void) { volatile int64_t x227 = INT64_MIN; uint16_t x228 = 59U; int32_t t47 = 322219714; t47 = (x225>((x226+x227)%x228)); if (t47 != 0) { NG(); } else { ; } } void f48(void) { int32_t x229 = -1; int8_t x230 = -1; int16_t x231 = 8; int16_t x232 = INT16_MIN; int32_t t48 = 3662; t48 = (x229>((x230+x231)%x232)); if (t48 != 0) { NG(); } else { ; } } void f49(void) { int8_t x233 = -30; int8_t x234 = INT8_MAX; volatile int32_t t49 = 31; t49 = (x233>((x234+x235)%x236)); if (t49 != 0) { NG(); } else { ; } } void f50(void) { volatile int16_t x237 = -1; static int64_t x238 = -1LL; static int32_t t50 = 401183058; t50 = (x237>((x238+x239)%x240)); if (t50 != 0) { NG(); } else { ; } } void f51(void) { static uint16_t x245 = UINT16_MAX; static volatile int8_t x246 = -1; uint64_t x247 = UINT64_MAX; int32_t t51 = -345; t51 = (x245>((x246+x247)%x248)); if (t51 != 1) { NG(); } else { ; } } void f52(void) { int8_t x249 = 0; static uint8_t x250 = 62U; int16_t x252 = 366; static int32_t t52 = -143405; t52 = (x249>((x250+x251)%x252)); if (t52 != 0) { NG(); } else { ; } } void f53(void) { int32_t x253 = INT32_MAX; static int8_t x255 = -1; int64_t x256 = -1LL; volatile int32_t t53 = 1; t53 = (x253>((x254+x255)%x256)); if (t53 != 1) { NG(); } else { ; } } void f54(void) { static uint32_t x257 = UINT32_MAX; uint16_t x258 = 199U; uint32_t x259 = 1010727470U; static volatile uint16_t x260 = 25U; t54 = (x257>((x258+x259)%x260)); if (t54 != 1) { NG(); } else { ; } } void f55(void) { volatile int32_t x261 = 26; static int64_t x263 = -1LL; static int8_t x264 = INT8_MIN; volatile int32_t t55 = -1894; t55 = (x261>((x262+x263)%x264)); if (t55 != 1) { NG(); } else { ; } } void f56(void) { int32_t x265 = -19790606; int32_t x266 = -1; int32_t x268 = INT32_MAX; volatile int32_t t56 = -1; t56 = (x265>((x266+x267)%x268)); if (t56 != 0) { NG(); } else { ; } } void f57(void) { int16_t x269 = -1; volatile int8_t x270 = INT8_MAX; static volatile uint32_t x271 = 532386U; static uint8_t x272 = UINT8_MAX; volatile int32_t t57 = 46664051; t57 = (x269>((x270+x271)%x272)); if (t57 != 1) { NG(); } else { ; } } void f58(void) { static int64_t x277 = INT64_MIN; int16_t x278 = -1; static int32_t x279 = -1; int16_t x280 = 40; volatile int32_t t58 = -517741; t58 = (x277>((x278+x279)%x280)); if (t58 != 0) { NG(); } else { ; } } void f59(void) { int8_t x281 = INT8_MAX; int8_t x282 = INT8_MIN; int16_t x283 = INT16_MAX; static int64_t x284 = INT64_MIN; volatile int32_t t59 = -1; t59 = (x281>((x282+x283)%x284)); if (t59 != 0) { NG(); } else { ; } } void f60(void) { int32_t x285 = -1; int32_t x286 = INT32_MIN; int16_t x287 = INT16_MAX; volatile int32_t t60 = 155719099; t60 = (x285>((x286+x287)%x288)); if (t60 != 0) { NG(); } else { ; } } void f61(void) { static int32_t x289 = INT32_MIN; uint32_t x290 = 5U; static uint64_t x291 = 1256942992539LLU; static int32_t t61 = -1; t61 = (x289>((x290+x291)%x292)); if (t61 != 1) { NG(); } else { ; } } void f62(void) { volatile uint32_t x298 = UINT32_MAX; int32_t x299 = INT32_MIN; uint32_t x300 = 22195594U; volatile int32_t t62 = 840600; t62 = (x297>((x298+x299)%x300)); if (t62 != 1) { NG(); } else { ; } } void f63(void) { static uint64_t x301 = 3701819593411LLU; static volatile int8_t x303 = -1; int16_t x304 = INT16_MAX; t63 = (x301>((x302+x303)%x304)); if (t63 != 1) { NG(); } else { ; } } void f64(void) { static int16_t x305 = -6383; uint64_t x306 = UINT64_MAX; int32_t x307 = INT32_MIN; static int16_t x308 = INT16_MIN; volatile int32_t t64 = -445685; t64 = (x305>((x306+x307)%x308)); if (t64 != 1) { NG(); } else { ; } } void f65(void) { volatile uint8_t x309 = 0U; uint16_t x310 = 227U; volatile uint32_t x312 = 267U; static int32_t t65 = 3; t65 = (x309>((x310+x311)%x312)); if (t65 != 0) { NG(); } else { ; } } void f66(void) { uint16_t x317 = 0U; volatile int16_t x318 = -1; int32_t t66 = 469; t66 = (x317>((x318+x319)%x320)); if (t66 != 0) { NG(); } else { ; } } void f67(void) { uint8_t x321 = 6U; int32_t x322 = 644377973; int32_t x323 = -1; static volatile uint8_t x324 = 1U; int32_t t67 = -4568; t67 = (x321>((x322+x323)%x324)); if (t67 != 1) { NG(); } else { ; } } void f68(void) { static volatile int64_t x325 = INT64_MAX; uint64_t x326 = UINT64_MAX; uint32_t x327 = 56U; uint16_t x328 = 82U; volatile int32_t t68 = 709; t68 = (x325>((x326+x327)%x328)); if (t68 != 1) { NG(); } else { ; } } void f69(void) { static int16_t x330 = -1; volatile int8_t x331 = INT8_MIN; int8_t x332 = -1; t69 = (x329>((x330+x331)%x332)); if (t69 != 0) { NG(); } else { ; } } void f70(void) { int32_t x333 = INT32_MIN; int8_t x334 = INT8_MAX; uint32_t x335 = 1374U; uint16_t x336 = 117U; int32_t t70 = -1; t70 = (x333>((x334+x335)%x336)); if (t70 != 1) { NG(); } else { ; } } void f71(void) { int8_t x341 = -1; int16_t x342 = INT16_MIN; volatile int8_t x343 = 0; volatile int32_t t71 = -469837282; t71 = (x341>((x342+x343)%x344)); if (t71 != 1) { NG(); } else { ; } } void f72(void) { int16_t x345 = -787; static uint8_t x346 = 19U; static int8_t x347 = INT8_MIN; uint32_t x348 = 1026147U; int32_t t72 = 30; t72 = (x345>((x346+x347)%x348)); if (t72 != 1) { NG(); } else { ; } } void f73(void) { int64_t x353 = -1LL; int32_t x355 = -1; int32_t t73 = -1786546; t73 = (x353>((x354+x355)%x356)); if (t73 != 0) { NG(); } else { ; } } void f74(void) { int16_t x357 = -3163; int64_t x358 = -1LL; int16_t x359 = INT16_MIN; uint8_t x360 = UINT8_MAX; int32_t t74 = -230835331; t74 = (x357>((x358+x359)%x360)); if (t74 != 0) { NG(); } else { ; } } void f75(void) { int32_t x361 = INT32_MIN; int8_t x362 = INT8_MIN; volatile uint8_t x363 = 14U; volatile int8_t x364 = INT8_MAX; int32_t t75 = 7740; t75 = (x361>((x362+x363)%x364)); if (t75 != 0) { NG(); } else { ; } } void f76(void) { int32_t x366 = INT32_MAX; int64_t x367 = INT64_MIN; int8_t x368 = 10; volatile int32_t t76 = -232258; t76 = (x365>((x366+x367)%x368)); if (t76 != 1) { NG(); } else { ; } } void f77(void) { uint32_t x370 = UINT32_MAX; int32_t x371 = INT32_MAX; int64_t x372 = -114580656LL; volatile int32_t t77 = -1336400; t77 = (x369>((x370+x371)%x372)); if (t77 != 0) { NG(); } else { ; } } void f78(void) { int64_t x373 = INT64_MAX; uint32_t x374 = 1U; static volatile int16_t x375 = 0; volatile int16_t x376 = INT16_MIN; static int32_t t78 = 23456123; t78 = (x373>((x374+x375)%x376)); if (t78 != 1) { NG(); } else { ; } } void f79(void) { volatile int64_t x378 = -1LL; int32_t x379 = INT32_MIN; uint8_t x380 = UINT8_MAX; volatile int32_t t79 = -3; t79 = (x377>((x378+x379)%x380)); if (t79 != 1) { NG(); } else { ; } } void f80(void) { int32_t x381 = 7; uint8_t x382 = UINT8_MAX; int16_t x383 = INT16_MAX; uint64_t x384 = 497LLU; t80 = (x381>((x382+x383)%x384)); if (t80 != 0) { NG(); } else { ; } } void f81(void) { int64_t x385 = INT64_MAX; static int32_t x386 = -1003; volatile int16_t x387 = 8; uint64_t x388 = 294161932411787LLU; t81 = (x385>((x386+x387)%x388)); if (t81 != 1) { NG(); } else { ; } } void f82(void) { int16_t x389 = -1; int32_t x390 = -1; uint32_t x392 = 1093U; int32_t t82 = 16513774; t82 = (x389>((x390+x391)%x392)); if (t82 != 1) { NG(); } else { ; } } void f83(void) { volatile int64_t x393 = -172LL; int64_t x394 = -68027522653822812LL; int16_t x396 = INT16_MIN; volatile int32_t t83 = -1; t83 = (x393>((x394+x395)%x396)); if (t83 != 1) { NG(); } else { ; } } void f84(void) { int64_t x397 = INT64_MAX; volatile int16_t x398 = -41; int8_t x399 = -1; static volatile uint32_t x400 = UINT32_MAX; static volatile int32_t t84 = -44801; t84 = (x397>((x398+x399)%x400)); if (t84 != 1) { NG(); } else { ; } } void f85(void) { int32_t x401 = INT32_MIN; int16_t x402 = -1; int8_t x403 = INT8_MIN; int8_t x404 = INT8_MIN; int32_t t85 = 797; t85 = (x401>((x402+x403)%x404)); if (t85 != 0) { NG(); } else { ; } } void f86(void) { int8_t x405 = -1; volatile uint32_t x407 = 374852U; static volatile int32_t x408 = INT32_MIN; int32_t t86 = 268886; t86 = (x405>((x406+x407)%x408)); if (t86 != 1) { NG(); } else { ; } } void f87(void) { volatile uint64_t x409 = 525433723LLU; int16_t x410 = -1409; volatile int16_t x412 = INT16_MAX; volatile int32_t t87 = 1; t87 = (x409>((x410+x411)%x412)); if (t87 != 0) { NG(); } else { ; } } void f88(void) { uint16_t x414 = 35U; static volatile uint16_t x415 = 29U; int8_t x416 = INT8_MIN; t88 = (x413>((x414+x415)%x416)); if (t88 != 0) { NG(); } else { ; } } void f89(void) { uint32_t x419 = 5U; uint64_t x420 = UINT64_MAX; int32_t t89 = -2417; t89 = (x417>((x418+x419)%x420)); if (t89 != 1) { NG(); } else { ; } } void f90(void) { int64_t x421 = -123342061492483LL; int16_t x422 = INT16_MIN; volatile int16_t x423 = INT16_MIN; t90 = (x421>((x422+x423)%x424)); if (t90 != 1) { NG(); } else { ; } } void f91(void) { volatile uint16_t x425 = UINT16_MAX; int64_t x426 = 63421452LL; uint32_t x427 = UINT32_MAX; volatile uint32_t x428 = UINT32_MAX; volatile int32_t t91 = 253932888; t91 = (x425>((x426+x427)%x428)); if (t91 != 0) { NG(); } else { ; } } void f92(void) { int8_t x429 = INT8_MIN; volatile int64_t x431 = -7521476655LL; int64_t x432 = -307336272817210LL; volatile int32_t t92 = -30705125; t92 = (x429>((x430+x431)%x432)); if (t92 != 1) { NG(); } else { ; } } void f93(void) { int32_t x433 = 706267348; uint32_t x434 = UINT32_MAX; int64_t x435 = -7301677587595LL; static int16_t x436 = -1; volatile int32_t t93 = -4814288; t93 = (x433>((x434+x435)%x436)); if (t93 != 1) { NG(); } else { ; } } void f94(void) { int8_t x437 = INT8_MIN; volatile int16_t x439 = INT16_MIN; int64_t x440 = -1LL; int32_t t94 = -242; t94 = (x437>((x438+x439)%x440)); if (t94 != 0) { NG(); } else { ; } } void f95(void) { int32_t x441 = INT32_MAX; int16_t x442 = INT16_MAX; volatile int32_t x443 = -1; int32_t t95 = 129820; t95 = (x441>((x442+x443)%x444)); if (t95 != 1) { NG(); } else { ; } } void f96(void) { uint64_t x445 = 1532LLU; static uint64_t x446 = 5115LLU; int8_t x447 = INT8_MIN; volatile int64_t x448 = INT64_MAX; volatile int32_t t96 = 13439; t96 = (x445>((x446+x447)%x448)); if (t96 != 0) { NG(); } else { ; } } void f97(void) { static uint8_t x449 = 20U; static uint64_t x450 = UINT64_MAX; uint8_t x451 = 1U; int8_t x452 = -1; int32_t t97 = -1; t97 = (x449>((x450+x451)%x452)); if (t97 != 1) { NG(); } else { ; } } void f98(void) { uint8_t x453 = UINT8_MAX; volatile uint64_t x454 = 12723230628312LLU; int8_t x456 = INT8_MAX; volatile int32_t t98 = -289926; t98 = (x453>((x454+x455)%x456)); if (t98 != 1) { NG(); } else { ; } } void f99(void) { static uint8_t x458 = 21U; int8_t x459 = INT8_MAX; uint8_t x460 = 1U; static int32_t t99 = -377; t99 = (x457>((x458+x459)%x460)); if (t99 != 0) { NG(); } else { ; } } void f100(void) { uint64_t x461 = 78254LLU; int16_t x463 = -1; uint8_t x464 = 37U; int32_t t100 = -31; t100 = (x461>((x462+x463)%x464)); if (t100 != 0) { NG(); } else { ; } } void f101(void) { int8_t x465 = INT8_MIN; int32_t x466 = INT32_MAX; static int8_t x467 = INT8_MIN; volatile int64_t x468 = INT64_MAX; static int32_t t101 = 183; t101 = (x465>((x466+x467)%x468)); if (t101 != 0) { NG(); } else { ; } } void f102(void) { static uint32_t x469 = UINT32_MAX; volatile int16_t x470 = INT16_MAX; int32_t x471 = -1; int16_t x472 = 7; volatile int32_t t102 = -1197404; t102 = (x469>((x470+x471)%x472)); if (t102 != 1) { NG(); } else { ; } } void f103(void) { static int32_t x473 = -1398; uint16_t x474 = 970U; uint8_t x476 = 1U; volatile int32_t t103 = 10; t103 = (x473>((x474+x475)%x476)); if (t103 != 0) { NG(); } else { ; } } void f104(void) { static uint8_t x477 = 0U; uint16_t x479 = 127U; volatile int32_t t104 = -27628860; t104 = (x477>((x478+x479)%x480)); if (t104 != 0) { NG(); } else { ; } } void f105(void) { volatile uint32_t x481 = UINT32_MAX; uint8_t x482 = 1U; static int16_t x483 = INT16_MAX; static volatile int32_t x484 = -1; volatile int32_t t105 = 3; t105 = (x481>((x482+x483)%x484)); if (t105 != 1) { NG(); } else { ; } } void f106(void) { static uint32_t x485 = 245939U; int64_t x486 = INT64_MIN; static volatile int32_t t106 = -7104; t106 = (x485>((x486+x487)%x488)); if (t106 != 1) { NG(); } else { ; } } void f107(void) { int8_t x490 = 30; uint8_t x491 = 1U; int16_t x492 = INT16_MAX; int32_t t107 = -8525; t107 = (x489>((x490+x491)%x492)); if (t107 != 1) { NG(); } else { ; } } void f108(void) { int64_t x493 = 149238608444019LL; uint16_t x494 = 7494U; int16_t x496 = INT16_MIN; static volatile int32_t t108 = 5157; t108 = (x493>((x494+x495)%x496)); if (t108 != 1) { NG(); } else { ; } } void f109(void) { volatile int16_t x498 = -1; uint16_t x499 = UINT16_MAX; uint8_t x500 = UINT8_MAX; t109 = (x497>((x498+x499)%x500)); if (t109 != 0) { NG(); } else { ; } } void f110(void) { int16_t x501 = -1; volatile uint16_t x503 = 5664U; static int32_t x504 = INT32_MAX; int32_t t110 = -3594185; t110 = (x501>((x502+x503)%x504)); if (t110 != 1) { NG(); } else { ; } } void f111(void) { uint8_t x505 = 60U; int32_t x506 = -841; volatile int16_t x507 = INT16_MIN; uint16_t x508 = 1326U; volatile int32_t t111 = 75; t111 = (x505>((x506+x507)%x508)); if (t111 != 1) { NG(); } else { ; } } void f112(void) { int32_t x509 = INT32_MAX; static int16_t x510 = 17; static int64_t x511 = -16032LL; static int32_t t112 = -1; t112 = (x509>((x510+x511)%x512)); if (t112 != 1) { NG(); } else { ; } } void f113(void) { uint8_t x517 = 11U; uint64_t x518 = UINT64_MAX; int64_t x519 = INT64_MAX; volatile int32_t t113 = 5; t113 = (x517>((x518+x519)%x520)); if (t113 != 1) { NG(); } else { ; } } void f114(void) { uint64_t x521 = 1729306475224948322LLU; volatile int64_t x522 = -727319389803800LL; uint8_t x524 = 12U; t114 = (x521>((x522+x523)%x524)); if (t114 != 0) { NG(); } else { ; } } void f115(void) { int32_t x527 = INT32_MIN; volatile int16_t x528 = -13; volatile int32_t t115 = 1777; t115 = (x525>((x526+x527)%x528)); if (t115 != 0) { NG(); } else { ; } } void f116(void) { static volatile int32_t x529 = INT32_MIN; int32_t x530 = -1; int64_t x531 = 126674755951214836LL; int16_t x532 = INT16_MIN; volatile int32_t t116 = -2032; t116 = (x529>((x530+x531)%x532)); if (t116 != 0) { NG(); } else { ; } } void f117(void) { int16_t x533 = 2860; int64_t x534 = INT64_MIN; static volatile int32_t x535 = 56809098; volatile int8_t x536 = INT8_MAX; static int32_t t117 = 418450300; t117 = (x533>((x534+x535)%x536)); if (t117 != 1) { NG(); } else { ; } } void f118(void) { int64_t x537 = INT64_MIN; int64_t x538 = INT64_MAX; int64_t x540 = 10875865LL; volatile int32_t t118 = -2; t118 = (x537>((x538+x539)%x540)); if (t118 != 0) { NG(); } else { ; } } void f119(void) { int16_t x541 = INT16_MIN; static uint16_t x542 = 26310U; int32_t x544 = INT32_MIN; static int32_t t119 = 737368182; t119 = (x541>((x542+x543)%x544)); if (t119 != 1) { NG(); } else { ; } } void f120(void) { int64_t x547 = -1LL; int8_t x548 = INT8_MIN; volatile int32_t t120 = -4949759; t120 = (x545>((x546+x547)%x548)); if (t120 != 0) { NG(); } else { ; } } void f121(void) { static int32_t x549 = INT32_MIN; int32_t x550 = 12; volatile uint8_t x551 = 1U; t121 = (x549>((x550+x551)%x552)); if (t121 != 1) { NG(); } else { ; } } void f122(void) { int32_t x554 = 501217; int8_t x556 = INT8_MIN; int32_t t122 = 21098; t122 = (x553>((x554+x555)%x556)); if (t122 != 0) { NG(); } else { ; } } void f123(void) { int8_t x558 = -1; int16_t x559 = INT16_MIN; volatile int32_t t123 = -410483; t123 = (x557>((x558+x559)%x560)); if (t123 != 1) { NG(); } else { ; } } void f124(void) { static uint64_t x566 = 16136LLU; int32_t x567 = INT32_MIN; uint8_t x568 = UINT8_MAX; volatile int32_t t124 = 39; t124 = (x565>((x566+x567)%x568)); if (t124 != 1) { NG(); } else { ; } } void f125(void) { uint8_t x569 = UINT8_MAX; static int8_t x571 = -1; static volatile int64_t x572 = INT64_MIN; volatile int32_t t125 = 11262; t125 = (x569>((x570+x571)%x572)); if (t125 != 1) { NG(); } else { ; } } void f126(void) { uint32_t x573 = 10239115U; uint64_t x574 = 1786915062LLU; uint64_t x575 = 60613204363626162LLU; volatile uint8_t x576 = UINT8_MAX; int32_t t126 = -54588611; t126 = (x573>((x574+x575)%x576)); if (t126 != 1) { NG(); } else { ; } } void f127(void) { volatile int64_t x578 = -7LL; int32_t x579 = INT32_MAX; int16_t x580 = INT16_MAX; volatile int32_t t127 = 214212766; t127 = (x577>((x578+x579)%x580)); if (t127 != 1) { NG(); } else { ; } } void f128(void) { volatile int8_t x581 = INT8_MAX; int8_t x583 = INT8_MAX; static int64_t x584 = INT64_MIN; static volatile int32_t t128 = -4174; t128 = (x581>((x582+x583)%x584)); if (t128 != 0) { NG(); } else { ; } } void f129(void) { uint64_t x585 = 64079LLU; uint8_t x587 = UINT8_MAX; static int64_t x588 = INT64_MAX; volatile int32_t t129 = 1; t129 = (x585>((x586+x587)%x588)); if (t129 != 0) { NG(); } else { ; } } void f130(void) { static volatile int64_t x589 = INT64_MAX; static int16_t x590 = 1; int64_t x591 = -1LL; int32_t x592 = 2071681; volatile int32_t t130 = 7479; t130 = (x589>((x590+x591)%x592)); if (t130 != 1) { NG(); } else { ; } } void f131(void) { int16_t x594 = INT16_MAX; int16_t x595 = -1; int32_t x596 = INT32_MIN; volatile int32_t t131 = -84800; t131 = (x593>((x594+x595)%x596)); if (t131 != 0) { NG(); } else { ; } } void f132(void) { int32_t x597 = INT32_MIN; int16_t x598 = INT16_MAX; static int16_t x599 = 356; int8_t x600 = -32; static int32_t t132 = 786; t132 = (x597>((x598+x599)%x600)); if (t132 != 0) { NG(); } else { ; } } void f133(void) { static int32_t x601 = INT32_MIN; int16_t x603 = INT16_MAX; volatile int32_t x604 = -1; int32_t t133 = -7565; t133 = (x601>((x602+x603)%x604)); if (t133 != 0) { NG(); } else { ; } } void f134(void) { int64_t x607 = -31885569818187215LL; static volatile int32_t t134 = 103443; t134 = (x605>((x606+x607)%x608)); if (t134 != 0) { NG(); } else { ; } } void f135(void) { int16_t x609 = INT16_MAX; int64_t x610 = INT64_MIN; static uint8_t x611 = UINT8_MAX; uint8_t x612 = 2U; volatile int32_t t135 = -17; t135 = (x609>((x610+x611)%x612)); if (t135 != 1) { NG(); } else { ; } } void f136(void) { int16_t x614 = -10; int8_t x616 = -1; volatile int32_t t136 = 4; t136 = (x613>((x614+x615)%x616)); if (t136 != 0) { NG(); } else { ; } } void f137(void) { int32_t x617 = INT32_MIN; int8_t x618 = -1; int64_t x620 = INT64_MIN; volatile int32_t t137 = 17828988; t137 = (x617>((x618+x619)%x620)); if (t137 != 0) { NG(); } else { ; } } void f138(void) { int32_t x623 = INT32_MIN; static volatile uint16_t x624 = UINT16_MAX; volatile int32_t t138 = 121031; t138 = (x621>((x622+x623)%x624)); if (t138 != 0) { NG(); } else { ; } } void f139(void) { static int8_t x625 = -1; int16_t x626 = 58; volatile int8_t x627 = -1; int32_t t139 = 10816; t139 = (x625>((x626+x627)%x628)); if (t139 != 0) { NG(); } else { ; } } void f140(void) { int8_t x629 = INT8_MIN; volatile int32_t x630 = -50; static volatile int64_t x631 = 15953LL; volatile int32_t t140 = -4179; t140 = (x629>((x630+x631)%x632)); if (t140 != 0) { NG(); } else { ; } } void f141(void) { int8_t x641 = INT8_MIN; int64_t x643 = INT64_MIN; volatile uint32_t x644 = 6095531U; int32_t t141 = -2384778; t141 = (x641>((x642+x643)%x644)); if (t141 != 1) { NG(); } else { ; } } void f142(void) { int8_t x645 = -1; int8_t x646 = -1; volatile int64_t x647 = INT64_MAX; static int64_t x648 = INT64_MAX; volatile int32_t t142 = -228; t142 = (x645>((x646+x647)%x648)); if (t142 != 0) { NG(); } else { ; } } void f143(void) { volatile int64_t x649 = INT64_MAX; uint32_t x651 = 1311071507U; int8_t x652 = INT8_MAX; t143 = (x649>((x650+x651)%x652)); if (t143 != 1) { NG(); } else { ; } } void f144(void) { int8_t x653 = INT8_MIN; uint32_t x654 = UINT32_MAX; int32_t x655 = -1; volatile int32_t t144 = -21; t144 = (x653>((x654+x655)%x656)); if (t144 != 0) { NG(); } else { ; } } void f145(void) { volatile int16_t x657 = -1; uint64_t x658 = UINT64_MAX; int8_t x660 = INT8_MAX; t145 = (x657>((x658+x659)%x660)); if (t145 != 1) { NG(); } else { ; } } void f146(void) { volatile int64_t x661 = INT64_MAX; static volatile uint16_t x662 = UINT16_MAX; volatile int32_t x663 = INT32_MIN; uint32_t x664 = UINT32_MAX; int32_t t146 = 67; t146 = (x661>((x662+x663)%x664)); if (t146 != 1) { NG(); } else { ; } } void f147(void) { static uint8_t x669 = 5U; volatile uint16_t x670 = 163U; static uint32_t x672 = 328031594U; static int32_t t147 = -1455613; t147 = (x669>((x670+x671)%x672)); if (t147 != 0) { NG(); } else { ; } } void f148(void) { int64_t x673 = -17LL; int16_t x674 = INT16_MIN; uint16_t x676 = 384U; int32_t t148 = -252; t148 = (x673>((x674+x675)%x676)); if (t148 != 1) { NG(); } else { ; } } void f149(void) { volatile int16_t x677 = -1; int16_t x679 = INT16_MIN; int32_t t149 = 35582931; t149 = (x677>((x678+x679)%x680)); if (t149 != 0) { NG(); } else { ; } } void f150(void) { uint32_t x681 = 109984365U; static int8_t x683 = INT8_MIN; volatile int8_t x684 = -1; volatile int32_t t150 = 331168794; t150 = (x681>((x682+x683)%x684)); if (t150 != 1) { NG(); } else { ; } } void f151(void) { volatile int32_t x685 = INT32_MIN; int16_t x686 = -1; volatile uint32_t x687 = 5676U; int8_t x688 = -1; int32_t t151 = 5647730; t151 = (x685>((x686+x687)%x688)); if (t151 != 1) { NG(); } else { ; } } void f152(void) { static int16_t x689 = -1; static int16_t x691 = -1; uint64_t x692 = 32119947330301999LLU; int32_t t152 = -11; t152 = (x689>((x690+x691)%x692)); if (t152 != 1) { NG(); } else { ; } } void f153(void) { uint64_t x693 = UINT64_MAX; int32_t x695 = INT32_MAX; int8_t x696 = INT8_MAX; volatile int32_t t153 = 3706578; t153 = (x693>((x694+x695)%x696)); if (t153 != 1) { NG(); } else { ; } } void f154(void) { int8_t x697 = 4; static int64_t x698 = -791193LL; volatile int64_t x699 = -1LL; static int8_t x700 = -1; volatile int32_t t154 = 14786; t154 = (x697>((x698+x699)%x700)); if (t154 != 1) { NG(); } else { ; } } void f155(void) { int16_t x701 = -1; volatile uint16_t x702 = 0U; uint32_t x703 = 1491U; volatile int32_t t155 = -15627; t155 = (x701>((x702+x703)%x704)); if (t155 != 1) { NG(); } else { ; } } void f156(void) { static uint32_t x705 = UINT32_MAX; int8_t x707 = 1; int32_t t156 = -1338925; t156 = (x705>((x706+x707)%x708)); if (t156 != 1) { NG(); } else { ; } } void f157(void) { int32_t x712 = INT32_MAX; volatile int32_t t157 = 675070; t157 = (x709>((x710+x711)%x712)); if (t157 != 1) { NG(); } else { ; } } void f158(void) { static volatile int32_t x713 = -48397290; static uint64_t x714 = 627LLU; uint8_t x716 = 26U; volatile int32_t t158 = -20; t158 = (x713>((x714+x715)%x716)); if (t158 != 1) { NG(); } else { ; } } void f159(void) { volatile int32_t x717 = 133761568; uint16_t x719 = 1312U; int32_t t159 = 170490; t159 = (x717>((x718+x719)%x720)); if (t159 != 1) { NG(); } else { ; } } void f160(void) { static int32_t x725 = INT32_MIN; int32_t x726 = INT32_MAX; int8_t x728 = INT8_MAX; t160 = (x725>((x726+x727)%x728)); if (t160 != 1) { NG(); } else { ; } } void f161(void) { int64_t x730 = -1LL; static int8_t x731 = INT8_MIN; int16_t x732 = INT16_MIN; t161 = (x729>((x730+x731)%x732)); if (t161 != 0) { NG(); } else { ; } } void f162(void) { volatile uint8_t x733 = 0U; int64_t x734 = INT64_MIN; static int64_t x735 = 1112757616706519LL; int8_t x736 = 2; volatile int32_t t162 = 176018099; t162 = (x733>((x734+x735)%x736)); if (t162 != 1) { NG(); } else { ; } } void f163(void) { int64_t x737 = 1698867719968078324LL; static uint16_t x738 = 299U; uint8_t x739 = 18U; int16_t x740 = INT16_MIN; t163 = (x737>((x738+x739)%x740)); if (t163 != 1) { NG(); } else { ; } } void f164(void) { int16_t x741 = -1; int16_t x742 = 1; uint64_t x743 = UINT64_MAX; uint64_t x744 = UINT64_MAX; volatile int32_t t164 = -14; t164 = (x741>((x742+x743)%x744)); if (t164 != 1) { NG(); } else { ; } } void f165(void) { int32_t x755 = 1; uint32_t x756 = 106U; volatile int32_t t165 = -1596970; t165 = (x753>((x754+x755)%x756)); if (t165 != 1) { NG(); } else { ; } } void f166(void) { static int8_t x758 = -1; static uint8_t x759 = 15U; int8_t x760 = INT8_MIN; volatile int32_t t166 = -67; t166 = (x757>((x758+x759)%x760)); if (t166 != 1) { NG(); } else { ; } } void f167(void) { static int32_t x761 = 74316; int8_t x762 = INT8_MIN; static volatile int64_t x763 = 0LL; int8_t x764 = INT8_MIN; volatile int32_t t167 = -47307; t167 = (x761>((x762+x763)%x764)); if (t167 != 1) { NG(); } else { ; } } void f168(void) { int64_t x765 = INT64_MIN; uint16_t x766 = 11U; volatile uint16_t x767 = 633U; int32_t x768 = -17; int32_t t168 = -239; t168 = (x765>((x766+x767)%x768)); if (t168 != 0) { NG(); } else { ; } } void f169(void) { volatile uint64_t x769 = 65044199954816199LLU; volatile int64_t x770 = -1LL; int16_t x771 = -1; static int8_t x772 = INT8_MAX; int32_t t169 = 21366; t169 = (x769>((x770+x771)%x772)); if (t169 != 0) { NG(); } else { ; } } void f170(void) { int8_t x773 = -11; uint16_t x774 = 2U; uint32_t x775 = 6834399U; int32_t t170 = 0; t170 = (x773>((x774+x775)%x776)); if (t170 != 1) { NG(); } else { ; } } void f171(void) { int32_t x777 = 27838; static volatile int64_t x779 = INT64_MIN; static int8_t x780 = -1; int32_t t171 = 2; t171 = (x777>((x778+x779)%x780)); if (t171 != 1) { NG(); } else { ; } } void f172(void) { uint16_t x781 = UINT16_MAX; int32_t x782 = -1; static int64_t x783 = INT64_MAX; static int8_t x784 = INT8_MAX; t172 = (x781>((x782+x783)%x784)); if (t172 != 1) { NG(); } else { ; } } void f173(void) { int64_t x785 = INT64_MIN; int32_t x786 = INT32_MIN; static int64_t x788 = -1LL; volatile int32_t t173 = 7661534; t173 = (x785>((x786+x787)%x788)); if (t173 != 0) { NG(); } else { ; } } void f174(void) { static volatile uint8_t x789 = UINT8_MAX; static int8_t x790 = INT8_MIN; static int16_t x791 = INT16_MAX; static int8_t x792 = INT8_MAX; int32_t t174 = 1; t174 = (x789>((x790+x791)%x792)); if (t174 != 1) { NG(); } else { ; } } void f175(void) { static uint64_t x793 = 678695LLU; static int16_t x795 = INT16_MAX; int32_t t175 = -750966513; t175 = (x793>((x794+x795)%x796)); if (t175 != 1) { NG(); } else { ; } } void f176(void) { int64_t x801 = INT64_MAX; static int32_t t176 = -35; t176 = (x801>((x802+x803)%x804)); if (t176 != 1) { NG(); } else { ; } } void f177(void) { uint16_t x805 = UINT16_MAX; static int8_t x806 = INT8_MIN; uint32_t x807 = 713U; static uint32_t x808 = 104298U; volatile int32_t t177 = 5; t177 = (x805>((x806+x807)%x808)); if (t177 != 1) { NG(); } else { ; } } void f178(void) { uint64_t x809 = 2LLU; int64_t x810 = 37LL; static int16_t x811 = INT16_MIN; static volatile int8_t x812 = INT8_MAX; t178 = (x809>((x810+x811)%x812)); if (t178 != 0) { NG(); } else { ; } } void f179(void) { volatile uint32_t x813 = UINT32_MAX; static int8_t x814 = 15; int16_t x815 = INT16_MIN; static int32_t t179 = 211670820; t179 = (x813>((x814+x815)%x816)); if (t179 != 1) { NG(); } else { ; } } void f180(void) { volatile uint64_t x817 = 96412922LLU; uint32_t x818 = UINT32_MAX; uint8_t x820 = 90U; volatile int32_t t180 = -33; t180 = (x817>((x818+x819)%x820)); if (t180 != 1) { NG(); } else { ; } } void f181(void) { uint32_t x821 = 4U; int16_t x824 = INT16_MAX; volatile int32_t t181 = 174263450; t181 = (x821>((x822+x823)%x824)); if (t181 != 1) { NG(); } else { ; } } void f182(void) { volatile int64_t x825 = INT64_MAX; int16_t x826 = -12222; static uint16_t x827 = UINT16_MAX; volatile int32_t t182 = 475; t182 = (x825>((x826+x827)%x828)); if (t182 != 1) { NG(); } else { ; } } void f183(void) { uint32_t x829 = 2720287U; int8_t x830 = 3; int32_t x831 = 22; int8_t x832 = 15; int32_t t183 = -109; t183 = (x829>((x830+x831)%x832)); if (t183 != 1) { NG(); } else { ; } } void f184(void) { int8_t x833 = 2; volatile uint32_t x834 = 27770171U; int32_t x836 = INT32_MIN; static int32_t t184 = -1195; t184 = (x833>((x834+x835)%x836)); if (t184 != 0) { NG(); } else { ; } } void f185(void) { int16_t x839 = 14358; uint8_t x840 = 2U; static int32_t t185 = 4168796; t185 = (x837>((x838+x839)%x840)); if (t185 != 0) { NG(); } else { ; } } void f186(void) { static int64_t x845 = INT64_MIN; uint8_t x846 = 0U; uint8_t x847 = UINT8_MAX; int16_t x848 = -5; int32_t t186 = -647080653; t186 = (x845>((x846+x847)%x848)); if (t186 != 0) { NG(); } else { ; } } void f187(void) { int32_t x849 = INT32_MIN; volatile uint64_t x850 = UINT64_MAX; uint32_t x851 = 612786U; uint32_t x852 = 1214U; t187 = (x849>((x850+x851)%x852)); if (t187 != 1) { NG(); } else { ; } } void f188(void) { int64_t x853 = -2103935LL; static int8_t x854 = 11; uint64_t x855 = 2182156135104LLU; volatile int32_t t188 = -156; t188 = (x853>((x854+x855)%x856)); if (t188 != 1) { NG(); } else { ; } } void f189(void) { static int16_t x857 = 1; int16_t x860 = INT16_MIN; static volatile int32_t t189 = -18; t189 = (x857>((x858+x859)%x860)); if (t189 != 0) { NG(); } else { ; } } void f190(void) { static uint32_t x861 = UINT32_MAX; static int64_t x862 = -13130421671757LL; uint8_t x863 = 25U; uint32_t x864 = UINT32_MAX; int32_t t190 = -17343; t190 = (x861>((x862+x863)%x864)); if (t190 != 1) { NG(); } else { ; } } void f191(void) { int16_t x865 = 0; uint8_t x866 = 1U; volatile uint64_t x867 = UINT64_MAX; uint32_t x868 = 53582U; t191 = (x865>((x866+x867)%x868)); if (t191 != 0) { NG(); } else { ; } } void f192(void) { int16_t x869 = 2; volatile int16_t x870 = INT16_MIN; volatile int8_t x871 = 0; int64_t x872 = INT64_MIN; static volatile int32_t t192 = 24; t192 = (x869>((x870+x871)%x872)); if (t192 != 1) { NG(); } else { ; } } void f193(void) { int64_t x873 = -1LL; static int64_t x874 = -5421851794594LL; static volatile uint64_t x875 = 107255LLU; int16_t x876 = -403; t193 = (x873>((x874+x875)%x876)); if (t193 != 1) { NG(); } else { ; } } void f194(void) { static int32_t x877 = -1; static uint8_t x879 = 103U; int32_t x880 = 2640; t194 = (x877>((x878+x879)%x880)); if (t194 != 0) { NG(); } else { ; } } void f195(void) { int8_t x881 = INT8_MIN; int32_t x882 = 1; static volatile uint64_t x883 = UINT64_MAX; volatile int64_t x884 = 138545567884LL; volatile int32_t t195 = -1; t195 = (x881>((x882+x883)%x884)); if (t195 != 1) { NG(); } else { ; } } void f196(void) { volatile int16_t x885 = INT16_MAX; int8_t x886 = INT8_MIN; int8_t x887 = INT8_MIN; int32_t x888 = 27524346; volatile int32_t t196 = 27520; t196 = (x885>((x886+x887)%x888)); if (t196 != 1) { NG(); } else { ; } } void f197(void) { int64_t x890 = -3052279764385820LL; int32_t x892 = -6334; int32_t t197 = -34906829; t197 = (x889>((x890+x891)%x892)); if (t197 != 1) { NG(); } else { ; } } void f198(void) { int32_t x893 = -473589; uint32_t x894 = UINT32_MAX; int64_t x895 = INT64_MIN; int8_t x896 = -1; int32_t t198 = 0; t198 = (x893>((x894+x895)%x896)); if (t198 != 0) { NG(); } else { ; } } void f199(void) { int32_t x897 = INT32_MIN; int32_t x898 = INT32_MIN; uint32_t x899 = UINT32_MAX; volatile uint64_t x900 = 21295182LLU; int32_t t199 = 4674363; t199 = (x897>((x898+x899)%x900)); if (t199 != 1) { NG(); } else { ; } } int main(void) { f0(); f1(); f2(); f3(); f4(); f5(); f6(); f7(); f8(); f9(); f10(); f11(); f12(); f13(); f14(); f15(); f16(); f17(); f18(); f19(); f20(); f21(); f22(); f23(); f24(); f25(); f26(); f27(); f28(); f29(); f30(); f31(); f32(); f33(); f34(); f35(); f36(); f37(); f38(); f39(); f40(); f41(); f42(); f43(); f44(); f45(); f46(); f47(); f48(); f49(); f50(); f51(); f52(); f53(); f54(); f55(); f56(); f57(); f58(); f59(); f60(); f61(); f62(); f63(); f64(); f65(); f66(); f67(); f68(); f69(); f70(); f71(); f72(); f73(); f74(); f75(); f76(); f77(); f78(); f79(); f80(); f81(); f82(); f83(); f84(); f85(); f86(); f87(); f88(); f89(); f90(); f91(); f92(); f93(); f94(); f95(); f96(); f97(); f98(); f99(); f100(); f101(); f102(); f103(); f104(); f105(); f106(); f107(); f108(); f109(); f110(); f111(); f112(); f113(); f114(); f115(); f116(); f117(); f118(); f119(); f120(); f121(); f122(); f123(); f124(); f125(); f126(); f127(); f128(); f129(); f130(); f131(); f132(); f133(); f134(); f135(); f136(); f137(); f138(); f139(); f140(); f141(); f142(); f143(); f144(); f145(); f146(); f147(); f148(); f149(); f150(); f151(); f152(); f153(); f154(); f155(); f156(); f157(); f158(); f159(); f160(); f161(); f162(); f163(); f164(); f165(); f166(); f167(); f168(); f169(); f170(); f171(); f172(); f173(); f174(); f175(); f176(); f177(); f178(); f179(); f180(); f181(); f182(); f183(); f184(); f185(); f186(); f187(); f188(); f189(); f190(); f191(); f192(); f193(); f194(); f195(); f196(); f197(); f198(); f199(); return 0; }
import os """Sample event["response"]: {"userAttributes": {"sub": "d5267ee4-3563-4e8b-b4f7-8af4929fc9e8", "website": "https://forms.beta.chinmayamission.com/admin/", "cognito:email_alias": "dxftsc+2ots8kjmm@sharklasers.com", "email_verified": "false", "cognito:user_status": "UNCONFIRMED", "name": "User", "email": "dxftsc+2ots8kjmm@sharklasers.com"}, "codeParameter": "941468", "linkParameter": "{##Click Here##}", "usernameParameter": null} """ def lambda_handler(event, context): if ( event["userPoolId"] != os.environ["USER_POOL_ID"] or event["triggerSource"] != "CustomMessage_SignUp" ): return event if event["callerContext"]["clientId"] == os.environ["CHINMAYA_ECHOES_CLIENT_ID"]: code = event["request"]["codeParameter"] username = event["request"]["userAttributes"]["sub"] event["response"][ "emailSubject" ] = "Chinmaya Mission Account - Please verify your account" event["response"][ "smsMessage" ] = f"Welcome to the service. Your confirmation code is {code}" event["response"][ "emailMessage" ] = f""" Hari OM,<br> Your verification code for ChinmayaEchoes is {code}<br> Thanks,<br> Chinmaya Mission IT Team """ return event else: code = event["request"]["codeParameter"] username = event["request"]["userAttributes"]["sub"] url = os.environ["API_ENDPOINT"] link = f"{url}confirmSignUp?code={code}&username={username}" event["response"][ "emailSubject" ] = "Chinmaya Mission Account - Please verify your account" event["response"][ "smsMessage" ] = f"Welcome to the service. Your confirmation code is {code}" event["response"][ "emailMessage" ] = f""" Hari OM,<br> Please click on the link below to verify your email address.<br><br> <a href='{link}'>Verify your email address</a><br><br> If the link above does not work, please go to {link} in your browser.<br><br> Thanks,<br> Chinmaya Mission IT Team """ return event
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:46:51 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/Frameworks/SafariServices.framework/SafariServices * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <UIKitCore/UILongPressGestureRecognizer.h> #import <UIKit/UIGestureRecognizerDelegate.h> @class UIBarButtonItem, NSString; @interface SFBarButtonItemLongPressGestureRecognizer : UILongPressGestureRecognizer <UIGestureRecognizerDelegate> { UIBarButtonItem* _barButtonItem; id _target; SEL _longPressAction; SEL _touchDownAction; } @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; +(id)gestureRecognizerTarget:(id)arg1 longPressAction:(SEL)arg2 touchDownAction:(SEL)arg3 attachedToBarButtonItem:(id)arg4 ; -(void)_contentSizeCategoryDidChange:(id)arg1 ; -(void)_updateMinimumPressDurationForContentSizeCategory:(id)arg1 ; -(void)_invokeLongPressAction; -(BOOL)gestureRecognizerShouldBegin:(id)arg1 ; -(void)touchesBegan:(id)arg1 withEvent:(id)arg2 ; -(void)longPress:(id)arg1 ; @end
# Copyright 2021, Google LLC. # # 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. """Utils function for configuring a federated or centralized task.""" import collections from typing import Callable, Dict, Iterator, List, Optional, Tuple import tensorflow as tf import tensorflow_federated as tff from generalization.tasks import training_specs from generalization.utils import client_data_utils from generalization.utils import eval_metric_distribution SamplerType = Iterator[List[tf.data.Dataset]] MetricsDictType = training_specs.MetricsDictType FederatedEvalFnType = training_specs.FederatedEvalFnType CentralizedEvalFnType = training_specs.CentralizedEvalFnType FederatedModelFnType = training_specs.FederatedModelFnType StatFnType = eval_metric_distribution.StatFnType ClientData = tff.simulation.datasets.ClientData ServerState = tff.learning.framework.ServerState def _create_samplers( *, # Caller passes below args by name. part_train_eval_cd: tff.simulation.datasets.ClientData, part_val_cd: tff.simulation.datasets.ClientData, unpart_cd: tff.simulation.datasets.ClientData, test_cd: Optional[tff.simulation.datasets.ClientData], part_clients_per_eval: Optional[int], unpart_clients_per_eval: Optional[int], test_clients_for_eval: Optional[int], resample_eval_clients: bool, eval_clients_random_seed: Optional[int], ) -> Tuple[SamplerType, SamplerType, SamplerType, Optional[SamplerType]]: """Create four samplers.""" part_train_eval_sampler = client_data_utils.FederatedDatasetSampler( client_data=part_train_eval_cd, num_sample_clients=part_clients_per_eval, resample=resample_eval_clients, seed=eval_clients_random_seed) part_val_sampler = client_data_utils.FederatedDatasetSampler( client_data=part_val_cd, num_sample_clients=part_clients_per_eval, resample=resample_eval_clients, seed=eval_clients_random_seed) unpart_sampler = client_data_utils.FederatedDatasetSampler( client_data=unpart_cd, num_sample_clients=unpart_clients_per_eval, resample=resample_eval_clients, seed=eval_clients_random_seed) if test_cd is not None: test_sampler = client_data_utils.FederatedDatasetSampler( client_data=test_cd, num_sample_clients=test_clients_for_eval, seed=eval_clients_random_seed) else: test_sampler = None return (part_train_eval_sampler, part_val_sampler, unpart_sampler, test_sampler) def create_federated_eval_fns( *, # Caller passes below args by name. tff_model_builder: FederatedModelFnType, metrics_builder: Callable[[], List[tf.keras.metrics.Metric]], part_train_eval_cd: tff.simulation.datasets.ClientData, part_val_cd: tff.simulation.datasets.ClientData, unpart_cd: tff.simulation.datasets.ClientData, test_cd: Optional[tff.simulation.datasets.ClientData], stat_fns: Dict[str, StatFnType], rounds_per_eval: int, part_clients_per_eval: Optional[int], unpart_clients_per_eval: Optional[int], test_clients_for_eval: Optional[int], resample_eval_clients: bool, eval_clients_random_seed: Optional[int], ) -> Tuple[FederatedEvalFnType, FederatedEvalFnType, FederatedEvalFnType, Optional[FederatedEvalFnType]]: """Create federated evaluation functions: train_eval, validation and test. Args: tff_model_builder: A callable with no args that returns a `tff.learning.Model`. metrics_builder: A callable with no args that returns a list of keras metrics. part_train_eval_cd: Preprocessed training chunk of for training ClientData used for evaluation. part_val_cd: Preprocessed validation chunk of training ClientData. unpart_cd: Preprocessed validation ClientData. test_cd: Optional preprocessed ClientData for test after training. If None, the test function will not be constructed, and None value will be returned at the position of test function. stat_fns: A mapping in which each key-value pair represents a custom statistic to be evaluated on the client metrics. Each pair consists of a string-typed key describing this statistic, and a callable-typed value that computes the statistic of metrics. The callable value should accept two sequence-typed arguments `all_clients_this_metric` and `all_clients_num_examples` and returns the corresponding statistics. rounds_per_eval: An integer representing how often to evaluate the global model on training and validation dataset. part_clients_per_eval: An optional integer representing the number of training clients taken from training dataset for evaluation per round. If `None`, all training clients will be used. unpart_clients_per_eval: An optional integer representing the number of clients taken from validation dataset. If `None`, all validation clients will be used. test_clients_for_eval: An optional integer representing the number of clients taken from test dataset, valid only if test_cd is not None. If `None`, all test clients will be used. resample_eval_clients: A bool used to decide whether or not to resample validation clients every evaluation round. eval_clients_random_seed: An optional integer used to seed which validation and test clients are sampled. If `None`, no seed is used. Returns: Federated train_train_eval, train_validation, validation and test functions. """ (part_train_eval_sampler, part_val_sampler, unpart_sampler, test_sampler) = _create_samplers( part_train_eval_cd=part_train_eval_cd, part_val_cd=part_val_cd, unpart_cd=unpart_cd, test_cd=test_cd, part_clients_per_eval=part_clients_per_eval, unpart_clients_per_eval=unpart_clients_per_eval, test_clients_for_eval=test_clients_for_eval, resample_eval_clients=resample_eval_clients, eval_clients_random_seed=eval_clients_random_seed) evaluate_fn = eval_metric_distribution.create_federated_eval_distribution_fn( model_fn=tff_model_builder, metrics_builder=metrics_builder, stat_fns=stat_fns) def part_train_eval_fn(state: ServerState, round_num: int) -> MetricsDictType: if round_num % rounds_per_eval == 0: return evaluate_fn(state.model, next(part_train_eval_sampler)) else: return collections.OrderedDict() def part_val_fn(state: ServerState, round_num: int) -> MetricsDictType: if round_num % rounds_per_eval == 0: return evaluate_fn(state.model, next(part_val_sampler)) else: return collections.OrderedDict() def unpart_fn(state: ServerState, round_num: int) -> MetricsDictType: if round_num % rounds_per_eval == 0: return evaluate_fn(state.model, next(unpart_sampler)) else: return collections.OrderedDict() if test_sampler is not None: def test_fn(state: ServerState, round_num: int = 0) -> MetricsDictType: # test_fn does not need round_num. We define to keep interface consistent. del round_num return evaluate_fn(state.model, next(test_sampler)) else: test_fn = None return part_train_eval_fn, part_val_fn, unpart_fn, test_fn def create_centralized_eval_fns( *, # Caller passes below args by name. tff_model_builder: FederatedModelFnType, metrics_builder: Callable[[], List[tf.keras.metrics.Metric]], part_train_eval_cd: ClientData, part_val_cd: ClientData, unpart_cd: ClientData, test_cd: Optional[ClientData], stat_fns: Dict[str, StatFnType], part_clients_per_eval: Optional[int], unpart_clients_per_eval: Optional[int], test_clients_for_eval: Optional[int], resample_eval_clients: bool, eval_clients_random_seed: Optional[int], ) -> Tuple[CentralizedEvalFnType, CentralizedEvalFnType, CentralizedEvalFnType, CentralizedEvalFnType]: """Create centralized evaluation functions: train_eval, validation and test. Args: tff_model_builder: A callable with no args that returns a `tff.learning.Model`. metrics_builder: A callable with no args that returns a list of keras metrics. part_train_eval_cd: Preprocessed training chunk of for training ClientData used for evaluation. part_val_cd: Preprocessed validation chunk of training ClientData. unpart_cd: Preprocessed validation ClientData. test_cd: Optional preprocessed ClientData for test after training. If None, the test function will not be constructed, and None value will be returned at the position of test function. stat_fns: A mapping in which each key-value pair represents a custom statistic to be evaluated on the client metrics. Each pair consists of a string-typed key describing this statistic, and a callable-typed value that computes the statistic of metrics. The callable value should accept two sequence-typed arguments `all_clients_this_metric` and `all_clients_num_examples` and returns the corresponding statistics. part_clients_per_eval: An optional integer representing the number of training clients taken from training dataset for evaluation per round. If `None`, all training clients will be used. unpart_clients_per_eval: An optional integer representing the number of clients taken from validation dataset. If `None`, all validation clients will be used. test_clients_for_eval: An optional integer representing the number of clients taken from test dataset. If `None`, all test clients will be used. resample_eval_clients: A bool used to decide whether or not to resample validation clients every evaluation round. eval_clients_random_seed: An optional integer used to seed which validation and test clients are sampled. If `None`, no seed is used. Returns: Centralized train_eval fn, validation fn and test fn, all of type CentralizedEvalFnType. """ (part_train_eval_sampler, part_val_sampler, unpart_sampler, test_sampler) = _create_samplers( part_train_eval_cd=part_train_eval_cd, part_val_cd=part_val_cd, unpart_cd=unpart_cd, test_cd=test_cd, part_clients_per_eval=part_clients_per_eval, unpart_clients_per_eval=unpart_clients_per_eval, test_clients_for_eval=test_clients_for_eval, resample_eval_clients=resample_eval_clients, eval_clients_random_seed=eval_clients_random_seed) evaluate_fn = eval_metric_distribution.create_federated_eval_distribution_fn( model_fn=tff_model_builder, metrics_builder=metrics_builder, stat_fns=stat_fns) def part_train_eval_fn(keras_model: tf.keras.Model) -> MetricsDictType: return evaluate_fn( tff.learning.ModelWeights.from_model(keras_model), next(part_train_eval_sampler)) def part_val_fn(keras_model: tf.keras.Model) -> MetricsDictType: return evaluate_fn( tff.learning.ModelWeights.from_model(keras_model), next(part_val_sampler)) def unpart_fn(keras_model: tf.keras.Model) -> MetricsDictType: return evaluate_fn( tff.learning.ModelWeights.from_model(keras_model), next(unpart_sampler)) if test_sampler is not None: def test_fn(keras_model: tf.keras.Model) -> MetricsDictType: return evaluate_fn( tff.learning.ModelWeights.from_model(keras_model), next(test_sampler)) else: test_fn = None return part_train_eval_fn, part_val_fn, unpart_fn, test_fn
import { TreeGrid, Reorder as TreeGridReorder } from '@syncfusion/ej2-treegrid'; /** * To handle column reorder action from TreeGrid */ var Reorder = /** @class */ (function () { function Reorder(gantt) { this.parent = gantt; TreeGrid.Inject(TreeGridReorder); this.parent.treeGrid.allowReordering = this.parent.allowReordering; this.bindEvents(); } /** * Get module name */ Reorder.prototype.getModuleName = function () { return 'reorder'; }; /** * To bind reorder events. * @return {void} * @private */ Reorder.prototype.bindEvents = function () { var _this = this; this.parent.treeGrid.columnDragStart = function (args) { _this.parent.trigger('columnDragStart', args); }; this.parent.treeGrid.columnDrag = function (args) { _this.parent.trigger('columnDrag', args); }; this.parent.treeGrid.columnDrop = function (args) { _this.parent.trigger('columnDrop', args); }; }; /** * To destroy the column-reorder. * @return {void} * @private */ Reorder.prototype.destroy = function () { // Destroy Method }; return Reorder; }()); export { Reorder };
from flask import Flask, request from flask_restful import Api, Resource import json import cal_id from models import db, Like class LikeList(Resource): def get_likes(self): likes = Like.query.all() return likes def get(self): likes = self.get_likes() ret = '' for like in likes: ret += '[user_id: {}, article_id: {}]'.format(like.user_id, like.article_id) return ret def post(self): r_json = request.get_json() user_id = r_json['user_id'] article_id = r_json['article_id'] like = Like.query.filter(user_id == user_id and article_id == article_id).first() if like: return 'Unlike successfully' new_like = Like(user_id, article_id) db.session.add(new_like) db.session.commit() return 'Like successfully'
import re import ast from setuptools import find_packages _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('vnc_viewer/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) from distutils.core import setup setup( name = 'vnc_viewer', version = version, url = '', license = '', author = 'a.biryukov', include_package_data=True, packages = find_packages(), package_data = {'templates': ['*.html', 'static/*.js', 'static/*.css', 'static/*.png'],}, author_email = 'feano4ik@gmail.com', description = '', install_requires = ['libvirt-python', 'flask', 'websockify', ], entry_points = { 'console_scripts': [ 'vnc_daemon=vnc_viewer.engine:main' ], } )
# coding=utf-8 # Copyright 2019 The Google Research Authors. # # 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. """Defines VariableMgr and subclasses used to manage variables. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib import re import tensorflow as tf from cnn_quantization.tf_cnn_benchmarks import allreduce from cnn_quantization.tf_cnn_benchmarks import batch_allreduce from cnn_quantization.tf_cnn_benchmarks import variable_mgr_util class VariableMgr(object): """Abstract superclass for class used by BenchmarkCNN to control variables. Functions on this class are used to control how variables are created and managed, and how gradients are computed and applied. """ def __init__(self, benchmark_cnn): self.benchmark_cnn = benchmark_cnn self.staging_delta_ops = [] self.use_resource_vars = benchmark_cnn.params.use_resource_vars # A variable for automatic loss scaling. self.grad_has_inf_nan = None self._reuse_vars = False def each_tower_has_variables(self): """Returns True if each GPU tower of the model has separate variables.""" assert False, 'Must be implemented in subclass' def supports_staged_vars(self): """Whether staged variable management is supported.""" return False def create_outer_variable_scope(self, device_num): """Create the tf.variable_scope around all model graph operations.""" del device_num # unused by this implementation assert False, 'Must be implemented in subclass' def preprocess_device_grads(self, device_grads): """Preprocess the device gradients prior to applying them. Args: device_grads: List of lists of (gradient, variable) tuples. device_grads[t][g] = (gradient, variable), where t is the index of the tower and g is the index of the gradient-variable pair. Returns: a tuple of (apply_gradients_devices, gradient_state). gradient_state is an opaque structure that should be passed to get_gradients_to_apply() and append_apply_gradients_ops() (in that order). apply_gradients_devices is a list of devices where the gradients will be applied with get_gradients_to_apply() and append_apply_gradients_ops(). """ del device_grads # unused by this implementation assert False, 'Must be implemented in subclass' def get_gradients_to_apply(self, device_num, gradient_state): """Returns the [(gradient, variable)] list to apply for device_num. Args: device_num: indexes into apply_gradients_devices, which was returned by an earlier call to preprocess_device_grads. gradient_state: from previous call to apply_gradients_devices. """ del device_num, gradient_state # unused by this implementation assert False, 'Must be implemented in subclass' def append_apply_gradients_ops(self, gradient_state, opt, grads, training_ops, loss_scale_params): """Adds training ops for grads to 'training_ops'. Args: gradient_state: from previous call to apply_gradients_devices. opt: the underlying optimizer grads: [(grad, var)] to apply training_ops: list to which to add ops loss_scale_params: parameters for loss scaling. """ del gradient_state # unused by this implementation def get_apply_gradients_ops_func(): """Returns the apply_gradients op.""" return [opt.apply_gradients(grads)] variable_mgr_util.append_gradients_with_loss_scale( training_ops, get_apply_gradients_ops_func, loss_scale_params, self.grad_has_inf_nan) def get_post_init_ops(self): """Returns ops that should run post-initialization.""" return [] def get_devices(self): """Returns devices to use for computation; includes replica selection.""" assert False, 'Must be implemented in subclass' def savable_variables(self): """Returns a list/dict of savable variables to pass to tf.train.Saver.""" return tf.global_variables() def trainable_variables_on_device(self, rel_device_num, abs_device_num, writable=False): """Return the set of trainable variables on device. Args: rel_device_num: local worker device index. abs_device_num: global graph device index. writable: whether to get a reference to the underlying variable. Returns: The set of trainable variables on the specified device. """ del rel_device_num, writable if self.each_tower_has_variables(): params = [ v for v in tf.trainable_variables() if v.name.startswith('v%s/' % abs_device_num) ] else: params = tf.trainable_variables() return params @contextlib.contextmanager def reuse_variables(self): """Context manager that causes variables requested to be reused. Variables requested under this context manager must already exist, and will be reused instead of being created again. This should be used if the evaluation model is being built after the training model has already been built. This is because the evaluation model should reuse variables from the training model. Yields: Nothing. """ old_reuse_vars = self._reuse_vars try: self._reuse_vars = True yield finally: self._reuse_vars = old_reuse_vars class VariableMgrIndependent(VariableMgr): """VariableMgr that implements the --independent mode for local jobs. Each GPU has its own copy of the variables, and gradients are not shared between towers. This can be used to check performance when no data is moved between GPUs. """ def each_tower_has_variables(self): return True def create_outer_variable_scope(self, device_num): return tf.variable_scope('v%s' % device_num, reuse=self._reuse_vars, use_resource=self.use_resource_vars) def preprocess_device_grads(self, device_grads): return (self.benchmark_cnn.devices, device_grads) def get_gradients_to_apply(self, device_num, gradient_state): device_grads = gradient_state tower_grad = device_grads[device_num] if self.benchmark_cnn.enable_auto_loss_scale and device_num == 0: # Since we don't aggregate variables in --independent mode, we cannot tell # if there are NaNs on all GPUs. So we arbitrarily choose to only check # NaNs on the first GPU. has_inf_nan_list = [] for grad, _ in tower_grad: has_inf_nan_list.append(tf.reduce_all(tf.is_finite(grad))) self.grad_has_inf_nan = tf.logical_not(tf.reduce_all(has_inf_nan_list)) return tower_grad def get_devices(self): return self.benchmark_cnn.raw_devices class VariableMgrLocalFetchFromPS(VariableMgr): """VariableMgr that implements the --parameter_server mode for local jobs. Variables are stored on a parameter server. For each step, each tower gets a copy of the variables from the parameter server, and sends its gradients to the param server. """ def each_tower_has_variables(self): return False def create_outer_variable_scope(self, device_num): return tf.variable_scope('v', reuse=bool(device_num) or self._reuse_vars, use_resource=self.use_resource_vars) def preprocess_device_grads(self, device_grads): return ([self.benchmark_cnn.param_server_device], device_grads) def get_gradients_to_apply(self, device_num, gradient_state): assert device_num == 0 device_grads = gradient_state agg_grads, self.grad_has_inf_nan = ( variable_mgr_util. aggregate_gradients_using_copy_with_variable_colocation( device_grads, use_mean=True, check_inf_nan=self.benchmark_cnn.enable_auto_loss_scale)) return agg_grads def get_devices(self): raw_devices = self.benchmark_cnn.raw_devices if self.benchmark_cnn.local_parameter_device_flag == 'gpu': return [ variable_mgr_util.ParamServerDeviceSetter(d, raw_devices) for d in raw_devices ] else: return [ tf.train.replica_device_setter( worker_device=d, ps_device=self.benchmark_cnn.param_server_device, ps_tasks=1) for d in raw_devices ] class VariableMgrLocalFetchFromStagedPS(VariableMgrLocalFetchFromPS): """Implements fetching a local variable through staging buffers. """ def __init__(self, benchmark_cnn): super(VariableMgrLocalFetchFromStagedPS, self).__init__(benchmark_cnn) # A data structure to track where the variables are used on each device. # Indexed by device_num and var_name, each entry stores the "put" and "get" # ops used for that variable on that device: # staging_vars_on_devices[device_num][var_name] == (put_op, get_op) self.staging_vars_on_devices = [ dict() for _ in self.benchmark_cnn.raw_devices ] def supports_staged_vars(self): return True def create_outer_variable_scope(self, device_num): self._custom_getter = variable_mgr_util.StagedVariableGetter( device_num, self.benchmark_cnn.raw_devices, None, self) return tf.variable_scope( 'v', reuse=bool(device_num) or self._reuse_vars, custom_getter=self._custom_getter, use_resource=self.use_resource_vars) def trainable_variables_on_device(self, rel_device_num, abs_device_num, writable=False): return self._custom_getter.trainable_variables_on_device( rel_device_num, abs_device_num, writable=writable) class VariableMgrLocalReplicated(VariableMgr): """VariableMgr that implements the --replicated mode for local jobs. Each GPU has its own copy of the variables. To apply gradients, either a local all-reduce algorithm is applied or a regular cross-device aggregation is used to replicate the combined gradients to all towers. """ def __init__(self, benchmark_cnn, all_reduce_spec, agg_small_grads_max_bytes, agg_small_grads_max_group, allreduce_merge_scope): super(VariableMgrLocalReplicated, self).__init__(benchmark_cnn) if all_reduce_spec: spec = allreduce.parse_all_reduce_spec(all_reduce_spec) if len(spec) != 1: raise ValueError( 'replicated mode does not support hybrid all-reduce strategies') self._all_reduce_spec = spec[0] else: self._all_reduce_spec = None self._agg_small_grads_max_bytes = agg_small_grads_max_bytes self._agg_small_grads_max_group = agg_small_grads_max_group self._warmup_ops = [] self._allreduce_merge_scope = allreduce_merge_scope self._gradient_put_ops = None def each_tower_has_variables(self): return True def create_outer_variable_scope(self, device_num): return tf.variable_scope('v%s' % device_num, reuse=self._reuse_vars, use_resource=self.use_resource_vars) def preprocess_device_grads(self, device_grads): compact_grads = (self.benchmark_cnn.params.use_fp16 and self.benchmark_cnn.params.compact_gradient_transfer) defer_grads = (self.benchmark_cnn.params.variable_consistency == 'relaxed') grads_to_reduce = [[g for g, _ in grad_vars] for grad_vars in device_grads] algorithm = batch_allreduce.algorithm_from_params(self.benchmark_cnn.params) reduced_grads, self._warmup_ops = algorithm.batch_all_reduce( grads_to_reduce, self.benchmark_cnn.params.gradient_repacking, compact_grads, defer_grads, self.benchmark_cnn.params.xla_compile) if self.benchmark_cnn.enable_auto_loss_scale: # Check for infs or nans is_finite_list = [] with tf.name_scope('check_for_inf_and_nan'): for tower_grads in reduced_grads: with tf.colocate_with(tower_grads[0]): # TODO(tanmingxing): Create fused op that takes in a list of tensors # as input and returns scalar boolean True if there are any # infs/nans. is_finite_list.append(tf.reduce_all( [tf.reduce_all(tf.is_finite(g)) for g in tower_grads])) self.grad_has_inf_nan = tf.logical_not(tf.reduce_all(is_finite_list)) reduced_device_grads = [[ (g, v) for g, (_, v) in zip(grads, grad_vars) ] for grads, grad_vars in zip(reduced_grads, device_grads)] return self.benchmark_cnn.devices, reduced_device_grads def get_gradients_to_apply(self, device_num, gradient_state): device_grads = gradient_state return device_grads[device_num] def get_post_init_ops(self): # Copy initialized values for variables on GPU 0 to other GPUs. global_vars = tf.global_variables() var_by_name = dict([(v.name, v) for v in global_vars]) post_init_ops = [] for v in global_vars: split_name = v.name.split('/') # TODO(b/62630508): use more specific prefix than v or v0. if split_name[0] == 'v0' or not v.name.startswith('v'): continue split_name[0] = 'v0' copy_from = var_by_name['/'.join(split_name)] post_init_ops.append(v.assign(copy_from.read_value())) post_init_ops += self._warmup_ops return post_init_ops def savable_variables(self): """Return the set of variables used for saving/loading the model.""" params = [] for v in tf.global_variables(): split_name = v.name.split('/') if split_name[0] == 'v0' or not v.name.startswith('v'): params.append(v) return params def get_devices(self): return self.benchmark_cnn.raw_devices class VariableMgrDistributedAllReduce(VariableMgr): """VariableMgr that implements the --distributed_all_reduce mode. Each GPU has its own copy of the variables. To apply gradients, the specified all-reduce algorithm is used to reduce the gradients and replicate the final value to all GPUs. """ def __init__(self, benchmark_cnn, all_reduce_spec, job_name, num_workers, agg_small_grads_max_bytes, agg_small_grads_max_group, allreduce_merge_scope): super(VariableMgrDistributedAllReduce, self).__init__(benchmark_cnn) if not all_reduce_spec: raise ValueError( 'distributed_all_reduce requires a non-empty all_reduce_spec') self._all_reduce_spec = allreduce.parse_all_reduce_spec(all_reduce_spec) self._all_reduce_device_prefixes = ( allreduce.build_all_reduce_device_prefixes(job_name, num_workers)) self._num_workers = num_workers self._agg_small_grads_max_bytes = agg_small_grads_max_bytes self._agg_small_grads_max_group = agg_small_grads_max_group self._allreduce_merge_scope = allreduce_merge_scope if not self._all_reduce_spec: raise ValueError('all_reduce_spec must be specified') self._single_session = True def each_tower_has_variables(self): return True def create_outer_variable_scope(self, device_num): """Create a scope for the named device. Args: device_num: index of device for variable scope. (Note that device_num spans all processes in cluster since a single global graph is used.) Returns: the requested variable_scope """ return tf.variable_scope('v%s' % device_num, reuse=self._reuse_vars, use_resource=self.use_resource_vars) def preprocess_device_grads(self, device_grads): remaining_grads = device_grads aggregated_grads = [] for spec_tuple in self._all_reduce_spec: if spec_tuple.limit < 0: this_grads = remaining_grads remaining_grads = [] else: (this_grads, remaining_grads) = allreduce.split_grads_by_size( spec_tuple.limit, remaining_grads) if this_grads: range_agg_grads = allreduce.sum_gradients_all_reduce( self._single_session, self._all_reduce_device_prefixes, this_grads, self._num_workers, spec_tuple.alg, spec_tuple.shards, self.benchmark_cnn.gpu_indices, agg_small_grads_max_bytes=self._agg_small_grads_max_bytes, agg_small_grads_max_group=self._agg_small_grads_max_group, allreduce_merge_scope=self._allreduce_merge_scope) if not aggregated_grads: aggregated_grads = range_agg_grads else: assert len(aggregated_grads) == len(range_agg_grads) for i in range(len(aggregated_grads)): aggregated_grads[i] += range_agg_grads[i] assert not remaining_grads full_device_set = [] for grads in device_grads: g, v = grads[0] del v full_device_set.append(g.device) return (full_device_set, aggregated_grads) def get_gradients_to_apply(self, device_num, gradient_state): device_grads = gradient_state if device_num >= len(device_grads): raise ValueError('device_num %d exceeds length of device_grads (%d)' % (device_num, len(device_grads))) return device_grads[device_num] def get_post_init_ops(self): """Copy initialized values for variables to other devices.""" global_vars = tf.global_variables() var_by_name = dict([(v.name, v) for v in global_vars]) post_init_ops = [] for v in global_vars: split_name = v.name.split('/') # TODO(b/62630508): use more specific prefix than v or v0. if split_name[0] == 'v0' or not v.name.startswith('v'): continue split_name[0] = 'v0' copy_from = var_by_name['/'.join(split_name)] post_init_ops.append(v.assign(copy_from.read_value())) return post_init_ops def savable_variables(self): """Return the set of variables used for saving/loading the model.""" params = [] for v in tf.global_variables(): split_name = v.name.split('/') if split_name[0] == 'v0' or not v.name.startswith('v'): params.append(v) return params def get_devices(self): return self.benchmark_cnn.raw_devices # TODO(tucker): Merge this mode with DistributedAllReduce. class VariableMgrCollectiveAllReduce(VariableMgr): """VariableMgr that implements the --collective_all_reduce mode. Each GPU has its own copy of the variables. To apply gradients the TF native collective all-reduce op is used to reduce the gradients and replicate the final value to all GPUs. """ def __init__(self, benchmark_cnn, all_reduce_spec, num_workers, num_gpus, task_id, allreduce_merge_scope): super(VariableMgrCollectiveAllReduce, self).__init__(benchmark_cnn) if not all_reduce_spec: raise ValueError( 'collective_all_reduce requires a non-empty all_reduce_spec: %s' % all_reduce_spec) parsed_spec = allreduce.parse_all_reduce_spec(all_reduce_spec) # So far we only support a length-1 all_reduce_spec if len(parsed_spec) > 1 or parsed_spec[0].limit > 0: raise ValueError( 'collective_all_reduce requires one single-range all_reduce_spec %s' % parsed_spec) self._all_reduce_spec = parsed_spec[0] if self._all_reduce_spec.alg != 'collective': raise ValueError( 'VariableMgrCollectiveAllReduce initialized with non-collective ' 'all_reduce_spec %s' % self.all_reduce_spec) self._num_workers = num_workers self._num_gpus = num_gpus self._task_id = task_id self._allreduce_merge_scope = allreduce_merge_scope self._instance_key_counter = 10000 self._instance_key_table = dict() self._single_session = False # List of prefixes for generating PS devices, unused here. self._all_reduce_device_prefixes = None def each_tower_has_variables(self): return True def create_outer_variable_scope(self, device_num): """Create a scope for the named device. Args: device_num: index of device for variable scope. Returns: the requested variable_scope """ return tf.variable_scope('v%s' % device_num, reuse=self._reuse_vars) def preprocess_device_grads(self, device_grads): reduced_grads = allreduce.sum_gradients_all_reduce( self._single_session, self._all_reduce_device_prefixes, device_grads, self._num_workers, 'collective', self._all_reduce_spec.shards, self.benchmark_cnn.gpu_indices, allreduce_merge_scope=self._allreduce_merge_scope) assert len(reduced_grads) == len(device_grads) full_device_set = [] for grads in device_grads: g, _ = grads[0] full_device_set.append(g.device) return (full_device_set, reduced_grads) def get_gradients_to_apply(self, device_num, gradient_state): device_grads = gradient_state if device_num >= len(device_grads): raise ValueError('device_num %d exceeds length of device_grads (%d)' % (device_num, len(device_grads))) return device_grads[device_num] def _get_instance_key(self, name): if name not in self._instance_key_table.keys(): self._instance_key_counter += 1 self._instance_key_table[name] = self._instance_key_counter return self._instance_key_table[name] def get_post_init_ops(self): """Broadcast initialized values of variables to other devices. Returns: At task 0 device 0, broadcast_send. At all other devices and tasks, broadcast_recv. """ global_vars = tf.global_variables() group_size = self._num_workers * self._num_gpus post_init_ops = [] # Gather variables into same-var-different-device groups. vars_by_suffix = dict() for v in global_vars: split_name = v.name.split('/') mo = re.match(r'v(\d+)$', split_name[0]) if mo: device_id = int(mo.group(1)) suffix = '/'.join(split_name[1:]) if suffix in vars_by_suffix.keys(): vars_by_suffix[suffix].append(v) else: vars_by_suffix[suffix] = [v] # Generate broadcast ops for each such group. for suffix in sorted(vars_by_suffix): vlist = vars_by_suffix[suffix] assert self._num_gpus == len(vlist) devices = [v.device for v in vlist] # NOTE: this key should generate the same value for all tasks group_key = allreduce.collective_group_key(devices) group_size = self._num_workers * len(devices) instance_key = self._get_instance_key(suffix) for v in vlist: split_name = v.name.split('/') mo = re.match(r'v(\d+)$', split_name[0]) if mo: device_id = int(mo.group(1)) if (self._task_id == 0 and device_id == 0): with tf.device(v.device): bcast_send = allreduce.broadcast_send( v, v.shape, v.dtype, group_size, group_key, instance_key) post_init_ops.append(v.assign(bcast_send)) else: with tf.device(v.device): bcast_recv = allreduce.broadcast_recv( v.shape, v.dtype, group_size, group_key, instance_key) post_init_ops.append(v.assign(bcast_recv)) return post_init_ops def savable_variables(self): """Return the set of variables used for saving/loading the model.""" params = [] if self._task_id == 0: for v in tf.global_variables(): split_name = v.name.split('/') if split_name[0] == 'v0' or not v.name.startswith('v'): params.append(v) return params def get_devices(self): return self.benchmark_cnn.raw_devices class VariableMgrDistributedFetchFromPS(VariableMgr): """Implements --variable_update=parameter_server mode for distributed jobs. Variables are stored on a parameter server. For each step, each tower gets a copy of the variables from the parameter server, and sends its gradients to the param server. """ def each_tower_has_variables(self): return False def create_outer_variable_scope(self, device_num): if self.benchmark_cnn.local_parameter_device_flag == 'gpu': caching_devices = self.benchmark_cnn.raw_devices else: caching_devices = [self.benchmark_cnn.cpu_device] custom_getter = variable_mgr_util.OverrideCachingDevice( caching_devices, self.benchmark_cnn.cpu_device, 1024 * 64) return tf.variable_scope( 'v', reuse=bool(device_num) or self._reuse_vars, custom_getter=custom_getter, use_resource=self.use_resource_vars) def preprocess_device_grads(self, device_grads): # Returns (gradient_devices, gradient_state) return ([self.benchmark_cnn.param_server_device], device_grads) def get_gradients_to_apply(self, device_num, gradient_state): assert device_num == 0 agg_grads, self.grad_has_inf_nan = ( variable_mgr_util.aggregate_gradients_using_copy( gradient_state, use_mean=True, check_inf_nan=self.benchmark_cnn.enable_auto_loss_scale)) return agg_grads def get_devices(self): ps_strategy = tf.contrib.training.GreedyLoadBalancingStrategy( self.benchmark_cnn.num_ps, tf.contrib.training.byte_size_load_fn) return [ tf.train.replica_device_setter( worker_device=d, cluster=self.benchmark_cnn.cluster_manager.get_cluster_spec(), ps_strategy=ps_strategy) for d in self.benchmark_cnn.raw_devices ] class VariableMgrDistributedFetchFromStagedPS( VariableMgrDistributedFetchFromPS): """Extends VariableMgrDistributedFetchFromPS for --staged_vars.""" def __init__(self, benchmark_cnn): super(VariableMgrDistributedFetchFromStagedPS, self).__init__(benchmark_cnn) self.staging_vars_on_devices = [ dict() for _ in self.benchmark_cnn.raw_devices ] self.staged_vars_on_cpu = {} def create_outer_variable_scope(self, device_num): self._custom_getter = variable_mgr_util.StagedVariableGetter( device_num, self.benchmark_cnn.raw_devices, self.benchmark_cnn.cpu_device, self) return tf.variable_scope( 'v', reuse=bool(device_num) or self._reuse_vars, custom_getter=self._custom_getter, use_resource=self.use_resource_vars) def supports_staged_vars(self): return True def trainable_variables_on_device(self, rel_device_num, abs_device_num, writable=False): return self._custom_getter.trainable_variables_on_device( rel_device_num, abs_device_num, writable=writable) class VariableMgrDistributedReplicated(VariableMgr): """VariableMgr that implements the --distributed_replicated mode. Each GPU has a copy of the variables, and updates its copy after the parameter servers are all updated with the gradients from all servers. Only works with cross_replica_sync=true. Unlike 'replicated', does not use nccl all-reduce for replicating within a server. """ def each_tower_has_variables(self): return True def create_outer_variable_scope(self, device_num): return tf.variable_scope( 'v%s' % device_num, reuse=self._reuse_vars, custom_getter=variable_mgr_util.OverrideToLocalVariableIfNotPsVar(), use_resource=self.use_resource_vars) def preprocess_device_grads(self, device_grads): return ([self.benchmark_cnn.param_server_device], device_grads) def get_gradients_to_apply(self, device_num, gradient_state): device_grads = gradient_state # From 2nd result of preprocess_device_grads. avg_grads, self.grad_has_inf_nan = ( variable_mgr_util.aggregate_gradients_using_copy_with_device_selection( self.benchmark_cnn, device_grads, use_mean=True, check_inf_nan=self.benchmark_cnn.enable_auto_loss_scale)) # Make shadow variable on a parameter server for each original trainable # variable. for i, (g, v) in enumerate(avg_grads): my_name = variable_mgr_util.PS_SHADOW_VAR_PREFIX + '/' + v.name if my_name.endswith(':0'): my_name = my_name[:-2] new_v = tf.get_variable( my_name, dtype=v.dtype.base_dtype, initializer=v.initial_value, trainable=True) avg_grads[i] = (g, new_v) return avg_grads def append_apply_gradients_ops(self, gradient_state, opt, grads, training_ops, loss_scale_params): device_grads = gradient_state # From 2nd result of preprocess_device_grads. def get_apply_gradients_ops_func(): """Returns a list of ops for updating gradients.""" apply_gradients_ops = [] # For each variable, apply the combined gradients for this server on # the parameter server, and then wait for all other servers to do this. for i, (g, v) in enumerate(grads): apply_gradient_op = opt.apply_gradients([(g, v)]) barrier = self.benchmark_cnn.add_sync_queues_and_barrier( 'replicate_variable_%s' % i, [apply_gradient_op]) with tf.control_dependencies([barrier]): with tf.device(self.benchmark_cnn.cpu_device): updated_value = v.read_value() for my_d in range(len(self.benchmark_cnn.devices)): apply_gradients_ops.append( device_grads[my_d][i][1].assign(updated_value)) return apply_gradients_ops variable_mgr_util.append_gradients_with_loss_scale( training_ops, get_apply_gradients_ops_func, loss_scale_params, self.grad_has_inf_nan) def _strip_port(self, s): if s.endswith(':0'): return s[:-2] return s def get_post_init_ops(self): # Copy initialized variables for variables on the parameter server # to the local copy of the variable. local_vars = tf.local_variables() local_var_by_name = dict( [(self._strip_port(v.name), v) for v in local_vars]) post_init_ops = [] for v in tf.global_variables(): if v.name.startswith(variable_mgr_util.PS_SHADOW_VAR_PREFIX + '/v0/'): prefix = self._strip_port( v.name[len(variable_mgr_util.PS_SHADOW_VAR_PREFIX + '/v0'):]) for i in range(self.benchmark_cnn.num_gpus): name = 'v%s%s' % (i, prefix) if name in local_var_by_name: copy_to = local_var_by_name[name] post_init_ops.append(copy_to.assign(v.read_value())) return post_init_ops def _remove_shadow_var_prefix_if_present(self, var_name): if var_name.startswith(variable_mgr_util.PS_SHADOW_VAR_PREFIX + '/'): return var_name[len(variable_mgr_util.PS_SHADOW_VAR_PREFIX + '/'):] else: return var_name def var_dict_name(self, v): return self._strip_port(self._remove_shadow_var_prefix_if_present(v.name)) def savable_variables(self): """Returns a list/dict of savable variables to pass to tf.train.Saver.""" params = {} for v in tf.global_variables(): assert (v.name.startswith(variable_mgr_util.PS_SHADOW_VAR_PREFIX + '/v0/') or v.name in ('global_step:0', 'loss_scale:0', 'loss_scale_normal_steps:0')), ( 'Invalid global variable: %s' % v) # We store variables in the checkpoint with the shadow variable prefix # removed so we can evaluate checkpoints in non-distributed replicated # mode. The checkpoints can also be loaded for training in # distributed_replicated mode. name = self._strip_port(self._remove_shadow_var_prefix_if_present(v.name)) params[name] = v for v in tf.local_variables(): # Non-trainable variables, such as batch norm moving averages, do not have # corresponding global shadow variables, so we add them here. Trainable # local variables have corresponding global shadow variables, which were # added in the global variable loop above. if v.name.startswith('v0/') and v not in tf.trainable_variables(): params[self._strip_port(v.name)] = v return params def get_devices(self): return self.benchmark_cnn.raw_devices
from Simulator.UrdfWrapper import UrdfWrapper from Simulator.ObdlRender import ObdlRender from Simulator.ObdlSim import ObdlSim from jaxRBDL.Dynamics.ForwardDynamics import ForwardDynamics, ForwardDynamicsCore from envs.core import Env import gym import jax import jax.numpy as jnp from jax.api import jit from jaxRBDL.Dynamics.CompositeRigidBodyAlgorithm import CompositeRigidBodyAlgorithm from jaxRBDL.Dynamics.InverseDynamics import InverseDynamics from jax.numpy.linalg import inv from jaxRBDL.Contact.DetectContact import DetectContact from jaxRBDL.Contact.CalcContactForceDirect import CalcContactForceDirect from jaxRBDL.Contact.SolveContactLCP import SolveContactLCP # from jaxRBDL.Dynamics.ForwardDynamics import ForwardDynamics from jaxRBDL.Kinematics.CalcBodyToBaseCoordinates import CalcBodyToBaseCoordinates class Qaudrupedal(Env): """ Description: A quadrupedal robot(UNITREE) environment. The robot has totally 14 joints, the previous two are one virtual joint and a base to chasis joint. """ def __init__(self, reward_fn=None, seed=0): self.dt = 2e-03 self.q_threshold = 1.0 self.qdot_threshold = 1000 self.target = jnp.zeros(14) self.target = jax.ops.index_update(self.target, 1, 1.57) #joint number 6,9 front and rear left leg lift up # self.target = jax.ops.index_update(self.target, 6, 0.9) # self.target = jax.ops.index_update(self.target, 9, 0.9) self.qdot_target = jnp.zeros(14) model = UrdfWrapper("urdf/laikago/laikagolow.urdf").model model["jtype"] = jnp.asarray(model["jtype"]) model["parent"] = jnp.asarray(model["parent"]) self.model = model # self.osim = ObdlSim(self.model,dt=self.dt,vis=True) self.rder = ObdlRender(self.model) # @jit def _dynamics(state, action): q, qdot = state torque = action/20 # # print("q",q) # # print("qdot",qdot) # # print("torque",torque) # input = (self.model, q, qdot, torque) # qddot = ForwardDynamics(*input) # qddot = qddot.flatten() # # print("qddot",qddot) # #step one forward # # for j in range(2,14): # # q[j] = q[j] + dt * qdot[j] # # qdot[j] = qdot[j] + dt * accelerations[j] # for i in range(2,14): # q = jax.ops.index_add(q, i, self.dt * qdot[i]) # qdot = jax.ops.index_add(qdot, i, self.dt * qddot[i]) _X = jnp.hstack((q,qdot)) _model = self.model _model['tau'] = torque _model['ST'] = jnp.zeros((3,)) # useless NB = int(_model["NB"]) NC = int(_model["NC"]) ST = _model["ST"] # Get q qdot tau q = _X[0:NB] qdot = _X[NB: 2 * NB] tau = _model["tau"] # Calcualte H C model["H"] = CompositeRigidBodyAlgorithm(model, q) model["C"] = InverseDynamics(model, q, qdot, jnp.zeros((NB, 1))) model["Hinv"] = inv(model["H"]) contact_cond = dict() contact_cond["contact_pos_lb"] = jnp.array([0.0001, 0.0001, 0.0001]).reshape(-1, 1) contact_cond["contact_pos_ub"] = jnp.array([0.0001, 0.0001, 0.0001]).reshape(-1, 1) contact_cond["contact_vel_lb"] = jnp.array([-0.05, -0.05, -0.05]).reshape(-1, 1) contact_cond["contact_vel_ub"] = jnp.array([0.01, 0.01, 0.01]).reshape(-1, 1) #forward dynamics T = self.dt contact_force = dict() model["contact_cond"] = contact_cond # Calculate contact force in joint space # flag_contact = DetectContact(model, q, qdot, contact_cond) flag_contact_tuple = DetectContact(model, q, qdot) flag_contact_list = [] flag_contact_list.append(flag_contact_tuple) print("flag_contact_list",flag_contact_list) flag_contact = jnp.array(flag_contact_list).flatten() print("flag_contact",flag_contact) # print("In Dynamics!!!") # print(flag_contact) if jnp.sum(flag_contact) !=0: # lambda, fqp, fpd] = SolveContactLCP(q, qdot, tau, flag_contact); # lam, fqp, fc, fcqp, fcpd = CalcContactForceDirect(_model, q, qdot, tau, flag_contact, 2) lam, fqp, fc, fcqp, fcpd = SolveContactLCP(_model, q, qdot, tau, flag_contact,0.1) contact_force["fc"] = fc contact_force["fcqp"] = fcqp contact_force["fcpd"] = fcpd else: # print("No Conatact") lam = jnp.zeros((NB, 1)) contact_force["fc"] = jnp.zeros((3*NC, 1)) contact_force["fcqp"] = jnp.zeros((3*NC, 1)) contact_force["fcpd"] = jnp.zeros((3*NC, 1)) # Forward dynamics Tau = tau + lam qddot = ForwardDynamics(model, q, qdot, Tau).flatten() qdot_hat = qdot + qddot * T q_hat = q + qdot * T return jnp.array([q_hat, qdot_hat]) self.dynamics = _dynamics def reset(self): # q = jax.random.uniform( # self.random.get_key(), shape=(14,), minval=-0.05, maxval=0.05 # ) q = jnp.zeros(14) q = jax.ops.index_update(q, 1, 1.57) # qdot = jax.random.uniform( # self.random.get_key(), shape=(14,), minval=-0.05, maxval=0.05 # ) qdot = jnp.zeros(14) self.state = jnp.array([q,qdot]) return self.state def step(self, state, action): self.state = self.dynamics(state, action) q, qdot = self.state done = False # if (len(q[q>self.theta_threshold_radians]) >0): # print("q in done",q) # done = True reward = self.reward_func(self.state) if (len(qdot[qdot>self.qdot_threshold]) >0): # if (len(q[q>self.q_threshold]) >0): # print("q in done",q) done = True reward += 10 return self.state, reward, done, {} def reward_func(self,state): # # x, x_dot, theta, theta_dot = state # reward = state[0]**2 + (state[1])**2 + 100*state[2]**2 + state[3]**2 # # reward = jnp.exp(state[0])-1 + state[2]**2 + state[3]**2 q, qdot = state # reward = jnp.log(jnp.sum(jnp.square(q - self.target))) + jnp.log(jnp.sum(jnp.square(qdot - self.qdot_target))) # reward = jnp.log(jnp.sum(jnp.square(q - self.target))) reward = jnp.sum(jnp.square(q - self.target)) # reward = jnp.log((q[6]-0.9)**2) + jnp.log((q[9]-0.9)**2) return reward def osim_render(self): q, _ = self.state # print("q for render",q) self.rder.step_render(q)
$(document).ready(function(){ //$(document).on('keydown','.numonly',function(event) { // // Allow: backspace, delete, tab, escape, and enter // if( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || // // Allow: Num Pad Decimal // ( event.keyCode == 190 ) || // ( event.keyCode == 110 ) || // // Allow: Ctrl+A // (event.keyCode == 65 && event.ctrlKey === true) || // // Allow: home, end, left, right // (event.keyCode >= 35 && event.keyCode <= 39)) { // // let it happen, don't do anything // return; // }else{ // // Ensure that it is a number and stop the keypress // if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) { // event.preventDefault(); // } // } //}); //$('.numonly').maskNumber(); /** * Hiding Flash Messages */ $('div.alert').not('.alert-important').delay(3000).fadeOut(350); $('#flash-overlay-modal').modal({backdrop: 'static', keyboard: false}); // $('#flash-overlay-modal').modal(); /** * Retrieving Case */ if (window.location.pathname == '/' || window.location.pathname == '/home') { $.get('case-tracker/alerts', function(data, status) { if (!data.length) return; var $url = "/case-tracker"; var $currentCount = $("#total-no-of-notifications").text(); var $html = ''; $("#no-pending-notifications").hide(); $("#total-no-of-notifications").text(parseInt($currentCount) + data.length); $html = '<li>'; $html += '<a href="' + $url + '">'; $html += '<div> <i class="fa fa-balance-scale"></i>'; $html += " <strong style='color:red'>" +data.length + "</strong> case's with pending actions!"; $html += '</div>'; $html += '</a></li><li class="divider"></li>'; $(".dropdown-alerts").append($html); var isUserCaseWasNotified = $("#is_case_was_notified").val(); if (!isUserCaseWasNotified) { swal({ title: 'Pending Case Activity!', text: data.length + ' case(s) with pending actions!', type: 'warning', showCancelButton: true, confirmButtonColor: '#1c84c6', confirmButtonText: 'View', cancelButtonText: 'Close' }, function (isConfirm) { if (isConfirm) { window.location.href = $url; } }); } }); } }); // (function ($){ // $.fn.serializeAssoc = function(check = false, excludeFields = []){ // let fields = {}; // let toaster = []; // unmarker(this); // $.each(this.serializeArray(), function(key,item){ // if(check){ // toaster.push(excludeFields.filter(field => {return field == item.name}).length || item.value || sendError(item)); // } // fields[item.name] = item.value; // }); // return toaster.every(x => {return x && true }) ? fields : nofity(); // // }; // function nofity(){ // toastr['error']("Please fill up the red marked fields."); // return false; // } // function unmarker(elem){ // elem.on('click',function(){ // $(this).closest("div").removeClass('has-error'); // }); // } // function sendError(item){ // $(`[name=${item.name}`).closest("div").addClass('has-error'); // return false; // } // })(jQuery); // // jQuery.each( ["patch","put", "delete"], function( i, method ) { // jQuery[ method ] = function( url, data, callback, type ) { // if ( jQuery.isFunction( data ) ) { // type = type || callback; // callback = data; // data = undefined; // } // // return jQuery.ajax({ // url: url, // type: method, // dataType: type, // data: data, // success: callback // }); // }; // });
import { getMyTaskBar, myProjectItems, getLiaisonsViaPagination, deleteLiaison, updateLiaisonStatus, newLiaison, syncLiaisonBySirNo, getSingleLiaison, modifyLiaison, liaisonFileUpdate, getProjectMclDataStatistics, getSingleLiaisonBySlipNo, getMyMCL, getMyPCL, getMyApproval, getMyRelease, getMyConfirm } from '@/api/workbench'; import { getQaDetailByQaHead } from '@/api/qa'; import store from '..'; const state = { task_bar: {}, project_items: {}, slip_no_items: {}, slip_current_page: 1, slip_page_size: 10, slip_page_count: 1, slip_count: 0, slip_table: [], task_test_mcl: [], task_test_pcl: [], task_approval: [], task_confirm: [], task_confirm_detail: [], task_release: [] }; const mutations = { SET_TASK_BAR(state, task_bar) { state.task_bar = task_bar }, SET_PROJECT_ITEMS(state, project_items) { state.project_items = project_items }, SET_SLIP_NO_ITEMS(state, slip_no_items) { state.slip_no_items = slip_no_items }, SET_SLIP_CURRENT_PAGE(state, current_page) { state.slip_current_page = current_page }, SET_SLIP_PAGE_SIZE(state, page_size) { state.slip_page_size = page_size }, SET_SLIP_PAGE_COUNT(state) { var liaisonCount = state.slip_no_items.count var pageSize = state.slip_page_size var remainder = liaisonCount % pageSize state.slip_count = liaisonCount if (remainder === 0) { state.slip_page_count = liaisonCount / pageSize } else { state.slip_page_count = parseInt(liaisonCount / pageSize) + 1 } }, SET_SLIP_TABLE(state) { state.slip_table = [] var liaisons = state.slip_no_items.results; for (var i in liaisons) { var id = liaisons[i].id; var ftype = liaisons[i].ftype; var fstatus = liaisons[i].fstatus; var fslipno = liaisons[i].fslipno; var fbrief = liaisons[i].fbrief; var fplnstart = liaisons[i].fplnstart; var fplnend = liaisons[i].fplnend; var factstart = liaisons[i].factstart; var factend = liaisons[i].factend; var freleasedt = liaisons[i].freleasedt; var fodrno = liaisons[i].fodrno; var plan = fplnstart + ' ~ ' + fplnend; var actual = ''; if (fstatus === '1') { fstatus = '待办'; } else if (fstatus === '2') { fstatus = '进行中'; actual = factstart; } else if (fstatus === '3') { fstatus = '已完成'; actual = factstart + ' ~ ' + factend; } else if (fstatus === '4') { fstatus = '已发布'; actual = factstart + ' ~ ' + factend; } var liaison = { id: id, ftype: ftype, fstatus: fstatus, fslipno: fslipno, fbrief: fbrief, plan: plan, actual: actual, freleasedt: freleasedt, fodrno: fodrno }; state.slip_table.push(liaison); } }, SET_TASK_TEST_MCL(state, data) { state.task_test_mcl = data }, SET_TASK_TEST_PCL(state, data) { state.task_test_pcl = data }, SET_TASK_APPROVAL(state, data) { state.task_approval = data }, SET_TASK_CONFIRM(state, data) { state.task_confirm = data }, SET_CONFIRM_DETAIL(state, data) { for (var i in data) { if (data[i].fregression === 'Y') { data[i].fregression = '是'; } else { data[i].fregression = '否'; } if (data[i].fapproval === 'Y') { data[i].fapproval = '已审核'; } else { data[i].fapproval = '未审核'; } } state.task_confirm_detail = data }, SET_TASK_RELEASE(state, data) { state.task_release = data } }; const actions = { getMyTaskBar({ commit }) { return new Promise((resolve, reject) => { getMyTaskBar().then(response => { const { data } = response commit('SET_TASK_BAR', data) resolve(response) }).catch(error => { reject(error) }) }) }, refreshProjectItems({ commit }) { return new Promise((resolve, reject) => { myProjectItems() .then(response => { const { data } = response; commit('SET_PROJECT_ITEMS', data); resolve(data); }) .catch(error => { reject(error); }); }); }, getLiaisonsViaPagination({ commit, state }) { var page = store.getters.slip_current_page var size = store.getters.slip_page_size return new Promise((resolve, reject) => { getLiaisonsViaPagination(page, size) .then(response => { const { data } = response commit('SET_SLIP_NO_ITEMS', data) commit('SET_SLIP_PAGE_COUNT') commit('SET_SLIP_TABLE') resolve(data) }) .catch(error => { reject(error); }); }); }, deleteLiaison({ commit }, id) { return new Promise((resolve, reject) => { deleteLiaison(id).then(response => { store.dispatch('workbench/getLiaisonsViaPagination') store.dispatch('workbench/refreshProjectItems') resolve(response) }).catch(error => { reject(error) }) }) }, updateLiaisonStatus({ commit }, args) { return new Promise((resolve, reject) => { const { id, data } = args updateLiaisonStatus(id, data).then(response => { store.dispatch('workbench/getLiaisonsViaPagination') store.dispatch('workbench/refreshProjectItems') resolve(response) }).catch(error => { reject(error) }) }) }, newLiaison({ commit }, data) { return new Promise((resolve, reject) => { newLiaison(data).then(response => { store.dispatch('workbench/getLiaisonsViaPagination') store.dispatch('workbench/refreshProjectItems') resolve(response) }).catch(error => { reject(error) }) }) }, getSingleLiaison({ commit }, id) { return new Promise((resolve, reject) => { getSingleLiaison(id).then(response => { resolve(response) }).catch(error => { reject(error) }) }) }, modifyLiaison({ commit }, { id, data }) { return new Promise((resolve, reject) => { modifyLiaison(id, data).then(response => { store.dispatch('workbench/getLiaisonsViaPagination') store.dispatch('workbench/refreshProjectItems') resolve(response) }).catch(error => { reject(error) }) }) }, liaisonFileUpdate({ commit }, data) { return new Promise((resolve, reject) => { liaisonFileUpdate(data).then(response => { resolve(response) }).catch(error => { reject(error) }) }) }, syncLiaisonBySirNo({ commit }, sir_no) { return new Promise((resolve, reject) => { syncLiaisonBySirNo(sir_no).then(response => { resolve(response) }).catch(error => { reject(error) }) }) }, getProjectMclDataStatistics({ commit }, order_no) { return new Promise((resolve, reject) => { getProjectMclDataStatistics(order_no).then(response => { resolve(response) }).catch(error => { reject(error) }) }) }, getSingleLiaisonBySlipNo({ commit }, slip_no) { return new Promise((resolve, reject) => { getSingleLiaisonBySlipNo(slip_no).then(response => { resolve(response) }).catch(error => { reject(error) }) }) }, getMyMCL({ commit }) { return new Promise((resolve, reject) => { getMyMCL().then(response => { const { data } = response commit('SET_TASK_TEST_MCL', data) resolve(response) }).catch(error => { reject(error) }) }) }, getMyPCL({ commit }) { return new Promise((resolve, reject) => { getMyPCL().then(response => { const { data } = response commit('SET_TASK_TEST_PCL', data) resolve(response) }).catch(error => { reject(error) }) }) }, getMyApproval({ commit }) { return new Promise((resolve, reject) => { getMyApproval().then(response => { const { data } = response commit('SET_TASK_APPROVAL', data) resolve(response) }).catch(error => { reject(error) }) }) }, getMyConfirm({ commit }) { return new Promise((resolve, reject) => { getMyConfirm().then(response => { const { data } = response commit('SET_TASK_CONFIRM', data) resolve(response) }).catch(error => { reject(error) }) }) }, getMyConfirmDetail({ commit }, id) { return new Promise((resolve, reject) => { getQaDetailByQaHead(id).then(response => { const { data } = response commit('SET_CONFIRM_DETAIL', data) resolve(response) }) }) }, getMyRelease({ commit }) { return new Promise((resolve, reject) => { getMyRelease().then(response => { const { data } = response commit('SET_TASK_RELEASE', data) resolve(response) }).catch(error => { reject(error) }) }) } }; export default { namespaced: true, mutations, state, actions };
module.exports = new Date(1983, 0, 5)
import { createStore } from 'test/support/Helpers' import Model from 'app/model/Model' describe('Model – Inheritance - Relation instantiation', () => { it('should choose the appropriate STI model class when instantiating a belongsTo relation', () => { class Employee extends Model { static entity = 'employee' static fields () { return { id: this.attr(null), name: this.string(''), type: this.string('') } } static types () { return { boss: Boss } } } class Boss extends Employee { static entity = 'boss' static baseEntity = 'employee' } class Firm extends Model { static entity = 'firm' static fields () { return { id: this.attr(null), owner_id: this.attr(null), name: this.string(''), employees: this.hasMany(Employee, 'firm_id'), owner: this.belongsTo(Employee, 'owner_id') } } } createStore([ { model: Employee }, { model: Boss }, { model: Firm } ]) const firmData = { id: 1, name: 'VUEX ORM Ltd.', owner: { id: 'Jax', type: 'boss' } } const firm = new Firm(firmData) expect(firm.owner).toBeInstanceOf(Boss) }) it('should choose the appropriate STI model class when instantiating hasMany relations', () => { class Employee extends Model { static entity = 'employee' static fields () { return { id: this.attr(null), firm_id: this.attr(null), name: this.string(''), type: this.string('') } } static types () { return { HR: HumanResources, CEO: ChiefExecutiveOfficer } } } class HumanResources extends Employee { static entity = 'hr' static baseEntity = 'employee' } class ChiefExecutiveOfficer extends Employee { static entity = 'ceo' static baseEntity = 'employee' } class Firm extends Model { static entity = 'firm' static fields () { return { id: this.attr(null), name: this.string(''), employees: this.hasMany(Employee, 'firm_id') } } } createStore([ { model: Employee }, { model: HumanResources }, { model: ChiefExecutiveOfficer }, { model: Firm } ]) const firmData = { id: 1, name: 'VUEX ORM Ltd.', employees: [ { id: 1, name: 'John', type: 'HR' }, { id: 2, name: 'Jane', type: 'CEO' } ] } const firm = new Firm(firmData) expect(firm.employees.find(({ id }) => id === 1)).toBeInstanceOf(HumanResources) expect(firm.employees.find(({ id }) => id === 2)).toBeInstanceOf(ChiefExecutiveOfficer) }) it('should choose the appropriate STI model class when instantiating a morphTo relation', () => { class User extends Model { static entity = 'user' static fields () { return { id: this.attr(null), name: this.string(''), image: this.morphOne(Image, 'imageable_id', 'imageable_type') } } static types () { return { admin: Admin, user: User } } } class Admin extends User { static entity = 'admin' static baseEntity = 'user' } class Image extends Model { static entity = 'image' static fields () { return { id: this.attr(null), url: this.attr(''), imageable_id: this.attr(null), imageable_type: this.attr(null), imageable: this.morphTo('imageable_id', 'imageable_type') } } } createStore([ { model: User }, { model: Admin }, { model: Image } ]) const imageData = { id: 1, url: 'myPng.gif', imageable_type: 'user', imageable: { id: 1, name: 'Jane', type: 'admin' } } const image = new Image(imageData) expect(image.imageable).toBeInstanceOf(Admin) }) })
app.controller('Authentication', function (store, authenticationAPI, $mdBottomSheet, $mdSidenav) { var viewModel = this viewModel.authenticate = function (user) { authenticationAPI.authenticate(user) .then(function (promise) { if (promise.user && promise.token) { viewModel.user = promise.user store.set('jwt', promise.token) } else { $mdToast.showSimple(promise.error) } }) } viewModel.register = function (user) { authenticationAPI.register(user) .then(function (promise) { if (promise.user && promise.token) { viewModel.user = promise.user store.set('jwt', promise.token) } else { $mdToast.showSimple(promise.error) } }) } viewModel.toggleLeftSidenav = function () { console.log('hey') $mdSidenav('sidenav-left').toggle() } // viewModel.unauthenticate = function () { // authenticationAPI.unauthenticate($scope.currentUser) // .then(function (promise) { // $scope.currentUser = promise.user // }) // } })
import { ZoomMtg } from "@zoomus/websdk"; console.log("checkSystemRequirements"); console.log(JSON.stringify(ZoomMtg.checkSystemRequirements())); // it's option if you want to change the WebSDK dependency link resources. setZoomJSLib must be run at first // if (!china) ZoomMtg.setZoomJSLib('https://source.zoom.us/1.9.0/lib', '/av'); // CDN version default // else ZoomMtg.setZoomJSLib('https://jssdk.zoomus.cn/1.9.0/lib', '/av'); // china cdn option // ZoomMtg.setZoomJSLib('http://localhost:9999/node_modules/@zoomus/websdk/dist/lib', '/av'); // Local version default, Angular Project change to use cdn version ZoomMtg.preLoadWasm(); ZoomMtg.prepareJssdk(); const API_KEY = "Ji6MIz8SRCS8Kt82RMMcAA"; /** * NEVER PUT YOUR ACTUAL API SECRET IN CLIENT SIDE CODE, THIS IS JUST FOR QUICK PROTOTYPING * The below generateSignature should be done server side as not to expose your api secret in public * You can find an eaxmple in here: https://marketplace.zoom.us/docs/sdk/native-sdks/Web-Client-SDK/tutorial/generate-signature */ const API_SECRET = "raaof6SKBey7QeaWUacMyQhbG5QgDos4Y7wI"; testTool = window.testTool; document.getElementById("display_name").value = "Local" + ZoomMtg.getJSSDKVersion()[0] + testTool.detectOS() + "#" + testTool.getBrowserInfo(); document.getElementById("meeting_number").value = testTool.getCookie( "meeting_number" ); document.getElementById("meeting_pwd").value = testTool.getCookie( "meeting_pwd" ); if (testTool.getCookie("meeting_lang")) document.getElementById("meeting_lang").value = testTool.getCookie( "meeting_lang" ); document.getElementById("meeting_lang").addEventListener("change", (e) => { testTool.setCookie( "meeting_lang", document.getElementById("meeting_lang").value ); ZoomMtg.i18n.load(document.getElementById("meeting_lang").value); ZoomMtg.i18n.reload(document.getElementById("meeting_lang").value); ZoomMtg.reRender({ lang: document.getElementById("meeting_lang").value }); }); // copy zoom invite link to mn, autofill mn and pwd. document .getElementById("meeting_number") .addEventListener("input", function (e) { let tmpMn = e.target.value.replace(/([^0-9])+/i, ""); if (tmpMn.match(/([0-9]{9,11})/)) { tmpMn = tmpMn.match(/([0-9]{9,11})/)[1]; } let tmpPwd = e.target.value.match(/pwd=([\d,\w]+)/); if (tmpPwd) { document.getElementById("meeting_pwd").value = tmpPwd[1]; testTool.setCookie("meeting_pwd", tmpPwd[1]); } document.getElementById("meeting_number").value = tmpMn; testTool.setCookie( "meeting_number", document.getElementById("meeting_number").value ); }); document.getElementById("clear_all").addEventListener("click", (e) => { testTool.deleteAllCookies(); document.getElementById("display_name").value = ""; document.getElementById("meeting_number").value = ""; document.getElementById("meeting_pwd").value = ""; document.getElementById("meeting_lang").value = "en-US"; document.getElementById("meeting_role").value = 0; window.location.href = "/index.html"; }); document.getElementById("join_meeting").addEventListener("click", (e) => { e.preventDefault(); const meetingConfig = testTool.getMeetingConfig(); if (!meetingConfig.mn || !meetingConfig.name) { alert("Meeting number or username is empty"); return false; } testTool.setCookie("meeting_number", meetingConfig.mn); testTool.setCookie("meeting_pwd", meetingConfig.pwd); const signature = ZoomMtg.generateSignature({ meetingNumber: meetingConfig.mn, apiKey: API_KEY, apiSecret: API_SECRET, role: meetingConfig.role, success: function (res) { console.log(res.result); meetingConfig.signature = res.result; meetingConfig.apiKey = API_KEY; const joinUrl = "/meeting.html?" + testTool.serialize(meetingConfig); console.log(joinUrl); window.open(joinUrl, "_blank"); }, }); }); function copyToClipboard(elementId) { var aux = document.createElement("input"); aux.setAttribute("value", document.getElementById(elementId).getAttribute('link')); document.body.appendChild(aux); aux.select(); document.execCommand("copy"); document.body.removeChild(aux); } // click copy jon link button window.copyJoinLink = function (element) { const meetingConfig = testTool.getMeetingConfig(); if (!meetingConfig.mn || !meetingConfig.name) { alert("Meeting number or username is empty"); return false; } const signature = ZoomMtg.generateSignature({ meetingNumber: meetingConfig.mn, apiKey: API_KEY, apiSecret: API_SECRET, role: meetingConfig.role, success: function (res) { console.log(res.result); meetingConfig.signature = res.result; meetingConfig.apiKey = API_KEY; const joinUrl = testTool.getCurrentDomain() + "/meeting.html?" + testTool.serialize(meetingConfig); document.getElementById('copy_link_value').setAttribute('link', joinUrl); copyToClipboard('copy_link_value'); }, }); };
defineSuite([ 'Core/GoogleEarthEnterpriseMetadata', 'Core/decodeGoogleEarthEnterpriseData', 'Core/DefaultProxy', 'Core/defaultValue', 'Core/GoogleEarthEnterpriseTileInformation', 'Core/loadWithXhr', 'Core/Math', 'Core/Request', 'Core/Resource', 'ThirdParty/when' ], function( GoogleEarthEnterpriseMetadata, decodeGoogleEarthEnterpriseData, DefaultProxy, defaultValue, GoogleEarthEnterpriseTileInformation, loadWithXhr, CesiumMath, Request, Resource, when) { 'use strict'; it('tileXYToQuadKey', function() { expect(GoogleEarthEnterpriseMetadata.tileXYToQuadKey(1, 0, 0)).toEqual('2'); expect(GoogleEarthEnterpriseMetadata.tileXYToQuadKey(1, 2, 1)).toEqual('02'); expect(GoogleEarthEnterpriseMetadata.tileXYToQuadKey(3, 5, 2)).toEqual('021'); expect(GoogleEarthEnterpriseMetadata.tileXYToQuadKey(4, 7, 2)).toEqual('100'); }); it('quadKeyToTileXY', function() { expect(GoogleEarthEnterpriseMetadata.quadKeyToTileXY('2')).toEqual({ x : 1, y : 0, level : 0 }); expect(GoogleEarthEnterpriseMetadata.quadKeyToTileXY('02')).toEqual({ x : 1, y : 2, level : 1 }); expect(GoogleEarthEnterpriseMetadata.quadKeyToTileXY('021')).toEqual({ x : 3, y : 5, level : 2 }); expect(GoogleEarthEnterpriseMetadata.quadKeyToTileXY('100')).toEqual({ x : 4, y : 7, level : 2 }); }); it('decode', function() { CesiumMath.setRandomNumberSeed(123123); var key = new Uint8Array(1025); var data = new Uint8Array(1025); for (var i = 0; i < 1025; ++i) { key[i] = Math.floor(CesiumMath.nextRandomNumber() * 256); data[i] = Math.floor(CesiumMath.nextRandomNumber() * 256); } var keyBuffer = key.buffer.slice(0, 1024); // Key length should be divisible by 4 var dataBuffer = data.buffer.slice(); var a = new Uint8Array(dataBuffer); decodeGoogleEarthEnterpriseData(keyBuffer, dataBuffer); expect(a).not.toEqual(data); // For the algorithm encode/decode are the same decodeGoogleEarthEnterpriseData(keyBuffer, dataBuffer); expect(a).toEqual(data); }); it('decode requires key' , function() { var data = new Uint8Array(3); expect(function() { decodeGoogleEarthEnterpriseData(undefined, data.buffer); }).toThrowDeveloperError(); }); it('decode requires data' , function() { var key = new Uint8Array(4); expect(function() { decodeGoogleEarthEnterpriseData(key.buffer); }).toThrowDeveloperError(); }); it('decode throws if key length isn\'t greater than 0 and a multiple 4' , function() { var key; var data = new Uint8Array(3); key = new Uint8Array(0); expect(function() { decodeGoogleEarthEnterpriseData(key.buffer, data.buffer); }).toThrowRuntimeError(); key = new Uint8Array(1); expect(function() { decodeGoogleEarthEnterpriseData(key.buffer, data.buffer); }).toThrowRuntimeError(); key = new Uint8Array(2); expect(function() { decodeGoogleEarthEnterpriseData(key.buffer, data.buffer); }).toThrowRuntimeError(); key = new Uint8Array(3); expect(function() { decodeGoogleEarthEnterpriseData(key.buffer, data.buffer); }).toThrowRuntimeError(); }); it('populateSubtree', function() { var quad = '0123'; var index = 0; spyOn(GoogleEarthEnterpriseMetadata.prototype, 'getQuadTreePacket').and.callFake(function(quadKey, version, request) { quadKey = defaultValue(quadKey, '') + index.toString(); this._tileInfo[quadKey] = new GoogleEarthEnterpriseTileInformation(0xFF, 1, 1, 1); index = (index + 1) % 4; return when(); }); var metadata = new GoogleEarthEnterpriseMetadata({ url : 'http://test.server' }); var request = new Request({ throttle : true }); return metadata.readyPromise .then(function() { var tileXY = GoogleEarthEnterpriseMetadata.quadKeyToTileXY(quad); return metadata.populateSubtree(tileXY.x, tileXY.y, tileXY.level, request); }) .then(function() { expect(GoogleEarthEnterpriseMetadata.prototype.getQuadTreePacket.calls.count()).toEqual(4); expect(GoogleEarthEnterpriseMetadata.prototype.getQuadTreePacket).toHaveBeenCalledWith('', 1); expect(GoogleEarthEnterpriseMetadata.prototype.getQuadTreePacket).toHaveBeenCalledWith('0', 1, request); expect(GoogleEarthEnterpriseMetadata.prototype.getQuadTreePacket).toHaveBeenCalledWith('01', 1, request); expect(GoogleEarthEnterpriseMetadata.prototype.getQuadTreePacket).toHaveBeenCalledWith('012', 1, request); var tileInfo = metadata._tileInfo; expect(tileInfo['0']).toBeDefined(); expect(tileInfo['01']).toBeDefined(); expect(tileInfo['012']).toBeDefined(); expect(tileInfo['0123']).toBeDefined(); }); }); it('resolves readyPromise', function() { var baseurl = 'http://fake.fake.invalid/'; var req = 0; spyOn(loadWithXhr, 'load').and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(responseType).toEqual('arraybuffer'); if (req === 0) { expect(url).toEqual(baseurl + 'dbRoot.v5?output=proto'); deferred.reject(); // Reject dbRoot request and use defaults } else { expect(url).toEqual(baseurl + 'flatfile?q2-0-q.1'); loadWithXhr.defaultLoad('Data/GoogleEarthEnterprise/gee.metadata', responseType, method, data, headers, deferred); } ++req; }); var provider = new GoogleEarthEnterpriseMetadata({ url : baseurl }); return provider.readyPromise.then(function(result) { expect(result).toBe(true); expect(provider.imageryPresent).toBe(true); expect(provider.protoImagery).toBeUndefined(); expect(provider.terrainPresent).toBe(true); expect(provider.negativeAltitudeThreshold).toBe(CesiumMath.EPSILON12); expect(provider.negativeAltitudeExponentBias).toBe(32); expect(provider.providers).toEqual({}); var tileInfo = provider._tileInfo['0']; expect(tileInfo).toBeDefined(); expect(tileInfo._bits).toEqual(0x40); expect(tileInfo.cnodeVersion).toEqual(2); expect(tileInfo.imageryVersion).toEqual(1); expect(tileInfo.terrainVersion).toEqual(1); expect(tileInfo.ancestorHasTerrain).toEqual(false); expect(tileInfo.terrainState).toBeUndefined(); }); }); it('resolves readyPromise with Resource', function() { var baseurl = 'http://fake.fake.invalid/'; var resource = new Resource({ url : baseurl }); var req = 0; spyOn(loadWithXhr, 'load').and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(responseType).toEqual('arraybuffer'); if (req === 0) { expect(url).toEqual(baseurl + 'dbRoot.v5?output=proto'); deferred.reject(); // Reject dbRoot request and use defaults } else { expect(url).toEqual(baseurl + 'flatfile?q2-0-q.1'); loadWithXhr.defaultLoad('Data/GoogleEarthEnterprise/gee.metadata', responseType, method, data, headers, deferred); } ++req; }); var provider = new GoogleEarthEnterpriseMetadata(resource); return provider.readyPromise.then(function(result) { expect(result).toBe(true); expect(provider.imageryPresent).toBe(true); expect(provider.protoImagery).toBeUndefined(); expect(provider.terrainPresent).toBe(true); expect(provider.negativeAltitudeThreshold).toBe(CesiumMath.EPSILON12); expect(provider.negativeAltitudeExponentBias).toBe(32); expect(provider.providers).toEqual({}); var tileInfo = provider._tileInfo['0']; expect(tileInfo).toBeDefined(); expect(tileInfo._bits).toEqual(0x40); expect(tileInfo.cnodeVersion).toEqual(2); expect(tileInfo.imageryVersion).toEqual(1); expect(tileInfo.terrainVersion).toEqual(1); expect(tileInfo.ancestorHasTerrain).toEqual(false); expect(tileInfo.terrainState).toBeUndefined(); }); }); it('rejects readyPromise on error', function() { var url = 'host.invalid/'; var provider = new GoogleEarthEnterpriseMetadata({ url : url }); return provider.readyPromise.then(function() { fail('should not resolve'); }).otherwise(function(e) { expect(e.message).toContain(url); }); }); it('routes requests through a proxy if one is specified', function() { var proxy = new DefaultProxy('/proxy/'); var baseurl = 'http://fake.fake.invalid/'; var req = 0; spyOn(loadWithXhr, 'load').and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType) { expect(responseType).toEqual('arraybuffer'); if (req === 0) { expect(url).toEqual(proxy.getURL(baseurl + 'dbRoot.v5?output=proto')); deferred.reject(); // Reject dbRoot request and use defaults } else { expect(url).toEqual(proxy.getURL(baseurl + 'flatfile?q2-0-q.1')); loadWithXhr.defaultLoad('Data/GoogleEarthEnterprise/gee.metadata', responseType, method, data, headers, deferred); } ++req; }); var provider = new GoogleEarthEnterpriseMetadata({ url : baseurl, proxy : proxy }); expect(provider._resource._url).toEqual(baseurl); expect(provider.proxy).toEqual(proxy); return provider.readyPromise.then(function(result) { expect(result).toBe(true); var tileInfo = provider._tileInfo['0']; expect(tileInfo).toBeDefined(); expect(tileInfo._bits).toEqual(0x40); expect(tileInfo.cnodeVersion).toEqual(2); expect(tileInfo.imageryVersion).toEqual(1); expect(tileInfo.terrainVersion).toEqual(1); expect(tileInfo.ancestorHasTerrain).toEqual(false); expect(tileInfo.terrainState).toBeUndefined(); }); }); });
from __future__ import unicode_literals from django.contrib.gis.db import models from django.db.models import Manager as GeoManager from django.utils import timezone import folium import os.path # from .forecast_generator import add_stf class Dam(models.Model): name = models.CharField(max_length = 20) abbr = models.CharField(max_length = 5) location = models.PointField(srid=4326) # deprecated objects = GeoManager() def __str__(self): return self.abbr def create_map(self): coords = self.location.coords coords = [coords[1],coords[0]] m = folium.Map( location=coords, zoom_start=11 ) folium.CircleMarker( location=coords, radius=50, popup=self.name, color='#3186cc', fill=True, fill_color='#3186cc' ).add_to(m) m.save(f"reporter/static/maps/{self.abbr}.html") def save(self, *args, **kwargs): created = self.pk is None super(Dam, self).save(*args, **kwargs) if os.path.isfile(f"reporter/static/maps/{self.abbr}.html"): os.remove(f"reporter/static/maps/{self.abbr}.html") self.create_map() else: self.create_map() def map_path(self): return f"{self.abbr}.html" class Species(models.Model): name = models.CharField(max_length = 25) reference_name = models.CharField(max_length = 25) class Meta: verbose_name_plural = "Species" def __str__(self): return self.name class Forecasts(models.Model): species = models.ForeignKey(Species, on_delete=False) dam = models.ForeignKey(Dam, on_delete=False) forecast_range = models.DateField(default=timezone.now, blank=True) graph = models.FileField(upload_to=f"reporter/static/images/forecasts/",blank=True) forecast_csv = models.FileField(upload_to=f"reporter/static/csv/forecasts/",blank=True) def __str__(self): return self.dam.abbr + '_' + self.species.reference_name class Meta: verbose_name_plural = "Forecasts" def graph_path(self): return f"{self.dam.abbr}_{self.species.reference_name}_forecast.png" def forecast_csv_path(self): return f"{self.dam.abbr}_{self.species.reference_name}_forecast.csv"
import requests def read_statistics_from_db( dataset_name, subset_name=None, version='Hugging Face', transformation={'type': 'origin'}, ): end_point_upload_dataset = "https://datalab.nlpedia.ai/api/normal_dataset/read_stat" data_info = { 'dataset_name': dataset_name, 'subset_name': subset_name, 'version': version, 'transformation': transformation, } response = requests.post(end_point_upload_dataset, json=data_info) # message = json.loads(response.text.replace("null", ""))["message"] return response def write_statistics_to_db( dataset_name, subset_name=None, version='Hugging Face', transformation={'type': 'origin'}, content={}, ): end_point_upload_dataset = ( "https://datalab.nlpedia.ai/api/normal_dataset/update_stat" ) data_info = { 'dataset_name': dataset_name, 'subset_name': subset_name, 'version': version, 'transformation': transformation, 'content': content, } response = requests.post(end_point_upload_dataset, json=data_info) # message = json.loads(response.text.replace("null", ""))["message"] return response
"""Describes results. Is a JSON. """ import json import os from planemo.io import error class StructuredData(object): """Abstraction around a simple data structure describing test results.""" def __init__(self, json_path=None, data=None): """Create a :class:`StructuredData` from a JSON file.""" def data_error(): error("An invalid JSON for structured test result data - " "summary information and planemo reports will be " "incorrect.") self.json_path = json_path structured_data = {} structured_data_tests = {} if json_path and os.path.exists(json_path) and data is None: try: with open(json_path, "r") as output_json_f: data = json.load(output_json_f) except Exception: data_error() try: structured_data = data structured_data_tests = structured_data["tests"] except Exception: data_error() self.structured_data = structured_data self.structured_data_tests = structured_data_tests structured_data_by_id = {} for test in self.structured_data_tests: structured_data_by_id[test["id"]] = test["data"] self.structured_data_by_id = structured_data_by_id self.has_details = "summary" in structured_data if self.has_details: self.read_summary() def update(self): """Write out an updated version of this data structure to supplied json path.""" with open(self.json_path, "w") as out_f: json.dump(self.structured_data, out_f) def set_exit_code(self, exit_code): """Set the exit_code for the this test.""" self.structured_data["exit_code"] = exit_code def calculate_summary_data_if_needed(self): if "summary" not in self.structured_data: self.calculate_summary_data() def calculate_summary_data(self): """Use full details on individual test data to update structured data with summary info.""" num_tests = 0 num_failures = 0 num_skips = 0 num_errors = 0 for test in self.structured_data_tests: test_data = get_dict_value("data", test) status = get_dict_value("status", test_data) num_tests += 1 if status == "skip": num_skips += 1 elif status == "failure": num_failures += 1 elif status == "error": num_errors += 1 elif status != "success": raise Exception("Unknown test status encountered [%s]" % status) summary = {} summary["num_tests"] = num_tests summary["num_failures"] = num_failures summary["num_skips"] = num_skips summary["num_errors"] = num_errors self.structured_data["summary"] = summary self.read_summary() def read_summary(self): """Read summary data into properties on this class.""" summary = self.structured_data["summary"] num_tests = summary["num_tests"] num_failures = summary["num_failures"] num_skips = summary["num_skips"] num_errors = summary["num_errors"] self.num_tests = num_tests self.num_problems = num_skips + num_errors + num_failures self.exit_code = self.structured_data.get("exit_code", None) @property def failed_ids(self): """Find set of IDs for failed tests.""" ids = set([]) for test_data in self.structured_data_tests: if test_data["data"]["status"] == "success": continue test_case = test_data["id"].replace(".test_toolbox.", ".test_toolbox:") ids.add(test_case) return ids def get_dict_value(key, data): """Return data[key] with improved KeyError.""" try: return data[key] except (KeyError, TypeError): raise KeyError("No key [%s] in [%s]" % (key, data)) __all__ = ( "StructuredData", "get_dict_value", )
/* * * device driver for Conexant 2388x based TV cards * card-specific stuff. * * (c) 2003 Gerd Knorr <kraxel@bytesex.org> [SuSE Labs] * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/init.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/delay.h> #include "cx88.h" /* ------------------------------------------------------------------ */ /* board config info */ struct cx88_board cx88_boards[] = { [CX88_BOARD_UNKNOWN] = { .name = "UNKNOWN/GENERIC", .tuner_type = UNSET, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_COMPOSITE1, .vmux = 0, },{ .type = CX88_VMUX_COMPOSITE2, .vmux = 1, },{ .type = CX88_VMUX_COMPOSITE3, .vmux = 2, },{ .type = CX88_VMUX_COMPOSITE4, .vmux = 3, }}, }, [CX88_BOARD_HAUPPAUGE] = { .name = "Hauppauge WinTV 34xxx models", .tuner_type = UNSET, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0xff00, // internal decoder },{ .type = CX88_VMUX_DEBUG, .vmux = 0, .gpio0 = 0xff01, // mono from tuner chip },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0xff02, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0xff02, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0xff01, }, }, [CX88_BOARD_GDI] = { .name = "GDI Black Gold", .tuner_type = UNSET, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, }}, }, [CX88_BOARD_PIXELVIEW] = { .name = "PixelView", .tuner_type = TUNER_PHILIPS_PAL, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0xff00, // internal decoder },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0xff10, }, }, [CX88_BOARD_ATI_WONDER_PRO] = { .name = "ATI TV Wonder Pro", .tuner_type = TUNER_PHILIPS_4IN1, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT | TDA9887_INTERCARRIER, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x03ff, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x03fe, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x03fe, }}, }, [CX88_BOARD_WINFAST2000XP_EXPERT] = { .name = "Leadtek Winfast 2000XP Expert", .tuner_type = TUNER_PHILIPS_4IN1, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x00F5e700, .gpio1 = 0x00003004, .gpio2 = 0x00F5e700, .gpio3 = 0x02000000, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x00F5c700, .gpio1 = 0x00003004, .gpio2 = 0x00F5c700, .gpio3 = 0x02000000, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x00F5c700, .gpio1 = 0x00003004, .gpio2 = 0x00F5c700, .gpio3 = 0x02000000, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0x00F5d700, .gpio1 = 0x00003004, .gpio2 = 0x00F5d700, .gpio3 = 0x02000000, }, }, [CX88_BOARD_AVERTV_STUDIO_303] = { .name = "AverTV Studio 303 (M126)", .tuner_type = TUNER_PHILIPS_FM1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio1 = 0xe09f, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio1 = 0xe05f, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio1 = 0xe05f, }}, .radio = { .gpio1 = 0xe0df, .type = CX88_RADIO, }, }, [CX88_BOARD_MSI_TVANYWHERE_MASTER] = { // added gpio values thanks to Michal // values for PAL from DScaler .name = "MSI TV-@nywhere Master", .tuner_type = TUNER_MT2032, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT | TDA9887_INTERCARRIER_NTSC, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x000040bf, .gpio1 = 0x000080c0, .gpio2 = 0x0000ff40, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x000040bf, .gpio1 = 0x000080c0, .gpio2 = 0x0000ff40, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x000040bf, .gpio1 = 0x000080c0, .gpio2 = 0x0000ff40, }}, .radio = { .type = CX88_RADIO, }, }, [CX88_BOARD_WINFAST_DV2000] = { .name = "Leadtek Winfast DV2000", .tuner_type = TUNER_PHILIPS_FM1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x0035e700, .gpio1 = 0x00003004, .gpio2 = 0x0035e700, .gpio3 = 0x02000000, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x0035c700, .gpio1 = 0x00003004, .gpio2 = 0x0035c700, .gpio3 = 0x02000000, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x0035c700, .gpio1 = 0x0035c700, .gpio2 = 0x02000000, .gpio3 = 0x02000000, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0x0035d700, .gpio1 = 0x00007004, .gpio2 = 0x0035d700, .gpio3 = 0x02000000, }, }, [CX88_BOARD_LEADTEK_PVR2000] = { // gpio values for PAL version from regspy by DScaler .name = "Leadtek PVR 2000", .tuner_type = TUNER_PHILIPS_FM1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x0000bde2, .extadc = 1, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x0000bde6, .extadc = 1, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x0000bde6, .extadc = 1, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0x0000bd62, .extadc = 1, }, .mpeg = CX88_MPEG_BLACKBIRD, }, [CX88_BOARD_IODATA_GVVCP3PCI] = { .name = "IODATA GV-VCP3/PCI", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_COMPOSITE1, .vmux = 0, },{ .type = CX88_VMUX_COMPOSITE2, .vmux = 1, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, }}, }, [CX88_BOARD_PROLINK_PLAYTVPVR] = { .name = "Prolink PlayTV PVR", .tuner_type = TUNER_PHILIPS_FM1236_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0xbff0, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0xbff3, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0xbff3, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0xbff0, }, }, [CX88_BOARD_ASUS_PVR_416] = { .name = "ASUS PVR-416", .tuner_type = TUNER_PHILIPS_FM1236_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x0000fde6, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x0000fde6, // 0x0000fda6 L,R RCA audio in? .extadc = 1, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0x0000fde2, }, .mpeg = CX88_MPEG_BLACKBIRD, }, [CX88_BOARD_MSI_TVANYWHERE] = { .name = "MSI TV-@nywhere", .tuner_type = TUNER_MT2032, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x00000fbf, .gpio2 = 0x0000fc08, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x00000fbf, .gpio2 = 0x0000fc68, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x00000fbf, .gpio2 = 0x0000fc68, }}, }, [CX88_BOARD_KWORLD_DVB_T] = { .name = "KWorld/VStream XPert DVB-T", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x0700, .gpio2 = 0x0101, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x0700, .gpio2 = 0x0101, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_DVICO_FUSIONHDTV_DVB_T1] = { .name = "DViCO FusionHDTV DVB-T1", .tuner_type = TUNER_ABSENT, /* No analog tuner */ .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x000027df, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x000027df, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_KWORLD_LTV883] = { .name = "KWorld LTV883RF", .tuner_type = TUNER_TNF_8831BGFF, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x07f8, },{ .type = CX88_VMUX_DEBUG, .vmux = 0, .gpio0 = 0x07f9, // mono from tuner chip },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x000007fa, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x000007fa, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0x000007f8, }, }, [CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_Q] = { .name = "DViCO FusionHDTV 3 Gold-Q", .tuner_type = TUNER_MICROTUNE_4042FI5, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, /* GPIO[0] resets DT3302 DTV receiver 0 - reset asserted 1 - normal operation GPIO[1] mutes analog audio output connector 0 - enable selected source 1 - mute GPIO[2] selects source for analog audio output connector 0 - analog audio input connector on tab 1 - analog DAC output from CX23881 chip GPIO[3] selects RF input connector on tuner module 0 - RF connector labeled CABLE 1 - RF connector labeled ANT GPIO[4] selects high RF for QAM256 mode 0 - normal RF 1 - high RF */ .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x0f0d, },{ .type = CX88_VMUX_CABLE, .vmux = 0, .gpio0 = 0x0f05, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x0f00, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x0f00, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_HAUPPAUGE_DVB_T1] = { .name = "Hauppauge Nova-T DVB-T", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_DVB, .vmux = 0, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_CONEXANT_DVB_T1] = { .name = "Conexant DVB-T reference design", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_DVB, .vmux = 0, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_PROVIDEO_PV259] = { .name = "Provideo PV259", .tuner_type = TUNER_PHILIPS_FQ1216ME, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .extadc = 1, }}, .mpeg = CX88_MPEG_BLACKBIRD, }, [CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PLUS] = { .name = "DViCO FusionHDTV DVB-T Plus", .tuner_type = TUNER_ABSENT, /* No analog tuner */ .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x000027df, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x000027df, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_DNTV_LIVE_DVB_T] = { .name = "digitalnow DNTV Live! DVB-T", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x00000700, .gpio2 = 0x00000101, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x00000700, .gpio2 = 0x00000101, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_PCHDTV_HD3000] = { .name = "pcHDTV HD3000 HDTV", .tuner_type = TUNER_THOMSON_DTT761X, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x00008484, .gpio1 = 0x00000000, .gpio2 = 0x00000000, .gpio3 = 0x00000000, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x00008400, .gpio1 = 0x00000000, .gpio2 = 0x00000000, .gpio3 = 0x00000000, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x00008400, .gpio1 = 0x00000000, .gpio2 = 0x00000000, .gpio3 = 0x00000000, }}, .radio = { .type = CX88_RADIO, .vmux = 2, .gpio0 = 0x00008400, .gpio1 = 0x00000000, .gpio2 = 0x00000000, .gpio3 = 0x00000000, }, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_HAUPPAUGE_ROSLYN] = { // entry added by Kaustubh D. Bhalerao <bhalerao.1@osu.edu> // GPIO values obtained from regspy, courtesy Sean Covel .name = "Hauppauge WinTV 28xxx (Roslyn) models", .tuner_type = UNSET, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0xed1a, .gpio2 = 0x00ff, },{ .type = CX88_VMUX_DEBUG, .vmux = 0, .gpio0 = 0xff01, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0xff02, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0xed92, .gpio2 = 0x00ff, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0xed96, .gpio2 = 0x00ff, }, .mpeg = CX88_MPEG_BLACKBIRD, }, [CX88_BOARD_DIGITALLOGIC_MEC] = { .name = "Digital-Logic MICROSPACE Entertainment Center (MEC)", .tuner_type = TUNER_PHILIPS_FM1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x00009d80, .extadc = 1, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x00009d76, .extadc = 1, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x00009d76, .extadc = 1, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0x00009d00, .extadc = 1, }, .mpeg = CX88_MPEG_BLACKBIRD, }, [CX88_BOARD_IODATA_GVBCTV7E] = { .name = "IODATA GV/BCTV7E", .tuner_type = TUNER_PHILIPS_FQ1286, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 1, .gpio1 = 0x0000e03f, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 2, .gpio1 = 0x0000e07f, },{ .type = CX88_VMUX_SVIDEO, .vmux = 3, .gpio1 = 0x0000e07f, }} }, [CX88_BOARD_PIXELVIEW_PLAYTV_ULTRA_PRO] = { .name = "PixelView PlayTV Ultra Pro (Stereo)", /* May be also TUNER_YMEC_TVF_5533MF for NTSC/M or PAL/M */ .tuner_type = TUNER_PHILIPS_FM1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0xbf61, /* internal decoder */ },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0xbf63, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0xbf63, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0xbf60, }, }, [CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_T] = { .name = "DViCO FusionHDTV 3 Gold-T", .tuner_type = TUNER_THOMSON_DTT761X, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x97ed, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x97e9, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x97e9, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_ADSTECH_DVB_T_PCI] = { .name = "ADS Tech Instant TV DVB-T PCI", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x0700, .gpio2 = 0x0101, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x0700, .gpio2 = 0x0101, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_TERRATEC_CINERGY_1400_DVB_T1] = { .name = "TerraTec Cinergy 1400 DVB-T", .tuner_type = TUNER_ABSENT, .input = {{ .type = CX88_VMUX_DVB, .vmux = 0, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 2, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_DVICO_FUSIONHDTV_5_GOLD] = { .name = "DViCO FusionHDTV 5 Gold", .tuner_type = TUNER_LG_TDVS_H06XF, /* TDVS-H062F */ .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x87fd, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x87f9, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x87f9, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_AVERMEDIA_ULTRATV_MC_550] = { .name = "AverMedia UltraTV Media Center PCI 550", .tuner_type = TUNER_PHILIPS_FM1236_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_COMPOSITE1, .vmux = 0, .gpio0 = 0x0000cd73, .extadc = 1, },{ .type = CX88_VMUX_SVIDEO, .vmux = 1, .gpio0 = 0x0000cd73, .extadc = 1, },{ .type = CX88_VMUX_TELEVISION, .vmux = 3, .gpio0 = 0x0000cdb3, .extadc = 1, }}, .radio = { .type = CX88_RADIO, .vmux = 2, .gpio0 = 0x0000cdf3, .extadc = 1, }, .mpeg = CX88_MPEG_BLACKBIRD, }, [CX88_BOARD_KWORLD_VSTREAM_EXPERT_DVD] = { /* Alexander Wold <awold@bigfoot.com> */ .name = "Kworld V-Stream Xpert DVD", .tuner_type = UNSET, .input = {{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x03000000, .gpio1 = 0x01000000, .gpio2 = 0x02000000, .gpio3 = 0x00100000, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x03000000, .gpio1 = 0x01000000, .gpio2 = 0x02000000, .gpio3 = 0x00100000, }}, }, [CX88_BOARD_ATI_HDTVWONDER] = { .name = "ATI HDTV Wonder", .tuner_type = TUNER_PHILIPS_TUV1236D, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x00000ff7, .gpio1 = 0x000000ff, .gpio2 = 0x00000001, .gpio3 = 0x00000000, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x00000ffe, .gpio1 = 0x000000ff, .gpio2 = 0x00000001, .gpio3 = 0x00000000, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x00000ffe, .gpio1 = 0x000000ff, .gpio2 = 0x00000001, .gpio3 = 0x00000000, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_WINFAST_DTV1000] = { .name = "WinFast DTV1000-T", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_DVB, .vmux = 0, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_AVERTV_303] = { .name = "AVerTV 303 (M126)", .tuner_type = TUNER_PHILIPS_FM1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x00ff, .gpio1 = 0xe09f, .gpio2 = 0x0010, .gpio3 = 0x0000, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x00ff, .gpio1 = 0xe05f, .gpio2 = 0x0010, .gpio3 = 0x0000, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x00ff, .gpio1 = 0xe05f, .gpio2 = 0x0010, .gpio3 = 0x0000, }}, }, [CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1] = { .name = "Hauppauge Nova-S-Plus DVB-S", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_DVB, .vmux = 0, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_HAUPPAUGE_NOVASE2_S1] = { .name = "Hauppauge Nova-SE2 DVB-S", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_DVB, .vmux = 0, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_KWORLD_DVBS_100] = { .name = "KWorld DVB-S 100", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_DVB, .vmux = 0, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_HAUPPAUGE_HVR1100] = { .name = "Hauppauge WinTV-HVR1100 DVB-T/Hybrid", .tuner_type = TUNER_PHILIPS_FMD1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, }}, /* fixme: Add radio support */ .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_HAUPPAUGE_HVR1100LP] = { .name = "Hauppauge WinTV-HVR1100 DVB-T/Hybrid (Low Profile)", .tuner_type = TUNER_PHILIPS_FMD1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, }}, /* fixme: Add radio support */ .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_DNTV_LIVE_DVB_T_PRO] = { .name = "digitalnow DNTV Live! DVB-T Pro", .tuner_type = TUNER_PHILIPS_FMD1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT | TDA9887_PORT1_ACTIVE | TDA9887_PORT2_ACTIVE, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0xf80808, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0xf80808, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0xf80808, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0xf80808, }, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_KWORLD_DVB_T_CX22702] = { /* Kworld V-stream Xpert DVB-T with Thomson tuner */ /* DTT 7579 Conexant CX22702-19 Conexant CX2388x */ /* Manenti Marco <marco_manenti@colman.it> */ .name = "KWorld/VStream XPert DVB-T with cx22702", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x0700, .gpio2 = 0x0101, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x0700, .gpio2 = 0x0101, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_DUAL] = { .name = "DViCO FusionHDTV DVB-T Dual Digital", .tuner_type = TUNER_ABSENT, /* No analog tuner */ .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x000067df, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x000067df, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_KWORLD_HARDWARE_MPEG_TV_XPERT] = { .name = "KWorld HardwareMpegTV XPert", .tuner_type = TUNER_PHILIPS_TDA8290, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x3de2, .gpio2 = 0x00ff, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x3de6, .extadc = 1, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x3de6, .extadc = 1, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0x3de6, .gpio2 = 0x00ff, }, .mpeg = CX88_MPEG_BLACKBIRD, }, [CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_HYBRID] = { .name = "DViCO FusionHDTV DVB-T Hybrid", .tuner_type = TUNER_THOMSON_FE6600, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x0000a75f, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x0000a75b, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x0000a75b, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_PCHDTV_HD5500] = { .name = "pcHDTV HD5500 HDTV", .tuner_type = TUNER_LG_TDVS_H06XF, /* TDVS-H064F */ .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x87fd, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x87f9, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x87f9, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_KWORLD_MCE200_DELUXE] = { /* FIXME: tested TV input only, disabled composite, svideo and radio until they can be tested also. */ .name = "Kworld MCE 200 Deluxe", .tuner_type = TUNER_TENA_9533_DI, .radio_type = UNSET, .tda9887_conf = TDA9887_PRESENT, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x0000BDE6 }}, .mpeg = CX88_MPEG_BLACKBIRD, }, [CX88_BOARD_PIXELVIEW_PLAYTV_P7000] = { /* FIXME: SVideo, Composite and FM inputs are untested */ .name = "PixelView PlayTV P7000", .tuner_type = TUNER_PHILIPS_FM1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT | TDA9887_PORT1_ACTIVE | TDA9887_PORT2_ACTIVE, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x5da6, }}, .mpeg = CX88_MPEG_BLACKBIRD, }, [CX88_BOARD_NPGTECH_REALTV_TOP10FM] = { .name = "NPG Tech Real TV FM Top 10", .tuner_type = TUNER_TNF_5335MF, /* Actually a TNF9535 */ .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x0788, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x078b, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x078b, }}, .radio = { .type = CX88_RADIO, .gpio0 = 0x074a, }, }, [CX88_BOARD_WINFAST_DTV2000H] = { /* video inputs and radio still in testing */ .name = "WinFast DTV2000 H", .tuner_type = TUNER_PHILIPS_FMD1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x00017304, .gpio1 = 0x00008203, .gpio2 = 0x00017304, .gpio3 = 0x02000000, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_GENIATECH_DVBS] = { .name = "Geniatech DVB-S", .tuner_type = TUNER_ABSENT, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_DVB, .vmux = 0, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_HAUPPAUGE_HVR3000] = { /* FIXME: Add dvb & radio support */ .name = "Hauppauge WinTV-HVR3000 TriMode Analog/DVB-S/DVB-T", .tuner_type = TUNER_PHILIPS_FMD1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x84bf, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x84bf, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x84bf, }}, .mpeg = CX88_MPEG_DVB, }, [CX88_BOARD_NORWOOD_MICRO] = { .name = "Norwood Micro TV Tuner", .tuner_type = TUNER_TNF_5335MF, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x0709, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x070b, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x070b, }}, }, [CX88_BOARD_TE_DTV_250_OEM_SWANN] = { .name = "Shenzhen Tungsten Ages Tech TE-DTV-250 / Swann OEM", .tuner_type = TUNER_LG_PAL_NEW_TAPC, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0x003fffff, .gpio1 = 0x00e00000, .gpio2 = 0x003fffff, .gpio3 = 0x02000000, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0x003fffff, .gpio1 = 0x00e00000, .gpio2 = 0x003fffff, .gpio3 = 0x02000000, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0x003fffff, .gpio1 = 0x00e00000, .gpio2 = 0x003fffff, .gpio3 = 0x02000000, }}, }, [CX88_BOARD_HAUPPAUGE_HVR1300] = { .name = "Hauppauge WinTV-HVR1300 DVB-T/Hybrid MPEG Encoder", .tuner_type = TUNER_PHILIPS_FMD1216ME_MK3, .radio_type = UNSET, .tuner_addr = ADDR_UNSET, .radio_addr = ADDR_UNSET, .tda9887_conf = TDA9887_PRESENT, .audio_chip = AUDIO_CHIP_WM8775, .input = {{ .type = CX88_VMUX_TELEVISION, .vmux = 0, .gpio0 = 0xe780, .extadc = 1, },{ .type = CX88_VMUX_COMPOSITE1, .vmux = 1, .gpio0 = 0xe780, .extadc = 1, },{ .type = CX88_VMUX_SVIDEO, .vmux = 2, .gpio0 = 0xe780, .extadc = 1, }}, /* fixme: Add radio support */ .mpeg = CX88_MPEG_DVB | CX88_MPEG_BLACKBIRD, }, }; const unsigned int cx88_bcount = ARRAY_SIZE(cx88_boards); /* ------------------------------------------------------------------ */ /* PCI subsystem IDs */ struct cx88_subid cx88_subids[] = { { .subvendor = 0x0070, .subdevice = 0x3400, .card = CX88_BOARD_HAUPPAUGE, },{ .subvendor = 0x0070, .subdevice = 0x3401, .card = CX88_BOARD_HAUPPAUGE, },{ .subvendor = 0x14c7, .subdevice = 0x0106, .card = CX88_BOARD_GDI, },{ .subvendor = 0x14c7, .subdevice = 0x0107, /* with mpeg encoder */ .card = CX88_BOARD_GDI, },{ .subvendor = PCI_VENDOR_ID_ATI, .subdevice = 0x00f8, .card = CX88_BOARD_ATI_WONDER_PRO, },{ .subvendor = 0x107d, .subdevice = 0x6611, .card = CX88_BOARD_WINFAST2000XP_EXPERT, },{ .subvendor = 0x107d, .subdevice = 0x6613, /* NTSC */ .card = CX88_BOARD_WINFAST2000XP_EXPERT, },{ .subvendor = 0x107d, .subdevice = 0x6620, .card = CX88_BOARD_WINFAST_DV2000, },{ .subvendor = 0x107d, .subdevice = 0x663b, .card = CX88_BOARD_LEADTEK_PVR2000, },{ .subvendor = 0x107d, .subdevice = 0x663c, .card = CX88_BOARD_LEADTEK_PVR2000, },{ .subvendor = 0x1461, .subdevice = 0x000b, .card = CX88_BOARD_AVERTV_STUDIO_303, },{ .subvendor = 0x1462, .subdevice = 0x8606, .card = CX88_BOARD_MSI_TVANYWHERE_MASTER, },{ .subvendor = 0x10fc, .subdevice = 0xd003, .card = CX88_BOARD_IODATA_GVVCP3PCI, },{ .subvendor = 0x1043, .subdevice = 0x4823, /* with mpeg encoder */ .card = CX88_BOARD_ASUS_PVR_416, },{ .subvendor = 0x17de, .subdevice = 0x08a6, .card = CX88_BOARD_KWORLD_DVB_T, },{ .subvendor = 0x18ac, .subdevice = 0xd810, .card = CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_Q, },{ .subvendor = 0x18ac, .subdevice = 0xd820, .card = CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_T, },{ .subvendor = 0x18ac, .subdevice = 0xdb00, .card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T1, },{ .subvendor = 0x0070, .subdevice = 0x9002, .card = CX88_BOARD_HAUPPAUGE_DVB_T1, },{ .subvendor = 0x14f1, .subdevice = 0x0187, .card = CX88_BOARD_CONEXANT_DVB_T1, },{ .subvendor = 0x1540, .subdevice = 0x2580, .card = CX88_BOARD_PROVIDEO_PV259, },{ .subvendor = 0x18ac, .subdevice = 0xdb10, .card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PLUS, },{ .subvendor = 0x1554, .subdevice = 0x4811, .card = CX88_BOARD_PIXELVIEW, },{ .subvendor = 0x7063, .subdevice = 0x3000, /* HD-3000 card */ .card = CX88_BOARD_PCHDTV_HD3000, },{ .subvendor = 0x17de, .subdevice = 0xa8a6, .card = CX88_BOARD_DNTV_LIVE_DVB_T, },{ .subvendor = 0x0070, .subdevice = 0x2801, .card = CX88_BOARD_HAUPPAUGE_ROSLYN, },{ .subvendor = 0x14f1, .subdevice = 0x0342, .card = CX88_BOARD_DIGITALLOGIC_MEC, },{ .subvendor = 0x10fc, .subdevice = 0xd035, .card = CX88_BOARD_IODATA_GVBCTV7E, },{ .subvendor = 0x1421, .subdevice = 0x0334, .card = CX88_BOARD_ADSTECH_DVB_T_PCI, },{ .subvendor = 0x153b, .subdevice = 0x1166, .card = CX88_BOARD_TERRATEC_CINERGY_1400_DVB_T1, },{ .subvendor = 0x18ac, .subdevice = 0xd500, .card = CX88_BOARD_DVICO_FUSIONHDTV_5_GOLD, },{ .subvendor = 0x1461, .subdevice = 0x8011, .card = CX88_BOARD_AVERMEDIA_ULTRATV_MC_550, },{ .subvendor = PCI_VENDOR_ID_ATI, .subdevice = 0xa101, .card = CX88_BOARD_ATI_HDTVWONDER, },{ .subvendor = 0x107d, .subdevice = 0x665f, .card = CX88_BOARD_WINFAST_DTV1000, },{ .subvendor = 0x1461, .subdevice = 0x000a, .card = CX88_BOARD_AVERTV_303, },{ .subvendor = 0x0070, .subdevice = 0x9200, .card = CX88_BOARD_HAUPPAUGE_NOVASE2_S1, },{ .subvendor = 0x0070, .subdevice = 0x9201, .card = CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1, },{ .subvendor = 0x0070, .subdevice = 0x9202, .card = CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1, },{ .subvendor = 0x17de, .subdevice = 0x08b2, .card = CX88_BOARD_KWORLD_DVBS_100, },{ .subvendor = 0x0070, .subdevice = 0x9400, .card = CX88_BOARD_HAUPPAUGE_HVR1100, },{ .subvendor = 0x0070, .subdevice = 0x9402, .card = CX88_BOARD_HAUPPAUGE_HVR1100, },{ .subvendor = 0x0070, .subdevice = 0x9800, .card = CX88_BOARD_HAUPPAUGE_HVR1100LP, },{ .subvendor = 0x0070, .subdevice = 0x9802, .card = CX88_BOARD_HAUPPAUGE_HVR1100LP, },{ .subvendor = 0x0070, .subdevice = 0x9001, .card = CX88_BOARD_HAUPPAUGE_DVB_T1, },{ .subvendor = 0x1822, .subdevice = 0x0025, .card = CX88_BOARD_DNTV_LIVE_DVB_T_PRO, },{ .subvendor = 0x17de, .subdevice = 0x08a1, .card = CX88_BOARD_KWORLD_DVB_T_CX22702, },{ .subvendor = 0x18ac, .subdevice = 0xdb50, .card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_DUAL, },{ .subvendor = 0x18ac, .subdevice = 0xdb54, .card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_DUAL, /* Re-branded DViCO: DigitalNow DVB-T Dual */ },{ .subvendor = 0x18ac, .subdevice = 0xdb11, .card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PLUS, /* Re-branded DViCO: UltraView DVB-T Plus */ },{ .subvendor = 0x17de, .subdevice = 0x0840, .card = CX88_BOARD_KWORLD_HARDWARE_MPEG_TV_XPERT, },{ .subvendor = 0x1421, .subdevice = 0x0305, .card = CX88_BOARD_KWORLD_HARDWARE_MPEG_TV_XPERT, },{ .subvendor = 0x18ac, .subdevice = 0xdb40, .card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_HYBRID, },{ .subvendor = 0x18ac, .subdevice = 0xdb44, .card = CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_HYBRID, },{ .subvendor = 0x7063, .subdevice = 0x5500, .card = CX88_BOARD_PCHDTV_HD5500, },{ .subvendor = 0x17de, .subdevice = 0x0841, .card = CX88_BOARD_KWORLD_MCE200_DELUXE, },{ .subvendor = 0x1822, .subdevice = 0x0019, .card = CX88_BOARD_DNTV_LIVE_DVB_T_PRO, },{ .subvendor = 0x1554, .subdevice = 0x4813, .card = CX88_BOARD_PIXELVIEW_PLAYTV_P7000, },{ .subvendor = 0x14f1, .subdevice = 0x0842, .card = CX88_BOARD_NPGTECH_REALTV_TOP10FM, },{ .subvendor = 0x107d, .subdevice = 0x665e, .card = CX88_BOARD_WINFAST_DTV2000H, },{ .subvendor = 0x18ac, .subdevice = 0xd800, /* FusionHDTV 3 Gold (original revision) */ .card = CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_Q, },{ .subvendor = 0x14f1, .subdevice = 0x0084, .card = CX88_BOARD_GENIATECH_DVBS, },{ .subvendor = 0x0070, .subdevice = 0x1404, .card = CX88_BOARD_HAUPPAUGE_HVR3000, },{ .subvendor = 0x1461, .subdevice = 0xc111, /* AverMedia M150-D */ /* This board is known to work with the ASUS PVR416 config */ .card = CX88_BOARD_ASUS_PVR_416, },{ .subvendor = 0xc180, .subdevice = 0xc980, .card = CX88_BOARD_TE_DTV_250_OEM_SWANN, },{ .subvendor = 0x0070, .subdevice = 0x9600, .card = CX88_BOARD_HAUPPAUGE_HVR1300, },{ .subvendor = 0x0070, .subdevice = 0x9601, .card = CX88_BOARD_HAUPPAUGE_HVR1300, },{ .subvendor = 0x0070, .subdevice = 0x9602, .card = CX88_BOARD_HAUPPAUGE_HVR1300, },{ .subvendor = 0x107d, .subdevice = 0x6632, .card = CX88_BOARD_LEADTEK_PVR2000, },{ .subvendor = 0x12ab, .subdevice = 0x2300, /* Club3D Zap TV2100 */ .card = CX88_BOARD_KWORLD_DVB_T_CX22702, },{ .subvendor = 0x0070, .subdevice = 0x9000, .card = CX88_BOARD_HAUPPAUGE_DVB_T1, },{ .subvendor = 0x0070, .subdevice = 0x1400, .card = CX88_BOARD_HAUPPAUGE_HVR3000, },{ .subvendor = 0x0070, .subdevice = 0x1401, .card = CX88_BOARD_HAUPPAUGE_HVR3000, },{ .subvendor = 0x0070, .subdevice = 0x1402, .card = CX88_BOARD_HAUPPAUGE_HVR3000, }, }; const unsigned int cx88_idcount = ARRAY_SIZE(cx88_subids); /* ----------------------------------------------------------------------- */ /* some leadtek specific stuff */ static void leadtek_eeprom(struct cx88_core *core, u8 *eeprom_data) { /* This is just for the "Winfast 2000XP Expert" board ATM; I don't have data on * any others. * * Byte 0 is 1 on the NTSC board. */ if (eeprom_data[4] != 0x7d || eeprom_data[5] != 0x10 || eeprom_data[7] != 0x66) { printk(KERN_WARNING "%s: Leadtek eeprom invalid.\n", core->name); return; } core->has_radio = 1; core->tuner_type = (eeprom_data[6] == 0x13) ? 43 : 38; printk(KERN_INFO "%s: Leadtek Winfast 2000XP Expert config: " "tuner=%d, eeprom[0]=0x%02x\n", core->name, core->tuner_type, eeprom_data[0]); } static void hauppauge_eeprom(struct cx88_core *core, u8 *eeprom_data) { struct tveeprom tv; tveeprom_hauppauge_analog(&core->i2c_client, &tv, eeprom_data); core->tuner_type = tv.tuner_type; core->tuner_formats = tv.tuner_formats; core->has_radio = tv.has_radio; /* Make sure we support the board model */ switch (tv.model) { case 14009: /* WinTV-HVR3000 (Retail, IR, b/panel video, 3.5mm audio in) */ case 14019: /* WinTV-HVR3000 (Retail, IR Blaster, b/panel video, 3.5mm audio in) */ case 14029: /* WinTV-HVR3000 (Retail, IR, b/panel video, 3.5mm audio in - 880 bridge) */ case 14109: /* WinTV-HVR3000 (Retail, IR, b/panel video, 3.5mm audio in - low profile) */ case 14129: /* WinTV-HVR3000 (Retail, IR, b/panel video, 3.5mm audio in - 880 bridge - LP) */ case 14559: /* WinTV-HVR3000 (OEM, no IR, b/panel video, 3.5mm audio in) */ case 14569: /* WinTV-HVR3000 (OEM, no IR, no back panel video) */ case 14659: /* WinTV-HVR3000 (OEM, no IR, b/panel video, RCA audio in - Low profile) */ case 14669: /* WinTV-HVR3000 (OEM, no IR, no b/panel video - Low profile) */ case 28552: /* WinTV-PVR 'Roslyn' (No IR) */ case 34519: /* WinTV-PCI-FM */ case 90002: /* Nova-T-PCI (9002) */ case 92001: /* Nova-S-Plus (Video and IR) */ case 92002: /* Nova-S-Plus (Video and IR) */ case 90003: /* Nova-T-PCI (9002 No RF out) */ case 90500: /* Nova-T-PCI (oem) */ case 90501: /* Nova-T-PCI (oem/IR) */ case 92000: /* Nova-SE2 (OEM, No Video or IR) */ case 94009: /* WinTV-HVR1100 (Video and IR Retail) */ case 94501: /* WinTV-HVR1100 (Video and IR OEM) */ case 96009: /* WinTV-HVR1300 (PAL Video, MPEG Video and IR RX) */ case 96019: /* WinTV-HVR1300 (PAL Video, MPEG Video and IR RX/TX) */ case 96559: /* WinTV-HVR1300 (PAL Video, MPEG Video no IR) */ case 96569: /* WinTV-HVR1300 () */ case 96659: /* WinTV-HVR1300 () */ case 98559: /* WinTV-HVR1100LP (Video no IR, Retail - Low Profile) */ /* known */ break; default: printk("%s: warning: unknown hauppauge model #%d\n", core->name, tv.model); break; } printk(KERN_INFO "%s: hauppauge eeprom: model=%d\n", core->name, tv.model); } /* ----------------------------------------------------------------------- */ /* some GDI (was: Modular Technology) specific stuff */ static struct { int id; int fm; char *name; } gdi_tuner[] = { [ 0x01 ] = { .id = TUNER_ABSENT, .name = "NTSC_M" }, [ 0x02 ] = { .id = TUNER_ABSENT, .name = "PAL_B" }, [ 0x03 ] = { .id = TUNER_ABSENT, .name = "PAL_I" }, [ 0x04 ] = { .id = TUNER_ABSENT, .name = "PAL_D" }, [ 0x05 ] = { .id = TUNER_ABSENT, .name = "SECAM" }, [ 0x10 ] = { .id = TUNER_ABSENT, .fm = 1, .name = "TEMIC_4049" }, [ 0x11 ] = { .id = TUNER_TEMIC_4136FY5, .name = "TEMIC_4136" }, [ 0x12 ] = { .id = TUNER_ABSENT, .name = "TEMIC_4146" }, [ 0x20 ] = { .id = TUNER_PHILIPS_FQ1216ME, .fm = 1, .name = "PHILIPS_FQ1216_MK3" }, [ 0x21 ] = { .id = TUNER_ABSENT, .fm = 1, .name = "PHILIPS_FQ1236_MK3" }, [ 0x22 ] = { .id = TUNER_ABSENT, .name = "PHILIPS_FI1236_MK3" }, [ 0x23 ] = { .id = TUNER_ABSENT, .name = "PHILIPS_FI1216_MK3" }, }; static void gdi_eeprom(struct cx88_core *core, u8 *eeprom_data) { char *name = (eeprom_data[0x0d] < ARRAY_SIZE(gdi_tuner)) ? gdi_tuner[eeprom_data[0x0d]].name : NULL; printk(KERN_INFO "%s: GDI: tuner=%s\n", core->name, name ? name : "unknown"); if (NULL == name) return; core->tuner_type = gdi_tuner[eeprom_data[0x0d]].id; core->has_radio = gdi_tuner[eeprom_data[0x0d]].fm; } /* ----------------------------------------------------------------------- */ /* some DViCO specific stuff */ static void dvico_fusionhdtv_hybrid_init(struct cx88_core *core) { struct i2c_msg msg = { .addr = 0x45, .flags = 0 }; int i, err; static u8 init_bufs[13][5] = { { 0x10, 0x00, 0x20, 0x01, 0x03 }, { 0x10, 0x10, 0x01, 0x00, 0x21 }, { 0x10, 0x10, 0x10, 0x00, 0xCA }, { 0x10, 0x10, 0x12, 0x00, 0x08 }, { 0x10, 0x10, 0x13, 0x00, 0x0A }, { 0x10, 0x10, 0x16, 0x01, 0xC0 }, { 0x10, 0x10, 0x22, 0x01, 0x3D }, { 0x10, 0x10, 0x73, 0x01, 0x2E }, { 0x10, 0x10, 0x72, 0x00, 0xC5 }, { 0x10, 0x10, 0x71, 0x01, 0x97 }, { 0x10, 0x10, 0x70, 0x00, 0x0F }, { 0x10, 0x10, 0xB0, 0x00, 0x01 }, { 0x03, 0x0C }, }; for (i = 0; i < 13; i++) { msg.buf = init_bufs[i]; msg.len = (i != 12 ? 5 : 2); err = i2c_transfer(&core->i2c_adap, &msg, 1); if (err != 1) { printk("dvico_fusionhdtv_hybrid_init buf %d failed (err = %d)!\n", i, err); return; } } } /* ----------------------------------------------------------------------- */ void cx88_card_list(struct cx88_core *core, struct pci_dev *pci) { int i; if (0 == pci->subsystem_vendor && 0 == pci->subsystem_device) { printk("%s: Your board has no valid PCI Subsystem ID and thus can't\n" "%s: be autodetected. Please pass card=<n> insmod option to\n" "%s: workaround that. Redirect complaints to the vendor of\n" "%s: the TV card. Best regards,\n" "%s: -- tux\n", core->name,core->name,core->name,core->name,core->name); } else { printk("%s: Your board isn't known (yet) to the driver. You can\n" "%s: try to pick one of the existing card configs via\n" "%s: card=<n> insmod option. Updating to the latest\n" "%s: version might help as well.\n", core->name,core->name,core->name,core->name); } printk("%s: Here is a list of valid choices for the card=<n> insmod option:\n", core->name); for (i = 0; i < cx88_bcount; i++) printk("%s: card=%d -> %s\n", core->name, i, cx88_boards[i].name); } void cx88_card_setup_pre_i2c(struct cx88_core *core) { switch (core->board) { case CX88_BOARD_HAUPPAUGE_HVR1300: /* Bring the 702 demod up before i2c scanning/attach or devices are hidden */ /* We leave here with the 702 on the bus */ cx_write(MO_GP0_IO, 0x0000e780); udelay(1000); cx_clear(MO_GP0_IO, 0x00000080); udelay(50); cx_set(MO_GP0_IO, 0x00000080); /* 702 out of reset */ udelay(1000); break; } } void cx88_card_setup(struct cx88_core *core) { static u8 eeprom[256]; if (0 == core->i2c_rc) { core->i2c_client.addr = 0xa0 >> 1; tveeprom_read(&core->i2c_client,eeprom,sizeof(eeprom)); } switch (core->board) { case CX88_BOARD_HAUPPAUGE: case CX88_BOARD_HAUPPAUGE_ROSLYN: if (0 == core->i2c_rc) hauppauge_eeprom(core,eeprom+8); break; case CX88_BOARD_GDI: if (0 == core->i2c_rc) gdi_eeprom(core,eeprom); break; case CX88_BOARD_WINFAST2000XP_EXPERT: if (0 == core->i2c_rc) leadtek_eeprom(core,eeprom); break; case CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1: case CX88_BOARD_HAUPPAUGE_NOVASE2_S1: case CX88_BOARD_HAUPPAUGE_DVB_T1: case CX88_BOARD_HAUPPAUGE_HVR1100: case CX88_BOARD_HAUPPAUGE_HVR1100LP: case CX88_BOARD_HAUPPAUGE_HVR3000: case CX88_BOARD_HAUPPAUGE_HVR1300: if (0 == core->i2c_rc) hauppauge_eeprom(core,eeprom); break; case CX88_BOARD_KWORLD_DVBS_100: cx_write(MO_GP0_IO, 0x000007f8); cx_write(MO_GP1_IO, 0x00000001); break; case CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_DUAL: /* GPIO0:6 is hooked to FX2 reset pin */ cx_set(MO_GP0_IO, 0x00004040); cx_clear(MO_GP0_IO, 0x00000040); msleep(1000); cx_set(MO_GP0_IO, 0x00004040); /* FALLTHROUGH */ case CX88_BOARD_DVICO_FUSIONHDTV_DVB_T1: case CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_PLUS: case CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_HYBRID: /* GPIO0:0 is hooked to mt352 reset pin */ cx_set(MO_GP0_IO, 0x00000101); cx_clear(MO_GP0_IO, 0x00000001); msleep(1); cx_set(MO_GP0_IO, 0x00000101); if (0 == core->i2c_rc && core->board == CX88_BOARD_DVICO_FUSIONHDTV_DVB_T_HYBRID) dvico_fusionhdtv_hybrid_init(core); break; case CX88_BOARD_KWORLD_DVB_T: case CX88_BOARD_DNTV_LIVE_DVB_T: cx_set(MO_GP0_IO, 0x00000707); cx_set(MO_GP2_IO, 0x00000101); cx_clear(MO_GP2_IO, 0x00000001); msleep(1); cx_clear(MO_GP0_IO, 0x00000007); cx_set(MO_GP2_IO, 0x00000101); break; case CX88_BOARD_DNTV_LIVE_DVB_T_PRO: cx_write(MO_GP0_IO, 0x00080808); break; case CX88_BOARD_ATI_HDTVWONDER: if (0 == core->i2c_rc) { /* enable tuner */ int i; static const u8 buffer [] = { 0x10,0x12,0x13,0x04,0x16,0x00,0x14,0x04,0x017,0x00 }; core->i2c_client.addr = 0x0a; for (i = 0; i < 5; i++) if (2 != i2c_master_send(&core->i2c_client,&buffer[i*2],2)) printk(KERN_WARNING "%s: Unable to enable tuner(%i).\n", core->name, i); } break; } if (cx88_boards[core->board].radio.type == CX88_RADIO) core->has_radio = 1; } /* ------------------------------------------------------------------ */ EXPORT_SYMBOL(cx88_boards); /* * Local variables: * c-basic-offset: 8 * End: * kate: eol "unix"; indent-width 3; remove-trailing-space on; replace-trailing-space-save on; tab-width 8; replace-tabs off; space-indent off; mixed-indent off */
from asyncio import get_event_loop import json import aiohttp from tentacruel.pinger import ensure_proactor HEOS_GATEWAY = "http://192.168.0.21:9617" async def amain(): async with aiohttp.ClientSession() as session: async with session.ws_connect('http://192.168.0.21:9617/heos') as socket: GET_PLAYERS = {"command":"player/get_players","parameters":{},"requestId":"2cc86994-73fa-4283-91b6-a42d93a6ee15"} await socket.send_str(json.dumps(GET_PLAYERS)) reply = json.loads(await socket.receive_str()) LIVING_ROOM = [line for line in reply["message"] if line["name"] == 'Living Room'][0]['pid'] print(LIVING_ROOM) if __name__ == "__main__": ensure_proactor() loop = get_event_loop() loop.run_until_complete(amain())
import argparse import os import numpy as np from sklearn.cross_validation import StratifiedKFold import autosklearn import autosklearn.data import autosklearn.data.competition_data_manager from autosklearn.evaluation.util import calculate_score from ParamSklearn.classification import ParamSklearnClassifier parser = argparse.ArgumentParser() parser.add_argument('input') parser.add_argument('output') args = parser.parse_args() input = args.input dataset = 'volkert' output = args.output path = os.path.join(input, dataset) D = autosklearn.data.competition_data_manager.CompetitionDataManager(path) X = D.data['X_train'] y = D.data['Y_train'] X_valid = D.data['X_valid'] X_test = D.data['X_test'] # Replace the following array by a new ensemble choices = \ [(0.480000, ParamSklearnClassifier(configuration={ 'balancing:strategy': 'none', 'classifier:__choice__': 'random_forest', 'classifier:random_forest:bootstrap': 'True', 'classifier:random_forest:criterion': 'entropy', 'classifier:random_forest:max_depth': 'None', 'classifier:random_forest:max_features': 4.885151102990943, 'classifier:random_forest:max_leaf_nodes': 'None', 'classifier:random_forest:min_samples_leaf': 2, 'classifier:random_forest:min_samples_split': 2, 'classifier:random_forest:min_weight_fraction_leaf': 0.0, 'classifier:random_forest:n_estimators': 100, 'imputation:strategy': 'median', 'one_hot_encoding:minimum_fraction': 0.059297498551361, 'one_hot_encoding:use_minimum_fraction': 'True', 'preprocessor:__choice__': 'gem', 'preprocessor:gem:N': 13, 'preprocessor:gem:precond': 0.31299029323203487, 'rescaling:__choice__': 'min/max'})), (0.300000, ParamSklearnClassifier( configuration={ 'balancing:strategy': 'none', 'classifier:__choice__': 'random_forest', 'classifier:random_forest:bootstrap': 'False', 'classifier:random_forest:criterion': 'entropy', 'classifier:random_forest:max_depth': 'None', 'classifier:random_forest:max_features': 4.908992016092793, 'classifier:random_forest:max_leaf_nodes': 'None', 'classifier:random_forest:min_samples_leaf': 2, 'classifier:random_forest:min_samples_split': 6, 'classifier:random_forest:min_weight_fraction_leaf': 0.0, 'classifier:random_forest:n_estimators': 100, 'imputation:strategy': 'mean', 'one_hot_encoding:minimum_fraction': 0.009349768412523697, 'one_hot_encoding:use_minimum_fraction': 'True', 'preprocessor:__choice__': 'fast_ica', 'preprocessor:fast_ica:algorithm': 'deflation', 'preprocessor:fast_ica:fun': 'exp', 'preprocessor:fast_ica:whiten': 'False', 'rescaling:__choice__': 'none'})), (0.180000, ParamSklearnClassifier( configuration={ 'balancing:strategy': 'weighting', 'classifier:__choice__': 'libsvm_svc', 'classifier:libsvm_svc:C': 445.91825904609124, 'classifier:libsvm_svc:gamma': 0.03873498413280048, 'classifier:libsvm_svc:kernel': 'rbf', 'classifier:libsvm_svc:max_iter': -1, 'classifier:libsvm_svc:shrinking': 'True', 'classifier:libsvm_svc:tol': 0.0008078719040695308, 'imputation:strategy': 'median', 'one_hot_encoding:use_minimum_fraction': 'False', 'preprocessor:__choice__': 'pca', 'preprocessor:pca:keep_variance': 0.7596970304901425, 'preprocessor:pca:whiten': 'True', 'rescaling:__choice__': 'standardize'})), (0.040000, ParamSklearnClassifier( configuration={ 'balancing:strategy': 'none', 'classifier:__choice__': 'random_forest', 'classifier:random_forest:bootstrap': 'False', 'classifier:random_forest:criterion': 'entropy', 'classifier:random_forest:max_depth': 'None', 'classifier:random_forest:max_features': 3.5340547102377364, 'classifier:random_forest:max_leaf_nodes': 'None', 'classifier:random_forest:min_samples_leaf': 2, 'classifier:random_forest:min_samples_split': 6, 'classifier:random_forest:min_weight_fraction_leaf': 0.0, 'classifier:random_forest:n_estimators': 100, 'imputation:strategy': 'mean', 'one_hot_encoding:minimum_fraction': 0.008518947433195237, 'one_hot_encoding:use_minimum_fraction': 'True', 'preprocessor:__choice__': 'fast_ica', 'preprocessor:fast_ica:algorithm': 'deflation', 'preprocessor:fast_ica:fun': 'cube', 'preprocessor:fast_ica:whiten': 'False', 'rescaling:__choice__': 'none'})), ] classifiers = [] targets = [] predictions = [] predictions_valid = [] predictions_test = [] # Make predictions and weight them iteration = 0 for weight, classifier in choices: iteration += 1 print dataset, "Iteration %d/%d" % (iteration, len(choices)) classifiers.append(classifier) try: classifier.fit(X.copy(), y.copy()) predictions_valid.append( classifier.predict_proba(X_valid.copy()) * weight) predictions_test.append( classifier.predict_proba(X_test.copy()) * weight) except Exception as e: print e print classifier # Output the predictions for name, predictions in [('valid', predictions_valid), ('test', predictions_test)]: predictions = np.array(predictions) predictions = np.sum(predictions, axis=0) filepath = os.path.join(output, '%s_%s_000.predict' % (dataset, name)) np.savetxt(filepath, predictions, delimiter=' ')
import mysql.connector from mysql.connector.constants import ClientFlag config = { 'user': 'root', 'password': 'admin666', 'host': '34.71.98.84', 'client_flags': [ClientFlag.SSL], 'ssl_ca': 'server-ca.pem', 'ssl_cert': 'client-cert.pem', 'ssl_key': 'client-key.pem' } config['database'] = 'pythondb' # add new database to config dict cnxn = mysql.connector.connect(**config) cursor = cnxn.cursor() cursor.execute("SELECT COUNT(wastetype) FROM wastedata WHERE wastetype = 'Organic'") out = cursor.fetchall() for row in out : organic=row[0] cursor.execute("SELECT COUNT(wastetype) FROM wastedata WHERE wastetype = 'Recyclable'") out1 = cursor.fetchall() for row in out1 : recyclable=row[0] cursor.execute("SELECT COUNT(wastetype) FROM wastedata WHERE wastetype = 'Electronic'") out2 = cursor.fetchall() for row in out2 : electronics=row[0]
import React from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { bindActionCreators } from "redux"; import toastr from "toastr"; import * as productAction from "../../action/ProductAction"; import ProductForm from "./ProductForm"; export class AddOrEditProductContainer extends React.Component { constructor() { super(); this.handleSave = this.handleSave.bind(this); this.handleCancel = this.handleCancel.bind(this); } componentDidMount() { this.props.action .getProductAction(this.props.match.params.id) .catch(error => { toastr.error(error); }); } handleSave(values) { const product = { id: values.id, code: values.code, name: values.name }; this.props.action .saveProductAction(product) .then(() => { toastr.success("Product saved"); this.props.history.push("/datas/products"); }) .catch(error => { toastr.error(error); }); } handleCancel(event) { event.preventDefault(); this.props.history.replace("/datas/products"); } render() { const { initialValues } = this.props; const heading = initialValues && initialValues.id ? "Edit" : "Add"; console.log(this.props.initialValues); return ( <div className="content-wrapper"> <div className="container"> <ProductForm heading={heading} handleSave={this.handleSave} handleCancel={this.handleCancel} initialValues={this.props.initialValues} /> </div> </div> ); } } const mapStateToProps = (state, ownProps) => { const productId = parseInt(ownProps.match.params.id); if ( productId && state.selectedProductReducer.product && productId === state.selectedProductReducer.product.id ) { return { initialValues: state.selectedProductReducer.product }; } else { return {}; } }; const mapDispatchToProps = dispatch => ({ action: bindActionCreators(productAction, dispatch) }); AddOrEditProductContainer.propTypes = { action: PropTypes.object.isRequired, history: PropTypes.object, initialValues: PropTypes.object, match: PropTypes.object.isRequired }; export default connect( mapStateToProps, mapDispatchToProps )(AddOrEditProductContainer);
# ---------------------------------------------------------------------------- # Copyright (c) 2017-2021, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import collections from sklearn.ensemble import IsolationForest from sklearn.metrics import mean_squared_error, accuracy_score from sklearn.feature_extraction import DictVectorizer from sklearn.pipeline import Pipeline import qiime2 import pandas as pd import biom import skbio from .utilities import (_load_data, _prepare_training_data, nested_cross_validation, _fit_estimator, _extract_features, _plot_accuracy, _summarize_estimator, predict_probabilities, _classifiers) defaults = { 'test_size': 0.2, 'step': 0.05, 'cv': 5, 'n_jobs': 1, 'n_estimators': 100, 'estimator_c': 'RandomForestClassifier', 'estimator_r': 'RandomForestRegressor', 'palette': 'sirocco', 'missing_samples': 'error' } def metatable(ctx, metadata, table=None, missing_samples='ignore', missing_values='error', drop_all_unique=False): # gather numeric metadata metadata = metadata.filter_columns( column_type='numeric', drop_all_unique=drop_all_unique, drop_zero_variance=True, drop_all_missing=True).to_dataframe() if missing_values == 'drop_samples': metadata = metadata.dropna(axis=0) elif missing_values == 'drop_features': metadata = metadata.dropna(axis=1) elif missing_values == 'error' and metadata.isnull().values.any(): raise ValueError('You are attempting to coerce metadata containing ' 'missing values into a feature table! These may ' 'cause fatal errors downstream and must be removed ' 'or converted to 0. See the missing_values parameter ' 'to review your options.') elif missing_values == 'fill': metadata = metadata.fillna(0.) # drop columns with negative values # grab column IDs with all values >= 0 metadata = metadata.loc[:, (metadata >= 0).all(axis=0)] if len(metadata.columns) == 0: raise ValueError('All metadata columns have been filtered.') if len(metadata.index) == 0: raise ValueError('All metadata samples have been filtered.') # only retain IDs that intersect with table if table is not None: tab = table.view(biom.Table) table_ids = set(tab.ids()) metadata_ids = set(metadata.index) sample_ids = table_ids.intersection(metadata_ids) if missing_samples == 'error' and len(sample_ids) != len(table_ids): raise ValueError('Missing samples in metadata: %r' % table_ids.difference(metadata_ids)) else: metadata = metadata.loc[sample_ids] if len(sample_ids) < len(table_ids): tab = tab.filter( ids_to_keep=sample_ids, axis='sample', inplace=False) table = ctx.make_artifact('FeatureTable[Frequency]', tab) # convert to FeatureTable[Frequency] metadata = metadata.T metadata = biom.table.Table( metadata.values, metadata.index, metadata.columns) metatab = ctx.make_artifact('FeatureTable[Frequency]', metadata) # optionally merge with existing feature table if table is not None: merge = ctx.get_action('feature_table', 'merge') metatab, = merge( [table, metatab], overlap_method='error_on_overlapping_feature') return metatab def classify_samples_from_dist(ctx, distance_matrix, metadata, k=1, palette=defaults['palette']): ''' Returns knn classifier results from a distance matrix.''' distance_matrix = distance_matrix.view(skbio.DistanceMatrix) predictions = [] metadata_series = metadata.to_series() for i, row in enumerate(distance_matrix): dists = [] categories = [] for j, dist in enumerate(row): if j == i: continue # exclude self dists.append(dist) categories.append(metadata_series[distance_matrix.ids[j]]) # k-long series of (category: dist) ordered small -> large nn_categories = pd.Series(dists, index=categories).nsmallest(k) counter = collections.Counter(nn_categories.index) max_counts = max(counter.values()) # in order of closeness, pick a category that is or shares # max_counts for category in nn_categories.index: if counter[category] == max_counts: predictions.append(category) break predictions = pd.Series(predictions, index=distance_matrix.ids) predictions.index.name = 'SampleID' pred = qiime2.Artifact.import_data( 'SampleData[ClassifierPredictions]', predictions) confusion = ctx.get_action('sample_classifier', 'confusion_matrix') accuracy_results, = confusion( pred, metadata, missing_samples='ignore', palette=palette) return pred, accuracy_results def classify_samples(ctx, table, metadata, test_size=defaults['test_size'], step=defaults['step'], cv=defaults['cv'], random_state=None, n_jobs=defaults['n_jobs'], n_estimators=defaults['n_estimators'], estimator=defaults['estimator_c'], optimize_feature_selection=False, parameter_tuning=False, palette=defaults['palette'], missing_samples=defaults['missing_samples']): split = ctx.get_action('sample_classifier', 'split_table') fit = ctx.get_action('sample_classifier', 'fit_classifier') predict_test = ctx.get_action( 'sample_classifier', 'predict_classification') summarize_estimator = ctx.get_action('sample_classifier', 'summarize') confusion = ctx.get_action('sample_classifier', 'confusion_matrix') heat = ctx.get_action('sample_classifier', 'heatmap') X_train, X_test = split(table, metadata, test_size, random_state, stratify=True, missing_samples=missing_samples) sample_estimator, importance = fit( X_train, metadata, step, cv, random_state, n_jobs, n_estimators, estimator, optimize_feature_selection, parameter_tuning, missing_samples='ignore') predictions, probabilities, = predict_test( X_test, sample_estimator, n_jobs) summary, = summarize_estimator(sample_estimator) accuracy_results, = confusion(predictions, metadata, probabilities, missing_samples='ignore', palette=palette) _heatmap, _ = heat(table, importance, sample_metadata=metadata, group_samples=True, missing_samples=missing_samples) return (sample_estimator, importance, predictions, summary, accuracy_results, probabilities, _heatmap) def regress_samples(ctx, table, metadata, test_size=defaults['test_size'], step=defaults['step'], cv=defaults['cv'], random_state=None, n_jobs=defaults['n_jobs'], n_estimators=defaults['n_estimators'], estimator=defaults['estimator_r'], optimize_feature_selection=False, stratify=False, parameter_tuning=False, missing_samples=defaults['missing_samples']): split = ctx.get_action('sample_classifier', 'split_table') fit = ctx.get_action('sample_classifier', 'fit_regressor') predict_test = ctx.get_action('sample_classifier', 'predict_regression') summarize_estimator = ctx.get_action('sample_classifier', 'summarize') scatter = ctx.get_action('sample_classifier', 'scatterplot') X_train, X_test = split(table, metadata, test_size, random_state, stratify, missing_samples=missing_samples) sample_estimator, importance = fit( X_train, metadata, step, cv, random_state, n_jobs, n_estimators, estimator, optimize_feature_selection, parameter_tuning, missing_samples='ignore') predictions, = predict_test(X_test, sample_estimator, n_jobs) summary, = summarize_estimator(sample_estimator) accuracy_results, = scatter(predictions, metadata, 'ignore') return (sample_estimator, importance, predictions, summary, accuracy_results) def fit_classifier(table: biom.Table, metadata: qiime2.CategoricalMetadataColumn, step: float = defaults['step'], cv: int = defaults['cv'], random_state: int = None, n_jobs: int = defaults['n_jobs'], n_estimators: int = defaults['n_estimators'], estimator: str = defaults['estimator_c'], optimize_feature_selection: bool = False, parameter_tuning: bool = False, missing_samples: str = defaults['missing_samples'] ) -> (Pipeline, pd.DataFrame): estimator, importance = _fit_estimator( table, metadata, estimator, n_estimators, step, cv, random_state, n_jobs, optimize_feature_selection, parameter_tuning, missing_samples=missing_samples, classification=True) return estimator, importance def fit_regressor(table: biom.Table, metadata: qiime2.CategoricalMetadataColumn, step: float = defaults['step'], cv: int = defaults['cv'], random_state: int = None, n_jobs: int = defaults['n_jobs'], n_estimators: int = defaults['n_estimators'], estimator: str = defaults['estimator_r'], optimize_feature_selection: bool = False, parameter_tuning: bool = False, missing_samples: str = defaults['missing_samples'] ) -> (Pipeline, pd.DataFrame): estimator, importance = _fit_estimator( table, metadata, estimator, n_estimators, step, cv, random_state, n_jobs, optimize_feature_selection, parameter_tuning, missing_samples=missing_samples, classification=False) return estimator, importance def predict_base(table, sample_estimator, n_jobs): # extract feature data from biom feature_data = _extract_features(table) index = table.ids() # reset n_jobs if this is a valid parameter for the estimator if 'est__n_jobs' in sample_estimator.get_params().keys(): sample_estimator.set_params(est__n_jobs=n_jobs) # predict values and output as series y_pred = sample_estimator.predict(feature_data) # need to flatten arrays that come out as multidimensional y_pred = y_pred.flatten() y_pred = pd.Series(y_pred, index=index, name='prediction') y_pred.index.name = 'SampleID' # log prediction probabilities (classifiers only) if sample_estimator.named_steps.est.__class__.__name__ in _classifiers: probs = predict_probabilities(sample_estimator, feature_data, index) else: probs = None return y_pred, probs def predict_classification(table: biom.Table, sample_estimator: Pipeline, n_jobs: int = defaults['n_jobs']) -> ( pd.Series, pd.DataFrame): return predict_base(table, sample_estimator, n_jobs) def predict_regression(table: biom.Table, sample_estimator: Pipeline, n_jobs: int = defaults['n_jobs']) -> pd.Series: # we only return the predictions, not the probabilities, which are empty # for regressors. return predict_base(table, sample_estimator, n_jobs)[0] def split_table(table: biom.Table, metadata: qiime2.MetadataColumn, test_size: float = defaults['test_size'], random_state: int = None, stratify: str = True, missing_samples: str = defaults['missing_samples'] ) -> (biom.Table, biom.Table): column = metadata.name X_train, X_test, y_train, y_test = _prepare_training_data( table, metadata, column, test_size, random_state, load_data=True, stratify=stratify, missing_samples=missing_samples) # TODO: we can consider returning the metadata (y_train, y_test) if a # SampleData[Metadata] type comes into existence. For now we will just # throw this out. return X_train, X_test def regress_samples_ncv( table: biom.Table, metadata: qiime2.NumericMetadataColumn, cv: int = defaults['cv'], random_state: int = None, n_jobs: int = defaults['n_jobs'], n_estimators: int = defaults['n_estimators'], estimator: str = defaults['estimator_r'], stratify: str = False, parameter_tuning: bool = False, missing_samples: str = defaults['missing_samples'] ) -> (pd.Series, pd.DataFrame): y_pred, importances, probabilities = nested_cross_validation( table, metadata, cv, random_state, n_jobs, n_estimators, estimator, stratify, parameter_tuning, classification=False, scoring=mean_squared_error, missing_samples=missing_samples) return y_pred, importances def classify_samples_ncv( table: biom.Table, metadata: qiime2.CategoricalMetadataColumn, cv: int = defaults['cv'], random_state: int = None, n_jobs: int = defaults['n_jobs'], n_estimators: int = defaults['n_estimators'], estimator: str = defaults['estimator_c'], parameter_tuning: bool = False, missing_samples: str = defaults['missing_samples'] ) -> (pd.Series, pd.DataFrame, pd.DataFrame): y_pred, importances, probabilities = nested_cross_validation( table, metadata, cv, random_state, n_jobs, n_estimators, estimator, stratify=True, parameter_tuning=parameter_tuning, classification=False, scoring=accuracy_score, missing_samples=missing_samples) return y_pred, importances, probabilities def scatterplot(output_dir: str, predictions: pd.Series, truth: qiime2.NumericMetadataColumn, missing_samples: str = defaults['missing_samples']) -> None: predictions = pd.to_numeric(predictions) _plot_accuracy(output_dir, predictions, truth, probabilities=None, missing_samples=missing_samples, classification=False, palette=None, plot_title='regression scatterplot') def confusion_matrix(output_dir: str, predictions: pd.Series, truth: qiime2.CategoricalMetadataColumn, probabilities: pd.DataFrame = None, missing_samples: str = defaults['missing_samples'], vmin: int = 'auto', vmax: int = 'auto', palette: str = defaults['palette']) -> None: if vmin == 'auto': vmin = None if vmax == 'auto': vmax = None predictions = predictions.astype(str) _plot_accuracy(output_dir, predictions, truth, probabilities, missing_samples=missing_samples, classification=True, palette=palette, plot_title='confusion matrix', vmin=vmin, vmax=vmax) def summarize(output_dir: str, sample_estimator: Pipeline): _summarize_estimator(output_dir, sample_estimator) def heatmap(ctx, table, importance, sample_metadata=None, feature_metadata=None, feature_count=50, importance_threshold=0, group_samples=False, normalize=True, missing_samples='ignore', metric='braycurtis', method='average', cluster='features', color_scheme='rocket'): filter_features = ctx.get_action('feature_table', 'filter_features') group = ctx.get_action('feature_table', 'group') make_heatmap = ctx.get_action('feature_table', 'heatmap') filter_samples = ctx.get_action('feature_table', 'filter_samples') if group_samples and sample_metadata is None: raise ValueError( 'If group_samples is enabled, sample_metadata are not optional.') if missing_samples == 'ignore' and sample_metadata is None: raise ValueError( 'If missing_samples is ignore, metadata are not optional') clustermap_params = { 'cluster': cluster, 'normalize': normalize, 'metric': metric, 'method': method, 'color_scheme': color_scheme} # load importance data and sum rows (to average importances if there are # multiple scores). importance = importance.view(pd.DataFrame) importance = importance.sum(1) # filter importances by user criteria importance = importance.sort_values(ascending=False) if importance_threshold > 0: importance = importance[importance > importance_threshold] if feature_count > 0: importance = importance[:feature_count] importance.name = 'importance' importance = qiime2.Metadata(importance.to_frame()) # filter features by importance table, = filter_features(table, metadata=importance) if missing_samples == 'ignore': table, = filter_samples( table, metadata=qiime2.Metadata(sample_metadata.to_dataframe())) # optionally group feature table by sample metadata # otherwise annotate heatmap with sample metadata if group_samples: table, = group(table, metadata=sample_metadata, axis='sample', mode='sum') elif sample_metadata is not None: clustermap_params['sample_metadata'] = sample_metadata # label features using feature metadata if feature_metadata is not None: clustermap_params['feature_metadata'] = feature_metadata # make yer heatmap clustermap, = make_heatmap(table, **clustermap_params) return clustermap, table # The following method is experimental and is not registered in the current # release. Any use of the API is at user's own risk. def detect_outliers(table: biom.Table, metadata: qiime2.Metadata, subset_column: str = None, subset_value: str = None, n_estimators: int = defaults['n_estimators'], contamination: float = 0.05, random_state: int = None, n_jobs: int = defaults['n_jobs'], missing_samples: str = 'ignore') -> (pd.Series): features, sample_md = _load_data( table, metadata, missing_samples=missing_samples) # if opting to train on a subset, choose subset that fits criteria if subset_column and subset_value: X_train = \ [f for s, f in zip(sample_md[subset_column] == subset_value, features) if s] # raise error if subset_column or subset_value (but not both) are set elif subset_column is not None or subset_value is not None: raise ValueError(( 'subset_column and subset_value must both be provided with a ' 'valid value to perform model training on a subset of data.')) else: X_train = features # fit isolation tree estimator = Pipeline([('dv', DictVectorizer()), ('est', IsolationForest(n_jobs=n_jobs, n_estimators=n_estimators, contamination=contamination, random_state=random_state, ))]) estimator.fit(X_train) # predict outlier status y_pred = estimator.predict(features) y_pred = pd.Series(y_pred, index=sample_md.index) # predict reports whether sample is an inlier; change to outlier status y_pred[y_pred == -1] = 'True' y_pred[y_pred == 1] = 'False' y_pred.name = "outlier" return y_pred
import { ARRAY_INSERT, ARRAY_MOVE, ARRAY_POP, ARRAY_PUSH, ARRAY_REMOVE, ARRAY_REMOVE_ALL, ARRAY_SHIFT, ARRAY_SPLICE, ARRAY_SWAP, ARRAY_UNSHIFT, AUTOFILL, BLUR, CHANGE, CLEAR_SUBMIT, CLEAR_SUBMIT_ERRORS, CLEAR_ASYNC_ERROR, DESTROY, FOCUS, INITIALIZE, REGISTER_FIELD, RESET, SET_SUBMIT_FAILED, SET_SUBMIT_SUCCEEDED, START_ASYNC_VALIDATION, START_SUBMIT, STOP_ASYNC_VALIDATION, STOP_SUBMIT, SUBMIT, TOUCH, UNREGISTER_FIELD, UNTOUCH, UPDATE_SYNC_ERRORS, UPDATE_SYNC_WARNINGS } from './actionTypes' export const arrayInsert = (form, field, index, value) => ({ type: ARRAY_INSERT, meta: { form, field, index }, payload: value }) export const arrayMove = (form, field, from, to) => ({ type: ARRAY_MOVE, meta: { form, field, from, to } }) export const arrayPop = (form, field) => ({ type: ARRAY_POP, meta: { form, field } }) export const arrayPush = (form, field, value) => ({ type: ARRAY_PUSH, meta: { form, field }, payload: value }) export const arrayRemove = (form, field, index) => ({ type: ARRAY_REMOVE, meta: { form, field, index } }) export const arrayRemoveAll = (form, field) => ({ type: ARRAY_REMOVE_ALL, meta: { form, field } }) export const arrayShift = (form, field) => ({ type: ARRAY_SHIFT, meta: { form, field } }) export const arraySplice = (form, field, index, removeNum, value) => { const action = { type: ARRAY_SPLICE, meta: { form, field, index, removeNum } } if (value !== undefined) { action.payload = value } return action } export const arraySwap = (form, field, indexA, indexB) => { if (indexA === indexB) { throw new Error('Swap indices cannot be equal') } if (indexA < 0 || indexB < 0) { throw new Error('Swap indices cannot be negative') } return { type: ARRAY_SWAP, meta: { form, field, indexA, indexB } } } export const arrayUnshift = (form, field, value) => ({ type: ARRAY_UNSHIFT, meta: { form, field }, payload: value }) export const autofill = (form, field, value) => ({ type: AUTOFILL, meta: { form, field }, payload: value }) export const blur = (form, field, value, touch) => ({ type: BLUR, meta: { form, field, touch }, payload: value }) export const change = (form, field, value, touch, persistentSubmitErrors) => ({ type: CHANGE, meta: { form, field, touch, persistentSubmitErrors }, payload: value }) export const clearSubmit = form => ({ type: CLEAR_SUBMIT, meta: { form } }) export const clearSubmitErrors = form => ({ type: CLEAR_SUBMIT_ERRORS, meta: { form } }) export const clearAsyncError = (form, field) => ({ type: CLEAR_ASYNC_ERROR, meta: { form, field } }) export const destroy = (...form) => ({ type: DESTROY, meta: { form } }) export const focus = (form, field) => ({ type: FOCUS, meta: { form, field } }) export const initialize = (form, values, keepDirty, otherMeta = {}) => { if (keepDirty instanceof Object) { otherMeta = keepDirty keepDirty = false } return { type: INITIALIZE, meta: { form, keepDirty, ...otherMeta }, payload: values } } export const registerField = (form, name, type) => ({ type: REGISTER_FIELD, meta: { form }, payload: { name, type } }) export const reset = form => ({ type: RESET, meta: { form } }) export const startAsyncValidation = (form, field) => ({ type: START_ASYNC_VALIDATION, meta: { form, field } }) export const startSubmit = form => ({ type: START_SUBMIT, meta: { form } }) export const stopAsyncValidation = (form, errors) => { const action = { type: STOP_ASYNC_VALIDATION, meta: { form }, payload: errors } if (errors && Object.keys(errors).length) { action.error = true } return action } export const stopSubmit = (form, errors) => { const action = { type: STOP_SUBMIT, meta: { form }, payload: errors } if (errors && Object.keys(errors).length) { action.error = true } return action } export const submit = form => ({ type: SUBMIT, meta: { form } }) export const setSubmitFailed = (form, ...fields) => ({ type: SET_SUBMIT_FAILED, meta: { form, fields }, error: true }) export const setSubmitSucceeded = (form, ...fields) => ({ type: SET_SUBMIT_SUCCEEDED, meta: { form, fields }, error: false }) export const touch = (form, ...fields) => ({ type: TOUCH, meta: { form, fields } }) export const unregisterField = (form, name, destroyOnUnmount = true) => ({ type: UNREGISTER_FIELD, meta: { form }, payload: { name, destroyOnUnmount } }) export const untouch = (form, ...fields) => ({ type: UNTOUCH, meta: { form, fields } }) export const updateSyncErrors = (form, syncErrors = {}, error) => ({ type: UPDATE_SYNC_ERRORS, meta: { form }, payload: { syncErrors, error } }) export const updateSyncWarnings = (form, syncWarnings = {}, warning) => ({ type: UPDATE_SYNC_WARNINGS, meta: { form }, payload: { syncWarnings, warning } })
# Code generated by `typeddictgen`. DO NOT EDIT. """V1alpha1CSIStorageCapacityListDict generated type.""" from typing import TypedDict, List from kubernetes_typed.client import V1ListMetaDict, V1alpha1CSIStorageCapacityDict V1alpha1CSIStorageCapacityListDict = TypedDict( "V1alpha1CSIStorageCapacityListDict", { "apiVersion": str, "items": List[V1alpha1CSIStorageCapacityDict], "kind": str, "metadata": V1ListMetaDict, }, total=False, )