text
stringlengths
3
1.05M
import React, {useState} from 'react'; import Modal from 'react-modal'; import TextField from '@material-ui/core/TextField'; import { ThemeProvider, createMuiTheme } from '@material-ui/core/styles'; import { WORDPRESS_HOST } from '../../config'; import axios from 'axios'; import './ContactForm.scss'; function ContactForm({isOpen, closeModal}){ const [thename, setName] = useState(""); const [email, setEmail] = useState(""); const [message, setMessage] = useState(""); const [sent, setSent] = useState(false); const darkTheme = createMuiTheme({ palette: { type: 'dark', }, }); const customStyles = { overlay : { display: 'flex', justifyContent: 'center', alignItems: 'center', zIndex: 2 }, content : { backgroundColor: "#000", } }; const formData = new FormData(); formData.append("thename", thename); formData.append("email", email); formData.append("message", message); function send(e){ e.preventDefault(); axios.post(`${WORDPRESS_HOST}/wp-json/contact-form-7/v1/contact-forms/5/feedback`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(({data}) => { const {status} = data; if(status === 'mail_sent'){ setName(""); setEmail(""); setMessage(""); setSent(true); } }) .catch(e => console.log(e)) } return( <Modal isOpen={isOpen} onRequestClose={closeModal} contentLabel="Contact" shouldCloseOnOverlayClick={true} shouldCloseOnEsc={true} style={customStyles} > <div className="left"> <img className="Unique_product" src={require("../../photos/history.png")} alt="Unique_product" /> </div> <div className="right"> <div onClick={closeModal} className="x">x</div> <h2>Let's talk</h2> <h4>Drop us a few lines</h4> {sent ? <div className="ty">Thank you for contacting us!</div> : <form> <ThemeProvider theme={darkTheme}> <div className="row"> <TextField style={{width: "47.5%", marginRight: "2.5%"}} color="primary" id="name" label="name" value={thename} onChange={({target}) => setName(target.value)} /> <TextField style={{width: "47.5%", marginLeft: "2.5%"}} color="primary" id="email" type="email" label="email" value={email} onChange={({target}) => setEmail(target.value)} /> </div> <div className="row"> <TextField style={{width: "100%", marginTop: "20px"}} rows={8} color="primary" id="message" label="message" variant="filled" multiline value={message} onChange={({target}) => setMessage(target.value)} /> </div> <div className="row-three"> <button onClick={send}>Send</button> </div> </ThemeProvider> </form>} </div> </Modal> ) } export default ContactForm;
/*! Amaze UI v2.5.1 ~ Handlebars helper | by Amaze UI Team | (c) 2016 AllMobilize, Inc. | Licensed under MIT | 2016-01-19T14:45:42+0800 */ (function(i){"use strict";var n=function(i){i.registerHelper("ifCond",function(i,n,t,a){switch(n){case"==":return i==t?a.fn(this):a.inverse(this);case"===":return i===t?a.fn(this):a.inverse(this);case"<":return t>i?a.fn(this):a.inverse(this);case"<=":return t>=i?a.fn(this):a.inverse(this);case">":return i>t?a.fn(this):a.inverse(this);case">=":return i>=t?a.fn(this):a.inverse(this);default:return a.inverse(this)}return a.inverse(this)})};"undefined"!=typeof module&&module.exports&&(module.exports=n),this.Handlebars&&n(this.Handlebars)}).call(this),function(i){"use strict";var n=function(i){i.registerPartial("accordion",'{{#this}}\n <section data-am-widget="accordion" class="am-accordion {{#if theme}}am-accordion-{{theme}}{{else}}am-accordion-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"{{#if id}} id="{{id}}"{{/if}} data-am-accordion=\'{ {{#if options.multiple}}"multiple": true{{/if}} }\'>\n {{#each content}}\n <dl class="am-accordion-item{{#if active}} am-active{{/if}}{{#if disabled}} am-disabled{{/if}}">\n <dt class="am-accordion-title">\n {{{title}}}\n </dt>\n <dd class="am-accordion-bd am-collapse {{#if active}}am-in{{/if}}">\n <!-- 规避 Collapase 处理有 padding 的折叠内容计算计算有误问题, 加一个容器 -->\n <div class="am-accordion-content">\n {{{content}}}\n </div>\n </dd>\n </dl>\n {{/each}}\n </section>\n{{/this}}\n'),i.registerPartial("divider",'{{#this}}\n <hr data-am-widget="divider" style="{{#if options.width}}width:{{{options.width}}};{{/if}}{{#if options.height}}height:{{{options.height}}};{{/if}}" class="am-divider {{#if theme}}am-divider-{{theme}}{{else}}am-divider-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"{{#if id}} id="{{id}}"{{/if}} />\n{{/this}}\n'),i.registerPartial("duoshuo",'{{#this}}\n <div data-am-widget="duoshuo" class="am-duoshuo{{#if theme}} am-duoshuo-{{theme}}{{else}} am-duoshuo-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"{{#if id}} id="{{id}}"{{/if}} {{#if options.shortName}}data-ds-short-name="{{options.shortName}}"{{/if}}>\n <div class="ds-thread" {{#if content}}{{#each content}}{{#ifCond @key \'==\' \'threadKey\'}} data-thread-key="{{this}}"{{else}} data-{{@key}}="{{this}}"{{/ifCond}}{{/each}}{{/if}}>\n </div>\n </div>\n{{/this}}'),i.registerPartial("figure",'{{#this}}\n <figure data-am-widget="figure" class="am am-figure {{#if theme}}am-figure-{{theme}}{{else}}am-figure-default{{/if}} {{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}" {{#if id}}\n id="{{id}}"{{/if}} data-am-figure="{ {{#if options.zoomAble}} pureview: \'{{options.zoomAble}}\'{{/if}} }">\n {{#if content.link}}<a href="{{content.link}}" title="{{content.figcaption}}" class="{{className}}">{{/if}}\n\n {{#if options.figcaptionPosition}}\n {{#ifCond options.figcaptionPosition \'==\' \'top\'}}\n {{#if content.figcaption}}\n <figcaption class="am-figure-capition-top">\n {{content.figcaption}}\n </figcaption>\n {{/if}}\n {{/ifCond}}\n {{/if}}\n\n {{#if content.img}}\n <img src="{{content.img}}" {{#if content.rel}}data-rel="{{content.rel}}"{{/if}} alt="{{#if content.imgAlt}}{{content.imgAlt}}{{else}}{{content.figcaption}}{{/if}}"/>\n {{/if}}\n {{#if options.figcaptionPosition}}\n {{#ifCond options.figcaptionPosition \'==\' \'bottom\'}}\n {{#if content.figcaption}}\n <figcaption class="am-figure-capition-btm">\n {{content.figcaption}}\n </figcaption>\n {{/if}}\n {{/ifCond}}\n {{else}}\n {{#if content.figcaption}}\n <figcaption class="am-figure-capition-btm">\n {{content.figcaption}}\n </figcaption>\n {{/if}}\n {{/if}}\n\n {{#if content.link}}</a>{{/if}}\n </figure>\n{{/this}}\n'),i.registerPartial("footer",'{{#this}}\n <footer data-am-widget="footer"\n class="am-footer {{#if theme}}am-footer-{{theme}}{{else}}am-footer-default {{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"\n {{#if id}}id="{{id}}"{{/if}} data-am-footer="{ {{#if options.addToHS}}addToHS: 1{{/if}} }">\n <div class="am-footer-switch">\n <span class="{{#if options.modal}}am-footer-ysp{{/if}}" data-rel="mobile"\n data-am-modal="{target: \'#am-switch-mode\'}">\n {{#unless content.switchName}}\n {{#ifCond content.lang \'==\' \'en\'}}\n Mobile\n {{else}}\n 云适配版\n {{/ifCond}}\n {{else}}\n {{content.switchName}}\n {{/unless}}\n </span>\n <span class="am-footer-divider"> | </span>\n <a id="godesktop" data-rel="desktop" class="am-footer-desktop" href="javascript:">\n {{#ifCond content.lang \'==\' \'en\'}}\n Desktop\n {{else}}\n 电脑版\n {{/ifCond}}\n </a>\n </div>\n <div class="am-footer-miscs {{#if options.textPosition}}am-text-left{{/if}}">\n\n {{#if options.techSupportCo}}\n {{#ifCond content.lang \'==\' \'en\'}}\n <p>Supported by {{#if options.techSupportSite}}<a href="{{options.techSupportSite}}"\n title="{{options.techSupportCo}}"\n target="_blank"> class="{{className}}"{{{options.techSupportCo}}}</a>{{else}}{{{options.techSupportCo}}}{{/if}}\n .</p>\n {{else}}\n <p>由 {{#if options.techSupportSite}}<a href="{{options.techSupportSite}}" title="{{options.techSupportCo}}"\n target="_blank" class="{{techSupportClassName}}">{{{options.techSupportCo}}}</a>{{else}}{{{options.techSupportCo}}}{{/if}}\n 提供技术支持</p>\n {{/ifCond}}\n {{/if}}\n {{#each content.companyInfo}}\n <p>{{{detail}}}</p>\n {{/each}}\n </div>\n </footer>\n\n <div id="am-footer-modal"\n class="am-modal am-modal-no-btn am-switch-mode-m {{#if theme}}am-switch-mode-m-{{theme}}{{/if}}">\n <div class="am-modal-dialog">\n <div class="am-modal-hd am-modal-footer-hd">\n <a href="javascript:void(0)" data-dismiss="modal" class="am-close am-close-spin {{className}}" data-am-modal-close>&times;</a>\n </div>\n <div class="am-modal-bd">\n {{#ifCond content.lang \'==\' \'en\'}}\n You are visiting\n {{else}}\n 您正在浏览的是\n {{/ifCond}}\n\n <span class="am-switch-mode-owner">\n {{#if content.owner}}\n {{content.owner}}\n {{else}}\n 云适配\n {{/if}}\n </span>\n\n <span class="am-switch-mode-slogan">\n {{#if content.slogan}}\n {{{content.slogan}}}\n {{else}}\n {{#ifCond content.lang \'==\' \'en\'}}\n mobilized version for your device.\n {{else}}\n 为您当前手机订制的移动网站。\n {{/ifCond}}\n {{/if}}\n </span>\n </div>\n </div>\n </div>\n{{/this}}\n'),i.registerPartial("gallery",'{{#this}}\n <ul data-am-widget="gallery" class="am-gallery{{#if options.cols}} am-avg-sm-{{options.cols}}{{else}} am-avg-sm-2{{/if}}\n am-avg-md-3 am-avg-lg-4 {{#if\n theme}}am-gallery-{{theme}}{{else}}am-gallery-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}" data-am-gallery="{ {{#if options.gallery}}pureview: true{{/if}} }" {{#if id}}id="{{id}}"{{/if}}>\n {{#each content}}\n <li>\n <div class="am-gallery-item">\n {{#if link}}\n <a href="{{link}}" class="{{className}}">\n {{#if img}}<img src="{{img}}" {{#if rel}}data-rel="{{rel}}"{{/if}} alt="{{title}}"/>{{/if}}\n {{#if title}}\n <h3 class="am-gallery-title">{{{title}}}</h3>\n {{/if}}\n {{#if desc}}\n <div class="am-gallery-desc">{{{desc}}}</div>\n {{/if}}\n </a>\n {{else}}\n {{#if img}}<img src="{{img}}" {{#if rel}}data-rel="{{rel}}"{{/if}} alt="{{title}}"/>{{/if}}\n {{#if title}}\n <h3 class="am-gallery-title">{{{title}}}</h3>\n {{/if}}\n {{#if desc}}\n <div class="am-gallery-desc">{{{desc}}}</div>\n {{/if}}\n {{/if}}\n </div>\n </li>\n {{/each}}\n </ul>\n{{/this}}\n'),i.registerPartial("gotop",'{{#this}}\n <div data-am-widget="gotop" class="am-gotop {{#if theme}}am-gotop-{{theme}}{{else}}am-gotop-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}" {{#if id}}id="{{id}}"{{/if}}>\n <a href="#top" title="{{content.title}}">\n {{#if content.title}}\n <span class="am-gotop-title">{{content.title}}</span>\n {{/if}}\n {{#if content.customIcon}}\n <img class="am-gotop-icon-custom" src="{{content.customIcon}}" />\n {{else}}\n {{#if content.icon}}\n <i class="am-gotop-icon am-icon-{{content.icon}}"></i>\n {{else}}\n <i class="am-gotop-icon am-icon-chevron-up"></i>\n {{/if}}\n {{/if}}\n </a>\n </div>\n{{/this}}\n'),i.registerPartial("header",'{{#this}}\n <header data-am-widget="header"\n class="am-header{{#if theme}} am-header-{{theme}}{{else}} am-header-default{{/if}}{{#if options.fixed}} am-header-fixed{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"{{#if id}}\n id="{{id}}"{{/if}}>\n {{#if content.left}}\n <div class="am-header-left am-header-nav">\n {{#each content.left}}\n <a href="{{link}}" class="{{className}}">\n {{#if title}}\n <span class="am-header-nav-title">\n {{title}}\n </span>\n {{/if}}\n\n {{# if customIcon}}\n <img class="am-header-icon-custom" src="{{customIcon}}" alt=""/>\n {{else}}\n {{#if icon}}\n <i class="am-header-icon am-icon-{{icon}}"></i>\n {{/if}}\n {{/if}}\n </a>\n {{/each}}\n </div>\n {{/if}}\n\n {{#if content.title}}\n <h1 class="am-header-title">\n {{#if content.link}}\n <a href="{{content.link}}" class="{{content.className}}">\n {{{content.title}}}\n </a>\n {{else}}\n {{{content.title}}}\n {{/if}}\n </h1>\n {{/if}}\n\n {{#if content.right}}\n <div class="am-header-right am-header-nav">\n {{#each content.right}}\n <a href="{{link}}" class="{{className}}">\n {{#if title}}\n <span class="am-header-nav-title">\n {{title}}\n </span>\n {{/if}}\n\n {{# if customIcon}}\n <img class="am-header-icon-custom" src="{{customIcon}}" alt=""/>\n {{else}}\n {{#if icon}}\n <i class="am-header-icon am-icon-{{icon}}"></i>\n {{/if}}\n {{/if}}\n </a>\n {{/each}}\n </div>\n {{/if}}\n </header>\n{{/this}}\n'),i.registerPartial("intro",'{{#this }}\n <div data-am-widget="intro"\n class="am-intro am-cf {{#if theme}}am-intro-{{theme}}{{else}}am-intro-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"\n {{#if id}}id="{{id}}"{{/if}}>\n {{#if content.title}}\n <div class="am-intro-hd">\n <h2 class="am-intro-title">{{{content.title}}}</h2>\n {{#if content.more.link}}\n {{#ifCond options.position \'==\' \'top\'}}\n <a class="am-intro-more am-intro-more-top {{content.more.className}}" href="{{content.more.link}}">{{content.more.title}}</a>\n {{/ifCond}}\n {{/if}}\n </div>\n {{/if}}\n\n <div class="am-g am-intro-bd">\n {{#if content.left}}\n <div\n class="am-intro-left {{#if options.leftCols}}am-u-sm-{{options.leftCols}}{{/if}}">{{{content.left}}}</div>\n {{/if}}\n {{#if content.right}}\n <div\n class="am-intro-right {{#if options.rightCols}}am-u-sm-{{options.rightCols}}{{/if}}">{{{content.right}}}</div>\n {{/if}}\n </div>\n {{#ifCond options.position \'==\' \'bottom\'}}\n <div class="am-intro-more-bottom">\n <a class="am-btn am-btn-default {{content.more.className}}"\n href="{{content.more.link}}">{{content.more.title}}</a>\n </div>\n {{/ifCond}}\n </div>\n{{/this}}\n'),i.registerPartial("list_news",'{{#this}}\n <div data-am-widget="list_news" class="am-list-news{{#if theme}} am-list-news-{{theme}}{{else}} am-list-news-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}" {{#if id}}id="{{id}}"{{/if}}>\n <!--列表标题-->\n {{#if content.header.title}}\n <div class="am-list-news-hd am-cf">\n {{#if content.header.link}} <!--带更多链接-->\n <a href="{{content.header.link}}" class="{{content.header.className}}">\n <h2>{{{content.header.title}}}</h2>\n {{#ifCond content.header.morePosition \'==\' \'top\'}}\n <span class="am-list-news-more am-fr">{{{content.header.moreText}}}</span>\n {{/ifCond}}\n </a>\n {{else}} <!--不带更多链接-->\n <h2>{{{content.header.title}}}</h2>\n {{/if}}\n </div>\n {{/if}}\n\n <div class="am-list-news-bd">\n <ul class="am-list">\n {{#ifCond options.type \'==\' \'thumb\'}}\n {{#ifCond options.thumbPosition \'==\' \'top\'}} <!--缩略图在标题上方-->\n {{#each content.main}}\n <li class="am-g{{#if date}} am-list-item-dated{{/if}}{{#if desc}} am-list-item-desced{{/if}}{{#if img}} am-list-item-thumbed am-list-item-thumb-top{{/if}}">\n {{!--\n am-list-item-dated - 带日期\n am-list-item-desced - 带描述\n am-list-item-thumbed - 带缩略图的\n --}}\n {{#if img}}\n <div class="am-list-thumb am-u-sm-12">\n <a href="{{link}}" class="{{className}}">\n <img src="{{img}}" alt="{{title}}"/>\n </a>\n {{#if thumbAddition}}\n <div class="am-list-thumb-addon">{{{thumbAddition}}}</div>\n {{/if}}\n </div>\n {{/if}}\n\n <div class="{{#if img}}{{/if}} am-list-main">\n {{#if title}}\n <h3 class="am-list-item-hd"><a href="{{link}}" class="{{className}}">{{{title}}}</a></h3>\n {{/if}}\n\n {{#if date}}\n <span class="am-list-date">{{date}}</span>\n {{/if}}\n\n {{#if desc}}\n <div class="am-list-item-text">{{{desc}}}</div>\n {{/if}}\n\n {{#if mainAddition}}\n <div class="am-list-news-addon">{{{mainAddition}}}</div>\n {{/if}}\n </div>\n </li>\n {{/each}}\n {{/ifCond}}\n\n {{#ifCond options.thumbPosition \'==\' \'bottom-left\'}} <!--缩略图在标题下方居左-->\n {{#each content.main}}\n <li class="am-g{{#if date}} am-list-item-dated{{/if}}{{#if desc}} am-list-item-desced{{/if}}{{#if img}} am-list-item-thumbed am-list-item-thumb-bottom-left{{/if}}">\n {{!--\n am-list-item-dated - 带日期\n am-list-item-desced - 带描述\n am-list-item-thumbed - 带缩略图的\n --}}\n {{#if title}}\n <h3 class="am-list-item-hd"><a href="{{link}}" class="{{className}}">{{{title}}}</a></h3>\n {{/if}}\n {{#if img}}\n <div class="am-u-sm-4 am-list-thumb">\n <a href="{{link}}" class="{{className}}">\n <img src="{{img}}" alt="{{title}}"/>\n </a>\n {{#if thumbAddition}}\n <div class="am-list-thumb-addon">{{{thumbAddition}}}</div>\n {{/if}}\n </div>\n {{/if}}\n\n <div class="{{#if img}} am-u-sm-8 {{/if}} am-list-main">\n {{#if date}}\n <span class="am-list-date">{{date}}</span>\n {{/if}}\n\n {{#if desc}}\n <div class="am-list-item-text">{{{desc}}}</div>\n {{/if}}\n\n {{#if mainAddition}}\n <div class="am-list-news-addon">{{{mainAddition}}}</div>\n {{/if}}\n </div>\n </li>\n {{/each}}\n {{/ifCond}}\n\n {{#ifCond options.thumbPosition \'==\' \'bottom-right\'}} <!--缩略图在标题下方居右-->\n {{#each content.main}}\n <li class="am-g{{#if date}} am-list-item-dated{{/if}}{{#if desc}} am-list-item-desced{{/if}}{{#if img}} am-list-item-thumbed am-list-item-thumb-bottom-right{{/if}}">\n {{!--\n am-list-item-dated - 带日期\n am-list-item-desced - 带描述\n am-list-item-thumbed - 带缩略图的\n --}}\n {{#if title}}\n <h3 class="am-list-item-hd"><a href="{{link}}" class="{{className}}">{{{title}}}</a></h3>\n {{/if}}\n\n <div class="{{#if img}} am-u-sm-8{{/if}} am-list-main">\n {{#if date}}\n <span class="am-list-date">{{date}}</span>\n {{/if}}\n\n {{#if desc}}\n <div class="am-list-item-text">{{{desc}}}</div>\n {{/if}}\n\n {{#if mainAddition}}\n <div class="am-list-news-addon">{{{mainAddition}}}</div>\n {{/if}}\n </div>\n {{#if img}}\n <div class="am-list-thumb am-u-sm-4">\n <a href="{{link}}" class="{{className}}">\n <img src="{{img}}" alt="{{title}}"/>\n </a>\n {{#if thumbAddition}}\n <div class="am-list-thumb-addon">{{{thumbAddition}}}</div>\n {{/if}}\n </div>\n {{/if}}\n </li>\n {{/each}}\n {{/ifCond}}\n\n {{#ifCond options.thumbPosition \'==\' \'left\'}} <!--缩略图在标题左边-->\n {{#each content.main}}\n <li class="am-g{{#if date}} am-list-item-dated{{/if}}{{#if desc}} am-list-item-desced{{/if}}{{#if img}} am-list-item-thumbed am-list-item-thumb-left{{/if}}">\n {{!--\n am-list-item-dated - 带日期\n am-list-item-desced - 带描述\n am-list-item-thumbed - 带缩略图的\n --}}\n {{#if img}}\n <div class="am-u-sm-4 am-list-thumb">\n <a href="{{link}}" class="{{className}}">\n <img src="{{img}}" alt="{{title}}"/>\n </a>\n {{#if thumbAddition}}\n <div class="am-list-thumb-addon">{{{thumbAddition}}}</div>\n {{/if}}\n </div>\n {{/if}}\n\n <div class="{{#if img}} am-u-sm-8{{/if}} am-list-main">\n {{#if title}}\n <h3 class="am-list-item-hd"><a href="{{link}}" class="{{className}}">{{{title}}}</a></h3>\n {{/if}}\n {{#if date}}\n <span class="am-list-date">{{date}}</span>\n {{/if}}\n\n {{#if desc}}\n <div class="am-list-item-text">{{{desc}}}</div>\n {{/if}}\n\n {{#if mainAddition}}\n <div class="am-list-news-addon">{{{mainAddition}}}</div>\n {{/if}}\n </div>\n </li>\n {{/each}}\n {{/ifCond}}\n\n {{#ifCond options.thumbPosition \'==\' \'right\'}} <!--缩略图在标题右边-->\n {{#each content.main}}\n <li class="am-g{{#if date}} am-list-item-dated{{/if}}{{#if desc}} am-list-item-desced{{/if}}{{#if img}} am-list-item-thumbed am-list-item-thumb-right{{/if}}">\n {{!--\n am-list-item-dated - 带日期\n am-list-item-desced - 带描述\n am-list-item-thumbed - 带缩略图的\n --}}\n <div class="{{#if img}} am-u-sm-8{{/if}} am-list-main">\n {{#if title}}\n <h3 class="am-list-item-hd"><a href="{{link}}" class="{{className}}">{{{title}}}</a></h3>\n {{/if}}\n\n {{#if date}}\n <span class="am-list-date">{{date}}</span>\n {{/if}}\n\n {{#if desc}}\n <div class="am-list-item-text">{{{desc}}}</div>\n {{/if}}\n\n {{#if mainAddition}}\n <div class="am-list-news-addon">{{{mainAddition}}}</div>\n {{/if}}\n </div>\n {{#if img}}\n <div class="am-u-sm-4 am-list-thumb">\n <a href="{{link}}" class="{{className}}">\n <img src="{{img}}" alt="{{title}}"/>\n </a>\n {{#if thumbAddition}}\n <div class="am-list-thumb-addon">{{{thumbAddition}}}</div>\n {{/if}}\n </div>\n {{/if}}\n </li>\n {{/each}}\n {{/ifCond}}\n\n {{else}}{{!--不带缩略图--}}\n {{#each content.main}}\n <li class="am-g{{#if date}} am-list-item-dated{{/if}}{{#if desc}} am-list-item-desced{{/if}}{{#if img}} am-list-item-thumbed{{/if}}">\n {{!--\n am-list-item-dated - 带日期\n am-list-item-desced - 带描述\n am-list-item-thumbed - 带缩略图的\n --}}\n {{#if title}}\n <a href="{{link}}" class="am-list-item-hd {{className}}">{{{title}}}</a>\n {{/if}}\n\n {{#if date}}\n <span class="am-list-date">{{date}}</span>\n {{/if}}\n\n {{#if desc}}\n <div class="am-list-item-text">{{{desc}}}</div>\n {{/if}}\n\n {{#if mainAddition}}\n <div class="am-list-news-addon">{{{mainAddition}}}</div>\n {{/if}}\n </li>\n {{/each}}\n {{/ifCond}}\n </ul>\n </div>\n\n {{#ifCond content.header.morePosition \'==\' \'bottom\'}}<!--更多在底部-->\n {{#if content.header.link}}\n <div class="am-list-news-ft">\n <a class="am-list-news-more am-btn am-btn-default {{content.header.className}}" href="{{content.header.link}}">{{{content.header.moreText}}}</a>\n </div>\n {{/if}}\n {{/ifCond}}\n </div>\n{{/this}}\n'),i.registerPartial("map",'{{#this}}\n <div data-am-widget="map" class="am-map {{#if theme}}am-map-{{theme}}{{else}}am-map-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"\n data-name="{{options.name}}" data-address="{{options.address}}" data-longitude="{{options.longitude}}" data-latitude="{{options.latitude}}" data-scaleControl="{{options.scaleControl}}" data-zoomControl="{{options.zoomControl}}" data-setZoom="{{options.setZoom}}" data-icon="{{options.icon}}">\n <div id="bd-map"></div>\n </div>\n{{/this}}'),i.registerPartial("mechat",'{{#this}}\n <section data-am-widget="mechat" class="am-mechat{{#if theme}} am-mechat-{{theme}}{{else}} am-mechat-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}" {{#if id}} id="{{id}}" {{/if}} {{#if options.unitid}}data-am-mechat-unitid="{{options.unitid}}"{{/if}}>\n <div id="mechat"></div>\n </section>\n{{/this}}'),i.registerPartial("menu",'{{#this}}\n <nav data-am-widget="menu" class="am-menu {{#if theme}} am-menu-{{theme}}{{else}} am-menu-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}" {{options.dataset}} {{#if id}}id="{{id}}"{{/if}}\n {{#ifCond theme \'==\' \'dropdown1\'}} data-am-menu-collapse{{/ifCond}}\n {{#ifCond theme \'==\' \'dropdown2\'}} data-am-menu-collapse{{/ifCond}}\n {{#ifCond theme \'==\' \'slide1\'}} data-am-menu-collapse{{/ifCond}}\n {{#ifCond theme \'==\' \'offcanvas1\'}} data-am-menu-offcanvas{{/ifCond}}\n {{#ifCond theme \'==\' \'offcanvas2\'}} data-am-menu-offcanvas{{/ifCond}}> {{!-- 与模板深耦合,与 JS 浅耦合 --}}\n <a href="javascript: void(0)" class="am-menu-toggle">\n {{#if options.toggleTitle}}\n <span class="am-menu-toggle-title">{{options.toggleTitle}}</span>\n {{/if}}\n {{#if options.toggleCustomIcon}}\n <img src="{{options.toggleCustomIcon}}" alt="Menu Toggle"/>\n {{else}}\n {{#if options.toggleIcon}}\n <i class="am-menu-toggle-icon am-icon-{{options.toggleIcon}}"></i>\n {{else}}\n <i class="am-menu-toggle-icon am-icon-bars"></i>\n {{/if}}\n {{/if}}\n </a>\n\n {{!-- offCanvas menu Wrap --}}\n {{!-- 问题:方便用户,但是与主题名称(类名)耦合过深 --}}\n {{#ifCond theme \'==\' \'offcanvas1\'}}\n <div class="am-offcanvas" {{#if options.closeOffCanvasOnclick}}data-dismiss-on="click"{{/if}}>\n <div class="am-offcanvas-bar{{#if options.offCanvasFlip}} am-offcanvas-bar-flip{{/if}}">\n {{/ifCond}}\n {{#ifCond theme \'==\' \'offcanvas2\'}}\n <div class="am-offcanvas">\n <div class="am-offcanvas-bar{{#if options.offCanvasFlip}} am-offcanvas-bar-flip{{/if}}">\n {{/ifCond}}\n\n {{#if content}}\n <ul class="am-menu-nav {{#if options.cols}}am-avg-sm-{{options\n .cols}}{{else}}am-avg-sm-1{{/if}}{{#ifCond theme \'==\' \'dropdown1\'}} am-collapse{{/ifCond}}{{#ifCond theme\n \'==\' \'dropdown2\'}} am-collapse{{/ifCond}}{{#ifCond theme\n \'==\' \'slide1\'}} am-collapse{{/ifCond}}">\n {{#each content}}\n <li class="{{#if subMenu}}am-parent{{/if}}{{#if className}} {{className}}{{/if}}">\n <a href="{{link}}" class="{{className}}" {{#if target}}target="{{target}}" {{/if}}>{{{title}}}</a>\n {{#if subMenu}}\n <ul class="am-menu-sub am-collapse {{#if subCols}} am-avg-sm-{{subCols}}{{else}}\n am-avg-sm-1{{/if}} {{subMenuClassName}}">\n {{#each subMenu}}\n <li class="{{#if subMenu}} am-parent{{/if}}{{#if className}} {{className}}{{/if}}">\n <a href="{{link}}" class="{{className}}" {{#if target}}target="{{target}}" {{/if}}>{{{title}}}</a>\n </li>\n {{/each}}\n {{!-- 显示进入栏目链接 --}}\n {{#if channelLink}}\n <li class="am-menu-nav-channel"><a href="{{link}}" class="{{className}}" title="{{title}}">{{{channelLink}}}</a></li>\n {{/if}}\n </ul>\n {{/if}}\n </li>\n {{/each}}\n </ul>\n {{/if}}\n\n {{#ifCond theme \'==\' \'offcanvas1\'}}\n </div>\n </div>\n {{/ifCond}}\n {{#ifCond theme \'==\' \'offcanvas2\'}}\n </div>\n </div>\n {{/ifCond}}\n {{!-- 不要问我为什么这样写,我也不想这样 --}}\n </nav>\n{{/this}}\n'),i.registerPartial("navbar",'{{#this}}\n <div data-am-widget="navbar" class="am-navbar am-cf {{#if theme}}am-navbar-{{theme}}{{else}}am-navbar-default{{/if}} {{#if options.iconPosition}}am-navbar-inline{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"\n id="{{id}}">\n {{#if content}}\n <ul class="am-navbar-nav am-cf {{#if options.cols}}am-avg-sm-{{options.cols}}{{/if}}">\n {{#each content}}\n <li {{{dataApi}}}>\n <a href="{{link}}" class="{{className}}">\n {{#if customIcon}}\n <img src="{{customIcon}}" alt="{{title}}"/>\n {{else}}\n {{#if icon}}\n <span class="am-icon-{{icon}}"></span>\n {{/if}}\n {{/if}}\n {{#if title}}\n <span class="am-navbar-label">{{title}}</span>\n {{/if}}\n </a>\n </li>\n {{/each}}\n </ul>\n {{/if}}\n </div>\n{{/this}}\n'),i.registerPartial("pagination",'{{#this}}\n <ul data-am-widget="pagination"\n class="am-pagination {{#if theme}}am-pagination-{{theme}}{{else}}am-pagination-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"\n {{#if id}}id="{{id}}"{{/if}}>\n\n {{#if content.firstTitle}}\n <li class="am-pagination-first {{content.firstClassName}}">\n <a href="{{content.firstLink}}" class="{{content.firstClassName}}">{{{content.firstTitle}}}</a>\n </li>\n {{/if}}\n\n {{#if content.prevTitle}}\n <li class="am-pagination-prev {{content.prevClassName}}">\n <a href="{{content.prevLink}}" class="{{content.prevClassName}}">{{{content.prevTitle}}}</a>\n </li>\n {{/if}}\n\n {{! 移除 options.select,根据主题来判断结构,无奈 handlebars 逻辑处理...}}\n\n {{#if content.page}}\n {{#ifCond theme \'==\' \'select\'}}\n <li class="am-pagination-select">\n <select>\n {{#each content.page}}\n <option value="{{link}}" class="{{className}}">{{title}}{{#if ../content.total}}\n / {{../../content.total}}{{/if}}\n </option>\n {{/each}}\n </select>\n </li>\n {{else}}\n {{#ifCond theme \'==\' \'one\'}}\n <li class="am-pagination-select">\n <select>\n {{#each content.page}}\n {{content.total}}\n <option value="{{link}}" class="{{className}}">{{title}}{{#if ../content.total}}\n / {{../../content.total}}{{/if}}\n </option>\n {{/each}}\n </select>\n </li>\n {{else}}\n {{#each content.page}}\n <li class="{{className}}">\n <a href="{{link}}" class="{{className}}">{{{title}}}</a>\n </li>\n {{/each}}\n {{/ifCond}}\n {{/ifCond}}\n\n {{/if}}\n\n {{#if content.nextTitle}}\n <li class="am-pagination-next {{content.nextClassName}}">\n <a href="{{content.nextLink}}" class="{{content.nextClassName}}">{{{content.nextTitle}}}</a>\n </li>\n {{/if}}\n\n {{#if content.lastTitle}}\n <li class="am-pagination-last {{content.lastClassName}}">\n <a href="{{content.lastLink}}" class="{{content.lastClassName}}">{{{content.lastTitle}}}</a>\n </li>\n {{/if}}\n </ul>\n{{/this}}\n'),i.registerPartial("paragraph",'{{#this}}\n <article data-am-widget="paragraph"\n class="am-paragraph {{#if theme}}am-paragraph-{{theme}}{{else}}am-paragraph-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"\n {{#if id}}id="{{id}}"{{/if}}\n data-am-paragraph="{ {{#if options.tableScrollable}}tableScrollable: true,{{/if}} {{#if options.imgLightbox}}pureview: true{{/if}} }">\n\n {{#if content}}\n {{{ content.content }}}\n {{/if}}\n </article>\n{{/this}}\n'),i.registerPartial("slider",'{{#this}}\n <div data-am-widget="slider" class="am-slider {{#if theme}}am-slider-{{theme}}{{else}}am-slider-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}" data-am-slider=\'{{sliderConfig}}\' {{#if id}}id="{{id}}"{{/if}}>\n <ul class="am-slides">\n {{#each content}}\n <li{{#if thumb}} data-thumb="{{thumb}}"{{/if}}>\n {{#if link}}\n <a href="{{link}}" class="{{className}}">\n {{/if}}\n {{#if img}}\n <img src="{{img}}">\n {{/if}}\n {{#if desc}}\n <div class="am-slider-desc">{{{desc}}}</div>\n {{/if}}\n {{#if link}}</a>{{/if}} {{!--/end link--}}\n </li>\n {{/each}}\n </ul>\n</div>\n{{/this}}'),i.registerPartial("tabs",'{{#this}}\n <div data-am-widget="tabs"\n class="am-tabs{{#if theme}} am-tabs-{{theme}}{{else}} am-tabs-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"\n {{#if id}}id="{{id}}"{{/if}} {{#if options.noSwipe}}data-am-tabs-noswipe="1"{{/if}}>\n {{#if content}}\n <ul class="am-tabs-nav am-cf">\n {{#each content}}\n <li class="{{#if active}}am-active{{/if}}"><a href="[data-tab-panel-{{@index}}]">{{{title}}}</a></li>\n {{/each}}\n </ul>\n <div class="am-tabs-bd">\n {{#each content}}\n <div data-tab-panel-{{@index}} class="am-tab-panel {{#if active}}am-active{{/if}}">\n {{{content}}}\n </div>\n {{/each}}\n </div>\n {{/if}}\n </div>\n{{/this}}\n'),i.registerPartial("titlebar",'{{#this}}\n<div data-am-widget="titlebar" class="am-titlebar {{#if theme}}am-titlebar-{{theme}}{{else}}am-titlebar-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}" {{#if id}}id="{{id}}"{{/if}}>\n {{#if content.title}}\n <h2 class="am-titlebar-title {{#unless content.link}}{{content.className}}{{/unless}}">\n {{#if content.link}}\n <a href="{{content.link}}" class="{{content.className}}">{{{content.title}}}</a>\n {{else}}\n {{{content.title}}}\n {{/if}}\n </h2>\n {{/if}}\n\n {{#if content.nav}}\n <nav class="am-titlebar-nav">\n {{#each content.nav}}\n <a href="{{link}}" class="{{className}}">{{{title}}}</a>\n {{/each}}\n </nav>\n {{/if}}\n</div>\n{{/this}}\n'), i.registerPartial("wechatpay",'{{#this}}\n <div data-am-widget="wechatpay" class="am-wechatpay{{#if theme}} am-wechatpay-{{theme}}{{else}} am-wechatpay-default{{/if}}{{#if widgetId}} {{widgetId}}{{/if}}{{#if className}} {{className}}{{/if}}"{{#if id}} id="{{id}}"{{/if}} data-wechat-pay="{ {{#each content.order}} {{@key}}: \'{{this}}\',{{/each}} }">\n <button type="button" class="am-btn am-btn-primary am-btn-block am-wechatpay-btn">\n {{#if content.title}}\n {{content.title}}\n {{else}}\n 微信支付\n {{/if}}\n </button>\n </div>\n{{/this}}\n')};"undefined"!=typeof module&&module.exports&&(module.exports=n),this.Handlebars&&n(this.Handlebars)}.call(this);
/* jshint node: true */ var fs = require('fs') var RSVP = require('rsvp') var run = require('./run') var stat = RSVP.denodeify(fs.stat) var copy = RSVP.denodeify(require('ncp').ncp) function supportsWorktree() { return run('git', ['help', 'worktree']).then(function() { return true }, function() { return false }) } function prepareTree(targetDir, myRepo, repo, branch) { return stat(targetDir).then(function() { return run('git', ['reset', '--hard'], { cwd: targetDir }).then(function() { return run("git", ["pull"], { cwd: targetDir }) }) }, function(err) { if (err.code !== 'ENOENT') { throw err } return supportsWorktree().then(function(useWorktree) { if (useWorktree && myRepo === repo) { return run("git", ["worktree", "prune"]).then(function() { return run("git", ["worktree", "add", targetDir, branch]) }) } else { return run("git", ["clone", repo, targetDir, '--branch', branch]) } }) }) } function replaceTree(targetDir, ourDir, commitMessage) { return run("git", ["rm", "--ignore-unmatch", "-r", "."], { cwd: targetDir }).then(function() { return copy(ourDir, targetDir, { stopOnErr: true }) }).then(function() { return run('git', ['add', '-A'], { cwd: targetDir }) }).then(function() { return run('git', ['commit', '-m', `"${commitMessage || 'deploy'}"`], { cwd: targetDir }).catch(function(error) { if (/nothing to commit/.test(error)) { console.log('Nothing to commit...') return false } throw error }) }).then(function() { return true }) } function push(targetDir, repo, branch, force) { return run('git', ['push', force, repo, branch], { cwd: targetDir }) } function origin(targetDir) { return run("git", ["remote", "-v"], { cwd: targetDir }).then(function(output) { var m = /origin\s+(\S+)/.exec(output) if (m) { return m[1] } }) } exports.prepareTree = prepareTree exports.replaceTree = replaceTree exports.push = push exports.origin = origin
import hashlib from flask import abort from params import PI_ALLOWED_NETWORKS, PI_USE_PROXY_IP import os import sys from datetime import timedelta # Decorators def action(route, template='', methods=['GET']): """Decorator to create an action""" def real_decorator(function): function.pi_api_action = True function.pi_api_route = route function.pi_api_template = template function.pi_api_methods = methods if hasattr(function, 'pi_api_crossdomain'): if not function.pi_api_crossdomain_data['methods']: function.pi_api_crossdomain_data['methods'] = methods if 'OPTIONS' not in function.pi_api_methods: function.pi_api_methods += ['OPTIONS'] return function return real_decorator def only_logged_user(): """Decorator to specify the action must only be called by logger users""" def real_decorator(function): function.pi_api_only_logged_user = True return function return real_decorator def only_member_user(): """Decorator to specify the action must only be called by users members of the project""" def real_decorator(function): function.pi_api_only_member_user = True return function return real_decorator def only_admin_user(): """Decorator to specify the action must only be called by admin users of the project""" def real_decorator(function): function.pi_api_only_admin_user = True return function return real_decorator def only_orga_member_user(): """Decorator to specify the action must only be called by users members of the organization""" def real_decorator(function): function.pi_api_only_orga_member_user = True return function return real_decorator def only_orga_admin_user(): """Decorator to specify the action must only be called by admin users of the organization""" def real_decorator(function): function.pi_api_only_orga_admin_user = True return function return real_decorator def cache(time=0, byUser=None): """Decorator to specify the number of seconds the result should be cached, and if cache can be shared between users :param time: Cache timeout in seconds :param byUser: False by default, if true, cache is shared among users """ def real_decorator(function): function.pi_api_cache_time = time function.pi_api_cache_by_user = byUser return function return real_decorator def address_in_networks(networks): """Decorator to specify networks an Remote IP must be in to be allowed access to the page :param networks: List of networks in which the IP must be to allow request """ def real_decorator(function): function.pi_api_address_in_networks = networks return function return real_decorator def send_etag(): """Decorator to specify that in data returned, '_plugit_etag' shouldn't be send back as data but in etag header""" def real_decorator(function): function.pi_api_send_etag = True return function return real_decorator def user_info(props): """Decorator to specify a list of properties requested about the current user""" def real_decorator(function): function.pi_api_user_info = props return function return real_decorator def public(): """Decorator to specify the action as public page.""" def real_decorator(function): function.pi_api_public = True return function return real_decorator def json_only(): """Decorator to specify the action return json that should be send directly to the browser.""" def real_decorator(function): function.pi_api_json_only = True return function return real_decorator def xml_only(): """Decorator to specify the action return xml that should be send directly to the browser.""" def real_decorator(function): function.pi_api_xml_only = True return function return real_decorator def no_template(): """Decorator to specify the action return template that should be send directly to the browser.""" def real_decorator(function): function.pi_api_no_template = True return function return real_decorator def crossdomain(origin=None, methods=None, headers=None, max_age=21600): if methods is not None: methods = ', '.join(sorted(x.upper() for x in methods)) if headers is not None and not isinstance(headers, basestring): headers = ', '.join(x.upper() for x in headers) if not isinstance(origin, basestring): origin = ', '.join(origin) if isinstance(max_age, timedelta): max_age = max_age.total_seconds() def real_decorator(function): function.pi_api_crossdomain = True function.pi_api_crossdomain_data = { 'origin': origin, 'methods': methods, 'max_age': str(max_age), 'headers': headers, } return function return real_decorator # Utils def md5Checksum(filePath): """Compute the MD5 sum of a file""" with open(filePath, 'rb') as fh: m = hashlib.md5() while True: data = fh.read(8192) if not data: break m.update(data) return m.hexdigest() def add_unique_postfix(fn): """__source__ = 'http://code.activestate.com/recipes/577200-make-unique-file-name/'""" if not os.path.exists(fn): return fn path, name = os.path.split(fn) name, ext = os.path.splitext(name) make_fn = lambda i: os.path.join(path, '%s(%d)%s' % (name, i, ext)) for i in xrange(2, sys.maxint): uni_fn = make_fn(i) if not os.path.exists(uni_fn): return uni_fn def get_session_from_request(request): retour = {} for key, value in request.headers.items(): if key.startswith('X-Plugitsession-'): retour[key[16:].lower()] = value return retour # Class class PlugItRedirect(): """Object to perform a redirection""" def __init__(self, url, no_prefix=False): self.url = url self.no_prefix = no_prefix class PlugItSendFile(): """Object to send a file to the client browser""" """Use the flask function send_file to send the file to the PlugIt client""" def __init__(self, filename, mimetype, as_attachment=False, attachment_filename=''): self.mimetype = mimetype self.filename = filename self.as_attachment = as_attachment self.attachment_filename = attachment_filename class PlugItSetSession(): """Object to return normal value, but set elements in the session""" def __init__(self, base, things_to_set={}): self.base = base self.things_to_set = things_to_set def addressInNetwork(ip, net): "Is an address in a network" # http://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python import socket import struct ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') if int(bits) == 0: return True net = struct.unpack('=L', socket.inet_aton(netaddr))[0] mask = ((2L << int(bits) - 1) - 1) return (ipaddr & mask) == (net & mask) def check_ip(request): addr = request.remote_addr if PI_USE_PROXY_IP and request.access_route: addr = request.access_route[-1] for net in PI_ALLOWED_NETWORKS: if addressInNetwork(addr, net): return True # Ip not found abort(404)
import { parseNodeAsSelector } from './parse-selector'; import { parseNodeAsValue } from './parse-value'; // Export refresh export default async function refresh(node, on) { const type = getTypeFromNode(node); const beforeType = type && 'before' + getCapitalType(type); const specialType = type && getSpecialTypeFromNode(node); if (type && on[beforeType]) { await runAll(on[beforeType], node, this); } if (specialType) { const specialBeforeType = 'before' + getCapitalType(specialType); if (on[specialBeforeType]) { await runAll(on[specialBeforeType], node, this); } } if (node.type === 'rule') { const originalSelectors = node.selector; const selectors = parseNodeAsSelector(node); await refresh.call(this, selectors, on); const modifiedSelectors = String(selectors); if (originalSelectors !== modifiedSelectors) { node.selector = modifiedSelectors; } } else if (node.type === 'decl') { const originalValue = node.value; const values = parseNodeAsValue(node); await refresh.call(this, values, on); const modifiedValue = String(values); if (originalValue !== modifiedValue) { node.value = modifiedValue; } } if (hasChildNodes(node)) { for (const childNode of node.nodes) { await refresh.call(this, childNode, on); } } if (specialType && on[specialType]) { await runAll(on[specialType], node, this); } if (type && on[type]) { await runAll(on[type], node, this); } } function runAll(fns, node, result) { let promise = Promise.resolve(); for (const fn of fns) { promise = promise.then(() => fn(node, result)); } return promise; } function hasChildNodes(node) { return Object(node.nodes).length; } function getTypeFromNode(node) { return { atrule: 'rule', decl: 'declaration', func: 'function' }[node.type] || ( node.type === 'root' ? null : String(node.type).replace(/^./, $0 => $0.toLowerCase()) ); } function getKebabCaseAsCamelCase(value) { return String(value).replace(/-+(.?)/g, ($0, $1) => $1.toUpperCase()); } function getCapitalType(type) { return String(type).replace(/^(.)(.*)$/, ($0, firstCharacter, nextCharacters) => firstCharacter.toUpperCase() + nextCharacters); } function getSpecialTypeFromNode(node) { return node.type === 'atrule' ? getKebabCaseAsCamelCase(node.name) + 'Rule' : node.type === 'decl' ? getKebabCaseAsCamelCase(node.prop) + 'Declaration' : node.type === 'func' ? getKebabCaseAsCamelCase(node.value) + 'Function' : node.type === 'number' ? getKebabCaseAsCamelCase(node.unit).replace(/^%$/, 'percent') + 'Number' : null; }
# Copyright (c) 2018 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # Copyright (c) 2004-2006 The Regents of The University of Michigan # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Steve Reinhardt # Nathan Binkert ##################################################################### # # Proxy object support. # ##################################################################### from __future__ import print_function from __future__ import absolute_import import six if six.PY3: long = int import copy class BaseProxy(object): def __init__(self, search_self, search_up): self._search_self = search_self self._search_up = search_up self._multipliers = [] def __str__(self): if self._search_self and not self._search_up: s = 'Self' elif not self._search_self and self._search_up: s = 'Parent' else: s = 'ConfusedProxy' return s + '.' + self.path() def __setattr__(self, attr, value): if not attr.startswith('_'): raise AttributeError( "cannot set attribute '%s' on proxy object" % attr) super(BaseProxy, self).__setattr__(attr, value) # support for multiplying proxies by constants or other proxies to # other params def __mul__(self, other): if not (isinstance(other, (int, long, float)) or isproxy(other)): raise TypeError( "Proxy multiplier must be a constant or a proxy to a param") self._multipliers.append(other) return self __rmul__ = __mul__ def _mulcheck(self, result, base): for multiplier in self._multipliers: if isproxy(multiplier): multiplier = multiplier.unproxy(base) # assert that we are multiplying with a compatible # param if not isinstance(multiplier, params.NumericParamValue): raise TypeError( "Proxy multiplier must be a numerical param") multiplier = multiplier.getValue() result *= multiplier return result def unproxy(self, base): obj = base done = False if self._search_self: result, done = self.find(obj) if self._search_up: # Search up the tree but mark ourself # as visited to avoid a self-reference self._visited = True obj._visited = True while not done: obj = obj._parent if not obj: break result, done = self.find(obj) self._visited = False base._visited = False if not done: raise AttributeError( "Can't resolve proxy '%s' of type '%s' from '%s'" % \ (self.path(), self._pdesc.ptype_str, base.path())) if isinstance(result, BaseProxy): if result == self: raise RuntimeError("Cycle in unproxy") result = result.unproxy(obj) return self._mulcheck(result, base) def getindex(obj, index): if index == None: return obj try: obj = obj[index] except TypeError: if index != 0: raise # if index is 0 and item is not subscriptable, just # use item itself (so cpu[0] works on uniprocessors) return obj getindex = staticmethod(getindex) # This method should be called once the proxy is assigned to a # particular parameter or port to set the expected type of the # resolved proxy def set_param_desc(self, pdesc): self._pdesc = pdesc class AttrProxy(BaseProxy): def __init__(self, search_self, search_up, attr): super(AttrProxy, self).__init__(search_self, search_up) self._attr = attr self._modifiers = [] def __getattr__(self, attr): # python uses __bases__ internally for inheritance if attr.startswith('_'): return super(AttrProxy, self).__getattr__(self, attr) if hasattr(self, '_pdesc'): raise AttributeError("Attribute reference on bound proxy") # Return a copy of self rather than modifying self in place # since self could be an indirect reference via a variable or # parameter new_self = copy.deepcopy(self) new_self._modifiers.append(attr) return new_self # support indexing on proxies (e.g., Self.cpu[0]) def __getitem__(self, key): if not isinstance(key, int): raise TypeError("Proxy object requires integer index") if hasattr(self, '_pdesc'): raise AttributeError("Index operation on bound proxy") new_self = copy.deepcopy(self) new_self._modifiers.append(key) return new_self def find(self, obj): try: val = getattr(obj, self._attr) visited = False if hasattr(val, '_visited'): visited = getattr(val, '_visited') if visited: return None, False if not isproxy(val): # for any additional unproxying to be done, pass the # current, rather than the original object so that proxy # has the right context obj = val except: return None, False while isproxy(val): val = val.unproxy(obj) for m in self._modifiers: if isinstance(m, str): val = getattr(val, m) elif isinstance(m, int): val = val[m] else: assert("Item must be string or integer") while isproxy(val): val = val.unproxy(obj) return val, True def path(self): p = self._attr for m in self._modifiers: if isinstance(m, str): p += '.%s' % m elif isinstance(m, int): p += '[%d]' % m else: assert("Item must be string or integer") return p class AnyProxy(BaseProxy): def find(self, obj): return obj.find_any(self._pdesc.ptype) def path(self): return 'any' # The AllProxy traverses the entire sub-tree (not only the children) # and adds all objects of a specific type class AllProxy(BaseProxy): def find(self, obj): return obj.find_all(self._pdesc.ptype) def path(self): return 'all' def isproxy(obj): from . import params if isinstance(obj, (BaseProxy, params.EthernetAddr)): return True elif isinstance(obj, (list, tuple)): for v in obj: if isproxy(v): return True return False class ProxyFactory(object): def __init__(self, search_self, search_up): self.search_self = search_self self.search_up = search_up def __getattr__(self, attr): if attr == 'any': return AnyProxy(self.search_self, self.search_up) elif attr == 'all': if self.search_up: assert("Parant.all is not supported") return AllProxy(self.search_self, self.search_up) else: return AttrProxy(self.search_self, self.search_up, attr) # global objects for handling proxies Parent = ProxyFactory(search_self = False, search_up = True) Self = ProxyFactory(search_self = True, search_up = False) # limit exports on 'from proxy import *' __all__ = ['Parent', 'Self']
import React from 'react'; import PropTypes from 'prop-types'; export default function Confirm({ onCancel, onDangerClick, onDangerText, title }) { return( <div className="confirm"> {title} <p className="danger-text">{onDangerText}</p> <div className="confirm-button-group"> <button className="confirm-button outline-button cancel" onClick={onCancel}>Cancel</button> <button className="confirm-button outline-button confirm" onClick={onDangerClick}>Confirm</button> </div> </div> ); } Confirm.propTypes = { };
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import os from azure.cli.testsdk import ScenarioTest, ResourceGroupPreparer, StorageAccountPreparer TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) class HDInsightClusterTests(ScenarioTest): location = 'eastus2' # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_cluster_min_args(self, storage_account_info): self._create_hdinsight_cluster(self._wasb_arguments(storage_account_info, specify_key=False, specify_container=False)) # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_cluster_resize(self, storage_account_info): self._create_hdinsight_cluster( self._wasb_arguments(storage_account_info)) resize_cluster_format = 'az hdinsight resize -n {cluster} -g {rg} --target-instance-count 2' self.cmd(resize_cluster_format) self.cmd('az hdinsight show -n {cluster} -g {rg}', checks=[ self.check('properties.provisioningState', 'Succeeded'), self.check('properties.clusterState', 'Running'), self.check( "properties.computeProfile.roles[?name=='workernode'].targetInstanceCount", [2]) ]) # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_cluster_kafka(self, storage_account_info): self._create_hdinsight_cluster( HDInsightClusterTests._wasb_arguments(storage_account_info), HDInsightClusterTests._kafka_arguments() ) # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_cluster_kafka_with_optional_disk_args(self, storage_account_info): self._create_hdinsight_cluster( HDInsightClusterTests._wasb_arguments(storage_account_info), HDInsightClusterTests._kafka_arguments(), HDInsightClusterTests._optional_data_disk_arguments() ) # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_cluster_rserver(self, storage_account_info): self._create_hdinsight_cluster( HDInsightClusterTests._wasb_arguments(storage_account_info), HDInsightClusterTests._rserver_arguments() ) # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_cluster_with_component_version(self, storage_account_info): self._create_hdinsight_cluster( HDInsightClusterTests._wasb_arguments(storage_account_info), HDInsightClusterTests._component_version_arguments() ) # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_cluster_with_cluster_config(self, storage_account_info): self._create_hdinsight_cluster( HDInsightClusterTests._wasb_arguments(storage_account_info), HDInsightClusterTests._with_cluster_config() ) # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_cluster_with_ssh_creds(self, storage_account_info): self._create_hdinsight_cluster( HDInsightClusterTests._wasb_arguments(storage_account_info), HDInsightClusterTests._with_explicit_ssh_creds() ) # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_application(self, storage_account_info): self._create_hdinsight_cluster( HDInsightClusterTests._wasb_arguments(storage_account_info), HDInsightClusterTests._with_explicit_ssh_creds() ) # define application item names self.kwargs.update({ 'app': self.create_random_name(prefix='hdicliapp-', length=16), 'script_uri': 'https://hdiconfigactions.blob.core.windows.net/linuxhueconfigactionv02/install-hue-uber-v02.sh', 'script_action': 'InstallHue', 'script_params': '"-version latest -port 20000"' }) # create an application and wait for completion self.cmd('az hdinsight application create -g {rg} -n {cluster} --application-name {app} ' '--script-uri {script_uri} --script-action-name {script_action} --script-parameters {script_params}') self.cmd('az hdinsight application wait --created -n {cluster} -g {rg} --application-name {app}') # list all applications self.cmd('az hdinsight application list -g {rg} -n {cluster}', checks=[ self.check('type(@)', 'array'), self.check('length(@)', 1) ]) # get the specific application self.cmd('az hdinsight application show -g {rg} -n {cluster} --application-name {app}', checks=[ self.check('name', '{app}'), self.check('properties.provisioningState', 'Succeeded'), self.check('properties.applicationState', 'Running') ]) # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_usage(self, storage_account_info): self.kwargs.update({ 'loc': self.location }) self.cmd('az hdinsight list-usage -l {loc}', checks=[ self.check('type(value)', 'array'), self.check('length(value)', 1) ]) # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_monitor(self, storage_account_info): self.kwargs.update({ 'ws': self.create_random_name('testws', 20), 'la_prop_path': os.path.join(TEST_DIR, 'loganalytics.json') }) ws_response = self.cmd('resource create -g {rg} -n {ws} ' '--resource-type Microsoft.OperationalInsights/workspaces -p @"{la_prop_path}"') \ .get_output_in_json() ws_customer_id = ws_response['properties']['customerId'] self._create_hdinsight_cluster( HDInsightClusterTests._wasb_arguments(storage_account_info), HDInsightClusterTests._with_explicit_ssh_creds() ) # get monitor status self.cmd('az hdinsight monitor show -g {rg} -n {cluster}', checks=[ self.check('clusterMonitoringEnabled', False), self.check('workspaceId', None) ]) # enable monitoring self.cmd('az hdinsight monitor enable -g {rg} -n {cluster} --workspace {ws} --no-validation-timeout') # get monitor status self.cmd('az hdinsight monitor show -g {rg} -n {cluster}', checks=[ self.check('clusterMonitoringEnabled', True), self.check('workspaceId', ws_customer_id) ]) # disable monitor self.cmd('az hdinsight monitor disable -g {rg} -n {cluster}') # get monitor status self.cmd('az hdinsight monitor show -g {rg} -n {cluster}', checks=[ self.check('clusterMonitoringEnabled', False), self.check('workspaceId', None) ]) # Uses 'rg' kwarg @ResourceGroupPreparer(name_prefix='hdicli-', location=location, random_name_length=12) @StorageAccountPreparer(name_prefix='hdicli', location=location, parameter_name='storage_account') def test_hdinsight_script_action(self, storage_account_info): self.kwargs.update({ 'script_uri': 'https://hdiconfigactions.blob.core.windows.net/linuxgiraphconfigactionv01/giraph-installer-v01.sh', 'script_action': 'InstallGiraph', 'script_action_1': 'InstallGiraph1', 'head_node': 'headnode', 'worker_node': 'workernode' }) self._create_hdinsight_cluster( HDInsightClusterTests._wasb_arguments(storage_account_info), HDInsightClusterTests._with_explicit_ssh_creds() ) # execute script actions, and persist on success. self.cmd('az hdinsight script-action execute -g {rg} -n {cluster} ' '--script-action-name {script_action} --script-uri {script_uri} --roles {head_node},{worker_node} --persist-on-success') # list script actions and validate script is persisted. roles = [self.kwargs['head_node'], self.kwargs['worker_node']] self.cmd('az hdinsight script-action list -g {rg} -n {cluster} --persisted', checks=[ self.check('type(@)', 'array'), self.check('length(@)', 1), self.check('[0].name', '{script_action}'), self.check('[0].uri', '{script_uri}'), self.check('[0].roles', roles) ]) # delete script action. self.cmd('az hdinsight script-action delete -g {rg} -n {cluster} --script-action-name {script_action}') # list script actions and validate script is deleted. self.cmd('az hdinsight script-action list -g {rg} -n {cluster} --persisted', checks=[ self.check('type(@)', 'array'), self.check('length(@)', 0) ]) # list script action history and validate script appears there. script_actions = self.cmd('az hdinsight script-action list -g {rg} -n {cluster}', checks=[ self.check('type(@)', 'array'), self.check('length(@)', 1), self.check('[0].name', '{script_action}'), self.check('[0].uri', '{script_uri}'), self.check('[0].roles', roles), self.check('[0].status', 'Succeeded') ]).get_output_in_json() # get the script action by ID and validate it's the same action. self.kwargs['script_execution_id'] = str(script_actions[0]['scriptExecutionId']) script_actions = self.cmd('az hdinsight script-action show -g {rg} -n {cluster} ' '--script-execution-id {script_execution_id}', checks=[ self.check('name', '{script_action}') ]) # execute script actions, but don't persist on success. self.cmd('az hdinsight script-action execute -g {rg} -n {cluster} ' '--script-action-name {script_action_1} --script-uri {script_uri} --roles {head_node},{worker_node}') # list script action history and validate the new script also appears. script_actions = self.cmd('az hdinsight script-action list -g {rg} -n {cluster}', checks=[ self.check('type(@)', 'array'), self.check('length(@)', 2), self.check('[0].name', '{script_action_1}'), self.check("[0].uri", '{script_uri}'), self.check("[0].status", 'Succeeded') ]).get_output_in_json() # promote non-persisted script. self.kwargs['script_execution_id'] = str(script_actions[0]['scriptExecutionId']) script_actions = self.cmd('az hdinsight script-action promote -g {rg} -n {cluster} ' '--script-execution-id {script_execution_id}') # list script action list and validate the promoted script is the only one there. self.cmd('az hdinsight script-action list -g {rg} -n {cluster} --persisted', checks=[ self.check('type(@)', 'array'), self.check('length(@)', 1), self.check('[0].name', '{script_action_1}'), self.check('[0].uri', '{script_uri}'), self.check('[0].roles', roles), self.check('[0].status', None) ]) # list script action history and validate both scripts are there. script_actions = self.cmd('az hdinsight script-action list -g {rg} -n {cluster}', checks=[ self.check('type(@)', 'array'), self.check('length(@)', 2), self.check('[0].name', '{script_action_1}'), self.check("[0].uri", '{script_uri}'), self.check("[0].roles", roles), self.check("[0].status", 'Succeeded'), self.check('[1].name', '{script_action}'), self.check("[1].uri", '{script_uri}'), self.check("[1].roles", roles), self.check("[1].status", 'Succeeded') ]) def _create_hdinsight_cluster(self, *additional_create_arguments): self.kwargs.update({ 'loc': self.location, 'cluster': self.create_random_name(prefix='hdicli-', length=16), 'http_password': 'Password1!', 'cluster_type': 'spark' }) create_cluster_format = 'az hdinsight create -n {cluster} -g {rg} -l {loc} -p {http_password} -t {cluster_type} ' \ + '--no-validation-timeout ' \ + ' '.join(additional_create_arguments) # Wait some time to improve robustness if self.is_live or self.in_recording: import time time.sleep(60) self.cmd(create_cluster_format, checks=[ self.check('properties.provisioningState', 'Succeeded'), self.check('properties.clusterState', 'Running'), self.check("properties.computeProfile.roles[?name=='headnode']" ".osProfile.linuxOperatingSystemProfile.username", ['sshuser']) ]) self.cmd('az hdinsight show -n {cluster} -g {rg}', checks=[ self.check('properties.provisioningState', 'Succeeded'), self.check('properties.clusterState', 'Running') ]) @staticmethod def _wasb_arguments(storage_account_info, specify_key=False, specify_container=True): storage_account_name, storage_account_key = storage_account_info storage_account_key = storage_account_key.strip() key_args = ' --storage-account-key "{}"'.format(storage_account_key) if specify_key else "" container_args = ' --storage-default-container {}'.format('default') if specify_container else "" return '--storage-account {}{}{}'\ .format(storage_account_name, key_args, container_args) @staticmethod def _kafka_arguments(): return '-t {} --workernode-data-disks-per-node {}'.format('kafka', '4') @staticmethod def _optional_data_disk_arguments(): return '--workernode-data-disk-storage-account-type {} --workernode-data-disk-size {}'\ .format('Standard_LRS', '1023') @staticmethod def _rserver_arguments(): return '-t {} --edgenode-size {} -v 3.6'.format('rserver', 'large') @staticmethod def _component_version_arguments(): return '-t {} --component-version {}'.format('spark', 'spark=2.2') @staticmethod def _with_cluster_config(): return '--cluster-configurations {}'.format(r'{{\"gateway\":{{\"restAuthCredential.username\":\"admin\"}}}}') @staticmethod def _with_explicit_ssh_creds(): return '--ssh-user {} --ssh-password {}'.format('sshuser', 'Password1!')
import React from "react" import Layout from "../components/layout" import { graphql } from "gatsby" export default ({ data: post }) => { return ( <Layout> <h1>{post.markdownRemark.frontmatter.title}</h1> <h4> {post.markdownRemark.timeToRead}{" "} {post.markdownRemark.timeToRead > 1 ? "minutes" : "minute"} </h4> <div dangerouslySetInnerHTML={{ __html: post.markdownRemark.html }}></div> </Layout> ) } export const query = graphql` query($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html timeToRead frontmatter { title } } } `
import React, { useState, useEffect } from 'react'; import './Hospital.css'; import moment from 'moment'; import { getbedInfo, getHospitalDetails } from '../../../config/Service/Beds'; import compareByAsc from '../../../config/AscDsc/Asc'; import compareByDesc from '../../../config/AscDsc/Desc'; import { FaArrowsAltV, FaPhoneAlt, FaMapMarkedAlt } from 'react-icons/fa'; import titleValue from '../titleValue'; function HospitalLists() { const [bed, setBed] = useState([]); const [data, setData] = useState([]); const [hospital, setHospital] = useState(''); const [type, setType] = useState('beds'); const [loading, setLoading] = useState(true); useEffect(() => { getBed(); getBedDetails(); const timer = setInterval(() => getBed(), 60 * 1000 * 2); return () => clearInterval(timer); // eslint-disable-next-line }, []); const getBed = () => { getbedInfo(setBed, setLoading, hospital); }; const getBedDetails = () => { getHospitalDetails(setData, setLoading, hospital); }; const sorting = (key) => { let arrayCopy = [...bed]; const arrInStr = JSON.stringify(arrayCopy); arrayCopy.sort(compareByAsc(key)); const arrInStr1 = JSON.stringify(arrayCopy); if (arrInStr === arrInStr1) { arrayCopy.sort(compareByDesc(key)); } setBed(arrayCopy); // this.setState({ todos: arrayCopy }); }; const onChangeText = (event) => { setHospital(event.target.value); }; // eslint-disable-next-line useEffect(() => { getBed(); // eslint-disable-next-line }, [hospital]); const getData = () => bed.filter((c) => c.bed_type === type); const getDataData = (name) => data.filter((c) => c.name === name); return ( <> <div style={{ textAlign: 'left' }}> <span> <strong>Source :</strong> Data reported by Nodal officers of each Dedicated COVID-19 hospital &{' '} <a href='https://coronabeds.jantasamvad.org/' target='_blank' rel='noreferrer'> Coronabeds.jantasamvad.org </a> </span> <br></br> <span> <strong>Last Updated :</strong>{' '} {getData('beds') .slice(0, 1) .map((c) => moment(c.updated_at).local().format('YYYY-MM-DD HH:mm'))} </span> </div> <div style={{ textAlign: 'left', marginTop: '15px' }}> <div className='row style_row'> <div className='form-group col'> <label htmlFor='brand' className='label'> SELECT BEDS TYPE </label> <select className='form-control not_edit edit' onChange={(event) => setType(event.target.value)} name='oer' style={{ background: 'white' }} > {titleValue.map((c, i) => ( <option value={c.name} key={i + 1}> {c.title} </option> ))} </select> </div> <div className='form-group col'> <label htmlFor='brand' className='label'></label> <input type='text' placeholder='Search By Hospital Name' onChange={(tye) => onChangeText(tye)} className='form-control not_edit edit' style={{ marginTop: '8px' }} /> </div> </div> </div> <div style={{ textAlign: 'right' }}> <span> <span class='green1'></span> <strong>More than 50 Beds Available</strong> </span>{' '} &nbsp;&nbsp; <span> <span class='yellow1'></span> <strong>Less than 50 Beds Available</strong> </span>{' '} &nbsp;&nbsp; <span> <span class='red1'></span> <strong> No Beds Available</strong> </span> </div> <div className='data_tablee'> {loading ? ( <img src='https://digitalfleet.eu/app/static/media/spinner.0e833be9.gif' className='loading_data' alt='Loding' style={{ width: '170px', position: 'absolute', left: '50%' }} /> ) : ( <table className='table '> <thead className=''> <tr> <th></th> <th onClick={() => sorting('name')}> Hospital Name{' '} <span> <FaArrowsAltV /> </span> </th> <th style={{ width: '10%' }}> Total Beds{' '} {/* <span> <FaArrowsAltV /> </span> */} </th> <th style={{ width: '12%' }} onClick={() => sorting('vacant')}> Vacant Beds{' '} <span> <FaArrowsAltV /> </span> </th> <th style={{ width: '14%' }}>Occupied Beds </th> <th style={{ width: '17%' }}>Last Updated</th> <th style={{ width: '13%' }} onClick={() => sorting('oxygen_left_days')} > Oxygen left for{' '} <span> <FaArrowsAltV /> </span> </th> </tr> </thead> {getData('beds').map((c, i) => ( <tbody key={i + 1}> <tr className={ c.vacant >= 50 ? 'green accordion-toggle' : c.vacant <= 50 && c.vacant >= 1 ? 'yellow accordion-toggle' : 'red accordion-toggle' } > <td data-toggle='collapse' data-target={`#demo1${i + 1}`}> <button className={ c.vacant >= 50 ? 'btn btn-success' : c.vacant <= 50 && c.vacant >= 1 ? 'btn btn-warning' : 'btn btn-danger' } id='btn-icon' > <span className='plus_icon'> +</span> </button> </td> <td>{c.name ? c.name : ''}</td> <td>{c.total ? c.total : ''}</td> <td>{c.vacant ? c.vacant : ''}</td> <td>{c.occupied ? c.occupied : ''}</td> <td> {' '} {moment(c.updated_at).local().format('YYYY-MM-DD HH:mm')} </td> <td> {c.oxygen_left_days ? `${c.oxygen_left_days} ${ c.oxygen_left_days > 1 ? 'days' : 'day' }` : ''} {' '} {c.oxygen_left_hour ? `${c.oxygen_left_hour} ${ c.oxygen_left_hour > 1 ? 'hours' : 'hour' }` : ''} </td> </tr> <tr> <td colspan='12' className='hiddenRow'> <div className='accordian-body collapse' id={`demo1${i + 1}`} > {getDataData(c.name).map((d, i) => ( <div key={i + 1} className='collaps_data' style={{ textAlign: 'left' }} > <div className='name_address'> <h4> <strong>{d.name}</strong> </h4> <h6>{d.address}</h6> <hr></hr> </div> <div className='type'> <h6>Management: {c.hospital_type}</h6> <hr></hr> </div> <div className='call_number'> <h6> Contact number:{' '} {d.contact_number.map((c) => ( <a className='btn ' id='btn-call-number' href={`tel:${c}`} > {' '} <FaPhoneAlt /> {c} </a> ))} </h6> <hr></hr> </div> {d.map_link && ( <div className='type'> <h6> View Location in map :{' '} <a className='btn ' id='btn-map' href={d.map_link} target='_blank' rel='noreferrer' > {' '} <FaMapMarkedAlt style={{ fontSize: '25px' }} /> </a>{' '} </h6> <hr></hr> </div> )} </div> ))} </div> </td> </tr> </tbody> ))} </table> )} </div> </> ); } export default HospitalLists;
#skip.pythran export dilate_decompose(int[][], int) #pythran export dilate_decompose_loops(float[][], int) #skip.pythran export dilate_decompose_interior(int[][], int[][]) #skip.runas import numpy as np ; image = np.random.randint(0, 256, (width, height)) / 256.0 ; dilate_decompose_loops(image) #runas import numpy as np ; image = np.tri(100, 200) /2.0 ; dilate_decompose_loops(image, 4) #bench import numpy as np ; image = np.tri(500, 600) /2.0 ; dilate_decompose_loops(image, 4) from numpy import empty_like def dilate_decompose_loops(x, k): m,n = x.shape y = empty_like(x) for i in xrange(m): for j in xrange(n): left_idx = max(0, i-k//2) right_idx = min(m, i+k//2+1) currmax = x[left_idx, j] for ii in xrange(left_idx+1, right_idx): elt = x[ii, j] if elt > currmax: currmax = elt y[i, j] = currmax z = empty_like(x) for i in xrange(m): for j in xrange(n): left_idx = max(0, j-k//2) right_idx = min(n, j+k//2+1) currmax = y[i,left_idx] for jj in xrange(left_idx+1, right_idx): elt = y[i,jj] if elt > currmax: currmax = elt z[i,j] = currmax return z #def dilate_1d_naive(x_strip, k): # """ # Given a 1-dimensional input and 1-dimensional output, # fill output with 1d dilation of input # """ # nelts = len(x_strip) # y_strip = empty_like(x_strip) # half = k / 2 # for idx in xrange(nelts): # left_idx = max(idx-half,0) # right_idx = min(idx+half+1, nelts) # currmax = x_strip[left_idx] # for j in xrange(left_idx+1, right_idx): # elt = x_strip[j] # if elt > currmax: # currmax = elt # y_strip[idx] = currmax # return y_strip # #def dilate_decompose(x, k): # import numpy as np # m,n = x.shape # y = np.array([dilate_1d_naive(x[row_idx, :], k) for row_idx in xrange(m)]) # return np.array([dilate_1d_naive(y[:, col_idx], k) for col_idx in xrange(n)]).T # #def dilate_1d_interior(x_strip, k): # # nelts = len(x_strip) # y_strip = empty_like(x_strip) # half = k / 2 # # interior_start = half+1 # interior_stop = max(nelts-half, interior_start) # # # left boundary # for i in xrange(min(half+1, nelts)): # left_idx = max(i-half,0) # right_idx = min(i+half+1, nelts) # currmax = x_strip[left_idx] # for j in xrange(left_idx+1, right_idx): # elt = x_strip[j] # if elt > currmax: # currmax = elt # y_strip[i] = currmax # # #interior # for i in xrange(interior_start, interior_stop): # left_idx = i-half # right_idx = i+half+1 # currmax = x_strip[left_idx] # for j in xrange(left_idx+1, right_idx): # elt = x_strip[j] # if elt > currmax: # currmax = elt # y_strip[i] = currmax # # # right boundary # for i in xrange(interior_stop, nelts): # left_idx = max(i-half, 0) # right_idx = nelts # currmax = x_strip[left_idx] # for j in xrange(left_idx+1, right_idx): # elt = x_strip[j] # if elt > currmax: # currmax = elt # y_strip[i] = currmax # return y_strip # #def dilate_decompose_interior(x, k): # m,n = x.shape # y = np.array([dilate_1d_interior(x[row_idx, :],k) for row_idx in xrange(m)]) # return np.array([dilate_1d_interior(y[:, col_idx],k) for col_idx in xrange(n)]).T
import Icon from 'veui/components/Icon' Icon.register({ 'sound-market': { paths: [ { d: 'M23.07 0h.03a2 2 0 012 2v44a2 2 0 01-2 2h-.03a2 2 0 01-2-2V2c0-1.1.9-2 2-2zM12.8 10.29h.02a2 2 0 012 2v26.85a2 2 0 01-2 2h-.02a2 2 0 01-2-2V12.3c0-1.1.9-2 2-2zm20.57 0h.02a2 2 0 012 2v26.85a2 2 0 01-2 2h-.02a2 2 0 01-2-2V12.3c0-1.1.9-2 2-2zm10.28 6.85h.03a2 2 0 012 2v9.72a2 2 0 01-2 2h-.03a2 2 0 01-2-2v-9.72c0-1.1.9-2 2-2zm-41.14 0h.02a2 2 0 012 2v9.72a2 2 0 01-2 2H2.5a2 2 0 01-2-2v-9.72c0-1.1.9-2 2-2z' } ], width: '46', height: '48' } })
# Copyright (c) 2020 PaddlePaddle 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. """Traine main program.""" import argparse from collections import defaultdict import json import os import subprocess import time import numpy as np import paddle.fluid as fluid from paddle.fluid.incubate.fleet.collective import fleet, DistributedStrategy import paddle.fluid.incubate.fleet.base.role_maker as role_maker import models import tasks from utils import check_cuda, Timer from utils.args import parse_args, str2bool def setup_args(): """ Setup arguments. """ parser = argparse.ArgumentParser() parser.add_argument("--is_distributed", type=str2bool, default=False) parser.add_argument("--save_path", type=str, default="output") parser.add_argument("--train_file", type=str, required=True) parser.add_argument("--valid_file", type=str, required=True) parser.add_argument("--start_step", type=int, default=0) parser.add_argument("--num_epochs", type=int, default=20) parser.add_argument("--log_steps", type=int, default=100) parser.add_argument("--validation_steps", type=int, default=1000) parser.add_argument("--save_steps", type=int, default=5000) models.add_cmdline_args(parser) tasks.add_cmdline_args(parser) args = parse_args(parser) args.load(args.config_path, "Model") print(json.dumps(args, indent=2)) return args def train(args): """ Train main function. """ if args.is_distributed: role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) dev_count = fluid.core.get_cuda_device_count() gpu_id = int(os.getenv("FLAGS_selected_gpus")) trainers_num = fleet.worker_num() trainer_id = fleet.worker_index() else: dev_count = 1 gpu_id = 0 trainers_num = 1 trainer_id = 0 place = fluid.CUDAPlace(gpu_id) task = tasks.create_task(args) model = models.create_model(args, place) train_generator = task.get_data_loader( model, input_file=args.train_file, num_epochs=args.num_epochs, num_part=trainers_num, part_id=trainer_id, phase="train" ) valid_generator = task.get_data_loader( model, input_file=args.valid_file, num_part=dev_count, part_id=gpu_id, phase="distributed_valid" if args.is_distributed else "valid" ) # run training timer = Timer() timer.start() for step, data in enumerate(train_generator(), args.start_step + 1): outputs = task.train_step(model, data) timer.pause() if step % args.log_steps == 0: time_cost = timer.pass_time current_epoch, current_file_index, total_file = task.reader.get_train_progress() print(f"[train][{current_epoch}] progress: {current_file_index}/{total_file} " f"step: {step}, time: {time_cost:.3f}, " f"speed: {args.log_steps / time_cost:.3f} steps/s") print(f"\tcurrent lr: {outputs.pop('scheduled_lr'):.7f}") metrics = task.get_metrics(outputs) print("\t" + ", ".join(f"{k}: {v:.4f}" for k, v in metrics.items())) timer.reset() if step % args.validation_steps == 0: evaluate(task, model, valid_generator, args, dev_count, gpu_id, step) if step % args.save_steps == 0 and trainer_id == 0: save_path = f"{args.save_path}/step_{step}" model.save(save_path, is_checkpoint=True) with open(save_path + ".finish", "w") as f: pass timer.start() def evaluate(task, model, generator, args, dev_count, gpu_id, training_step): outputs = None print("=" * 80) print("Evaluation:") timer = Timer() timer.start() for step, data in enumerate(generator(), 1): part_outputs = task.eval_step(model, data) outputs = task.merge_mertrics_and_statistics(outputs, part_outputs) if step % args.log_steps == 0: metrics = task.get_metrics(outputs) print(f"\tstep {step}:" + ", ".join(f"{k}: {v:.4f}" for k, v in metrics.items())) if args.is_distributed: # merge evaluation outputs in distributed mode. part_file = os.path.join(args.save_path, f"evaluation_output.part_{gpu_id}") with open(part_file, "w") as fp: json.dump(outputs, fp, ensure_ascii=False) part_finish_file = os.path.join(args.save_path, f"evaluation_output.part_{gpu_id}.finish") with open(part_finish_file, "w"): pass if gpu_id == 0: part_files = f"evaluation_output.part_*.finish" while True: ret = subprocess.getoutput(f"find {args.save_path} -maxdepth 1 -name {part_files}") num_completed = len(ret.split("\n")) if num_completed != dev_count: time.sleep(1) continue outputs = None for dev_id in range(dev_count): part_file = os.path.join(args.save_path, f"evaluation_output.part_{dev_id}") with open(part_file, "r") as fp: part_outputs = json.load(fp) outputs = task.merge_mertrics_and_statistics(outputs, part_outputs) break subprocess.getoutput("rm " + os.path.join(args.save_path, f"evaluation_output.part*")) if gpu_id == 0: metrics = task.get_metrics(outputs) print(f"[Evaluation][{training_step}]" + ", ".join(f"{k}: {v:.4f}" for k, v in metrics.items())) print(f"\ttime cost: {timer.pass_time:.3f}") print("=" * 80) return if __name__ == "__main__": args = setup_args() check_cuda(True) train(args)
import { textWasPrinted } from "./input"; import { font } from "./style"; import { append as appendToWindow, get as getWindow } from "./window"; // output buffers for all windows const outputBuffer = [ "" ]; // custom output filters let outputFilter = null; /** * Make text HTML-printable * * @param text * @returns {string} */ function encodeHtml( text ) { let encoded = ""; for( let i = 0; i < text.length; ++i ) { // Extended Latin-1 characters need to be added as HTML entities if( text.charCodeAt( i ) > 127 ) { encoded += "&#" + text.charCodeAt( i ) + ";"; } else { switch( text[ i ] ) { case "&": encoded += "&amp;"; break; case "<": encoded += "&lt;"; break; case ">": encoded += "&gt;"; break; case "\r": encoded += "\n"; break; default: encoded += text[ i ]; break; } } } return encoded; } /** * Add text to the text buffer * * @param text * @param targetWindow */ export function append( text, targetWindow = 0 ) { if( !outputBuffer[ targetWindow ] ) { outputBuffer[ targetWindow ] = ""; } if( text.indexOf( "\n" ) > -1 || text.indexOf( "\r" ) > -1 ) { const nextLBR = Math.max( text.lastIndexOf( "\n" ), text.lastIndexOf( "\r" ) ) + 1; outputBuffer[ targetWindow ] += encodeHtml( text.substr( 0, nextLBR ) ); flush( targetWindow ); outputBuffer[ targetWindow ] = encodeHtml( text.substr( nextLBR ) ); } else { outputBuffer[ targetWindow ] += encodeHtml( text ); } } /** * Print out the text buffer * * @param targetWindow */ export function flush( targetWindow ) { if( targetWindow === undefined ) { for( var i in outputBuffer ) { flush( +i ); } return; } if( !outputBuffer[ targetWindow ] || !getWindow( targetWindow ) ) { return; } let output = outputBuffer[ targetWindow ]; // call output filters if( targetWindow === 0 && outputFilter && output !== "" ) { const currentStyles = font.get()[ 0 ]; const filterResult = outputFilter( output, { style: { bold: Boolean( currentStyles.bold ), italic: Boolean( currentStyles.italic ) } } ); if( typeof filterResult === "string" ) { output = filterResult; } } appendToWindow( output, targetWindow ); outputBuffer[ targetWindow ] = ""; if( targetWindow === 0 ) { textWasPrinted( true ); } } /** * Register the output filter */ export function init( opt ) { if( opt && opt.outputFilter ) { outputFilter = opt.outputFilter; } } /** * Add a newline to the buffer. * * @param targetWindow */ export function newline( targetWindow ) { if( outputBuffer[ targetWindow ] ) { outputBuffer[ targetWindow ] += "\n"; } else { outputBuffer[ targetWindow ] = "\n"; } flush( targetWindow ); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const bus_http_1 = require("@comunica/bus-http"); /** * A comunica Proxy Http Actor. */ class ActorHttpProxy extends bus_http_1.ActorHttp { constructor(args) { super(args); } async test(action) { if (!action.context) { throw new Error(`Actor ${this.name} could not find a context.`); } const proxyHandler = action.context.get(exports.KEY_CONTEXT_HTTPPROXYHANDLER); if (!proxyHandler) { throw new Error(`Actor ${this.name} could not find a proxy handler in the context.`); } if (!await proxyHandler.getProxy(action)) { throw new Error(`Actor ${this.name} could not determine a proxy for the given request.`); } return { time: Infinity }; } async run(action) { const requestedUrl = typeof action.input === 'string' ? action.input : action.input.url; if (!action.context) { throw new Error('Illegal state: missing context'); } const proxyHandler = action.context.get(exports.KEY_CONTEXT_HTTPPROXYHANDLER); // Send a request for the modified request const output = await this.mediatorHttp.mediate(Object.assign(Object.assign({}, await proxyHandler.getProxy(action)), { context: action.context.delete(exports.KEY_CONTEXT_HTTPPROXYHANDLER) })); // Modify the response URL output.url = output.headers.get('x-final-url') || requestedUrl; return output; } } exports.ActorHttpProxy = ActorHttpProxy; exports.KEY_CONTEXT_HTTPPROXYHANDLER = '@comunica/actor-http-proxy:httpProxyHandler'; //# sourceMappingURL=ActorHttpProxy.js.map
import Discord from "discord.js"; export default function returnNoEmbed(yeslist, client) { /* we map through all the users outputting them numerically */ if (yeslist.err === true) return this.errorEmbed("List is currently empty."); if (!yeslist.id) return this.errorEmbed("Event does not exist"); const embed = new Discord.RichEmbed() .setAuthor(`❌ ${yeslist.title} (${yeslist.id})`) .setColor("#de561c") .setDescription( yeslist.usersArr.map((m, index) => { if (index + 1 > 30) return; return `${index + 1}. <@${m}> \n` }) ) .setFooter( "Relative of the Billy Herrington bot. | Made by 𝓗𝓮𝔁.", "https://cdn.discordapp.com/avatars/469204371289145345/561ea91258cf5ccad4685a1b4f52355e.png?size=2048" ); return embed; }
import React from "react"; import TitleCertifications from "./certifications/title"; import CertificationsContent from "./certifications/allcertifications"; const Certification = () => ( <section className="no-certifications"> <div className="container"> <div className="row justify-content-center"> <TitleCertifications /> <CertificationsContent /> </div> </div> </section> ); export default Certification;
""" Create by: apenasrr Source: https://github.com/apenasrr/mass_videojoin A smart tool to optimize and make turbo join in a massive video collection """ from configparser import ConfigParser import datetime import logging import os import pandas as pd import sys import unidecode from transition import check_transition_resolution, \ get_video_resolution_format, \ get_dict_transition_resolution from utils_mass_videojoin import (exclude_all_files_from_folder, create_report_backup, get_folder_script_path, time_is_hh_mm_ss_ms, sort_human, sort_df_column_from_list, check_col_unique_values, get_serie_sub_folder, normalize_string) from video_tools import join_mp4, get_duration, \ timedelta_to_string, float_seconds_to_string, \ float_seconds_from_string from make_split import search_to_split_videos from prefill_reencode_plan import prefill_reencode_plan import make_reencode import video_report import json def logging_config(): logfilename = 'log-' + 'mass_videojoin' + '.txt' logging.basicConfig(filename=logfilename, level=logging.INFO, format=' %(asctime)s-%(levelname)s-%(message)s') # set up logging to console console = logging.StreamHandler() console.setLevel(logging.INFO) # set a format which is simpler for console use formatter = logging.Formatter(' %(asctime)s-%(levelname)s-%(message)s') console.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(console) def clean_cmd(): def clear(): return os.system('cls') clear() def df_sort_human(df, key_column_name): """ Sort files and folders in human way. So after folder/file '1' comes '2', instead of '10' and '11'. Simple yet flexible natural sorting in Python. When you try to sort a list of strings that contain numbers, the normal python sort algorithm sorts lexicographically, so you might not get the results that you expect: More info: https://github.com/SethMMorton/natsort :input: DataFrame. With columns [path_file] :return: DataFrame. Sort in a human way by [file_path_folder, file_name] """ key_column_name_norm = key_column_name + '_norm' df[key_column_name_norm] = df[key_column_name].apply(normalize_string) list_path_file = df[key_column_name_norm].tolist() sorter = sort_human(list_path_file) df = sort_df_column_from_list(df, key_column_name_norm, sorter) df.drop([key_column_name_norm], 1, inplace=True) df = df.reset_index() return df def set_mark_group_encode(df): df['key_join_checker'] = df['audio_codec'] + '-' + \ df['video_codec'] + '-' + \ df['video_resolution_width'].astype(str) + '-' + \ df['video_resolution_height'].astype(str) serie_group_encode_bool = ( df['key_join_checker'] != df['key_join_checker'].shift(1)) return serie_group_encode_bool def set_mask_group_per_folder(serie_folder_path): serie_first_column = get_serie_sub_folder(serie_folder_path) df_first_column = serie_first_column.to_frame('folder') df_first_column['folder_prior'] = df_first_column['folder'].shift(1) serie_change_folder_bool = ( df_first_column['folder_prior'] != df_first_column['folder']) return serie_change_folder_bool def get_serie_group(serie_change_bool): """ from boolean serie, make cumulative sum returning serie int true, false, false, true, false 1, 1, 1, 2, 2 """ return serie_change_bool.cumsum() def get_video_details_with_group(df): # set mask group per encode serie_group_encode_bool = set_mark_group_encode(df) # set mask group per folder serie_folder_path = df['file_path_folder_origin'] serie_change_folder_bool = set_mask_group_per_folder(serie_folder_path) # agregate group masks serie_change_bool = serie_group_encode_bool | serie_change_folder_bool # create group_encode column df['group_encode'] = get_serie_group(serie_change_bool) return df def get_list_chunk_videos_from_group(df, group_no, max_size_mb, duration_limit='00:00:00.00'): max_size_bytes = max_size_mb * 1024**2 mask = df['group_encode'].isin([int(group_no)]) df['file_path'] = df['file_path_folder'] + '\\' + \ df['file_name'] df_group = df.loc[mask, :] df_group['float_duration'] = \ df_group['duration'].apply(float_seconds_from_string) if duration_limit != '00:00:00.00': float_duration_limit = float_seconds_from_string(duration_limit) else: # symbolic limit not attainable float_duration_limit = float_seconds_from_string('99:99:99') list_chunk_videos = [] chunk_size = 0 chunk_duration = 0 list_videos = [] for _, row in df_group.iterrows(): chunk_size_after = chunk_size + row['file_size'] chunk_duration_after = chunk_duration + row['float_duration'] if (chunk_size_after > max_size_bytes) or \ (chunk_duration_after > float_duration_limit): logging.info(f'join video from {len(list_videos)} files') if len(list_videos) == 0: logging.error('There is a video bigger than limit, ' + 'after split process.') logging.error(row) sys.exit() list_chunk_videos.append(list_videos) list_videos = [] chunk_size = 0 chunk_duration = 0 list_videos.append(row['file_path']) chunk_size += row['file_size'] chunk_duration += row['float_duration'] if len(list_videos) > 0: logging.info(f'join video from {len(list_videos)} files') list_chunk_videos.append(list_videos) list_videos = [] logging.info(f'group {group_no} will generate ' + f'{len(list_chunk_videos)} videos') return list_chunk_videos def get_list_chunk_videos(df, max_size_mb, duration_limit='00:00:00.00'): list_group = df['group_encode'].unique().tolist() list_final = [] for group_no in list_group: group_no = str(group_no) list_chunk_videos = \ get_list_chunk_videos_from_group(df, group_no, max_size_mb, duration_limit) list_final += list_chunk_videos print('') return list_final def get_path_folder_cache(path_dir): dir_name_normalize = get_folder_name_normalized(path_dir) folder_name = os.path.join('projects', 'output_' + dir_name_normalize) ensure_folder_existence([folder_name]) path_folder_cache = os.path.join(folder_name, 'cache') ensure_folder_existence([path_folder_cache]) return path_folder_cache def join_videos_process_df(df, list_file_path, file_name_output, list_dict_videos_duration, transition_effect=False): """"update video_details dataframe with columns: file_output, video_duration_real" Args: df (dataframe): video_details dataframe. Required columns: file_path list_file_path (list): list of original video files file_name_output (string): file_name of joined video output list_dict_videos_duration (list): list of dicts, with keys: file_path_origin (string). file_path of original video, duration_real (string). real video duration, Format hh:mm:ss transition_effect {bol}: True if list_file_path contain transition effects Returns: dataframe: dataframe updated with columns: file_output, video_duration_real """ # add column file_output mask_files_joined = df['file_path'].isin(list_file_path) df.loc[mask_files_joined, 'file_output'] = file_name_output # add column video_duration_real index_video_in_df = 0 if transition_effect: transition_duration_str = list_dict_videos_duration[0]['duration_real'] # convert to timedelta transition_duration = \ strptimedelta_hh_mm_ss_ms(str_hh_mm_ss_ms=transition_duration_str) else: transition_duration = \ strptimedelta_hh_mm_ss_ms(str_hh_mm_ss_ms='00:00:00') for dict_videos_duration in list_dict_videos_duration: file_path_origin = dict_videos_duration['file_path_origin'] mask_file = df['file_path'].isin([file_path_origin]) # if video_path is in dataframe, instead of being a transition video if mask_file.any(): dict_videos_duration = \ update_dict_videos_duration(dict_videos_duration, index_video_in_df, transition_duration) index_video_in_df += 1 string_video_duration_real = dict_videos_duration['duration_real'] df.loc[mask_file, 'video_duration_real'] = \ string_video_duration_real return df def join_videos_update_col_duration(df): """rename columns durations of video_details dataframe. from 'duration' to 'video_origin_duration_pre_join'}, from 'video_duration_real' to 'duration' Args: df (dataframe): video_details with columns: duration, video_duration_real Returns: dataframe: video_details with duration columns renamed """ list_dict_replace = [{'duration': 'video_origin_duration_pre_join'}, {'video_duration_real': 'duration'}] for dict_ in list_dict_replace: df = df.rename(columns=dict_) return df def transition_update_chunk_videos(list_chunk_videos): """includes transition effect in the video join plan Args: list_chunk_videos (list): list of groups. Each group is a list of video path_files """ def get_transition_path_file(video_path_file): video_resolution = get_video_resolution_format(video_path_file) dict_transition_resolution = get_dict_transition_resolution() transition_path_file = dict_transition_resolution[video_resolution] return transition_path_file list_chunk_videos_update = [] for chunk_videos in list_chunk_videos: # find transition_path_file based on the resolution of first video_path video_path_file = chunk_videos[0] transition_path_file = get_transition_path_file(video_path_file) for index, video_path in enumerate(chunk_videos): if index == 0: chunk_videos_update = [] chunk_videos_update.append(transition_path_file) chunk_videos_update.append(video_path) chunk_videos_update.append(transition_path_file) list_chunk_videos_update.append(chunk_videos_update) return list_chunk_videos_update def strptimedelta_hh_mm_ss_ms(str_hh_mm_ss_ms): hr, min, sec = map(float, str_hh_mm_ss_ms.split(':')) duration_timedelta = datetime.timedelta(hours=hr, minutes=min, seconds=sec) return duration_timedelta def ensure_transitions(list_chunk_videos): """ensures that there is an appropriate transition, based on resolution, for each chunk_videos Args: list_chunk_videos (list): list of chunk_videos. Chunk_videos are list of video path_file """ list_path_file_chunk_representatives = [] for chunk_videos in list_chunk_videos: first_path_file = chunk_videos[0] list_path_file_chunk_representatives.append(first_path_file) check_transition_resolution(list_path_file_chunk_representatives) def join_videos(df, max_size_mb, filename_output, path_folder_videos_joined, path_folder_videos_cache, start_index_output, duration_limit='00:00:00.00', transition_status=False): """join videos according to column 'group_encode' in df dataframe Args: df (dataframe): video_details dataframe. Required columns: file_dolder, file_name, group_encode max_size_mb (int): max size of each block of videos joined path_folder_videos_joined (str): destination path_folder for grouped videos path_folder_videos_cache (str): path_folder for cache data start_index_output (int): initial number that the exported video files will receive as a suffix duration_limit (str): duration limit in format: hh:mm:ss.ms transition_status (bol): true to activate transition effect Returns: dataframe: video_details dataframe updated with new columns: [file_output, video_origin_duration_pre_join] """ df['file_path'] = df['file_path_folder'] + '\\' + df['file_name'] list_chunk_videos = get_list_chunk_videos(df, max_size_mb, duration_limit) df['file_output'] = '' list_chunk_videos_original = list_chunk_videos.copy() # make list_chunk_videos with transition effect if transition_status: ensure_transitions(list_chunk_videos) # include transition_video between each file in list_chunk_videos list_chunk_videos = \ transition_update_chunk_videos(list_chunk_videos) for index, list_file_path in enumerate(list_chunk_videos): file_count = index + start_index_output file_name_output = f'{filename_output}-%03d.mp4' % file_count file_path_output = os.path.join(path_folder_videos_joined, file_name_output) # make video join list_dict_videos_duration = join_mp4(list_file_path, file_path_output, path_folder_videos_cache) list_file_path_original = list_chunk_videos_original[index] df = join_videos_process_df(df, list_file_path_original, file_name_output, list_dict_videos_duration, transition_status) # register file_name_output in dataframe mask_files_joined = df['file_path'].isin(list_file_path) df.loc[mask_files_joined, 'file_output'] = file_name_output df.loc[mask_files_joined, 'file_path_output'] = \ os.path.abspath(file_path_output) df = join_videos_update_col_duration(df) print(f'total: {len(list_chunk_videos)} videos') return df def update_dict_videos_duration(dict_videos_duration, index, transition_duration): """update video_duration key in dict, with duration if transition effects Args: dict_videos_duration (dict): required key 'duration_real' index (int): index position in group videos transition_duration (timedelta): video transition duration Returns: dict: dict_videos_duration updated """ if index == 0: plus_timedelta = transition_duration + transition_duration else: plus_timedelta = transition_duration duration_pre_transition = \ dict_videos_duration['duration_real'] duration_pre_transition_timedelta = \ strptimedelta_hh_mm_ss_ms( str_hh_mm_ss_ms=duration_pre_transition) duration_pos_transition_timedelta = \ duration_pre_transition_timedelta + \ plus_timedelta duration_pos_transition_str = \ timedelta_to_string(duration_pos_transition_timedelta) dict_videos_duration['duration_real'] = duration_pos_transition_str return dict_videos_duration def correct_duration(path_file_report): """Corrects the duration metadata in the project report Args: path_file_report (str): absolute report path file. Required columns in report: [file_path_folder, file_name, duration, duration_seconds] Returns: dataframe: updated with: -corrected duration column -new column duration_original """ logging.info('Correcting duration metadata...') # set cache folder # ensure folder cache in project folder project_dir_path = os.path.dirname(path_file_report) project_ts_dir_path = os.path.join(project_dir_path, 'cache') ensure_folder_existence([project_ts_dir_path]) # load report project df = pd.read_excel(path_file_report, engine='openpyxl') # create backup column df['duration_original'] = df['duration'] df['duration_seconds_original'] = df['duration_seconds'] # iterate through video files series_file_path = df['file_path_folder'] + '\\' + df['file_name'] list_file_path = series_file_path.tolist() for index, file_path in enumerate(list_file_path): # convert file file_name_ts = f'{index+1}.ts' path_file_name_ts = os.path.join( project_ts_dir_path, file_name_ts) os.system("ffmpeg -i " + '"' + file_path + '"' + " -c copy -bsf:v h264_mp4toannexb -f mpegts " + path_file_name_ts) # get duration float_duration = get_duration(path_file_name_ts) string_duration = \ float_seconds_to_string(float_duration) # include in report file df.loc[index, 'duration'] = string_duration df.loc[index, 'duration_seconds'] = float_duration # remove temp file exclude_all_files_from_folder(path_folder=project_ts_dir_path) return df def menu_ask(): print('1-Generate worksheet listing the files') print('2-Process reencode of videos marked in column ' + '"video_resolution_to_change"') print('3-Group videos into groups up to 1 gb with the same codec ' + 'and resolution') msg_type_answer = 'Type your answer: ' make_report = int(input(f'\n{msg_type_answer}')) if make_report == 1: return 1 elif make_report == 2: return 2 elif make_report == 3: return 3 else: msg_invalid_option = "Invalid option" raise msg_invalid_option def userpref_size_per_file_mb(size_per_file_mb, path_file_config): print(f'The maximum size of each file will be {size_per_file_mb}. Ok?') answer_use = input('(None for yes) Answer: ') if answer_use == '': return size_per_file_mb else: question_new_value = 'What should be the maximum size of each ' + \ 'file in mb (e.g.: 500)? ' new_size_per_file_mb = input(question_new_value) config_update_data(path_file_config, 'size_per_file_mb', new_size_per_file_mb) return new_size_per_file_mb def get_transition_effect_status(activate_transition): if activate_transition == 'true': transition_effect_status = True else: transition_effect_status = False return transition_effect_status def get_duration_limit(duration_limit): # ensure duration_limit is valid or raise error time_is_hh_mm_ss_ms(str_hh_mm_ss_ms=duration_limit) return duration_limit def ensure_folder_existence(folders_path): """ :input: folders_path: List """ for folder_path in folders_path: existence = os.path.isdir(folder_path) if existence is False: os.mkdir(folder_path) def get_folder_name_normalized(path_dir): def normalize_string_to_link(string_actual): string_new = unidecode.unidecode(string_actual) for c in r"!@#$%^&*()[]{};:,./<>?\|`~-=_+": string_new = string_new.translate({ord(c): "_"}) string_new = string_new.replace(' ', '_') string_new = string_new.replace('___', '_') string_new = string_new.replace('__', '_') return string_new dir_name = os.path.basename(path_dir) dir_name_normalize = normalize_string_to_link(dir_name) return dir_name_normalize def save_metadata_json_files(list_dict_inf_ffprobe, path_file_report): """save in project_folder/metadata/ , the metadata of each video file in json format Args: list_dict_inf_ffprobe (list): list of dict of metadata path_file_report (str): path_file if videodetails.xlsx """ path_folder_report = os.path.dirname(path_file_report) path_folder_metadata = os.path.join(path_folder_report, 'metadata') ensure_folder_existence([path_folder_metadata]) for dict_inf_ffprobe in list_dict_inf_ffprobe: path_file_origin = dict_inf_ffprobe['path_file'] file_name_origin = os.path.basename(path_file_origin) file_path_folder_origin = os.path.dirname(path_file_origin) file_name_origin_without_ext = os.path.splitext(file_name_origin)[0] file_name_json = file_name_origin_without_ext + '.json' file_name_dest = \ make_reencode.get_file_name_dest(file_path_folder_origin, file_name_json, 'video_metadata_') json_path_file = os.path.join(path_folder_metadata, file_name_dest) dict_metadata = dict_inf_ffprobe['metadata'] with open(json_path_file, "w") as fout: json.dump(dict_metadata, fout, indent=2) def step_create_report_filled(path_dir, path_file_report, video_extensions): list_file_selected = video_report.get_list_path_video(path_dir, video_extensions) list_dict_inf_ffprobe = video_report.get_list_dict_inf_ffprobe(list_file_selected) save_metadata_json_files(list_dict_inf_ffprobe, path_file_report) list_dict = video_report.gen_report(list_dict_inf_ffprobe) df = pd.DataFrame(list_dict) # sort path_file by natural human way df = df_sort_human(df, key_column_name='path_file') # prefill column video_resolution_to_change df = prefill_reencode_plan(df) # save df.to_excel(path_file_report, index=False) # Make backup. _origin create_report_backup( df=df, path_file_report=path_file_report, tag='origin') def set_make_reencode(path_file_report, path_folder_videos_encoded): df = make_reencode.make_reencode(path_file_report, path_folder_videos_encoded) df.to_excel(path_file_report, index=False) # make backup create_report_backup( df=df, path_file_report=path_file_report, tag='reencode') print('\nReencode finished') def set_correct_duration(path_file_report): df = correct_duration(path_file_report) df.to_excel(path_file_report, index=False) # make backup create_report_backup( df=df, path_file_report=path_file_report, tag='correct_duration') def set_group_column(path_file_report): # update video_details with group_encode column df = pd.read_excel(path_file_report, engine='openpyxl') df = get_video_details_with_group(df) df.to_excel(path_file_report, index=False) print(f"File '{path_file_report}' was updated with " + "a guide column to fast join (group_encode) \n") # Note: backup is not performed here as the # grouping can be adjusted manually def set_split_videos(path_file_report, mb_limit, path_folder_videos_splitted, duration_limit='00:00:00,00'): df = pd.read_excel(path_file_report, engine='openpyxl') # backup group, after adjusted manually create_report_backup( df=df, path_file_report=path_file_report, tag='grouped') # Find for file_video too big and split them df = search_to_split_videos(df, mb_limit, path_folder_videos_splitted, duration_limit) df.to_excel(path_file_report, index=False) create_report_backup( df=df, path_file_report=path_file_report, tag='splited') def set_join_videos(path_file_report, mb_limit, filename_output, path_folder_videos_joined, path_folder_videos_cache, duration_limit='00:00:00,00', start_index_output=1, activate_transition='false'): df = pd.read_excel(path_file_report, engine='openpyxl') transition_status = get_transition_effect_status(activate_transition) df = join_videos(df, mb_limit, filename_output, path_folder_videos_joined, path_folder_videos_cache, start_index_output, duration_limit, transition_status) df.to_excel(path_file_report, index=False) # backup joined create_report_backup( df=df, path_file_report=path_file_report, tag='joined') def set_path_file_report(path_dir): folder_name_normalized = get_folder_name_normalized(path_dir) folder_path_output_relative = \ os.path.join('projects', 'output_' + folder_name_normalized) ensure_folder_existence([folder_path_output_relative]) path_file_report = os.path.join(folder_path_output_relative, 'video_details.xlsx') return path_file_report def set_path_folder_videos_encoded(path_dir): dir_name_normalize = get_folder_name_normalized(path_dir) folder_path_output_relative = os.path.join('projects', 'output_' + dir_name_normalize) path_folder_videos_encoded = os.path.join(folder_path_output_relative, 'videos_encoded') return path_folder_videos_encoded def set_path_folder_videos_splitted(path_dir): dir_name_normalize = get_folder_name_normalized(path_dir) folder_path_output_relative = os.path.join('projects', 'output_' + dir_name_normalize) path_folder_videos_splitted = os.path.join(folder_path_output_relative, 'videos_splitted') return path_folder_videos_splitted def set_path_folder_videos_joined(path_dir): dir_name_normalize = get_folder_name_normalized(path_dir) folder_path_output_relative = os.path.join('projects', 'output_' + dir_name_normalize) path_folder_videos_joined = os.path.join(folder_path_output_relative, 'output_videos') return path_folder_videos_joined def set_path_folder_videos_cache(path_dir): dir_name_normalize = get_folder_name_normalized(path_dir) folder_path_output_relative = os.path.join('projects', 'output_' + dir_name_normalize) path_folder_videos_cache = os.path.join(folder_path_output_relative, 'cache') return path_folder_videos_cache def get_config_data(path_file_config): """get default configuration data from file config.ini Returns: dict: config data """ config_file = ConfigParser() config_file.read(path_file_config) default_config = dict(config_file['default']) return default_config def config_update_data(path_file_config, variable_name, variable_value): config = ConfigParser() config.read(path_file_config) config.set('default', variable_name, variable_value) with open(path_file_config, "w+") as config_updated: config.write(config_updated) def get_path_dir(path_dir): if path_dir is None: path_dir = input('\nPaste the folder link where are the video files: ') else: pass return path_dir def get_path_file_report(path_file_report, path_dir): if path_file_report is None: path_file_report = set_path_file_report(path_dir) else: pass return path_file_report def main(): folder_script_path = get_folder_script_path() path_file_config = os.path.join(folder_script_path, 'config.ini') config_data = get_config_data(path_file_config) size_per_file_mb = int(config_data['size_per_file_mb']) activate_transition = config_data['activate_transition'] duration_limit = config_data['duration_limit'] video_extensions = config_data['video_extensions'].split(',') start_index = int(config_data['start_index']) path_file_report = None path_dir = None ensure_folder_existence(['projects']) while True: menu_answer = menu_ask() if menu_answer == 1: # create Dataframe of video details path_dir = get_path_dir(path_dir) path_file_report = set_path_file_report(path_dir) step_create_report_filled(path_dir, path_file_report, video_extensions) print('\nIf necessary, change the reencode plan in the column ' + '"video_resolution_to_change"') # break_point input('Type Enter to continue') clean_cmd() continue elif menu_answer == 2: # make reencode # correct duration path_dir = get_path_dir(path_dir) path_file_report = get_path_file_report(path_file_report, path_dir) path_folder_videos_encoded = \ set_path_folder_videos_encoded(path_dir) ensure_folder_existence([path_folder_videos_encoded]) # reencode videos mark in column video_resolution_to_change set_make_reencode(path_file_report, path_folder_videos_encoded) print('start correcting the duration metadata') # correct videos duration set_correct_duration(path_file_report) print('\nDuration metadata corrected.') # break_point input('\nType something to go to the main menu, ' + 'and proceed to the "Group videos" process.') clean_cmd() continue elif menu_answer == 3: # define variables path_dir = get_path_dir(path_dir) path_file_report = get_path_file_report(path_file_report, path_dir) path_folder_videos_splitted = \ set_path_folder_videos_splitted(path_dir) ensure_folder_existence([path_folder_videos_splitted]) path_folder_videos_joined = \ set_path_folder_videos_joined(path_dir) ensure_folder_existence([path_folder_videos_joined]) filename_output = get_folder_name_normalized(path_dir) path_folder_videos_cache = \ set_path_folder_videos_cache(path_dir) ensure_folder_existence([path_folder_videos_cache]) mb_limit = int(userpref_size_per_file_mb(size_per_file_mb, path_file_config)) duration_limit = get_duration_limit(duration_limit) # establishes separation criteria for the join videos step set_group_column(path_file_report) # break_point input('Review the file and then type something to ' + 'start the process that look for videos that ' + 'are too big and should be splitted') set_split_videos(path_file_report, mb_limit, path_folder_videos_splitted, duration_limit) # join all videos set_join_videos(path_file_report, mb_limit, filename_output, path_folder_videos_joined, path_folder_videos_cache, duration_limit, start_index, activate_transition) return else: return if __name__ == "__main__": logging_config() main()
// SMALLER UTILITY FUNCTIONS GO HERE const { v4: uuid } = require("uuid"); const logger = require("./logger.js"); const fetch = require('node-fetch'); const xmlparser = require('fast-xml-parser'); // IM MEMORY CACHE, containing specified ad list for each tenant. const TENANT_CACHE = {}; async function UpdateCache(tenant, feedURI, cache) { // Start Over Clean cache[tenant] = {} try { const response = await fetch(feedURI); const xml = await response.text(); const json = xmlparser.parse(xml); let feedEntry = json.feed.entry; // Transform feed entry into expected Ad Objects, with fallback values. feedEntry = feedEntry.map(entry => ( { universalId: entry.universalId || uuid(), id: entry.id || "streamingtech_ad", url: entry.link || "https://testcontent.eyevinn.technology/ads/probably-the-best-10s.mp4", duration: entry.duration || "00:00:10", bitrate: entry.bitrate || "17700", width: entry.width || "1920", height: entry.height || "1080", codec: entry.codec || "H.264" } )); // Add new values. cache[tenant].cachedAdList = feedEntry; cache[tenant].lastUpdated = Date.now(); return; } catch (err) { delete cache[tenant] logger.error(err.message, { label: "Error in UpdateCache()" }); return; } } /** * * @param {Array} list - Full list of objects. * @param {string} page - Desired page number. * @param {string} limit - Limit for amount of objects on each page. * * @example * list = [{...}, {...}, {...}] * page = '2' * limit = '5' * */ function PaginateMemoryDB(list = [], pageNum, pageLimit) { const limit = parseInt(pageLimit, 10) || 80; const page = parseInt(pageNum, 10) || 1; const startAt = (page - 1) * limit; const endAt = page * limit; const totalCount = list.length; let sessions = list.slice(startAt, endAt); return { previousPage: getPreviousPage(page), currentPage: page, nextPage: getNextPage(page, limit, totalCount), totalPages: getTotalPages(limit, totalCount), limit: limit, totalItems: totalCount, data: sessions, }; } const getTotalPages = (limit, totalCount) => { return Math.ceil(totalCount / limit); }; const getNextPage = (page, limit, total) => { if (total / limit > page) { return page + 1; } return null; }; const getPreviousPage = (page) => { if (page <= 1) { return null; } return page - 1; }; const CloudWatchLog = (type, host, logEntry) => { logEntry.type = type; logEntry.host = host; logEntry.time = (new Date()).toISOString(); console.log(JSON.stringify(logEntry)); }; // Function that allows you to specify how to return the data to the client function Transform(session) { return { sessionId: session.sessionId, userId: session.getUser(), created: session.created, adBreakDuration: session.adBreakDuration, clientRequest: session.getClientRequest(), response: session.getVastXml().toString(), }; } module.exports = { PaginateMemoryDB, Transform, CloudWatchLog, TENANT_CACHE, UpdateCache };
var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; define(["require", "exports", "jsbi", "./JsbiSupport", "./IonBinary", "./IonUnicode", "./IonDecimal", "./IonTypes", "./IonConstants", "./IonTimestamp", "./SignAndMagnitudeInt", "./JsbiSerde"], function (require, exports, jsbi_1, JsbiSupport_1, IonBinary, IonUnicode_1, IonDecimal_1, IonTypes_1, IonConstants_1, IonTimestamp_1, SignAndMagnitudeInt_1, JsbiSerde_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); jsbi_1 = __importDefault(jsbi_1); IonBinary = __importStar(IonBinary); SignAndMagnitudeInt_1 = __importDefault(SignAndMagnitudeInt_1); const DEBUG_FLAG = true; const EOF = -1; const ERROR = -2; const TB_UNUSED__ = 15; const TB_DATAGRAM = 20; const TB_SEXP_CLOSE = 21; const TB_LIST_CLOSE = 22; const TB_STRUCT_CLOSE = 23; function get_ion_type(rt) { switch (rt) { case IonBinary.TB_NULL: return IonTypes_1.IonTypes.NULL; case IonBinary.TB_BOOL: return IonTypes_1.IonTypes.BOOL; case IonBinary.TB_INT: return IonTypes_1.IonTypes.INT; case IonBinary.TB_NEG_INT: return IonTypes_1.IonTypes.INT; case IonBinary.TB_FLOAT: return IonTypes_1.IonTypes.FLOAT; case IonBinary.TB_DECIMAL: return IonTypes_1.IonTypes.DECIMAL; case IonBinary.TB_TIMESTAMP: return IonTypes_1.IonTypes.TIMESTAMP; case IonBinary.TB_SYMBOL: return IonTypes_1.IonTypes.SYMBOL; case IonBinary.TB_STRING: return IonTypes_1.IonTypes.STRING; case IonBinary.TB_CLOB: return IonTypes_1.IonTypes.CLOB; case IonBinary.TB_BLOB: return IonTypes_1.IonTypes.BLOB; case IonBinary.TB_SEXP: return IonTypes_1.IonTypes.SEXP; case IonBinary.TB_LIST: return IonTypes_1.IonTypes.LIST; case IonBinary.TB_STRUCT: return IonTypes_1.IonTypes.STRUCT; default: return undefined; } } const TS_SHIFT = 5; const TS_MASK = 0x1f; function encode_type_stack(type_, len) { var ts = (len << TS_SHIFT) | (type_ & TS_MASK); return ts; } function decode_type_stack_type(ts) { return ts & TS_MASK; } function decode_type_stack_len(ts) { return ts >>> TS_SHIFT; } const VINT_SHIFT = 7; const VINT_MASK = 0x7f; const VINT_FLAG = 0x80; function high_nibble(tb) { return ((tb >> IonBinary.TYPE_SHIFT) & IonBinary.NIBBLE_MASK); } function low_nibble(tb) { return (tb & IonBinary.NIBBLE_MASK); } const empty_array = []; const ivm_sid = IonConstants_1.IVM.sid; const ivm_image_0 = IonConstants_1.IVM.binary[0]; const ivm_image_1 = IonConstants_1.IVM.binary[1]; const ivm_image_2 = IonConstants_1.IVM.binary[2]; const ivm_image_3 = IonConstants_1.IVM.binary[3]; class ParserBinaryRaw { constructor(source) { this._raw_type = EOF; this._len = -1; this._curr = undefined; this._null = false; this._fid = -1; this._as = -1; this._ae = -1; this._a = []; this._ts = [TB_DATAGRAM]; this._in_struct = false; this._in = source; } static _readFloatFrom(input, numberOfBytes) { let tempBuf; switch (numberOfBytes) { case 0: return 0.0; case 4: tempBuf = new DataView(input.chunk(4).buffer); return tempBuf.getFloat32(0, false); case 8: tempBuf = new DataView(input.chunk(8).buffer); return tempBuf.getFloat64(0, false); case 15: return null; default: throw new Error("Illegal float length: " + numberOfBytes); } } static _readVarUnsignedIntFrom(input) { let numberOfBits = 0; let byte; let magnitude = 0; while (true) { byte = input.next(); magnitude = (magnitude << 7) | (byte & 0x7F); numberOfBits += 7; if (byte & 0x80) { break; } } if (numberOfBits > 31) { throw new Error("VarUInt values larger than 31 bits must be read using LongInt."); } return magnitude; } static _readVarSignedIntFrom(input) { let v = input.next(), byte; let isNegative = v & 0x40; let stopBit = v & 0x80; v &= 0x3F; let bits = 6; while (!stopBit) { byte = input.next(); stopBit = byte & 0x80; byte &= 0x7F; v <<= 7; v |= byte; bits += 7; } if (bits > 32) { throw new Error("VarInt values larger than 32 bits must be read using LongInt"); } return isNegative ? -v : v; } static _readSignedIntFrom(input, numberOfBytes) { if (numberOfBytes == 0) { return new SignAndMagnitudeInt_1.default(JsbiSupport_1.JsbiSupport.ZERO); } let bytes = input.view(numberOfBytes); let isNegative = (bytes[0] & 0x80) == 0x80; let numbers = Array.prototype.slice.call(bytes); numbers[0] = bytes[0] & 0x7F; let magnitude = JsbiSerde_1.JsbiSerde.fromUnsignedBytes(numbers); return new SignAndMagnitudeInt_1.default(magnitude, isNegative); } static _readUnsignedIntAsBigIntFrom(input, numberOfBytes) { return JsbiSerde_1.JsbiSerde.fromUnsignedBytes(Array.prototype.slice.call(input.view(numberOfBytes))); } static _readUnsignedIntAsNumberFrom(input, numberOfBytes) { let value = 0; let bytesRead = 0; let bytesAvailable = input.getRemaining(); let byte; if (numberOfBytes < 1) { return 0; } else if (numberOfBytes > 6) { throw new Error(`Attempted to read a ${numberOfBytes}-byte unsigned integer,` + ` which is too large for a to be stored in a number without losing precision.`); } if (bytesAvailable < numberOfBytes) { throw new Error(`Attempted to read a ${numberOfBytes}-byte unsigned integer,` + ` but only ${bytesAvailable} bytes were available.`); } while (bytesRead < numberOfBytes) { byte = input.next(); bytesRead++; value *= 256; value = value + byte; } return value; } static readDecimalValueFrom(input, numberOfBytes) { let initialPosition = input.position(); let exponent = ParserBinaryRaw._readVarSignedIntFrom(input); let numberOfExponentBytes = input.position() - initialPosition; let numberOfCoefficientBytes = numberOfBytes - numberOfExponentBytes; let signedInt = ParserBinaryRaw._readSignedIntFrom(input, numberOfCoefficientBytes); let isNegative = signedInt.isNegative; let coefficient = isNegative ? jsbi_1.default.unaryMinus(signedInt.magnitude) : signedInt.magnitude; return IonDecimal_1.Decimal._fromBigIntCoefficient(isNegative, coefficient, exponent); } next() { if (this._curr === undefined && this._len > 0) { this._in.skip(this._len); } else { this.clear_value(); } if (this._in_struct) { this._fid = this.readVarUnsignedInt(); } return this.load_next(); } stepIn() { var len, ts, t = this; switch (t._raw_type) { case IonBinary.TB_STRUCT: case IonBinary.TB_LIST: case IonBinary.TB_SEXP: break; default: throw new Error("you can only 'stepIn' to a container"); } len = t._in.getRemaining() - t._len; ts = encode_type_stack(t._raw_type, len); t._ts.push(ts); t._in_struct = (t._raw_type === IonBinary.TB_STRUCT); t._in.setRemaining(t._len); t.clear_value(); } stepOut() { var parent_type, ts, l, r, t = this; if (t._ts.length < 2) { throw new Error("you can't stepOut unless you stepped in"); } ts = t._ts.pop(); l = decode_type_stack_len(ts); parent_type = decode_type_stack_type(t._ts[t._ts.length - 1]); t._in_struct = (parent_type === IonBinary.TB_STRUCT); t.clear_value(); r = t._in.getRemaining(); t._in.skip(r); t._in.setRemaining(l); } isNull() { return this._null; } depth() { return this._ts.length - 1; } getFieldId() { return this._fid; } hasAnnotations() { return (this._as >= 0); } getAnnotations() { var a, t = this; if ((t._a === undefined) || (t._a.length === 0)) { t.load_annotation_values(); } return t._a; } getAnnotation(index) { var a, t = this; if ((t._a === undefined) || (t._a.length === 0)) { t.load_annotation_values(); } return t._a[index]; } ionType() { return get_ion_type(this._raw_type); } _getSid() { this.load_value(); if (this._raw_type == IonBinary.TB_SYMBOL) { return this._curr === undefined ? null : this._curr; } return null; } _stringRepresentation() { let t = this; switch (t._raw_type) { case IonBinary.TB_NULL: case IonBinary.TB_BOOL: case IonBinary.TB_INT: case IonBinary.TB_NEG_INT: case IonBinary.TB_FLOAT: case IonBinary.TB_DECIMAL: case IonBinary.TB_TIMESTAMP: case IonBinary.TB_SYMBOL: case IonBinary.TB_STRING: break; default: throw new Error("Cannot convert to string."); } if (t.isNull()) { switch (t._raw_type) { case IonBinary.TB_BOOL: case IonBinary.TB_INT: case IonBinary.TB_NEG_INT: case IonBinary.TB_FLOAT: case IonBinary.TB_DECIMAL: case IonBinary.TB_TIMESTAMP: case IonBinary.TB_SYMBOL: case IonBinary.TB_STRING: "null." + t.ionType().name; break; } } else { t.load_value(); switch (t._raw_type) { case IonBinary.TB_BOOL: case IonBinary.TB_INT: case IonBinary.TB_NEG_INT: case IonBinary.TB_DECIMAL: case IonBinary.TB_TIMESTAMP: return t._curr.toString(); case IonBinary.TB_FLOAT: let s = t.numberValue().toString(); if (s.indexOf("e") === -1) return s + "e0"; case IonBinary.TB_STRING: if (t._null) { return null; } return t._curr; } } } byteValue() { switch (this._raw_type) { case IonBinary.TB_NULL: return null; case IonBinary.TB_CLOB: case IonBinary.TB_BLOB: if (this.isNull()) { return null; } this.load_value(); return this._curr; default: throw new Error('Current value is not a blob or clob.'); } } booleanValue() { switch (this._raw_type) { case IonBinary.TB_NULL: return null; case IonBinary.TB_BOOL: if (this.isNull()) { return null; } return this._curr; } throw new Error('Current value is not a Boolean.'); } decimalValue() { switch (this._raw_type) { case IonBinary.TB_NULL: return null; case IonBinary.TB_DECIMAL: if (this.isNull()) { return null; } this.load_value(); return this._curr; } throw new Error('Current value is not a decimal.'); } bigIntValue() { switch (this._raw_type) { case IonBinary.TB_NULL: return null; case IonBinary.TB_INT: case IonBinary.TB_NEG_INT: if (this.isNull()) { return null; } this.load_value(); return this._curr; default: throw new Error('bigIntValue() was called when the current value was not an int.'); } } numberValue() { switch (this._raw_type) { case IonBinary.TB_NULL: return null; case IonBinary.TB_INT: case IonBinary.TB_NEG_INT: if (this.isNull()) { return null; } this.load_value(); let bigInt = this._curr; return JsbiSupport_1.JsbiSupport.clampToSafeIntegerRange(bigInt); case IonBinary.TB_FLOAT: if (this.isNull()) { return null; } this.load_value(); return this._curr; default: throw new Error('Current value is not a float or int.'); } } stringValue() { switch (this._raw_type) { case IonBinary.TB_NULL: return null; case IonBinary.TB_STRING: case IonBinary.TB_SYMBOL: if (this.isNull()) { return null; } this.load_value(); return this._curr; } throw new Error('Current value is not a string or symbol.'); } timestampValue() { switch (this._raw_type) { case IonBinary.TB_NULL: return null; case IonBinary.TB_TIMESTAMP: if (this.isNull()) { return null; } this.load_value(); return this._curr; } throw new Error('Current value is not a timestamp.'); } read_binary_float() { return ParserBinaryRaw._readFloatFrom(this._in, this._len); } readVarUnsignedInt() { return ParserBinaryRaw._readVarUnsignedIntFrom(this._in); } readVarSignedInt() { return ParserBinaryRaw._readVarSignedIntFrom(this._in); } readUnsignedIntAsBigInt() { return ParserBinaryRaw._readUnsignedIntAsBigIntFrom(this._in, this._len); } readUnsignedIntAsNumber() { return ParserBinaryRaw._readUnsignedIntAsNumberFrom(this._in, this._len); } read_decimal_value() { return ParserBinaryRaw.readDecimalValueFrom(this._in, this._len); } read_timestamp_value() { if (!(this._len > 0)) { return null; } let offset; let year; let month; let day; let hour; let minute; let secondInt; let fractionalSeconds = IonDecimal_1.Decimal.ZERO; let precision = IonTimestamp_1.TimestampPrecision.YEAR; let end = this._in.position() + this._len; offset = this.readVarSignedInt(); if (this._in.position() < end) { year = this.readVarUnsignedInt(); } else { throw new Error('Timestamps must include a year.'); } if (this._in.position() < end) { month = this.readVarUnsignedInt(); precision = IonTimestamp_1.TimestampPrecision.MONTH; } if (this._in.position() < end) { day = this.readVarUnsignedInt(); precision = IonTimestamp_1.TimestampPrecision.DAY; } if (this._in.position() < end) { hour = this.readVarUnsignedInt(); if (this._in.position() >= end) { throw new Error('Timestamps with an hour must include a minute.'); } else { minute = this.readVarUnsignedInt(); } precision = IonTimestamp_1.TimestampPrecision.HOUR_AND_MINUTE; } if (this._in.position() < end) { secondInt = this.readVarUnsignedInt(); precision = IonTimestamp_1.TimestampPrecision.SECONDS; } if (this._in.position() < end) { let exponent = this.readVarSignedInt(); let coefficient = JsbiSupport_1.JsbiSupport.ZERO; let isNegative = false; if (this._in.position() < end) { let deserializedSignedInt = ParserBinaryRaw._readSignedIntFrom(this._in, end - this._in.position()); isNegative = deserializedSignedInt._isNegative; coefficient = deserializedSignedInt._magnitude; } let dec = IonDecimal_1.Decimal._fromBigIntCoefficient(isNegative, coefficient, exponent); let [_, fractionStr] = IonTimestamp_1.Timestamp._splitSecondsDecimal(dec); fractionalSeconds = IonDecimal_1.Decimal.parse(secondInt + '.' + fractionStr); } let msSinceEpoch = Date.UTC(year, month ? month - 1 : 0, day ? day : 1, hour ? hour : 0, minute ? minute : 0, secondInt ? secondInt : 0, 0); msSinceEpoch = IonTimestamp_1.Timestamp._adjustMsSinceEpochIfNeeded(year, msSinceEpoch); let date = new Date(msSinceEpoch); return IonTimestamp_1.Timestamp._valueOf(date, offset, fractionalSeconds, precision); } read_string_value() { return IonUnicode_1.decodeUtf8(this._in.chunk(this._len)); } clear_value() { this._raw_type = EOF; this._curr = undefined; this._a = empty_array; this._as = -1; this._null = false; this._fid = -1; this._len = -1; } load_length(tb) { let t = this; t._len = low_nibble(tb); switch (t._len) { case 1: if (high_nibble(tb) === IonBinary.TB_STRUCT) { t._len = this.readVarUnsignedInt(); } t._null = false; break; case IonBinary.LEN_VAR: t._null = false; t._len = this.readVarUnsignedInt(); break; case IonBinary.LEN_NULL: t._null = true; t._len = 0; break; default: t._null = false; break; } } load_next() { let t = this; var rt, tb; t._as = -1; if (t._in.is_empty()) { t.clear_value(); return undefined; } tb = t._in.next(); rt = high_nibble(tb); t.load_length(tb); if (rt === IonBinary.TB_ANNOTATION) { if (t._len < 1 && t.depth() === 0) { rt = t.load_ivm(); } else { rt = t.load_annotations(); } } switch (rt) { case IonBinary.TB_NULL: t._null = true; break; case IonBinary.TB_BOOL: if (t._len === 0 || t._len === 1) { t._curr = t._len === 1; t._len = 0; } break; } t._raw_type = rt; return rt; } load_annotations() { let t = this; var tb, type_, annotation_len; if (t._len < 1 && t.depth() === 0) { type_ = t.load_ivm(); } else { annotation_len = this.readVarUnsignedInt(); t._as = t._in.position(); t._in.skip(annotation_len); t._ae = t._in.position(); tb = t._in.next(); t.load_length(tb); type_ = high_nibble(tb); } return type_; } load_ivm() { let t = this; var span = t._in; if (span.next() !== ivm_image_1) throw new Error("invalid binary Ion at " + span.position()); if (span.next() !== ivm_image_2) throw new Error("invalid binary Ion at " + span.position()); if (span.next() !== ivm_image_3) throw new Error("invalid binary Ion at " + span.position()); t._curr = ivm_sid; t._len = 0; return IonBinary.TB_SYMBOL; } load_annotation_values() { let t = this; var a, b, pos, limit, arr; if ((pos = t._as) < 0) return; arr = []; limit = t._ae; a = 0; while (pos < limit) { b = t._in.valueAt(pos); pos++; a = (a << VINT_SHIFT) | (b & VINT_MASK); if ((b & VINT_FLAG) !== 0) { arr.push(a); a = 0; } } t._a = arr; } _readIntegerMagnitude() { if (this._len === 0) { return JsbiSupport_1.JsbiSupport.ZERO; } return this.readUnsignedIntAsBigInt(); } load_value() { if (this._curr != undefined) return; if (this.isNull()) return null; switch (this._raw_type) { case IonBinary.TB_BOOL: break; case IonBinary.TB_INT: this._curr = this._readIntegerMagnitude(); break; case IonBinary.TB_NEG_INT: this._curr = jsbi_1.default.unaryMinus(this._readIntegerMagnitude()); break; case IonBinary.TB_FLOAT: this._curr = this.read_binary_float(); break; case IonBinary.TB_DECIMAL: if (this._len === 0) { this._curr = IonDecimal_1.Decimal.ZERO; } else { this._curr = this.read_decimal_value(); } break; case IonBinary.TB_TIMESTAMP: this._curr = this.read_timestamp_value(); break; case IonBinary.TB_SYMBOL: this._curr = this.readUnsignedIntAsNumber(); break; case IonBinary.TB_STRING: this._curr = this.read_string_value(); break; case IonBinary.TB_CLOB: case IonBinary.TB_BLOB: if (this.isNull()) break; this._curr = this._in.chunk(this._len); break; default: throw new Error('Unexpected type: ' + this._raw_type); } } } exports.ParserBinaryRaw = ParserBinaryRaw; }); //# sourceMappingURL=IonParserBinaryRaw.js.map
"use strict"; (self["webpackChunkneo_mjs"] = self["webpackChunkneo_mjs"] || []).push([["vendors-src_form_field_Text_mjs"],{ /***/ "./src/form/field/Base.mjs": /*!*********************************!*\ !*** ./src/form/field/Base.mjs ***! \*********************************/ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ Base) /* harmony export */ }); /* harmony import */ var _component_Base_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../component/Base.mjs */ "./src/component/Base.mjs"); /** * Abstract base class for form fields * @class Neo.form.field.Base * @extends Neo.component.Base */ class Base extends _component_Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { static getConfig() {return { /** * @member {String} className='Neo.form.field.Base' * @protected */ className: 'Neo.form.field.Base', /** * @member {String} ntype='basefield' * @protected */ ntype: 'basefield', /** * @member {*} value_=null */ value_: null }} /** * Triggered after the value config got changed * @param {*} value * @param {*} oldValue */ afterSetValue(value, oldValue) { if (oldValue !== undefined) { this.fireChangeEvent(value, oldValue); } } /** * Override this method as needed * @param {*} value * @param {*} oldValue */ fireChangeEvent(value, oldValue) { this.fire('change', { component: this, oldValue : oldValue, value : value }); } /** * @returns {*} this.value */ getSubmitValue() { return this.value; } /** * @returns {Boolean} */ isValid() { return true; } /** * Resets the field to a new value or null * @param {*} [value=null] */ reset(value) { this.value = value; } } /** * The change event fires after the value config gets changed * @event change * @param {*} value * @param {*} oldValue * @returns {Object} */ Neo.applyClassConfig(Base); /***/ }), /***/ "./src/form/field/Text.mjs": /*!*********************************!*\ !*** ./src/form/field/Text.mjs ***! \*********************************/ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ Text) /* harmony export */ }); /* harmony import */ var _Base_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Base.mjs */ "./src/form/field/Base.mjs"); /* harmony import */ var _trigger_Base_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./trigger/Base.mjs */ "./src/form/field/trigger/Base.mjs"); /* harmony import */ var _trigger_Clear_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./trigger/Clear.mjs */ "./src/form/field/trigger/Clear.mjs"); /* harmony import */ var _util_Array_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../util/Array.mjs */ "./src/util/Array.mjs"); /* harmony import */ var _util_VDom_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../util/VDom.mjs */ "./src/util/VDom.mjs"); /* harmony import */ var _util_VNode_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../util/VNode.mjs */ "./src/util/VNode.mjs"); /** * @class Neo.form.field.Text * @extends Neo.form.field.Base */ class Text extends _Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { static getStaticConfig() {return { /** * Valid values for autoCapitalize * @member {String[]} autoCapitalizeValues=['characters','none','on','off','sentences','words'] * @protected * @static */ autoCapitalizeValues: ['characters', 'none', 'on', 'off', 'sentences', 'words'], /** * Valid values for labelPosition * @member {String[]} labelPositions=['bottom','inline','left','right','top'] * @protected * @static */ labelPositions: ['bottom', 'inline', 'left', 'right', 'top'] }} static getConfig() {return { /** * @member {String} className='Neo.form.field.Text' * @protected */ className: 'Neo.form.field.Text', /** * @member {String} ntype='textfield' * @protected */ ntype: 'textfield', /** * An enumerated attribute that controls whether and how text input is automatically capitalized as it is * entered/edited by the user. * Valid values: 'characters', 'none', 'on', 'off', 'sentences', 'words' * @member {String} autoCapitalize=off' */ autoCapitalize_: 'off', /** * @member {Boolean} autoComplete_=false */ autoComplete_: false, /** * Internal variable to store the actual width for the label centerBorderEl * (only needed for labelPosition: 'inline') * @member {Number|null} centerBorderElWidth=null * @protected */ centerBorderElWidth: null, /** * True shows a clear trigger in case the field has a non empty value. * @member {Boolean} clearable_=true */ clearable_: true, /** * True will reset the field to its initial value config. * Recommended for fields with required: true * @member {Boolean} clearToOriginalValue_=false */ clearToOriginalValue_: false, /** * @member {String[]} cls=['neo-textfield'] */ cls: ['neo-textfield'], /** * @member {Boolean} hideLabel_=false */ hideLabel_: false, /** * @member {String} inputType_='text' */ inputType_: 'text', /** * Valid values: 'bottom', 'inline', 'left', 'right', 'top' * @member {String} labelPosition_='left' */ labelPosition_: 'left', /** * @member {String} labelText_='LabelText' */ labelText_: 'LabelText', /** * defaults to px * @member {Number|String} labelWidth_=150 */ labelWidth_: 150, /** * @member {String|null} placeholderText_=null */ placeholderText_: null, /** * @member {Boolean} required_=false */ required_: false, /** * null => Follow the element's default behavior for spell checking * @member {Boolean|null} spellCheck_=false */ spellCheck_: false, /** * @member {Object|Object[]|null} triggers_=null */ triggers_: null, /** * @member {Object} _vdom */ _vdom: {cn: [ {tag: 'label', cls: ['neo-textfield-label'], style: {}}, {tag: 'input', cls: ['neo-textfield-input'], flag: 'neo-real-input', style: {}} ]} }} /** * @param {Object} config */ construct(config) { super.construct(config); let me = this, domListeners = me.domListeners; domListeners.push( {input: me.onInputValueChange, scope: me} ); me.domListeners = domListeners; } /** * Triggered after the appName config got changed * @param {String} value * @param {String|null} oldValue * @protected */ afterSetAppName(value, oldValue) { let me = this; super.afterSetAppName(value, oldValue); value && me.triggers?.forEach(item => { item.appName = value; }); } /** * Triggered after the autoCapitalize config got changed * @param {String} value * @param {String} oldValue * @protected */ afterSetAutoCapitalize(value, oldValue) { this.changeInputElKey('autocapitalize', value === 'off' || value === 'none' ? null : value); } /** * Triggered after the autoComplete config got changed * @param {Boolean} value * @param {Boolean} oldValue * @protected */ afterSetAutoComplete(value, oldValue) { this.changeInputElKey('autocomplete', value ? null : 'off'); } /** * Triggered after the clearable config got changed * @param {Boolean} value * @param {Boolean} oldValue * @protected */ afterSetClearable(value, oldValue) { let me = this, triggers; if (value) { triggers = me.triggers || []; triggers.unshift(_trigger_Clear_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]); me.triggers = triggers; } else { me.removeTrigger('clear'); } } /** * Triggered after the clearToOriginalValue config got changed * @param {Boolean} value * @param {Boolean} oldValue * @protected */ afterSetClearToOriginalValue(value, oldValue) { this.fire('changeClearToOriginalValue', { oldValue, value }); } /** * Triggered after the hideLabel config got changed * @param {Boolean} value * @param {Boolean} oldValue * @protected */ afterSetHideLabel(value, oldValue) { let me = this, vdom = me.vdom; vdom.cn[0].removeDom = value; me._vdom = vdom; // silent update me.updateInputWidth(); } /** * Triggered after the id config got changed * @param {String} value * @param {String} oldValue * @protected */ afterSetId(value, oldValue) { let me = this, inputEl = me.getInputEl(), inputElId = me.getInputElId(), labelEl = me.getLabelEl(); inputEl.id = inputElId; labelEl.id = me.getLabelId(); labelEl.for = inputElId; // silent vdom update, the super call will trigger the engine super.afterSetId(value, oldValue); } /** * Triggered after the inputType config got changed * @param {String} value * @param {String} oldValue * @protected */ afterSetInputType(value, oldValue) { this.changeInputElKey('type', value); } /** * Triggered after the labelPosition config got changed * @param {String} value * @param {String} oldValue * @protected */ afterSetLabelPosition(value, oldValue) { let me = this, cls = me.cls, centerBorderElCls, isEmpty, vdom; _util_Array_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].remove(cls, 'label-' + oldValue); _util_Array_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].add(cls, 'label-' + value); me[oldValue === 'inline' || value === 'inline' ? '_cls' : 'cls'] = cls; // silent update if needed if (oldValue === 'inline') { vdom = me.vdom; vdom.cn[0] = me.getLabelEl(); // remove the wrapper vdom.cn[0].width = me.labelWidth; me._vdom = vdom; // silent update me.updateInputWidth(); } else if (value === 'inline') { centerBorderElCls = ['neo-center-border']; isEmpty = me.isEmpty(); vdom = me.vdom; if (!isEmpty) { centerBorderElCls.push('neo-float-above'); } delete vdom.cn[0].width; vdom.cn[0] = { cls: ['neo-label-wrapper'], cn : [{ cls: ['neo-left-border'] }, { cls: centerBorderElCls, cn : [vdom.cn[0]] }, { cls: ['neo-right-border'] }] }; me._vdom = vdom; // silent update me.updateInputWidth(); if (!isEmpty) { setTimeout(() => { me.updateCenterBorderElWidth(false); }, 20); } } } /** * Triggered after the labelText config got changed * @param {String} value * @param {String} oldValue * @protected */ afterSetLabelText(value, oldValue) { let me = this, isEmpty = me.isEmpty(), vdom = me.vdom; me.getLabelEl().innerHTML = value; if (me.hideLabel) { me._vdom = vdom; // silent update } else { if (me.labelPosition === 'inline') { if (!isEmpty) { delete me.getCenterBorderEl().width; } me.promiseVdomUpdate(vdom).then(() => { me.updateCenterBorderElWidth(isEmpty); }); } else { me.vdom = vdom; } } } /** * Triggered after the labelWidth config got changed * @param {Number|String} value * @param {Number|String} oldValue * @protected */ afterSetLabelWidth(value, oldValue) { if (this.labelPosition !== 'inline') { let me = this, vdom = me.vdom, label = vdom.cn[0]; label.width = value; me._vdom = vdom; // silent update !me.hideLabel && me.updateInputWidth(); } } /** * Triggered after the mounted config got changed * @param {Boolean} value * @param {Boolean} oldValue * @protected */ afterSetMounted(value, oldValue) { super.afterSetMounted(value, oldValue); let me = this; if (oldValue !== undefined) { let triggers = me.triggers || [], i = 0, len = triggers.length; for (; i < len; i++) { if (!triggers[i].vdom.removeDom) { triggers[i].mounted = value; } } if (me.labelPosition === 'inline') { if (value) { me.updateCenterBorderElWidth(); } else { delete me.getCenterBorderEl().width; } } } } /** * Triggered after the placeholderText config got changed * @param {String|null} value * @param {String|null} oldValue * @protected */ afterSetPlaceholderText(value, oldValue) { this.changeInputElKey('placeholder', value === '' ? null : value); } /** * Triggered after the required config got changed * @param {Boolean} value * @param {Boolean} oldValue * @protected */ afterSetRequired(value, oldValue) { this.changeInputElKey('required', value ? value : null); } /** * Triggered after the spellCheck config got changed * @param {Boolean|null} value * @param {Boolean|null} oldValue * @protected */ afterSetSpellCheck(value, oldValue) { this.changeInputElKey('spellcheck', Neo.isBoolean(value) ? value : null); } /** * Triggered after the triggers config got changed * @param {Object[]} value * @param {Object[]} oldValue * @protected */ afterSetTriggers(value, oldValue) { let me = this, vdom = me.vdom, inputEl = vdom.cn[1], // inputEl or inputWrapperEl preTriggers = [], postTriggers = [], width; if (oldValue) { oldValue.forEach(item => { if (!me.getTrigger(item.type)) { item.destroy(); } }); } if (value.length > 0) { value.forEach(item => { if (item.align === 'start') { preTriggers.push(item); } else { postTriggers.push(item); } }); postTriggers.sort((a, b) => b.weight - a.weight); // DESC preTriggers .sort((a, b) => a.weight - b.weight); // ASC postTriggers = postTriggers.map(a => a.vdom); preTriggers = preTriggers .map(a => a.vdom); if (inputEl.tag === 'input') { // wrap the input tag vdom.cn[1] = { cls : ['neo-input-wrapper'], cn : [...preTriggers, inputEl, ...postTriggers], id : me.getInputWrapperId(), width: inputEl.width }; delete inputEl.width; } else { inputEl.cn = [...preTriggers, me.getInputEl(), ...postTriggers]; } } else { if (inputEl.tag !== 'input') { // replacing the input wrapper div with the input tag width = inputEl.width; vdom.cn[1] = me.getInputEl(); vdom.cn[1].width = width; } } me.promiseVdomUpdate().then(() => { me.updateTriggerVnodes(); }); } /** * Triggered after the value config got changed * todo: add validation logic * @param {String} value * @param {String} oldValue * @protected */ afterSetValue(value, oldValue) { let me = this, vdom = me.vdom; me.getInputEl().value = value; if (!!value !== !!oldValue) { // change from empty to non empty _util_Array_mjs__WEBPACK_IMPORTED_MODULE_3__["default"][value && value.toString().length > 0 ? 'add' : 'remove'](me._cls, 'neo-has-content'); } _util_Array_mjs__WEBPACK_IMPORTED_MODULE_3__["default"][me.originalConfig.value !== value ? 'add' : 'remove'](me._cls, 'neo-is-dirty'); me.vdom = vdom; super.afterSetValue(value, oldValue); // fires the change event } /** * Triggered after the width config got changed * @param {Number|String} value * @param {Number|String} oldValue * @protected */ afterSetWidth(value, oldValue) { super.afterSetWidth(value, oldValue); this.updateInputWidth(); } /** * Return a shallow copy of the triggers config * @param {Array|null} value * @protected */ beforeGetTriggers(value) { if (Array.isArray(value)) { return [...value]; } return value; } /** * Triggered before the autoCapitalize config gets changed * @param {String} value * @param {String} oldValue * @protected * @returns {String} */ beforeSetAutoCapitalize(value, oldValue) { return this.beforeSetEnumValue(value, oldValue, 'autoCapitalize', 'autoCapitalizeValues'); } /** * Triggered before the labelPosition config gets changed * @param {String} value * @param {String} oldValue * @protected * @returns {String} */ beforeSetLabelPosition(value, oldValue) { return this.beforeSetEnumValue(value, oldValue, 'labelPosition'); } /** * Triggered before the triggers config gets changed * @param {Object|Object[]} value * @param {Object[]} oldValue * @returns {Object[]} the parsed triggers config * @protected * @returns {Object|Object[]} */ beforeSetTriggers(value, oldValue) { if (!value) { value = []; } else if (!Array.isArray(value)) { value = [value]; } let me = this; value.forEach((item, index) => { if (item.isClass) { value[index] = Neo.create(item, { appName: me.appName, id : me.getTriggerId(item.prototype.type), field : me }); } else if (!(item instanceof _trigger_Base_mjs__WEBPACK_IMPORTED_MODULE_1__["default"])) { if (!item.module && !item.ntype) { item.ntype = 'trigger'; } if (item.module) { item.className = item.module.prototype.className; item.id = me.getTriggerId(item.module.prototype.type); } value[index] = Neo[item.className ? 'create' : 'ntype']({ ...item, appName: me.appName, field : me }); } }); return value; } /** * Changes the value of a inputEl vdom object attribute or removes it in case it has no value * @param {String} key * @param {Array|Number|Object|String|null} value */ changeInputElKey(key, value) { let me = this, vdom = me.vdom; if (value || Neo.isBoolean(value) || value === 0) { me.getInputEl()[key] = value; } else { delete me.getInputEl()[key]; } me.vdom = vdom; } /** * Resets the field to its original value or null depending on the clearToOriginalValue config */ clear() { let me = this; me.value = me.clearToOriginalValue ? me.originalConfig.value : null; me.fire('clear'); } /** * Calls focus() on the inputEl node instead * @param {String} id=this.id * @override */ focus(id=this.id) { super.focus(this.getInputElId()); } /** * @returns {Object|null} */ getCenterBorderEl() { let el = _util_VDom_mjs__WEBPACK_IMPORTED_MODULE_4__["default"].findVdomChild(this.vdom, {cls: 'neo-center-border'}); return el?.vdom; } /** * @returns {Object|null} */ getInputEl() { let el = _util_VDom_mjs__WEBPACK_IMPORTED_MODULE_4__["default"].findVdomChild(this.vdom, {flag: 'neo-real-input'}); return el?.vdom; } /** * @returns {String} */ getInputElId() { return `${this.id}__input`; } /** * Calculates the new inputWidth based on the labelWidth & total width * @returns {Number|null} null in case this.width is unknown */ getInputWidth() { let me = this, ignoreLabel = me.hideLabel || me.labelPosition === 'bottom' || me.labelPosition === 'inline' || me.labelPosition === 'top', labelWidth = ignoreLabel ? 0 : me.labelWidth, width = me.width; if (labelWidth && width) { return parseInt(width) - parseInt(labelWidth); } else if (width) { return width; } return null; } /** * @returns {String} */ getInputWrapperId() { return `${this.id}__input-wrapper`; } /** * @returns {Object|null} */ getLabelEl() { let el = _util_VDom_mjs__WEBPACK_IMPORTED_MODULE_4__["default"].findVdomChild(this.vdom, {tag: 'label'}); return el?.vdom; } /** * @returns {String} */ getLabelId() { return `${this.id}__label`; } /** * @param {String} type * @returns {Neo.form.field.trigger.Base|null} */ getTrigger(type) { let me = this, triggers = me.triggers || [], i = 0, len = triggers.length; for (; i < len; i++) { if (triggers[i].type === type) { return triggers[i]; } } return null; } /** * @param {String} id * @returns {Neo.form.field.trigger.Base|null} */ getTriggerById(id) { let me = this, triggers = me.triggers || [], i = 0, len = triggers.length; for (; i < len; i++) { if (triggers[i].id === id) { return triggers[i]; } } return null; } /** * @param {String} type * @protected * @returns {String} The trigger node id */ getTriggerId(type) { return this.id + '-trigger-' + type; } /** * Finds a trigger by a given type config * @param {String} type * @returns {Boolean} */ hasTrigger(type) { let triggers = this.triggers || [], i = 0, len = triggers.length; for (; i < len; i++) { if (triggers[i].type === type) { return true; } } return false; } /** * @returns {Boolean} */ isEmpty() { return !(this.value?.toString().length > 0); } /** * @returns {Boolean} */ isValid() { let me = this; if (me.required && (!me.value || me.value?.length < 1)) { return false; } return super.isValid(); } /** * @param {Object} config * @param {Boolean} [preventOriginalConfig] True prevents the instance from getting an originalConfig property * @returns {Object} config */ mergeConfig(...args) { let me = this, config = super.mergeConfig(...args), triggers = config.triggers || me.triggers; me[triggers ? 'triggers' : '_triggers'] = triggers; delete config.triggers; return config; } /** * @param {Object} data * @param {Object[]} data.path * @protected */ onFocusEnter(data) { let me = this, cls = me.cls, vdom; _util_Array_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].add(cls, 'neo-focus'); me.cls = cls; if (me.labelPosition === 'inline') { if (me.centerBorderElWidth) { vdom = me.vdom; me.getCenterBorderEl().width = me.centerBorderElWidth; me.vdom = vdom; } else { me.updateCenterBorderElWidth(false); } } } /** * @param {Object} data * @param {Object[]} data.oldPath * @protected */ onFocusLeave(data) { let me = this, centerBorderEl = me.getCenterBorderEl(), // labelPosition: 'inline' cls = me.cls, vdom; _util_Array_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].remove(cls, 'neo-focus'); if (centerBorderEl && me.isEmpty()) { me._cls = cls; // silent update vdom = me.vdom; delete centerBorderEl.width; me.vdom = vdom; } else { me.cls = cls; } } /** * @param {Object} data * @protected */ onInputValueChange(data) { let me = this, value = data.value, oldValue = me.value, vnode = _util_VNode_mjs__WEBPACK_IMPORTED_MODULE_5__["default"].findChildVnode(me.vnode, {nodeName: 'input'}); if (vnode) { // required for validation -> revert a wrong user input vnode.vnode.attributes.value = value; } if (value !== oldValue) { me.value = value; } } /** * Removes all triggers of a given type * @param {String} type * @param {Boolean} [silent=false] true prevents a vdom update * @param {Array} [triggerSource] pass a shallow copy of this.triggers * @returns {Boolean} true in case a trigger was found & removed */ removeTrigger(type, silent=false, triggerSource) { let me = this, hasMatch = false, triggers = triggerSource || me.triggers || [], i = 0, len = triggers.length, trigger; for (; i < len; i++) { trigger = triggers[i]; if (trigger.type === type) { _util_Array_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].remove(triggers, trigger); len--; hasMatch = true; } } if (hasMatch && !silent) { me.triggers = triggers; } return hasMatch; } /** * Resets the field to its original value or null depending on the clearToOriginalValue config * You can optionally pass a new value, which will adjust the originalConfig.value if needed. * @param {String|null} [value=null] */ reset(value=null) { if (value && this.clearToOriginalValue) { this.originalConfig.value = value; } super.reset(value); } /** * Used for labelPosition: 'inline' to adjust the top border matching to the length of the label * @param {Boolean} [silent=false] true to get the value, but not apply it to the DOM * @protected */ updateCenterBorderElWidth(silent=false) { let me = this; me.mounted && Neo.main.DomAccess.getBoundingClientRect({ id: me.getCenterBorderEl().id }).then(data => { me.centerBorderElWidth = Math.round(data.width * .7) + 8; if (!silent) { let vdom = me.vdom; me.getCenterBorderEl().width = me.centerBorderElWidth; me.vdom = vdom; } }); } /** * Calculates the new inputWidth based on the labelWidth & total width * @protected */ updateInputWidth() { let me = this, inputWidth = me.getInputWidth(), vdom = me.vdom; if (inputWidth !== null && inputWidth !== me.width) { vdom.cn[1].width = inputWidth; } else { delete vdom.cn[1].width; } me.vdom = vdom; } /** * Since triggers do not get rendered, assign the relevant props * todo: this could be handled by component.Base */ updateTriggerVnodes() { let me = this, triggerRoot = me.vnode?.childNodes[1], childNodes = triggerRoot?.childNodes || [], trigger; childNodes.forEach(vnode => { trigger = me.getTriggerById(vnode.id); trigger && Object.assign(trigger, { vnode, _rendered: true, _mounted : true }); }); } } Neo.applyClassConfig(Text); /***/ }), /***/ "./src/form/field/trigger/Base.mjs": /*!*****************************************!*\ !*** ./src/form/field/trigger/Base.mjs ***! \*****************************************/ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ Base) /* harmony export */ }); /* harmony import */ var _component_Base_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../component/Base.mjs */ "./src/component/Base.mjs"); /* harmony import */ var _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../util/Array.mjs */ "./src/util/Array.mjs"); /** * Base class for form field Triggers * @class Neo.form.field.trigger.Base * @extends Neo.component.Base */ class Base extends _component_Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { static getStaticConfig() {return { /** * Valid values for align * @member {String[]} alignValues=['end', 'start'] * @protected * @static */ alignValues: ['end', 'start'] }} static getConfig() {return { /** * @member {String} className='Neo.form.field.trigger.Base' * @protected */ className: 'Neo.form.field.trigger.Base', /** * @member {String} ntype='trigger' * @protected */ ntype: 'trigger', /** * @member {String} align_='end' */ align_: 'end', /** * @member {String[]} cls=['neo-field-trigger'] */ cls: ['neo-field-trigger'], /** * @member {Neo.form.field.Base|null} field=null */ field: null, /** * @member {Boolean} hidden_=false */ hidden_: false, /** * @member {String|null} iconCls_=null */ iconCls_: null, /** * @member {Boolean} isHovered=false * @protected */ isHovered: false, /** * The scope of the trigger handler * @member {Neo.core.Base|null} scope=null */ scope: null, /** * @member {Boolean} showOnHover=false */ showOnHover: false, /** * Internal flag used by field.getTrigger() * @member {String} type='base' * @protected */ type: 'base', /** * @member {Object} _vdom={tabIndex: -1} */ _vdom: {tabIndex: -1}, /** * @member {Number} weight_=10 */ weight_: 10 }} /** * @param {Object} config */ construct(config) { super.construct(config); let me = this, domListeners = me.domListeners || [], fieldListeners; domListeners.push( {click: me.onTriggerClick, scope: me} ); me.domListeners = domListeners; if (me.showOnHover) { me.hidden = true; me.field.on('constructed', () => { fieldListeners = me.field.domListeners || []; fieldListeners.push( {mouseenter: me.onMouseEnter, scope: me}, {mouseleave: me.onMouseLeave, scope: me} ); me.field.domListeners = fieldListeners; }, me); } } /** * Triggered after the align config got changed * @param {String} value * @param {String} oldValue * @protected */ afterSetAlign(value, oldValue) { let cls = this.cls; _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__["default"][value === 'start' ? 'add' : 'remove'](cls, 'neo-align-start'); this.cls = cls; } /** * Triggered after the hidden config got changed * @param {Boolean} value * @param {Boolean} oldValue * @protected */ afterSetHidden(value, oldValue) { let vdom = this.vdom, style = vdom.style || {}; style.display = value ? 'none' : 'inline-block'; this.vdom = vdom; } /** * Triggered after the iconCls config got changed * @param {String} value * @param {String} oldValue * @protected */ afterSetIconCls(value, oldValue) { let cls = this.cls; _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].remove(cls, oldValue); if (value && value !== '') { _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].add(cls, value); } this.cls = cls; } /** * Triggered before the align config gets changed * @param {String} value * @param {String} oldValue * @protected */ beforeSetAlign(value, oldValue) { return this.beforeSetEnumValue(value, oldValue, 'align', 'alignValues'); } /** * @param {Boolean} updateParentVdom * @param {Boolean} silent */ destroy(updateParentVdom, silent) { let me = this; me.removeDomListeners({click: {fn: me.onTriggerClick, scope: me}}); delete me.field; super.destroy(updateParentVdom, silent); } /** * */ onMouseEnter() { this.isHovered = true; this.hidden = false; } /** * */ onMouseLeave() { this.isHovered = false; this.hidden = true; } /** * click domEvent listener * @param {Object} data * @protected */ onTriggerClick(data) { let me = this, scope = me.scope || me; if (me.handler) { scope[me.handler].call(scope); } } } Neo.applyClassConfig(Base); /***/ }), /***/ "./src/form/field/trigger/Clear.mjs": /*!******************************************!*\ !*** ./src/form/field/trigger/Clear.mjs ***! \******************************************/ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ Clear) /* harmony export */ }); /* harmony import */ var _Base_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Base.mjs */ "./src/form/field/trigger/Base.mjs"); /* harmony import */ var _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../util/Array.mjs */ "./src/util/Array.mjs"); /** * Clear Trigger to remove the input value of TextFields or subclasses * @class Neo.form.field.trigger.Clear * @extends Neo.form.field.trigger.Base */ class Clear extends _Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { static getConfig() {return { /** * @member {String} className='Neo.form.field.trigger.Clear' * @protected */ className: 'Neo.form.field.trigger.Clear', /** * @member {String} ntype='trigger-clear' * @protected */ ntype: 'trigger-clear', /** * @member {String[]} cls=['neo-field-trigger', 'neo-trigger-clear'] */ cls: ['neo-field-trigger', 'neo-trigger-clear'], /** * @member {String|null} iconCls='fa fa-times' */ iconCls: 'fa fa-times', /** * Internal flag used by field.getTrigger() * @member {String} type='clear' * @protected */ type: 'clear', /** * @member {Number} weight_=20 */ weight: 20 }} /** * Triggered after the hidden config got changed * @param {Boolean} value * @param {Boolean} oldValue * @protected */ afterSetHidden(value, oldValue) { let cls = this.cls; _util_Array_mjs__WEBPACK_IMPORTED_MODULE_1__["default"][value ? 'add' : 'remove'](cls, 'neo-is-hidden'); this.cls = cls; } /** * Triggered before the hidden config gets changed. * @param {Boolean} value * @param {Boolean} oldValue * @protected */ beforeSetHidden(value, oldValue) { if (this.showOnHover && !this.isHovered) { return true; } return value; } /** * */ destroy(...args) { let me = this; me.field.un({ change : me.onFieldChange, changeClearToOriginalValue: me.onFieldChange, scope : me }); super.destroy(...args); } /** * @returns {Boolean} true in case the trigger should be hidden */ getHiddenState() { let me = this, field = me.field, value = field.value; if (field.clearToOriginalValue) { return value === field.originalConfig.value; } else { if (value === 0) { value = '0'; } return !field.value || value.toString().length < 1; } } /** * @param {Object} opts */ onFieldChange(opts) { this.hidden = this.getHiddenState(); } /** * */ onConstructed() { super.onConstructed(); let me = this; me.field.on({ change : me.onFieldChange, changeClearToOriginalValue: me.onFieldChange, scope : me }); me.hidden = me.getHiddenState(); } /** * @override */ onMouseEnter() { let me = this; me.isHovered = true; me.hidden = me.getHiddenState(); } /** * @param {Object} data */ onTriggerClick(data) { this.field.clear(); } } Neo.applyClassConfig(Clear); /***/ }) }]); //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2h1bmtzL2FwcC92ZW5kb3JzLXNyY19mb3JtX2ZpZWxkX1RleHRfbWpzLmpzIiwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7O0FBQWlEOztBQUVqRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsbUJBQW1CLDJEQUFTO0FBQzVCLHdCQUF3QjtBQUN4QjtBQUNBLG9CQUFvQixRQUFRO0FBQzVCO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLFFBQVE7QUFDNUI7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBb0IsR0FBRztBQUN2QjtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLGVBQWUsR0FBRztBQUNsQixlQUFlLEdBQUc7QUFDbEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLEdBQUc7QUFDbEIsZUFBZSxHQUFHO0FBQ2xCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFNBQVM7QUFDVDs7QUFFQTtBQUNBLGlCQUFpQixHQUFHO0FBQ3BCO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0EsaUJBQWlCO0FBQ2pCO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLEdBQUc7QUFDbEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxXQUFXLEdBQUc7QUFDZCxXQUFXLEdBQUc7QUFDZCxhQUFhO0FBQ2I7O0FBRUE7O0FBRXlCOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUNsRmE7QUFDUTtBQUNDO0FBQ0M7QUFDRDtBQUNDOztBQUVoRDtBQUNBO0FBQ0E7QUFDQTtBQUNBLG1CQUFtQixpREFBSTtBQUN2Qiw4QkFBOEI7QUFDOUI7QUFDQTtBQUNBLG9CQUFvQixVQUFVO0FBQzlCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixVQUFVO0FBQzlCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUEsd0JBQXdCO0FBQ3hCO0FBQ0Esb0JBQW9CLFFBQVE7QUFDNUI7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBb0IsUUFBUTtBQUM1QjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixRQUFRO0FBQzVCO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixTQUFTO0FBQzdCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBb0IsYUFBYTtBQUNqQztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLFNBQVM7QUFDN0I7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixTQUFTO0FBQzdCO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixVQUFVO0FBQzlCO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixTQUFTO0FBQzdCO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixRQUFRO0FBQzVCO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLFFBQVE7QUFDNUI7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLFFBQVE7QUFDNUI7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBb0IsZUFBZTtBQUNuQztBQUNBO0FBQ0E7QUFDQSxvQkFBb0IsYUFBYTtBQUNqQztBQUNBO0FBQ0E7QUFDQSxvQkFBb0IsU0FBUztBQUM3QjtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixjQUFjO0FBQ2xDO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixzQkFBc0I7QUFDMUM7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLFFBQVE7QUFDNUI7QUFDQTtBQUNBLFNBQVM7QUFDVCxhQUFhLHNEQUFzRDtBQUNuRSxhQUFhO0FBQ2I7QUFDQTs7QUFFQTtBQUNBLGVBQWUsUUFBUTtBQUN2QjtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBLGFBQWE7QUFDYjs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFFBQVE7QUFDdkIsZUFBZSxhQUFhO0FBQzVCO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQSxTQUFTO0FBQ1Q7O0FBRUE7QUFDQTtBQUNBLGVBQWUsUUFBUTtBQUN2QixlQUFlLFFBQVE7QUFDdkI7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxTQUFTO0FBQ3hCLGVBQWUsU0FBUztBQUN4QjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFNBQVM7QUFDeEIsZUFBZSxTQUFTO0FBQ3hCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLDZCQUE2QiwwREFBWTtBQUN6QztBQUNBLFVBQVU7QUFDVjtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLGVBQWUsU0FBUztBQUN4QixlQUFlLFNBQVM7QUFDeEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsU0FBUztBQUNUOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFNBQVM7QUFDeEIsZUFBZSxTQUFTO0FBQ3hCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQSx5QkFBeUI7O0FBRXpCO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLGVBQWUsUUFBUTtBQUN2QixlQUFlLFFBQVE7QUFDdkI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxRQUFRO0FBQ3ZCLGVBQWUsUUFBUTtBQUN2QjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFFBQVE7QUFDdkIsZUFBZSxRQUFRO0FBQ3ZCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQSxRQUFRLDhEQUFlO0FBQ3ZCLFFBQVEsMkRBQVk7QUFDcEIsZ0ZBQWdGOztBQUVoRjtBQUNBOztBQUVBLDBDQUEwQzs7QUFFMUM7O0FBRUEsNkJBQTZCO0FBQzdCO0FBQ0EsVUFBVTtBQUNWO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQSxpQkFBaUI7QUFDakI7QUFDQTtBQUNBLGlCQUFpQjtBQUNqQjtBQUNBLGlCQUFpQjtBQUNqQjs7QUFFQSw2QkFBNkI7QUFDN0I7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsaUJBQWlCO0FBQ2pCO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxRQUFRO0FBQ3ZCLGVBQWUsUUFBUTtBQUN2QjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQSw2QkFBNkI7QUFDN0IsVUFBVTtBQUNWO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxpQkFBaUI7QUFDakIsY0FBYztBQUNkO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLGVBQWU7QUFDOUIsZUFBZSxlQUFlO0FBQzlCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBLDZCQUE2Qjs7QUFFN0I7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFNBQVM7QUFDeEIsZUFBZSxTQUFTO0FBQ3hCO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBLG1CQUFtQixTQUFTO0FBQzVCO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBLGtCQUFrQjtBQUNsQjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLGFBQWE7QUFDNUIsZUFBZSxhQUFhO0FBQzVCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLGVBQWUsU0FBUztBQUN4QixlQUFlLFNBQVM7QUFDeEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxjQUFjO0FBQzdCLGVBQWUsY0FBYztBQUM3QjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFVBQVU7QUFDekIsZUFBZSxVQUFVO0FBQ3pCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsYUFBYTtBQUNiOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esa0JBQWtCO0FBQ2xCO0FBQ0E7QUFDQSxhQUFhOztBQUViLDhEQUE4RDtBQUM5RCw4REFBOEQ7O0FBRTlEO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLGNBQWM7QUFDZDtBQUNBO0FBQ0EsVUFBVTtBQUNWO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxTQUFTO0FBQ1Q7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsZUFBZSxRQUFRO0FBQ3ZCLGVBQWUsUUFBUTtBQUN2QjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBLHNDQUFzQztBQUN0QyxZQUFZLHVEQUFRO0FBQ3BCOztBQUVBLFFBQVEsdURBQVE7O0FBRWhCOztBQUVBLDhDQUE4QztBQUM5Qzs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxlQUFlO0FBQzlCLGVBQWUsZUFBZTtBQUM5QjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLGVBQWUsWUFBWTtBQUMzQjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxRQUFRO0FBQ3ZCLGVBQWUsUUFBUTtBQUN2QjtBQUNBLGlCQUFpQjtBQUNqQjtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxRQUFRO0FBQ3ZCLGVBQWUsUUFBUTtBQUN2QjtBQUNBLGlCQUFpQjtBQUNqQjtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxpQkFBaUI7QUFDaEMsZUFBZSxVQUFVO0FBQ3pCLGlCQUFpQixVQUFVO0FBQzNCO0FBQ0EsaUJBQWlCO0FBQ2pCO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBVTtBQUNWO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsaUJBQWlCO0FBQ2pCLGNBQWMsMkJBQTJCLHlEQUFXO0FBQ3BEO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGlCQUFpQjtBQUNqQjtBQUNBLFNBQVM7O0FBRVQ7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxRQUFRO0FBQ3ZCLGVBQWUsaUNBQWlDO0FBQ2hEO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxVQUFVO0FBQ1Y7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFFBQVE7QUFDdkI7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLGlCQUFpQjtBQUNqQjtBQUNBO0FBQ0EsaUJBQWlCLG9FQUFzQixhQUFhLHlCQUF5QjtBQUM3RTtBQUNBOztBQUVBO0FBQ0EsaUJBQWlCO0FBQ2pCO0FBQ0E7QUFDQSxpQkFBaUIsb0VBQXNCLGFBQWEsdUJBQXVCO0FBQzNFO0FBQ0E7QUFDQTtBQUNBLGlCQUFpQjtBQUNqQjtBQUNBO0FBQ0Esa0JBQWtCLFFBQVE7QUFDMUI7O0FBRUE7QUFDQTtBQUNBLGlCQUFpQixhQUFhO0FBQzlCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsVUFBVTtBQUNWO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBLGlCQUFpQjtBQUNqQjtBQUNBO0FBQ0Esa0JBQWtCLFFBQVE7QUFDMUI7O0FBRUE7QUFDQSxpQkFBaUI7QUFDakI7QUFDQTtBQUNBLGlCQUFpQixvRUFBc0IsYUFBYSxhQUFhO0FBQ2pFO0FBQ0E7O0FBRUE7QUFDQSxpQkFBaUI7QUFDakI7QUFDQTtBQUNBLGtCQUFrQixRQUFRO0FBQzFCOztBQUVBO0FBQ0EsZUFBZSxRQUFRO0FBQ3ZCLGlCQUFpQjtBQUNqQjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUEsZUFBZSxTQUFTO0FBQ3hCO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQSxlQUFlLFFBQVE7QUFDdkIsaUJBQWlCO0FBQ2pCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQSxlQUFlLFNBQVM7QUFDeEI7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBLGVBQWUsUUFBUTtBQUN2QjtBQUNBLGlCQUFpQixRQUFRO0FBQ3pCO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFFBQVE7QUFDdkIsaUJBQWlCO0FBQ2pCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUEsZUFBZSxTQUFTO0FBQ3hCO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQSxpQkFBaUI7QUFDakI7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQSxpQkFBaUI7QUFDakI7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0EsZUFBZSxRQUFRO0FBQ3ZCLGVBQWUsU0FBUztBQUN4QixpQkFBaUIsUUFBUTtBQUN6QjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLGVBQWUsUUFBUTtBQUN2QixlQUFlLFVBQVU7QUFDekI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBLFFBQVEsMkRBQVk7QUFDcEI7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGNBQWM7QUFDZDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLGVBQWUsUUFBUTtBQUN2QixlQUFlLFVBQVU7QUFDekI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUEsUUFBUSw4REFBZTs7QUFFdkI7QUFDQSwyQkFBMkI7QUFDM0I7QUFDQTtBQUNBO0FBQ0EsVUFBVTtBQUNWO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLGVBQWUsUUFBUTtBQUN2QjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSx1QkFBdUIsc0VBQXdCLFlBQVksa0JBQWtCOztBQUU3RTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxRQUFRO0FBQ3ZCLGVBQWUsU0FBUztBQUN4QixlQUFlLE9BQU87QUFDdEIsaUJBQWlCLFNBQVM7QUFDMUI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQSxlQUFlLFNBQVM7QUFDeEI7O0FBRUE7QUFDQSxnQkFBZ0IsOERBQWU7QUFDL0I7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsZUFBZSxhQUFhO0FBQzVCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxTQUFTO0FBQ3hCO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxTQUFTO0FBQ1Q7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxTQUFTO0FBQ1Q7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsVUFBVTtBQUNWO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGFBQWE7QUFDYixTQUFTO0FBQ1Q7QUFDQTs7QUFFQTs7QUFFeUI7Ozs7Ozs7Ozs7Ozs7Ozs7O0FDbjlCMkI7QUFDSjs7QUFFaEQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG1CQUFtQiwyREFBUztBQUM1Qiw4QkFBOEI7QUFDOUI7QUFDQTtBQUNBLG9CQUFvQixVQUFVO0FBQzlCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUEsd0JBQXdCO0FBQ3hCO0FBQ0Esb0JBQW9CLFFBQVE7QUFDNUI7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBb0IsUUFBUTtBQUM1QjtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixRQUFRO0FBQzVCO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixVQUFVO0FBQzlCO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQiwwQkFBMEI7QUFDOUM7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLFNBQVM7QUFDN0I7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLGFBQWE7QUFDakM7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLFNBQVM7QUFDN0I7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixvQkFBb0I7QUFDeEM7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLFNBQVM7QUFDN0I7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBb0IsUUFBUTtBQUM1QjtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixRQUFRLE9BQU87QUFDbkM7QUFDQTtBQUNBLFNBQVMsYUFBYTtBQUN0QjtBQUNBLG9CQUFvQixRQUFRO0FBQzVCO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLGVBQWUsUUFBUTtBQUN2QjtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0EsYUFBYTtBQUNiOztBQUVBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBLHFCQUFxQix1Q0FBdUM7QUFDNUQscUJBQXFCO0FBQ3JCOztBQUVBO0FBQ0EsYUFBYTtBQUNiO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLGVBQWUsUUFBUTtBQUN2QixlQUFlLFFBQVE7QUFDdkI7QUFDQTtBQUNBO0FBQ0E7O0FBRUEsUUFBUSx1REFBUTtBQUNoQjtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFNBQVM7QUFDeEIsZUFBZSxTQUFTO0FBQ3hCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFFBQVE7QUFDdkIsZUFBZSxRQUFRO0FBQ3ZCO0FBQ0E7QUFDQTtBQUNBOztBQUVBLFFBQVEsOERBQWU7O0FBRXZCO0FBQ0EsWUFBWSwyREFBWTtBQUN4Qjs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFFBQVE7QUFDdkIsZUFBZSxRQUFRO0FBQ3ZCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQSxlQUFlLFNBQVM7QUFDeEIsZUFBZSxTQUFTO0FBQ3hCO0FBQ0E7QUFDQTs7QUFFQSwrQkFBK0IsUUFBUSxrQ0FBa0M7O0FBRXpFOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLGVBQWUsUUFBUTtBQUN2QjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRXlCOzs7Ozs7Ozs7Ozs7Ozs7OztBQ3ZOUztBQUNhOztBQUUvQztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLGlEQUFJO0FBQ3hCLHdCQUF3QjtBQUN4QjtBQUNBLG9CQUFvQixRQUFRO0FBQzVCO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLFFBQVE7QUFDNUI7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBb0IsVUFBVTtBQUM5QjtBQUNBO0FBQ0E7QUFDQSxvQkFBb0IsYUFBYTtBQUNqQztBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFvQixRQUFRO0FBQzVCO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLFFBQVE7QUFDNUI7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxlQUFlLFNBQVM7QUFDeEIsZUFBZSxTQUFTO0FBQ3hCO0FBQ0E7QUFDQTtBQUNBOztBQUVBLFFBQVEsdURBQVE7QUFDaEI7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsZUFBZSxTQUFTO0FBQ3hCLGVBQWUsU0FBUztBQUN4QjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsU0FBUzs7QUFFVDtBQUNBOztBQUVBO0FBQ0EsaUJBQWlCLFNBQVM7QUFDMUI7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsVUFBVTtBQUNWO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQSxlQUFlLFFBQVE7QUFDdkI7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFNBQVM7O0FBRVQ7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLGVBQWUsUUFBUTtBQUN2QjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUUwQiIsInNvdXJjZXMiOlsid2VicGFjazovL25lby5tanMvLi9zcmMvZm9ybS9maWVsZC9CYXNlLm1qcyIsIndlYnBhY2s6Ly9uZW8ubWpzLy4vc3JjL2Zvcm0vZmllbGQvVGV4dC5tanMiLCJ3ZWJwYWNrOi8vbmVvLm1qcy8uL3NyYy9mb3JtL2ZpZWxkL3RyaWdnZXIvQmFzZS5tanMiLCJ3ZWJwYWNrOi8vbmVvLm1qcy8uL3NyYy9mb3JtL2ZpZWxkL3RyaWdnZXIvQ2xlYXIubWpzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBDb21wb25lbnQgZnJvbSAnLi4vLi4vY29tcG9uZW50L0Jhc2UubWpzJztcblxuLyoqXG4gKiBBYnN0cmFjdCBiYXNlIGNsYXNzIGZvciBmb3JtIGZpZWxkc1xuICogQGNsYXNzIE5lby5mb3JtLmZpZWxkLkJhc2VcbiAqIEBleHRlbmRzIE5lby5jb21wb25lbnQuQmFzZVxuICovXG5jbGFzcyBCYXNlIGV4dGVuZHMgQ29tcG9uZW50IHtcbiAgICBzdGF0aWMgZ2V0Q29uZmlnKCkge3JldHVybiB7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtTdHJpbmd9IGNsYXNzTmFtZT0nTmVvLmZvcm0uZmllbGQuQmFzZSdcbiAgICAgICAgICogQHByb3RlY3RlZFxuICAgICAgICAgKi9cbiAgICAgICAgY2xhc3NOYW1lOiAnTmVvLmZvcm0uZmllbGQuQmFzZScsXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtTdHJpbmd9IG50eXBlPSdiYXNlZmllbGQnXG4gICAgICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgICAgICovXG4gICAgICAgIG50eXBlOiAnYmFzZWZpZWxkJyxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIgeyp9IHZhbHVlXz1udWxsXG4gICAgICAgICAqL1xuICAgICAgICB2YWx1ZV86IG51bGxcbiAgICB9fVxuXG4gICAgLyoqXG4gICAgICogVHJpZ2dlcmVkIGFmdGVyIHRoZSB2YWx1ZSBjb25maWcgZ290IGNoYW5nZWRcbiAgICAgKiBAcGFyYW0geyp9IHZhbHVlXG4gICAgICogQHBhcmFtIHsqfSBvbGRWYWx1ZVxuICAgICAqL1xuICAgIGFmdGVyU2V0VmFsdWUodmFsdWUsIG9sZFZhbHVlKSB7XG4gICAgICAgIGlmIChvbGRWYWx1ZSAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgICAgICB0aGlzLmZpcmVDaGFuZ2VFdmVudCh2YWx1ZSwgb2xkVmFsdWUpO1xuICAgICAgICB9XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogT3ZlcnJpZGUgdGhpcyBtZXRob2QgYXMgbmVlZGVkXG4gICAgICogQHBhcmFtIHsqfSB2YWx1ZVxuICAgICAqIEBwYXJhbSB7Kn0gb2xkVmFsdWVcbiAgICAgKi9cbiAgICBmaXJlQ2hhbmdlRXZlbnQodmFsdWUsIG9sZFZhbHVlKSB7XG4gICAgICAgIHRoaXMuZmlyZSgnY2hhbmdlJywge1xuICAgICAgICAgICAgY29tcG9uZW50OiB0aGlzLFxuICAgICAgICAgICAgb2xkVmFsdWUgOiBvbGRWYWx1ZSxcbiAgICAgICAgICAgIHZhbHVlICAgIDogdmFsdWVcbiAgICAgICAgfSk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQHJldHVybnMgeyp9IHRoaXMudmFsdWVcbiAgICAgKi9cbiAgICBnZXRTdWJtaXRWYWx1ZSgpIHtcbiAgICAgICAgcmV0dXJuIHRoaXMudmFsdWU7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQHJldHVybnMge0Jvb2xlYW59XG4gICAgICovXG4gICAgaXNWYWxpZCgpIHtcbiAgICAgICAgcmV0dXJuIHRydWU7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogUmVzZXRzIHRoZSBmaWVsZCB0byBhIG5ldyB2YWx1ZSBvciBudWxsXG4gICAgICogQHBhcmFtIHsqfSBbdmFsdWU9bnVsbF1cbiAgICAgKi9cbiAgICByZXNldCh2YWx1ZSkge1xuICAgICAgICB0aGlzLnZhbHVlID0gdmFsdWU7XG4gICAgfVxufVxuXG4vKipcbiAqIFRoZSBjaGFuZ2UgZXZlbnQgZmlyZXMgYWZ0ZXIgdGhlIHZhbHVlIGNvbmZpZyBnZXRzIGNoYW5nZWRcbiAqIEBldmVudCBjaGFuZ2VcbiAqIEBwYXJhbSB7Kn0gdmFsdWVcbiAqIEBwYXJhbSB7Kn0gb2xkVmFsdWVcbiAqIEByZXR1cm5zIHtPYmplY3R9XG4gKi9cblxuTmVvLmFwcGx5Q2xhc3NDb25maWcoQmFzZSk7XG5cbmV4cG9ydCB7QmFzZSBhcyBkZWZhdWx0fTtcbiIsImltcG9ydCBCYXNlICAgICAgICAgZnJvbSAnLi9CYXNlLm1qcyc7XG5pbXBvcnQgQmFzZVRyaWdnZXIgIGZyb20gJy4vdHJpZ2dlci9CYXNlLm1qcyc7XG5pbXBvcnQgQ2xlYXJUcmlnZ2VyIGZyb20gJy4vdHJpZ2dlci9DbGVhci5tanMnO1xuaW1wb3J0IE5lb0FycmF5ICAgICBmcm9tICcuLi8uLi91dGlsL0FycmF5Lm1qcyc7XG5pbXBvcnQgVkRvbVV0aWwgICAgIGZyb20gJy4uLy4uL3V0aWwvVkRvbS5tanMnO1xuaW1wb3J0IFZOb2RlVXRpbCAgICBmcm9tICcuLi8uLi91dGlsL1ZOb2RlLm1qcyc7XG5cbi8qKlxuICogQGNsYXNzIE5lby5mb3JtLmZpZWxkLlRleHRcbiAqIEBleHRlbmRzIE5lby5mb3JtLmZpZWxkLkJhc2VcbiAqL1xuY2xhc3MgVGV4dCBleHRlbmRzIEJhc2Uge1xuICAgIHN0YXRpYyBnZXRTdGF0aWNDb25maWcoKSB7cmV0dXJuIHtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFZhbGlkIHZhbHVlcyBmb3IgYXV0b0NhcGl0YWxpemVcbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nW119IGF1dG9DYXBpdGFsaXplVmFsdWVzPVsnY2hhcmFjdGVycycsJ25vbmUnLCdvbicsJ29mZicsJ3NlbnRlbmNlcycsJ3dvcmRzJ11cbiAgICAgICAgICogQHByb3RlY3RlZFxuICAgICAgICAgKiBAc3RhdGljXG4gICAgICAgICAqL1xuICAgICAgICBhdXRvQ2FwaXRhbGl6ZVZhbHVlczogWydjaGFyYWN0ZXJzJywgJ25vbmUnLCAnb24nLCAnb2ZmJywgJ3NlbnRlbmNlcycsICd3b3JkcyddLFxuICAgICAgICAvKipcbiAgICAgICAgICogVmFsaWQgdmFsdWVzIGZvciBsYWJlbFBvc2l0aW9uXG4gICAgICAgICAqIEBtZW1iZXIge1N0cmluZ1tdfSBsYWJlbFBvc2l0aW9ucz1bJ2JvdHRvbScsJ2lubGluZScsJ2xlZnQnLCdyaWdodCcsJ3RvcCddXG4gICAgICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgICAgICogQHN0YXRpY1xuICAgICAgICAgKi9cbiAgICAgICAgbGFiZWxQb3NpdGlvbnM6IFsnYm90dG9tJywgJ2lubGluZScsICdsZWZ0JywgJ3JpZ2h0JywgJ3RvcCddXG4gICAgfX1cblxuICAgIHN0YXRpYyBnZXRDb25maWcoKSB7cmV0dXJuIHtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge1N0cmluZ30gY2xhc3NOYW1lPSdOZW8uZm9ybS5maWVsZC5UZXh0J1xuICAgICAgICAgKiBAcHJvdGVjdGVkXG4gICAgICAgICAqL1xuICAgICAgICBjbGFzc05hbWU6ICdOZW8uZm9ybS5maWVsZC5UZXh0JyxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge1N0cmluZ30gbnR5cGU9J3RleHRmaWVsZCdcbiAgICAgICAgICogQHByb3RlY3RlZFxuICAgICAgICAgKi9cbiAgICAgICAgbnR5cGU6ICd0ZXh0ZmllbGQnLFxuICAgICAgICAvKipcbiAgICAgICAgICogQW4gZW51bWVyYXRlZCBhdHRyaWJ1dGUgdGhhdCBjb250cm9scyB3aGV0aGVyIGFuZCBob3cgdGV4dCBpbnB1dCBpcyBhdXRvbWF0aWNhbGx5IGNhcGl0YWxpemVkIGFzIGl0IGlzXG4gICAgICAgICAqIGVudGVyZWQvZWRpdGVkIGJ5IHRoZSB1c2VyLlxuICAgICAgICAgKiBWYWxpZCB2YWx1ZXM6ICdjaGFyYWN0ZXJzJywgJ25vbmUnLCAnb24nLCAnb2ZmJywgJ3NlbnRlbmNlcycsICd3b3JkcydcbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nfSBhdXRvQ2FwaXRhbGl6ZT1vZmYnXG4gICAgICAgICAqL1xuICAgICAgICBhdXRvQ2FwaXRhbGl6ZV86ICdvZmYnLFxuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7Qm9vbGVhbn0gYXV0b0NvbXBsZXRlXz1mYWxzZVxuICAgICAgICAgKi9cbiAgICAgICAgYXV0b0NvbXBsZXRlXzogZmFsc2UsXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBJbnRlcm5hbCB2YXJpYWJsZSB0byBzdG9yZSB0aGUgYWN0dWFsIHdpZHRoIGZvciB0aGUgbGFiZWwgY2VudGVyQm9yZGVyRWxcbiAgICAgICAgICogKG9ubHkgbmVlZGVkIGZvciBsYWJlbFBvc2l0aW9uOiAnaW5saW5lJylcbiAgICAgICAgICogQG1lbWJlciB7TnVtYmVyfG51bGx9IGNlbnRlckJvcmRlckVsV2lkdGg9bnVsbFxuICAgICAgICAgKiBAcHJvdGVjdGVkXG4gICAgICAgICAqL1xuICAgICAgICBjZW50ZXJCb3JkZXJFbFdpZHRoOiBudWxsLFxuICAgICAgICAvKipcbiAgICAgICAgICogVHJ1ZSBzaG93cyBhIGNsZWFyIHRyaWdnZXIgaW4gY2FzZSB0aGUgZmllbGQgaGFzIGEgbm9uIGVtcHR5IHZhbHVlLlxuICAgICAgICAgKiBAbWVtYmVyIHtCb29sZWFufSBjbGVhcmFibGVfPXRydWVcbiAgICAgICAgICovXG4gICAgICAgIGNsZWFyYWJsZV86IHRydWUsXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBUcnVlIHdpbGwgcmVzZXQgdGhlIGZpZWxkIHRvIGl0cyBpbml0aWFsIHZhbHVlIGNvbmZpZy5cbiAgICAgICAgICogUmVjb21tZW5kZWQgZm9yIGZpZWxkcyB3aXRoIHJlcXVpcmVkOiB0cnVlXG4gICAgICAgICAqIEBtZW1iZXIge0Jvb2xlYW59IGNsZWFyVG9PcmlnaW5hbFZhbHVlXz1mYWxzZVxuICAgICAgICAgKi9cbiAgICAgICAgY2xlYXJUb09yaWdpbmFsVmFsdWVfOiBmYWxzZSxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge1N0cmluZ1tdfSBjbHM9WyduZW8tdGV4dGZpZWxkJ11cbiAgICAgICAgICovXG4gICAgICAgIGNsczogWyduZW8tdGV4dGZpZWxkJ10sXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtCb29sZWFufSBoaWRlTGFiZWxfPWZhbHNlXG4gICAgICAgICAqL1xuICAgICAgICBoaWRlTGFiZWxfOiBmYWxzZSxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge1N0cmluZ30gaW5wdXRUeXBlXz0ndGV4dCdcbiAgICAgICAgICovXG4gICAgICAgIGlucHV0VHlwZV86ICd0ZXh0JyxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFZhbGlkIHZhbHVlczogJ2JvdHRvbScsICdpbmxpbmUnLCAnbGVmdCcsICdyaWdodCcsICd0b3AnXG4gICAgICAgICAqIEBtZW1iZXIge1N0cmluZ30gbGFiZWxQb3NpdGlvbl89J2xlZnQnXG4gICAgICAgICAqL1xuICAgICAgICBsYWJlbFBvc2l0aW9uXzogJ2xlZnQnLFxuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nfSBsYWJlbFRleHRfPSdMYWJlbFRleHQnXG4gICAgICAgICAqL1xuICAgICAgICBsYWJlbFRleHRfOiAnTGFiZWxUZXh0JyxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIGRlZmF1bHRzIHRvIHB4XG4gICAgICAgICAqIEBtZW1iZXIge051bWJlcnxTdHJpbmd9IGxhYmVsV2lkdGhfPTE1MFxuICAgICAgICAgKi9cbiAgICAgICAgbGFiZWxXaWR0aF86IDE1MCxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge1N0cmluZ3xudWxsfSBwbGFjZWhvbGRlclRleHRfPW51bGxcbiAgICAgICAgICovXG4gICAgICAgIHBsYWNlaG9sZGVyVGV4dF86IG51bGwsXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtCb29sZWFufSByZXF1aXJlZF89ZmFsc2VcbiAgICAgICAgICovXG4gICAgICAgIHJlcXVpcmVkXzogZmFsc2UsXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBudWxsID0+IEZvbGxvdyB0aGUgZWxlbWVudCdzIGRlZmF1bHQgYmVoYXZpb3IgZm9yIHNwZWxsIGNoZWNraW5nXG4gICAgICAgICAqIEBtZW1iZXIge0Jvb2xlYW58bnVsbH0gc3BlbGxDaGVja189ZmFsc2VcbiAgICAgICAgICovXG4gICAgICAgIHNwZWxsQ2hlY2tfOiBmYWxzZSxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge09iamVjdHxPYmplY3RbXXxudWxsfSB0cmlnZ2Vyc189bnVsbFxuICAgICAgICAgKi9cbiAgICAgICAgdHJpZ2dlcnNfOiBudWxsLFxuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7T2JqZWN0fSBfdmRvbVxuICAgICAgICAgKi9cbiAgICAgICAgX3Zkb206XG4gICAgICAgIHtjbjogW1xuICAgICAgICAgICAge3RhZzogJ2xhYmVsJywgY2xzOiBbJ25lby10ZXh0ZmllbGQtbGFiZWwnXSwgc3R5bGU6IHt9fSxcbiAgICAgICAgICAgIHt0YWc6ICdpbnB1dCcsIGNsczogWyduZW8tdGV4dGZpZWxkLWlucHV0J10sIGZsYWc6ICduZW8tcmVhbC1pbnB1dCcsIHN0eWxlOiB7fX1cbiAgICAgICAgXX1cbiAgICB9fVxuXG4gICAgLyoqXG4gICAgICogQHBhcmFtIHtPYmplY3R9IGNvbmZpZ1xuICAgICAqL1xuICAgIGNvbnN0cnVjdChjb25maWcpIHtcbiAgICAgICAgc3VwZXIuY29uc3RydWN0KGNvbmZpZyk7XG5cbiAgICAgICAgbGV0IG1lICAgICAgICAgICA9IHRoaXMsXG4gICAgICAgICAgICBkb21MaXN0ZW5lcnMgPSBtZS5kb21MaXN0ZW5lcnM7XG5cbiAgICAgICAgZG9tTGlzdGVuZXJzLnB1c2goXG4gICAgICAgICAgICB7aW5wdXQ6IG1lLm9uSW5wdXRWYWx1ZUNoYW5nZSwgc2NvcGU6IG1lfVxuICAgICAgICApO1xuXG4gICAgICAgIG1lLmRvbUxpc3RlbmVycyA9IGRvbUxpc3RlbmVycztcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBUcmlnZ2VyZWQgYWZ0ZXIgdGhlIGFwcE5hbWUgY29uZmlnIGdvdCBjaGFuZ2VkXG4gICAgICogQHBhcmFtIHtTdHJpbmd9IHZhbHVlXG4gICAgICogQHBhcmFtIHtTdHJpbmd8bnVsbH0gb2xkVmFsdWVcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICovXG4gICAgYWZ0ZXJTZXRBcHBOYW1lKHZhbHVlLCBvbGRWYWx1ZSkge1xuICAgICAgICBsZXQgbWUgPSB0aGlzO1xuXG4gICAgICAgIHN1cGVyLmFmdGVyU2V0QXBwTmFtZSh2YWx1ZSwgb2xkVmFsdWUpO1xuXG4gICAgICAgIHZhbHVlICYmIG1lLnRyaWdnZXJzPy5mb3JFYWNoKGl0ZW0gPT4ge1xuICAgICAgICAgICAgaXRlbS5hcHBOYW1lID0gdmFsdWU7XG4gICAgICAgIH0pO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFRyaWdnZXJlZCBhZnRlciB0aGUgYXV0b0NhcGl0YWxpemUgY29uZmlnIGdvdCBjaGFuZ2VkXG4gICAgICogQHBhcmFtIHtTdHJpbmd9IHZhbHVlXG4gICAgICogQHBhcmFtIHtTdHJpbmd9IG9sZFZhbHVlXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIGFmdGVyU2V0QXV0b0NhcGl0YWxpemUodmFsdWUsIG9sZFZhbHVlKSB7XG4gICAgICAgIHRoaXMuY2hhbmdlSW5wdXRFbEtleSgnYXV0b2NhcGl0YWxpemUnLCB2YWx1ZSA9PT0gJ29mZicgfHwgdmFsdWUgPT09ICdub25lJyA/IG51bGwgOiB2YWx1ZSk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogVHJpZ2dlcmVkIGFmdGVyIHRoZSBhdXRvQ29tcGxldGUgY29uZmlnIGdvdCBjaGFuZ2VkXG4gICAgICogQHBhcmFtIHtCb29sZWFufSB2YWx1ZVxuICAgICAqIEBwYXJhbSB7Qm9vbGVhbn0gb2xkVmFsdWVcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICovXG4gICAgYWZ0ZXJTZXRBdXRvQ29tcGxldGUodmFsdWUsIG9sZFZhbHVlKSB7XG4gICAgICAgIHRoaXMuY2hhbmdlSW5wdXRFbEtleSgnYXV0b2NvbXBsZXRlJywgdmFsdWUgPyBudWxsIDogJ29mZicpO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFRyaWdnZXJlZCBhZnRlciB0aGUgY2xlYXJhYmxlIGNvbmZpZyBnb3QgY2hhbmdlZFxuICAgICAqIEBwYXJhbSB7Qm9vbGVhbn0gdmFsdWVcbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IG9sZFZhbHVlXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIGFmdGVyU2V0Q2xlYXJhYmxlKHZhbHVlLCBvbGRWYWx1ZSkge1xuICAgICAgICBsZXQgbWUgPSB0aGlzLFxuICAgICAgICAgICAgdHJpZ2dlcnM7XG5cbiAgICAgICAgaWYgKHZhbHVlKSB7XG4gICAgICAgICAgICB0cmlnZ2VycyA9IG1lLnRyaWdnZXJzIHx8IFtdO1xuICAgICAgICAgICAgdHJpZ2dlcnMudW5zaGlmdChDbGVhclRyaWdnZXIpO1xuICAgICAgICAgICAgbWUudHJpZ2dlcnMgPSB0cmlnZ2VycztcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIG1lLnJlbW92ZVRyaWdnZXIoJ2NsZWFyJyk7XG4gICAgICAgIH1cbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBUcmlnZ2VyZWQgYWZ0ZXIgdGhlIGNsZWFyVG9PcmlnaW5hbFZhbHVlIGNvbmZpZyBnb3QgY2hhbmdlZFxuICAgICAqIEBwYXJhbSB7Qm9vbGVhbn0gdmFsdWVcbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IG9sZFZhbHVlXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIGFmdGVyU2V0Q2xlYXJUb09yaWdpbmFsVmFsdWUodmFsdWUsIG9sZFZhbHVlKSB7XG4gICAgICAgIHRoaXMuZmlyZSgnY2hhbmdlQ2xlYXJUb09yaWdpbmFsVmFsdWUnLCB7XG4gICAgICAgICAgICBvbGRWYWx1ZSxcbiAgICAgICAgICAgIHZhbHVlXG4gICAgICAgIH0pO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFRyaWdnZXJlZCBhZnRlciB0aGUgaGlkZUxhYmVsIGNvbmZpZyBnb3QgY2hhbmdlZFxuICAgICAqIEBwYXJhbSB7Qm9vbGVhbn0gdmFsdWVcbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IG9sZFZhbHVlXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIGFmdGVyU2V0SGlkZUxhYmVsKHZhbHVlLCBvbGRWYWx1ZSkge1xuICAgICAgICBsZXQgbWUgICA9IHRoaXMsXG4gICAgICAgICAgICB2ZG9tID0gbWUudmRvbTtcblxuICAgICAgICB2ZG9tLmNuWzBdLnJlbW92ZURvbSA9IHZhbHVlO1xuICAgICAgICBtZS5fdmRvbSA9IHZkb207IC8vIHNpbGVudCB1cGRhdGVcblxuICAgICAgICBtZS51cGRhdGVJbnB1dFdpZHRoKCk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogVHJpZ2dlcmVkIGFmdGVyIHRoZSBpZCBjb25maWcgZ290IGNoYW5nZWRcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gdmFsdWVcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gb2xkVmFsdWVcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICovXG4gICAgYWZ0ZXJTZXRJZCh2YWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgbGV0IG1lICAgICAgICA9IHRoaXMsXG4gICAgICAgICAgICBpbnB1dEVsICAgPSBtZS5nZXRJbnB1dEVsKCksXG4gICAgICAgICAgICBpbnB1dEVsSWQgPSBtZS5nZXRJbnB1dEVsSWQoKSxcbiAgICAgICAgICAgIGxhYmVsRWwgICA9IG1lLmdldExhYmVsRWwoKTtcblxuICAgICAgICBpbnB1dEVsLmlkICA9IGlucHV0RWxJZDtcbiAgICAgICAgbGFiZWxFbC5pZCAgPSBtZS5nZXRMYWJlbElkKCk7XG4gICAgICAgIGxhYmVsRWwuZm9yID0gaW5wdXRFbElkO1xuXG4gICAgICAgIC8vIHNpbGVudCB2ZG9tIHVwZGF0ZSwgdGhlIHN1cGVyIGNhbGwgd2lsbCB0cmlnZ2VyIHRoZSBlbmdpbmVcbiAgICAgICAgc3VwZXIuYWZ0ZXJTZXRJZCh2YWx1ZSwgb2xkVmFsdWUpO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFRyaWdnZXJlZCBhZnRlciB0aGUgaW5wdXRUeXBlIGNvbmZpZyBnb3QgY2hhbmdlZFxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSB2YWx1ZVxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSBvbGRWYWx1ZVxuICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgKi9cbiAgICBhZnRlclNldElucHV0VHlwZSh2YWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgdGhpcy5jaGFuZ2VJbnB1dEVsS2V5KCd0eXBlJywgdmFsdWUpO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFRyaWdnZXJlZCBhZnRlciB0aGUgbGFiZWxQb3NpdGlvbiBjb25maWcgZ290IGNoYW5nZWRcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gdmFsdWVcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gb2xkVmFsdWVcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICovXG4gICAgYWZ0ZXJTZXRMYWJlbFBvc2l0aW9uKHZhbHVlLCBvbGRWYWx1ZSkge1xuICAgICAgICBsZXQgbWUgID0gdGhpcyxcbiAgICAgICAgICAgIGNscyA9IG1lLmNscyxcbiAgICAgICAgICAgIGNlbnRlckJvcmRlckVsQ2xzLCBpc0VtcHR5LCB2ZG9tO1xuXG4gICAgICAgIE5lb0FycmF5LnJlbW92ZShjbHMsICdsYWJlbC0nICsgb2xkVmFsdWUpO1xuICAgICAgICBOZW9BcnJheS5hZGQoY2xzLCAnbGFiZWwtJyArIHZhbHVlKTtcbiAgICAgICAgbWVbb2xkVmFsdWUgPT09ICdpbmxpbmUnIHx8IHZhbHVlID09PSAnaW5saW5lJyA/ICdfY2xzJyA6ICdjbHMnXSA9IGNsczsgLy8gc2lsZW50IHVwZGF0ZSBpZiBuZWVkZWRcblxuICAgICAgICBpZiAob2xkVmFsdWUgPT09ICdpbmxpbmUnKSB7XG4gICAgICAgICAgICB2ZG9tID0gbWUudmRvbTtcblxuICAgICAgICAgICAgdmRvbS5jblswXSA9IG1lLmdldExhYmVsRWwoKTsgLy8gcmVtb3ZlIHRoZSB3cmFwcGVyXG5cbiAgICAgICAgICAgIHZkb20uY25bMF0ud2lkdGggPSBtZS5sYWJlbFdpZHRoO1xuXG4gICAgICAgICAgICBtZS5fdmRvbSA9IHZkb207IC8vIHNpbGVudCB1cGRhdGVcbiAgICAgICAgICAgIG1lLnVwZGF0ZUlucHV0V2lkdGgoKTtcbiAgICAgICAgfSBlbHNlIGlmICh2YWx1ZSA9PT0gJ2lubGluZScpIHtcbiAgICAgICAgICAgIGNlbnRlckJvcmRlckVsQ2xzID0gWyduZW8tY2VudGVyLWJvcmRlciddO1xuICAgICAgICAgICAgaXNFbXB0eSAgICAgICAgICAgPSBtZS5pc0VtcHR5KCk7XG4gICAgICAgICAgICB2ZG9tICAgICAgICAgICAgICA9IG1lLnZkb207XG5cbiAgICAgICAgICAgIGlmICghaXNFbXB0eSkge1xuICAgICAgICAgICAgICAgIGNlbnRlckJvcmRlckVsQ2xzLnB1c2goJ25lby1mbG9hdC1hYm92ZScpO1xuICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICBkZWxldGUgdmRvbS5jblswXS53aWR0aDtcblxuICAgICAgICAgICAgdmRvbS5jblswXSA9IHtcbiAgICAgICAgICAgICAgICBjbHM6IFsnbmVvLWxhYmVsLXdyYXBwZXInXSxcbiAgICAgICAgICAgICAgICBjbiA6IFt7XG4gICAgICAgICAgICAgICAgICAgIGNsczogWyduZW8tbGVmdC1ib3JkZXInXVxuICAgICAgICAgICAgICAgIH0sIHtcbiAgICAgICAgICAgICAgICAgICAgY2xzOiBjZW50ZXJCb3JkZXJFbENscyxcbiAgICAgICAgICAgICAgICAgICAgY24gOiBbdmRvbS5jblswXV1cbiAgICAgICAgICAgICAgICB9LCB7XG4gICAgICAgICAgICAgICAgICAgIGNsczogWyduZW8tcmlnaHQtYm9yZGVyJ11cbiAgICAgICAgICAgICAgICB9XVxuICAgICAgICAgICAgfTtcblxuICAgICAgICAgICAgbWUuX3Zkb20gPSB2ZG9tOyAvLyBzaWxlbnQgdXBkYXRlXG4gICAgICAgICAgICBtZS51cGRhdGVJbnB1dFdpZHRoKCk7XG5cbiAgICAgICAgICAgIGlmICghaXNFbXB0eSkge1xuICAgICAgICAgICAgICAgIHNldFRpbWVvdXQoKCkgPT4ge1xuICAgICAgICAgICAgICAgICAgICBtZS51cGRhdGVDZW50ZXJCb3JkZXJFbFdpZHRoKGZhbHNlKTtcbiAgICAgICAgICAgICAgICB9LCAyMCk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBUcmlnZ2VyZWQgYWZ0ZXIgdGhlIGxhYmVsVGV4dCBjb25maWcgZ290IGNoYW5nZWRcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gdmFsdWVcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gb2xkVmFsdWVcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICovXG4gICAgYWZ0ZXJTZXRMYWJlbFRleHQodmFsdWUsIG9sZFZhbHVlKSB7XG4gICAgICAgIGxldCBtZSAgICAgID0gdGhpcyxcbiAgICAgICAgICAgIGlzRW1wdHkgPSBtZS5pc0VtcHR5KCksXG4gICAgICAgICAgICB2ZG9tICAgID0gbWUudmRvbTtcblxuICAgICAgICBtZS5nZXRMYWJlbEVsKCkuaW5uZXJIVE1MID0gdmFsdWU7XG5cbiAgICAgICAgaWYgKG1lLmhpZGVMYWJlbCkge1xuICAgICAgICAgICAgbWUuX3Zkb20gPSB2ZG9tOyAvLyBzaWxlbnQgdXBkYXRlXG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICBpZiAobWUubGFiZWxQb3NpdGlvbiA9PT0gJ2lubGluZScpIHtcbiAgICAgICAgICAgICAgICBpZiAoIWlzRW1wdHkpIHtcbiAgICAgICAgICAgICAgICAgICAgZGVsZXRlIG1lLmdldENlbnRlckJvcmRlckVsKCkud2lkdGg7XG4gICAgICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICAgICAgbWUucHJvbWlzZVZkb21VcGRhdGUodmRvbSkudGhlbigoKSA9PiB7XG4gICAgICAgICAgICAgICAgICAgIG1lLnVwZGF0ZUNlbnRlckJvcmRlckVsV2lkdGgoaXNFbXB0eSk7XG4gICAgICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICAgIG1lLnZkb20gPSB2ZG9tO1xuICAgICAgICAgICAgfVxuICAgICAgICB9XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogVHJpZ2dlcmVkIGFmdGVyIHRoZSBsYWJlbFdpZHRoIGNvbmZpZyBnb3QgY2hhbmdlZFxuICAgICAqIEBwYXJhbSB7TnVtYmVyfFN0cmluZ30gdmFsdWVcbiAgICAgKiBAcGFyYW0ge051bWJlcnxTdHJpbmd9IG9sZFZhbHVlXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIGFmdGVyU2V0TGFiZWxXaWR0aCh2YWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgaWYgKHRoaXMubGFiZWxQb3NpdGlvbiAhPT0gJ2lubGluZScpIHtcbiAgICAgICAgICAgIGxldCBtZSAgICA9IHRoaXMsXG4gICAgICAgICAgICAgICAgdmRvbSAgPSBtZS52ZG9tLFxuICAgICAgICAgICAgICAgIGxhYmVsID0gdmRvbS5jblswXTtcblxuICAgICAgICAgICAgbGFiZWwud2lkdGggPSB2YWx1ZTtcblxuICAgICAgICAgICAgbWUuX3Zkb20gPSB2ZG9tOyAvLyBzaWxlbnQgdXBkYXRlXG5cbiAgICAgICAgICAgICFtZS5oaWRlTGFiZWwgJiYgbWUudXBkYXRlSW5wdXRXaWR0aCgpO1xuICAgICAgICB9XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogVHJpZ2dlcmVkIGFmdGVyIHRoZSBtb3VudGVkIGNvbmZpZyBnb3QgY2hhbmdlZFxuICAgICAqIEBwYXJhbSB7Qm9vbGVhbn0gdmFsdWVcbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IG9sZFZhbHVlXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIGFmdGVyU2V0TW91bnRlZCh2YWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgc3VwZXIuYWZ0ZXJTZXRNb3VudGVkKHZhbHVlLCBvbGRWYWx1ZSk7XG5cbiAgICAgICAgbGV0IG1lID0gdGhpcztcblxuICAgICAgICBpZiAob2xkVmFsdWUgIT09IHVuZGVmaW5lZCkge1xuICAgICAgICAgICAgbGV0IHRyaWdnZXJzID0gbWUudHJpZ2dlcnMgfHwgW10sXG4gICAgICAgICAgICAgICAgaSAgICAgICAgPSAwLFxuICAgICAgICAgICAgICAgIGxlbiAgICAgID0gdHJpZ2dlcnMubGVuZ3RoO1xuXG4gICAgICAgICAgICBmb3IgKDsgaSA8IGxlbjsgaSsrKSB7XG4gICAgICAgICAgICAgICAgaWYgKCF0cmlnZ2Vyc1tpXS52ZG9tLnJlbW92ZURvbSkge1xuICAgICAgICAgICAgICAgICAgICB0cmlnZ2Vyc1tpXS5tb3VudGVkID0gdmFsdWU7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICBpZiAobWUubGFiZWxQb3NpdGlvbiA9PT0gJ2lubGluZScpIHtcbiAgICAgICAgICAgICAgICBpZiAodmFsdWUpIHtcbiAgICAgICAgICAgICAgICAgICAgbWUudXBkYXRlQ2VudGVyQm9yZGVyRWxXaWR0aCgpO1xuICAgICAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgICAgICAgIGRlbGV0ZSBtZS5nZXRDZW50ZXJCb3JkZXJFbCgpLndpZHRoO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFRyaWdnZXJlZCBhZnRlciB0aGUgcGxhY2Vob2xkZXJUZXh0IGNvbmZpZyBnb3QgY2hhbmdlZFxuICAgICAqIEBwYXJhbSB7U3RyaW5nfG51bGx9IHZhbHVlXG4gICAgICogQHBhcmFtIHtTdHJpbmd8bnVsbH0gb2xkVmFsdWVcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICovXG4gICAgYWZ0ZXJTZXRQbGFjZWhvbGRlclRleHQodmFsdWUsIG9sZFZhbHVlKSB7XG4gICAgICAgIHRoaXMuY2hhbmdlSW5wdXRFbEtleSgncGxhY2Vob2xkZXInLCB2YWx1ZSA9PT0gJycgPyBudWxsIDogdmFsdWUpO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFRyaWdnZXJlZCBhZnRlciB0aGUgcmVxdWlyZWQgY29uZmlnIGdvdCBjaGFuZ2VkXG4gICAgICogQHBhcmFtIHtCb29sZWFufSB2YWx1ZVxuICAgICAqIEBwYXJhbSB7Qm9vbGVhbn0gb2xkVmFsdWVcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICovXG4gICAgYWZ0ZXJTZXRSZXF1aXJlZCh2YWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgdGhpcy5jaGFuZ2VJbnB1dEVsS2V5KCdyZXF1aXJlZCcsIHZhbHVlID8gdmFsdWUgOiBudWxsKTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBUcmlnZ2VyZWQgYWZ0ZXIgdGhlIHNwZWxsQ2hlY2sgY29uZmlnIGdvdCBjaGFuZ2VkXG4gICAgICogQHBhcmFtIHtCb29sZWFufG51bGx9IHZhbHVlXG4gICAgICogQHBhcmFtIHtCb29sZWFufG51bGx9IG9sZFZhbHVlXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIGFmdGVyU2V0U3BlbGxDaGVjayh2YWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgdGhpcy5jaGFuZ2VJbnB1dEVsS2V5KCdzcGVsbGNoZWNrJywgTmVvLmlzQm9vbGVhbih2YWx1ZSkgPyB2YWx1ZSA6IG51bGwpO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFRyaWdnZXJlZCBhZnRlciB0aGUgdHJpZ2dlcnMgY29uZmlnIGdvdCBjaGFuZ2VkXG4gICAgICogQHBhcmFtIHtPYmplY3RbXX0gdmFsdWVcbiAgICAgKiBAcGFyYW0ge09iamVjdFtdfSBvbGRWYWx1ZVxuICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgKi9cbiAgICBhZnRlclNldFRyaWdnZXJzKHZhbHVlLCBvbGRWYWx1ZSkge1xuICAgICAgICBsZXQgbWUgICAgICAgICAgID0gdGhpcyxcbiAgICAgICAgICAgIHZkb20gICAgICAgICA9IG1lLnZkb20sXG4gICAgICAgICAgICBpbnB1dEVsICAgICAgPSB2ZG9tLmNuWzFdLCAvLyBpbnB1dEVsIG9yIGlucHV0V3JhcHBlckVsXG4gICAgICAgICAgICBwcmVUcmlnZ2VycyAgPSBbXSxcbiAgICAgICAgICAgIHBvc3RUcmlnZ2VycyA9IFtdLFxuICAgICAgICAgICAgd2lkdGg7XG5cbiAgICAgICAgaWYgKG9sZFZhbHVlKSB7XG4gICAgICAgICAgICBvbGRWYWx1ZS5mb3JFYWNoKGl0ZW0gPT4ge1xuICAgICAgICAgICAgICAgIGlmICghbWUuZ2V0VHJpZ2dlcihpdGVtLnR5cGUpKSB7XG4gICAgICAgICAgICAgICAgICAgIGl0ZW0uZGVzdHJveSgpO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0pO1xuICAgICAgICB9XG5cbiAgICAgICAgaWYgKHZhbHVlLmxlbmd0aCA+IDApIHtcbiAgICAgICAgICAgIHZhbHVlLmZvckVhY2goaXRlbSA9PiB7XG4gICAgICAgICAgICAgICAgaWYgKGl0ZW0uYWxpZ24gPT09ICdzdGFydCcpIHtcbiAgICAgICAgICAgICAgICAgICAgcHJlVHJpZ2dlcnMucHVzaChpdGVtKTtcbiAgICAgICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICAgICAgICBwb3N0VHJpZ2dlcnMucHVzaChpdGVtKTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9KTtcblxuICAgICAgICAgICAgcG9zdFRyaWdnZXJzLnNvcnQoKGEsIGIpID0+IGIud2VpZ2h0IC0gYS53ZWlnaHQpOyAvLyBERVNDXG4gICAgICAgICAgICBwcmVUcmlnZ2VycyAuc29ydCgoYSwgYikgPT4gYS53ZWlnaHQgLSBiLndlaWdodCk7IC8vIEFTQ1xuXG4gICAgICAgICAgICBwb3N0VHJpZ2dlcnMgPSBwb3N0VHJpZ2dlcnMubWFwKGEgPT4gYS52ZG9tKTtcbiAgICAgICAgICAgIHByZVRyaWdnZXJzICA9IHByZVRyaWdnZXJzIC5tYXAoYSA9PiBhLnZkb20pO1xuXG4gICAgICAgICAgICBpZiAoaW5wdXRFbC50YWcgPT09ICdpbnB1dCcpIHtcbiAgICAgICAgICAgICAgICAvLyB3cmFwIHRoZSBpbnB1dCB0YWdcbiAgICAgICAgICAgICAgICB2ZG9tLmNuWzFdID0ge1xuICAgICAgICAgICAgICAgICAgICBjbHMgIDogWyduZW8taW5wdXQtd3JhcHBlciddLFxuICAgICAgICAgICAgICAgICAgICBjbiAgIDogWy4uLnByZVRyaWdnZXJzLCBpbnB1dEVsLCAuLi5wb3N0VHJpZ2dlcnNdLFxuICAgICAgICAgICAgICAgICAgICBpZCAgIDogbWUuZ2V0SW5wdXRXcmFwcGVySWQoKSxcbiAgICAgICAgICAgICAgICAgICAgd2lkdGg6IGlucHV0RWwud2lkdGhcbiAgICAgICAgICAgICAgICB9O1xuXG4gICAgICAgICAgICAgICAgZGVsZXRlIGlucHV0RWwud2lkdGg7XG4gICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICAgIGlucHV0RWwuY24gPSBbLi4ucHJlVHJpZ2dlcnMsIG1lLmdldElucHV0RWwoKSwgLi4ucG9zdFRyaWdnZXJzXTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIGlmIChpbnB1dEVsLnRhZyAhPT0gJ2lucHV0Jykge1xuICAgICAgICAgICAgICAgIC8vIHJlcGxhY2luZyB0aGUgaW5wdXQgd3JhcHBlciBkaXYgd2l0aCB0aGUgaW5wdXQgdGFnXG4gICAgICAgICAgICAgICAgd2lkdGggPSBpbnB1dEVsLndpZHRoO1xuICAgICAgICAgICAgICAgIHZkb20uY25bMV0gPSBtZS5nZXRJbnB1dEVsKCk7XG4gICAgICAgICAgICAgICAgdmRvbS5jblsxXS53aWR0aCA9IHdpZHRoO1xuICAgICAgICAgICAgfVxuICAgICAgICB9XG5cbiAgICAgICAgbWUucHJvbWlzZVZkb21VcGRhdGUoKS50aGVuKCgpID0+IHtcbiAgICAgICAgICAgIG1lLnVwZGF0ZVRyaWdnZXJWbm9kZXMoKTtcbiAgICAgICAgfSk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogVHJpZ2dlcmVkIGFmdGVyIHRoZSB2YWx1ZSBjb25maWcgZ290IGNoYW5nZWRcbiAgICAgKiB0b2RvOiBhZGQgdmFsaWRhdGlvbiBsb2dpY1xuICAgICAqIEBwYXJhbSB7U3RyaW5nfSB2YWx1ZVxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSBvbGRWYWx1ZVxuICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgKi9cbiAgICBhZnRlclNldFZhbHVlKHZhbHVlLCBvbGRWYWx1ZSkge1xuICAgICAgICBsZXQgbWUgICA9IHRoaXMsXG4gICAgICAgICAgICB2ZG9tID0gbWUudmRvbTtcblxuICAgICAgICBtZS5nZXRJbnB1dEVsKCkudmFsdWUgPSB2YWx1ZTtcblxuICAgICAgICBpZiAoISF2YWx1ZSAhPT0gISFvbGRWYWx1ZSkgeyAvLyBjaGFuZ2UgZnJvbSBlbXB0eSB0byBub24gZW1wdHlcbiAgICAgICAgICAgIE5lb0FycmF5W3ZhbHVlICYmIHZhbHVlLnRvU3RyaW5nKCkubGVuZ3RoID4gMCA/ICdhZGQnIDogJ3JlbW92ZSddKG1lLl9jbHMsICduZW8taGFzLWNvbnRlbnQnKTtcbiAgICAgICAgfVxuXG4gICAgICAgIE5lb0FycmF5W21lLm9yaWdpbmFsQ29uZmlnLnZhbHVlICE9PSB2YWx1ZSA/ICdhZGQnIDogJ3JlbW92ZSddKG1lLl9jbHMsICduZW8taXMtZGlydHknKTtcblxuICAgICAgICBtZS52ZG9tID0gdmRvbTtcblxuICAgICAgICBzdXBlci5hZnRlclNldFZhbHVlKHZhbHVlLCBvbGRWYWx1ZSk7IC8vIGZpcmVzIHRoZSBjaGFuZ2UgZXZlbnRcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBUcmlnZ2VyZWQgYWZ0ZXIgdGhlIHdpZHRoIGNvbmZpZyBnb3QgY2hhbmdlZFxuICAgICAqIEBwYXJhbSB7TnVtYmVyfFN0cmluZ30gdmFsdWVcbiAgICAgKiBAcGFyYW0ge051bWJlcnxTdHJpbmd9IG9sZFZhbHVlXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIGFmdGVyU2V0V2lkdGgodmFsdWUsIG9sZFZhbHVlKSB7XG4gICAgICAgIHN1cGVyLmFmdGVyU2V0V2lkdGgodmFsdWUsIG9sZFZhbHVlKTtcbiAgICAgICAgdGhpcy51cGRhdGVJbnB1dFdpZHRoKCk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogUmV0dXJuIGEgc2hhbGxvdyBjb3B5IG9mIHRoZSB0cmlnZ2VycyBjb25maWdcbiAgICAgKiBAcGFyYW0ge0FycmF5fG51bGx9IHZhbHVlXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIGJlZm9yZUdldFRyaWdnZXJzKHZhbHVlKSB7XG4gICAgICAgIGlmIChBcnJheS5pc0FycmF5KHZhbHVlKSkge1xuICAgICAgICAgICAgcmV0dXJuIFsuLi52YWx1ZV07XG4gICAgICAgIH1cblxuICAgICAgICByZXR1cm4gdmFsdWU7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogVHJpZ2dlcmVkIGJlZm9yZSB0aGUgYXV0b0NhcGl0YWxpemUgY29uZmlnIGdldHMgY2hhbmdlZFxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSB2YWx1ZVxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSBvbGRWYWx1ZVxuICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgKiBAcmV0dXJucyB7U3RyaW5nfVxuICAgICAqL1xuICAgIGJlZm9yZVNldEF1dG9DYXBpdGFsaXplKHZhbHVlLCBvbGRWYWx1ZSkge1xuICAgICAgICByZXR1cm4gdGhpcy5iZWZvcmVTZXRFbnVtVmFsdWUodmFsdWUsIG9sZFZhbHVlLCAnYXV0b0NhcGl0YWxpemUnLCAnYXV0b0NhcGl0YWxpemVWYWx1ZXMnKTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBUcmlnZ2VyZWQgYmVmb3JlIHRoZSBsYWJlbFBvc2l0aW9uIGNvbmZpZyBnZXRzIGNoYW5nZWRcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gdmFsdWVcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gb2xkVmFsdWVcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICogQHJldHVybnMge1N0cmluZ31cbiAgICAgKi9cbiAgICBiZWZvcmVTZXRMYWJlbFBvc2l0aW9uKHZhbHVlLCBvbGRWYWx1ZSkge1xuICAgICAgICByZXR1cm4gdGhpcy5iZWZvcmVTZXRFbnVtVmFsdWUodmFsdWUsIG9sZFZhbHVlLCAnbGFiZWxQb3NpdGlvbicpO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFRyaWdnZXJlZCBiZWZvcmUgdGhlIHRyaWdnZXJzIGNvbmZpZyBnZXRzIGNoYW5nZWRcbiAgICAgKiBAcGFyYW0ge09iamVjdHxPYmplY3RbXX0gdmFsdWVcbiAgICAgKiBAcGFyYW0ge09iamVjdFtdfSBvbGRWYWx1ZVxuICAgICAqIEByZXR1cm5zIHtPYmplY3RbXX0gdGhlIHBhcnNlZCB0cmlnZ2VycyBjb25maWdcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICogQHJldHVybnMge09iamVjdHxPYmplY3RbXX1cbiAgICAgKi9cbiAgICBiZWZvcmVTZXRUcmlnZ2Vycyh2YWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgaWYgKCF2YWx1ZSkge1xuICAgICAgICAgICAgdmFsdWUgPSBbXTtcbiAgICAgICAgfSBlbHNlIGlmICghQXJyYXkuaXNBcnJheSh2YWx1ZSkpIHtcbiAgICAgICAgICAgIHZhbHVlID0gW3ZhbHVlXTtcbiAgICAgICAgfVxuXG4gICAgICAgIGxldCBtZSA9IHRoaXM7XG5cbiAgICAgICAgdmFsdWUuZm9yRWFjaCgoaXRlbSwgaW5kZXgpID0+IHtcbiAgICAgICAgICAgIGlmIChpdGVtLmlzQ2xhc3MpIHtcbiAgICAgICAgICAgICAgICB2YWx1ZVtpbmRleF0gPSBOZW8uY3JlYXRlKGl0ZW0sIHtcbiAgICAgICAgICAgICAgICAgICAgYXBwTmFtZTogbWUuYXBwTmFtZSxcbiAgICAgICAgICAgICAgICAgICAgaWQgICAgIDogbWUuZ2V0VHJpZ2dlcklkKGl0ZW0ucHJvdG90eXBlLnR5cGUpLFxuICAgICAgICAgICAgICAgICAgICBmaWVsZCAgOiBtZVxuICAgICAgICAgICAgICAgIH0pO1xuICAgICAgICAgICAgfSBlbHNlIGlmICghKGl0ZW0gaW5zdGFuY2VvZiBCYXNlVHJpZ2dlcikpIHtcbiAgICAgICAgICAgICAgICBpZiAoIWl0ZW0ubW9kdWxlICYmICFpdGVtLm50eXBlKSB7XG4gICAgICAgICAgICAgICAgICAgIGl0ZW0ubnR5cGUgPSAndHJpZ2dlcic7XG4gICAgICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICAgICAgaWYgKGl0ZW0ubW9kdWxlKSB7XG4gICAgICAgICAgICAgICAgICAgIGl0ZW0uY2xhc3NOYW1lID0gaXRlbS5tb2R1bGUucHJvdG90eXBlLmNsYXNzTmFtZTtcbiAgICAgICAgICAgICAgICAgICAgaXRlbS5pZCAgICAgICAgPSBtZS5nZXRUcmlnZ2VySWQoaXRlbS5tb2R1bGUucHJvdG90eXBlLnR5cGUpO1xuICAgICAgICAgICAgICAgIH1cblxuICAgICAgICAgICAgICAgIHZhbHVlW2luZGV4XSA9IE5lb1tpdGVtLmNsYXNzTmFtZSA/ICdjcmVhdGUnIDogJ250eXBlJ10oe1xuICAgICAgICAgICAgICAgICAgICAuLi5pdGVtLFxuICAgICAgICAgICAgICAgICAgICBhcHBOYW1lOiBtZS5hcHBOYW1lLFxuICAgICAgICAgICAgICAgICAgICBmaWVsZCAgOiBtZVxuICAgICAgICAgICAgICAgIH0pO1xuICAgICAgICAgICAgfVxuICAgICAgICB9KTtcblxuICAgICAgICByZXR1cm4gdmFsdWU7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQ2hhbmdlcyB0aGUgdmFsdWUgb2YgYSBpbnB1dEVsIHZkb20gb2JqZWN0IGF0dHJpYnV0ZSBvciByZW1vdmVzIGl0IGluIGNhc2UgaXQgaGFzIG5vIHZhbHVlXG4gICAgICogQHBhcmFtIHtTdHJpbmd9IGtleVxuICAgICAqIEBwYXJhbSB7QXJyYXl8TnVtYmVyfE9iamVjdHxTdHJpbmd8bnVsbH0gdmFsdWVcbiAgICAgKi9cbiAgICBjaGFuZ2VJbnB1dEVsS2V5KGtleSwgdmFsdWUpIHtcbiAgICAgICAgbGV0IG1lICAgPSB0aGlzLFxuICAgICAgICAgICAgdmRvbSA9IG1lLnZkb207XG5cbiAgICAgICAgaWYgKHZhbHVlIHx8IE5lby5pc0Jvb2xlYW4odmFsdWUpIHx8IHZhbHVlID09PSAwKSB7XG4gICAgICAgICAgICBtZS5nZXRJbnB1dEVsKClba2V5XSA9IHZhbHVlO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgZGVsZXRlIG1lLmdldElucHV0RWwoKVtrZXldO1xuICAgICAgICB9XG5cbiAgICAgICAgbWUudmRvbSA9IHZkb207XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogUmVzZXRzIHRoZSBmaWVsZCB0byBpdHMgb3JpZ2luYWwgdmFsdWUgb3IgbnVsbCBkZXBlbmRpbmcgb24gdGhlIGNsZWFyVG9PcmlnaW5hbFZhbHVlIGNvbmZpZ1xuICAgICAqL1xuICAgIGNsZWFyKCkge1xuICAgICAgICBsZXQgbWUgPSB0aGlzO1xuXG4gICAgICAgIG1lLnZhbHVlID0gbWUuY2xlYXJUb09yaWdpbmFsVmFsdWUgPyBtZS5vcmlnaW5hbENvbmZpZy52YWx1ZSA6IG51bGw7XG4gICAgICAgIG1lLmZpcmUoJ2NsZWFyJyk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQ2FsbHMgZm9jdXMoKSBvbiB0aGUgaW5wdXRFbCBub2RlIGluc3RlYWRcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gaWQ9dGhpcy5pZFxuICAgICAqIEBvdmVycmlkZVxuICAgICAqL1xuICAgIGZvY3VzKGlkPXRoaXMuaWQpIHtcbiAgICAgICAgc3VwZXIuZm9jdXModGhpcy5nZXRJbnB1dEVsSWQoKSk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQHJldHVybnMge09iamVjdHxudWxsfVxuICAgICAqL1xuICAgIGdldENlbnRlckJvcmRlckVsKCkge1xuICAgICAgICBsZXQgZWwgPSBWRG9tVXRpbC5maW5kVmRvbUNoaWxkKHRoaXMudmRvbSwge2NsczogJ25lby1jZW50ZXItYm9yZGVyJ30pO1xuICAgICAgICByZXR1cm4gZWw/LnZkb207XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQHJldHVybnMge09iamVjdHxudWxsfVxuICAgICAqL1xuICAgIGdldElucHV0RWwoKSB7XG4gICAgICAgIGxldCBlbCA9IFZEb21VdGlsLmZpbmRWZG9tQ2hpbGQodGhpcy52ZG9tLCB7ZmxhZzogJ25lby1yZWFsLWlucHV0J30pO1xuICAgICAgICByZXR1cm4gZWw/LnZkb207XG4gICAgfVxuICAgIC8qKlxuICAgICAqIEByZXR1cm5zIHtTdHJpbmd9XG4gICAgICovXG4gICAgZ2V0SW5wdXRFbElkKCkge1xuICAgICAgICByZXR1cm4gYCR7dGhpcy5pZH1fX2lucHV0YDtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBDYWxjdWxhdGVzIHRoZSBuZXcgaW5wdXRXaWR0aCBiYXNlZCBvbiB0aGUgbGFiZWxXaWR0aCAmIHRvdGFsIHdpZHRoXG4gICAgICogQHJldHVybnMge051bWJlcnxudWxsfSBudWxsIGluIGNhc2UgdGhpcy53aWR0aCBpcyB1bmtub3duXG4gICAgICovXG4gICAgZ2V0SW5wdXRXaWR0aCgpIHtcbiAgICAgICAgbGV0IG1lICAgICAgICAgID0gdGhpcyxcbiAgICAgICAgICAgIGlnbm9yZUxhYmVsID0gbWUuaGlkZUxhYmVsIHx8IG1lLmxhYmVsUG9zaXRpb24gPT09ICdib3R0b20nIHx8IG1lLmxhYmVsUG9zaXRpb24gPT09ICdpbmxpbmUnIHx8IG1lLmxhYmVsUG9zaXRpb24gPT09ICd0b3AnLFxuICAgICAgICAgICAgbGFiZWxXaWR0aCAgPSBpZ25vcmVMYWJlbCA/IDAgOiBtZS5sYWJlbFdpZHRoLFxuICAgICAgICAgICAgd2lkdGggICAgICAgPSBtZS53aWR0aDtcblxuICAgICAgICBpZiAobGFiZWxXaWR0aCAmJiB3aWR0aCkge1xuICAgICAgICAgICAgcmV0dXJuIHBhcnNlSW50KHdpZHRoKSAtIHBhcnNlSW50KGxhYmVsV2lkdGgpO1xuICAgICAgICB9IGVsc2UgaWYgKHdpZHRoKSB7XG4gICAgICAgICAgICByZXR1cm4gd2lkdGg7XG4gICAgICAgIH1cblxuICAgICAgICByZXR1cm4gbnVsbDtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBAcmV0dXJucyB7U3RyaW5nfVxuICAgICAqL1xuICAgIGdldElucHV0V3JhcHBlcklkKCkge1xuICAgICAgICByZXR1cm4gYCR7dGhpcy5pZH1fX2lucHV0LXdyYXBwZXJgO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIEByZXR1cm5zIHtPYmplY3R8bnVsbH1cbiAgICAgKi9cbiAgICBnZXRMYWJlbEVsKCkge1xuICAgICAgICBsZXQgZWwgPSBWRG9tVXRpbC5maW5kVmRvbUNoaWxkKHRoaXMudmRvbSwge3RhZzogJ2xhYmVsJ30pO1xuICAgICAgICByZXR1cm4gZWw/LnZkb207XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQHJldHVybnMge1N0cmluZ31cbiAgICAgKi9cbiAgICBnZXRMYWJlbElkKCkge1xuICAgICAgICByZXR1cm4gYCR7dGhpcy5pZH1fX2xhYmVsYDtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gdHlwZVxuICAgICAqIEByZXR1cm5zIHtOZW8uZm9ybS5maWVsZC50cmlnZ2VyLkJhc2V8bnVsbH1cbiAgICAgKi9cbiAgICBnZXRUcmlnZ2VyKHR5cGUpIHtcbiAgICAgICAgbGV0IG1lICAgICAgID0gdGhpcyxcbiAgICAgICAgICAgIHRyaWdnZXJzID0gbWUudHJpZ2dlcnMgfHwgW10sXG4gICAgICAgICAgICBpICAgICAgICA9IDAsXG4gICAgICAgICAgICBsZW4gICAgICA9IHRyaWdnZXJzLmxlbmd0aDtcblxuICAgICAgICBmb3IgKDsgaSA8IGxlbjsgaSsrKSB7XG4gICAgICAgICAgICBpZiAodHJpZ2dlcnNbaV0udHlwZSA9PT0gdHlwZSkge1xuICAgICAgICAgICAgICAgIHJldHVybiB0cmlnZ2Vyc1tpXTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuXG4gICAgICAgIHJldHVybiBudWxsO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSBpZFxuICAgICAqIEByZXR1cm5zIHtOZW8uZm9ybS5maWVsZC50cmlnZ2VyLkJhc2V8bnVsbH1cbiAgICAgKi9cbiAgICBnZXRUcmlnZ2VyQnlJZChpZCkge1xuICAgICAgICBsZXQgbWUgICAgICAgPSB0aGlzLFxuICAgICAgICAgICAgdHJpZ2dlcnMgPSBtZS50cmlnZ2VycyB8fCBbXSxcbiAgICAgICAgICAgIGkgICAgICAgID0gMCxcbiAgICAgICAgICAgIGxlbiAgICAgID0gdHJpZ2dlcnMubGVuZ3RoO1xuXG4gICAgICAgIGZvciAoOyBpIDwgbGVuOyBpKyspIHtcbiAgICAgICAgICAgIGlmICh0cmlnZ2Vyc1tpXS5pZCA9PT0gaWQpIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gdHJpZ2dlcnNbaV07XG4gICAgICAgICAgICB9XG4gICAgICAgIH1cblxuICAgICAgICByZXR1cm4gbnVsbDtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gdHlwZVxuICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgKiBAcmV0dXJucyB7U3RyaW5nfSBUaGUgdHJpZ2dlciBub2RlIGlkXG4gICAgICovXG4gICAgZ2V0VHJpZ2dlcklkKHR5cGUpIHtcbiAgICAgICAgcmV0dXJuIHRoaXMuaWQgKyAnLXRyaWdnZXItJyArIHR5cGU7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogRmluZHMgYSB0cmlnZ2VyIGJ5IGEgZ2l2ZW4gdHlwZSBjb25maWdcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gdHlwZVxuICAgICAqIEByZXR1cm5zIHtCb29sZWFufVxuICAgICAqL1xuICAgIGhhc1RyaWdnZXIodHlwZSkge1xuICAgICAgICBsZXQgdHJpZ2dlcnMgPSB0aGlzLnRyaWdnZXJzIHx8IFtdLFxuICAgICAgICAgICAgaSAgICAgICAgPSAwLFxuICAgICAgICAgICAgbGVuICAgICAgPSB0cmlnZ2Vycy5sZW5ndGg7XG5cbiAgICAgICAgZm9yICg7IGkgPCBsZW47IGkrKykge1xuICAgICAgICAgICAgaWYgKHRyaWdnZXJzW2ldLnR5cGUgPT09IHR5cGUpIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gdHJ1ZTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuXG4gICAgICAgIHJldHVybiBmYWxzZTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBAcmV0dXJucyB7Qm9vbGVhbn1cbiAgICAgKi9cbiAgICBpc0VtcHR5KCkge1xuICAgICAgICByZXR1cm4gISh0aGlzLnZhbHVlPy50b1N0cmluZygpLmxlbmd0aCA+IDApO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIEByZXR1cm5zIHtCb29sZWFufVxuICAgICAqL1xuICAgIGlzVmFsaWQoKSB7XG4gICAgICAgIGxldCBtZSA9IHRoaXM7XG5cbiAgICAgICAgaWYgKG1lLnJlcXVpcmVkICYmICghbWUudmFsdWUgfHwgbWUudmFsdWU/Lmxlbmd0aCA8IDEpKSB7XG4gICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgIH1cblxuICAgICAgICByZXR1cm4gc3VwZXIuaXNWYWxpZCgpO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIEBwYXJhbSB7T2JqZWN0fSBjb25maWdcbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IFtwcmV2ZW50T3JpZ2luYWxDb25maWddIFRydWUgcHJldmVudHMgdGhlIGluc3RhbmNlIGZyb20gZ2V0dGluZyBhbiBvcmlnaW5hbENvbmZpZyBwcm9wZXJ0eVxuICAgICAqIEByZXR1cm5zIHtPYmplY3R9IGNvbmZpZ1xuICAgICAqL1xuICAgIG1lcmdlQ29uZmlnKC4uLmFyZ3MpIHtcbiAgICAgICAgbGV0IG1lICAgICAgID0gdGhpcyxcbiAgICAgICAgICAgIGNvbmZpZyAgID0gc3VwZXIubWVyZ2VDb25maWcoLi4uYXJncyksXG4gICAgICAgICAgICB0cmlnZ2VycyA9IGNvbmZpZy50cmlnZ2VycyB8fCBtZS50cmlnZ2VycztcblxuICAgICAgICBtZVt0cmlnZ2VycyA/ICd0cmlnZ2VycycgOiAnX3RyaWdnZXJzJ10gPSB0cmlnZ2VycztcblxuICAgICAgICBkZWxldGUgY29uZmlnLnRyaWdnZXJzO1xuICAgICAgICByZXR1cm4gY29uZmlnO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIEBwYXJhbSB7T2JqZWN0fSBkYXRhXG4gICAgICogQHBhcmFtIHtPYmplY3RbXX0gZGF0YS5wYXRoXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIG9uRm9jdXNFbnRlcihkYXRhKSB7XG4gICAgICAgIGxldCBtZSAgPSB0aGlzLFxuICAgICAgICAgICAgY2xzID0gbWUuY2xzLFxuICAgICAgICAgICAgdmRvbTtcblxuICAgICAgICBOZW9BcnJheS5hZGQoY2xzLCAnbmVvLWZvY3VzJyk7XG4gICAgICAgIG1lLmNscyA9IGNscztcblxuICAgICAgICBpZiAobWUubGFiZWxQb3NpdGlvbiA9PT0gJ2lubGluZScpIHtcbiAgICAgICAgICAgIGlmIChtZS5jZW50ZXJCb3JkZXJFbFdpZHRoKSB7XG4gICAgICAgICAgICAgICAgdmRvbSA9IG1lLnZkb207XG4gICAgICAgICAgICAgICAgbWUuZ2V0Q2VudGVyQm9yZGVyRWwoKS53aWR0aCA9IG1lLmNlbnRlckJvcmRlckVsV2lkdGg7XG4gICAgICAgICAgICAgICAgbWUudmRvbSA9IHZkb207XG4gICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICAgIG1lLnVwZGF0ZUNlbnRlckJvcmRlckVsV2lkdGgoZmFsc2UpO1xuICAgICAgICAgICAgfVxuICAgICAgICB9XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQHBhcmFtIHtPYmplY3R9IGRhdGFcbiAgICAgKiBAcGFyYW0ge09iamVjdFtdfSBkYXRhLm9sZFBhdGhcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICovXG4gICAgb25Gb2N1c0xlYXZlKGRhdGEpIHtcbiAgICAgICAgbGV0IG1lICAgICAgICAgICAgID0gdGhpcyxcbiAgICAgICAgICAgIGNlbnRlckJvcmRlckVsID0gbWUuZ2V0Q2VudGVyQm9yZGVyRWwoKSwgLy8gbGFiZWxQb3NpdGlvbjogJ2lubGluZSdcbiAgICAgICAgICAgIGNscyAgICAgICAgICAgID0gbWUuY2xzLFxuICAgICAgICAgICAgdmRvbTtcblxuICAgICAgICBOZW9BcnJheS5yZW1vdmUoY2xzLCAnbmVvLWZvY3VzJyk7XG5cbiAgICAgICAgaWYgKGNlbnRlckJvcmRlckVsICYmIG1lLmlzRW1wdHkoKSkge1xuICAgICAgICAgICAgbWUuX2NscyA9IGNsczsgLy8gc2lsZW50IHVwZGF0ZVxuICAgICAgICAgICAgdmRvbSA9IG1lLnZkb207XG4gICAgICAgICAgICBkZWxldGUgY2VudGVyQm9yZGVyRWwud2lkdGg7XG4gICAgICAgICAgICBtZS52ZG9tID0gdmRvbTtcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIG1lLmNscyA9IGNscztcbiAgICAgICAgfVxuICAgIH1cblxuICAgIC8qKlxuICAgICAqIEBwYXJhbSB7T2JqZWN0fSBkYXRhXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIG9uSW5wdXRWYWx1ZUNoYW5nZShkYXRhKSB7XG4gICAgICAgIGxldCBtZSAgICAgICA9IHRoaXMsXG4gICAgICAgICAgICB2YWx1ZSAgICA9IGRhdGEudmFsdWUsXG4gICAgICAgICAgICBvbGRWYWx1ZSA9IG1lLnZhbHVlLFxuICAgICAgICAgICAgdm5vZGUgICAgPSBWTm9kZVV0aWwuZmluZENoaWxkVm5vZGUobWUudm5vZGUsIHtub2RlTmFtZTogJ2lucHV0J30pO1xuXG4gICAgICAgIGlmICh2bm9kZSkge1xuICAgICAgICAgICAgLy8gcmVxdWlyZWQgZm9yIHZhbGlkYXRpb24gLT4gcmV2ZXJ0IGEgd3JvbmcgdXNlciBpbnB1dFxuICAgICAgICAgICAgdm5vZGUudm5vZGUuYXR0cmlidXRlcy52YWx1ZSA9IHZhbHVlO1xuICAgICAgICB9XG5cbiAgICAgICAgaWYgKHZhbHVlICE9PSBvbGRWYWx1ZSkge1xuICAgICAgICAgICAgbWUudmFsdWUgPSB2YWx1ZTtcbiAgICAgICAgfVxuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFJlbW92ZXMgYWxsIHRyaWdnZXJzIG9mIGEgZ2l2ZW4gdHlwZVxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSB0eXBlXG4gICAgICogQHBhcmFtIHtCb29sZWFufSBbc2lsZW50PWZhbHNlXSB0cnVlIHByZXZlbnRzIGEgdmRvbSB1cGRhdGVcbiAgICAgKiBAcGFyYW0ge0FycmF5fSBbdHJpZ2dlclNvdXJjZV0gcGFzcyBhIHNoYWxsb3cgY29weSBvZiB0aGlzLnRyaWdnZXJzXG4gICAgICogQHJldHVybnMge0Jvb2xlYW59IHRydWUgaW4gY2FzZSBhIHRyaWdnZXIgd2FzIGZvdW5kICYgcmVtb3ZlZFxuICAgICAqL1xuICAgIHJlbW92ZVRyaWdnZXIodHlwZSwgc2lsZW50PWZhbHNlLCB0cmlnZ2VyU291cmNlKSB7XG4gICAgICAgIGxldCBtZSAgICAgICA9IHRoaXMsXG4gICAgICAgICAgICBoYXNNYXRjaCA9IGZhbHNlLFxuICAgICAgICAgICAgdHJpZ2dlcnMgPSB0cmlnZ2VyU291cmNlIHx8IG1lLnRyaWdnZXJzIHx8IFtdLFxuICAgICAgICAgICAgaSAgICAgICAgPSAwLFxuICAgICAgICAgICAgbGVuICAgICAgPSB0cmlnZ2Vycy5sZW5ndGgsXG4gICAgICAgICAgICB0cmlnZ2VyO1xuXG4gICAgICAgIGZvciAoOyBpIDwgbGVuOyBpKyspIHtcbiAgICAgICAgICAgIHRyaWdnZXIgPSB0cmlnZ2Vyc1tpXTtcblxuICAgICAgICAgICAgaWYgKHRyaWdnZXIudHlwZSA9PT0gdHlwZSkge1xuICAgICAgICAgICAgICAgIE5lb0FycmF5LnJlbW92ZSh0cmlnZ2VycywgdHJpZ2dlcik7XG4gICAgICAgICAgICAgICAgbGVuLS07XG4gICAgICAgICAgICAgICAgaGFzTWF0Y2ggPSB0cnVlO1xuICAgICAgICAgICAgfVxuICAgICAgICB9XG5cbiAgICAgICAgaWYgKGhhc01hdGNoICYmICFzaWxlbnQpIHtcbiAgICAgICAgICAgIG1lLnRyaWdnZXJzID0gdHJpZ2dlcnM7XG4gICAgICAgIH1cblxuICAgICAgICByZXR1cm4gaGFzTWF0Y2g7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogUmVzZXRzIHRoZSBmaWVsZCB0byBpdHMgb3JpZ2luYWwgdmFsdWUgb3IgbnVsbCBkZXBlbmRpbmcgb24gdGhlIGNsZWFyVG9PcmlnaW5hbFZhbHVlIGNvbmZpZ1xuICAgICAqIFlvdSBjYW4gb3B0aW9uYWxseSBwYXNzIGEgbmV3IHZhbHVlLCB3aGljaCB3aWxsIGFkanVzdCB0aGUgb3JpZ2luYWxDb25maWcudmFsdWUgaWYgbmVlZGVkLlxuICAgICAqIEBwYXJhbSB7U3RyaW5nfG51bGx9IFt2YWx1ZT1udWxsXVxuICAgICAqL1xuICAgIHJlc2V0KHZhbHVlPW51bGwpIHtcbiAgICAgICAgaWYgKHZhbHVlICYmIHRoaXMuY2xlYXJUb09yaWdpbmFsVmFsdWUpIHtcbiAgICAgICAgICAgIHRoaXMub3JpZ2luYWxDb25maWcudmFsdWUgPSB2YWx1ZTtcbiAgICAgICAgfVxuXG4gICAgICAgIHN1cGVyLnJlc2V0KHZhbHVlKTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBVc2VkIGZvciBsYWJlbFBvc2l0aW9uOiAnaW5saW5lJyB0byBhZGp1c3QgdGhlIHRvcCBib3JkZXIgbWF0Y2hpbmcgdG8gdGhlIGxlbmd0aCBvZiB0aGUgbGFiZWxcbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IFtzaWxlbnQ9ZmFsc2VdIHRydWUgdG8gZ2V0IHRoZSB2YWx1ZSwgYnV0IG5vdCBhcHBseSBpdCB0byB0aGUgRE9NXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIHVwZGF0ZUNlbnRlckJvcmRlckVsV2lkdGgoc2lsZW50PWZhbHNlKSB7XG4gICAgICAgIGxldCBtZSA9IHRoaXM7XG5cbiAgICAgICAgbWUubW91bnRlZCAmJiBOZW8ubWFpbi5Eb21BY2Nlc3MuZ2V0Qm91bmRpbmdDbGllbnRSZWN0KHtcbiAgICAgICAgICAgIGlkOiBtZS5nZXRDZW50ZXJCb3JkZXJFbCgpLmlkXG4gICAgICAgIH0pLnRoZW4oZGF0YSA9PiB7XG4gICAgICAgICAgICBtZS5jZW50ZXJCb3JkZXJFbFdpZHRoID0gTWF0aC5yb3VuZChkYXRhLndpZHRoICogLjcpICsgODtcblxuICAgICAgICAgICAgaWYgKCFzaWxlbnQpIHtcbiAgICAgICAgICAgICAgICBsZXQgdmRvbSA9IG1lLnZkb207XG5cbiAgICAgICAgICAgICAgICBtZS5nZXRDZW50ZXJCb3JkZXJFbCgpLndpZHRoID0gbWUuY2VudGVyQm9yZGVyRWxXaWR0aDtcbiAgICAgICAgICAgICAgICBtZS52ZG9tID0gdmRvbTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQ2FsY3VsYXRlcyB0aGUgbmV3IGlucHV0V2lkdGggYmFzZWQgb24gdGhlIGxhYmVsV2lkdGggJiB0b3RhbCB3aWR0aFxuICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgKi9cbiAgICB1cGRhdGVJbnB1dFdpZHRoKCkge1xuICAgICAgICBsZXQgbWUgICAgICAgICA9IHRoaXMsXG4gICAgICAgICAgICBpbnB1dFdpZHRoID0gbWUuZ2V0SW5wdXRXaWR0aCgpLFxuICAgICAgICAgICAgdmRvbSAgICAgICA9IG1lLnZkb207XG5cbiAgICAgICAgaWYgKGlucHV0V2lkdGggIT09IG51bGwgJiYgaW5wdXRXaWR0aCAhPT0gbWUud2lkdGgpIHtcbiAgICAgICAgICAgIHZkb20uY25bMV0ud2lkdGggPSBpbnB1dFdpZHRoO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgZGVsZXRlIHZkb20uY25bMV0ud2lkdGg7XG4gICAgICAgIH1cblxuICAgICAgICBtZS52ZG9tID0gdmRvbTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBTaW5jZSB0cmlnZ2VycyBkbyBub3QgZ2V0IHJlbmRlcmVkLCBhc3NpZ24gdGhlIHJlbGV2YW50IHByb3BzXG4gICAgICogdG9kbzogdGhpcyBjb3VsZCBiZSBoYW5kbGVkIGJ5IGNvbXBvbmVudC5CYXNlXG4gICAgICovXG4gICAgdXBkYXRlVHJpZ2dlclZub2RlcygpIHtcbiAgICAgICAgbGV0IG1lICAgICAgICAgICA9IHRoaXMsXG4gICAgICAgICAgICB0cmlnZ2VyUm9vdCAgPSBtZS52bm9kZT8uY2hpbGROb2Rlc1sxXSxcbiAgICAgICAgICAgIGNoaWxkTm9kZXMgICA9IHRyaWdnZXJSb290Py5jaGlsZE5vZGVzIHx8IFtdLFxuICAgICAgICAgICAgdHJpZ2dlcjtcblxuICAgICAgICBjaGlsZE5vZGVzLmZvckVhY2godm5vZGUgPT4ge1xuICAgICAgICAgICAgdHJpZ2dlciA9IG1lLmdldFRyaWdnZXJCeUlkKHZub2RlLmlkKTtcblxuICAgICAgICAgICAgdHJpZ2dlciAmJiBPYmplY3QuYXNzaWduKHRyaWdnZXIsIHtcbiAgICAgICAgICAgICAgICB2bm9kZSxcbiAgICAgICAgICAgICAgICBfcmVuZGVyZWQ6IHRydWUsXG4gICAgICAgICAgICAgICAgX21vdW50ZWQgOiB0cnVlXG4gICAgICAgICAgICB9KTtcbiAgICAgICAgfSk7XG4gICAgfVxufVxuXG5OZW8uYXBwbHlDbGFzc0NvbmZpZyhUZXh0KTtcblxuZXhwb3J0IHtUZXh0IGFzIGRlZmF1bHR9O1xuIiwiaW1wb3J0IENvbXBvbmVudCBmcm9tICcuLi8uLi8uLi9jb21wb25lbnQvQmFzZS5tanMnO1xuaW1wb3J0IE5lb0FycmF5ICBmcm9tICcuLi8uLi8uLi91dGlsL0FycmF5Lm1qcyc7XG5cbi8qKlxuICogQmFzZSBjbGFzcyBmb3IgZm9ybSBmaWVsZCBUcmlnZ2Vyc1xuICogQGNsYXNzIE5lby5mb3JtLmZpZWxkLnRyaWdnZXIuQmFzZVxuICogQGV4dGVuZHMgTmVvLmNvbXBvbmVudC5CYXNlXG4gKi9cbmNsYXNzIEJhc2UgZXh0ZW5kcyBDb21wb25lbnQge1xuICAgIHN0YXRpYyBnZXRTdGF0aWNDb25maWcoKSB7cmV0dXJuIHtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFZhbGlkIHZhbHVlcyBmb3IgYWxpZ25cbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nW119IGFsaWduVmFsdWVzPVsnZW5kJywgJ3N0YXJ0J11cbiAgICAgICAgICogQHByb3RlY3RlZFxuICAgICAgICAgKiBAc3RhdGljXG4gICAgICAgICAqL1xuICAgICAgICBhbGlnblZhbHVlczogWydlbmQnLCAnc3RhcnQnXVxuICAgIH19XG5cbiAgICBzdGF0aWMgZ2V0Q29uZmlnKCkge3JldHVybiB7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtTdHJpbmd9IGNsYXNzTmFtZT0nTmVvLmZvcm0uZmllbGQudHJpZ2dlci5CYXNlJ1xuICAgICAgICAgKiBAcHJvdGVjdGVkXG4gICAgICAgICAqL1xuICAgICAgICBjbGFzc05hbWU6ICdOZW8uZm9ybS5maWVsZC50cmlnZ2VyLkJhc2UnLFxuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nfSBudHlwZT0ndHJpZ2dlcidcbiAgICAgICAgICogQHByb3RlY3RlZFxuICAgICAgICAgKi9cbiAgICAgICAgbnR5cGU6ICd0cmlnZ2VyJyxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge1N0cmluZ30gYWxpZ25fPSdlbmQnXG4gICAgICAgICAqL1xuICAgICAgICBhbGlnbl86ICdlbmQnLFxuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nW119IGNscz1bJ25lby1maWVsZC10cmlnZ2VyJ11cbiAgICAgICAgICovXG4gICAgICAgIGNsczogWyduZW8tZmllbGQtdHJpZ2dlciddLFxuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7TmVvLmZvcm0uZmllbGQuQmFzZXxudWxsfSBmaWVsZD1udWxsXG4gICAgICAgICAqL1xuICAgICAgICBmaWVsZDogbnVsbCxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge0Jvb2xlYW59IGhpZGRlbl89ZmFsc2VcbiAgICAgICAgICovXG4gICAgICAgIGhpZGRlbl86IGZhbHNlLFxuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nfG51bGx9IGljb25DbHNfPW51bGxcbiAgICAgICAgICovXG4gICAgICAgIGljb25DbHNfOiBudWxsLFxuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7Qm9vbGVhbn0gaXNIb3ZlcmVkPWZhbHNlXG4gICAgICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgICAgICovXG4gICAgICAgIGlzSG92ZXJlZDogZmFsc2UsXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBUaGUgc2NvcGUgb2YgdGhlIHRyaWdnZXIgaGFuZGxlclxuICAgICAgICAgKiBAbWVtYmVyIHtOZW8uY29yZS5CYXNlfG51bGx9IHNjb3BlPW51bGxcbiAgICAgICAgICovXG4gICAgICAgIHNjb3BlOiBudWxsLFxuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7Qm9vbGVhbn0gc2hvd09uSG92ZXI9ZmFsc2VcbiAgICAgICAgICovXG4gICAgICAgIHNob3dPbkhvdmVyOiBmYWxzZSxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEludGVybmFsIGZsYWcgdXNlZCBieSBmaWVsZC5nZXRUcmlnZ2VyKClcbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nfSB0eXBlPSdiYXNlJ1xuICAgICAgICAgKiBAcHJvdGVjdGVkXG4gICAgICAgICAqL1xuICAgICAgICB0eXBlOiAnYmFzZScsXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtPYmplY3R9IF92ZG9tPXt0YWJJbmRleDogLTF9XG4gICAgICAgICAqL1xuICAgICAgICBfdmRvbTpcbiAgICAgICAge3RhYkluZGV4OiAtMX0sXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtOdW1iZXJ9IHdlaWdodF89MTBcbiAgICAgICAgICovXG4gICAgICAgIHdlaWdodF86IDEwXG4gICAgfX1cblxuICAgIC8qKlxuICAgICAqIEBwYXJhbSB7T2JqZWN0fSBjb25maWdcbiAgICAgKi9cbiAgICBjb25zdHJ1Y3QoY29uZmlnKSB7XG4gICAgICAgIHN1cGVyLmNvbnN0cnVjdChjb25maWcpO1xuXG4gICAgICAgIGxldCBtZSAgICAgICAgICAgICA9IHRoaXMsXG4gICAgICAgICAgICBkb21MaXN0ZW5lcnMgICA9IG1lLmRvbUxpc3RlbmVycyB8fCBbXSxcbiAgICAgICAgICAgIGZpZWxkTGlzdGVuZXJzO1xuXG4gICAgICAgIGRvbUxpc3RlbmVycy5wdXNoKFxuICAgICAgICAgICAge2NsaWNrOiBtZS5vblRyaWdnZXJDbGljaywgc2NvcGU6IG1lfVxuICAgICAgICApO1xuXG4gICAgICAgIG1lLmRvbUxpc3RlbmVycyA9IGRvbUxpc3RlbmVycztcblxuICAgICAgICBpZiAobWUuc2hvd09uSG92ZXIpIHtcbiAgICAgICAgICAgIG1lLmhpZGRlbiA9IHRydWU7XG5cbiAgICAgICAgICAgIG1lLmZpZWxkLm9uKCdjb25zdHJ1Y3RlZCcsICgpID0+IHtcbiAgICAgICAgICAgICAgICBmaWVsZExpc3RlbmVycyA9IG1lLmZpZWxkLmRvbUxpc3RlbmVycyB8fCBbXTtcblxuICAgICAgICAgICAgICAgIGZpZWxkTGlzdGVuZXJzLnB1c2goXG4gICAgICAgICAgICAgICAgICAgIHttb3VzZWVudGVyOiBtZS5vbk1vdXNlRW50ZXIsIHNjb3BlOiBtZX0sXG4gICAgICAgICAgICAgICAgICAgIHttb3VzZWxlYXZlOiBtZS5vbk1vdXNlTGVhdmUsIHNjb3BlOiBtZX1cbiAgICAgICAgICAgICAgICApO1xuXG4gICAgICAgICAgICAgICAgbWUuZmllbGQuZG9tTGlzdGVuZXJzID0gZmllbGRMaXN0ZW5lcnM7XG4gICAgICAgICAgICB9LCBtZSk7XG4gICAgICAgIH1cbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBUcmlnZ2VyZWQgYWZ0ZXIgdGhlIGFsaWduIGNvbmZpZyBnb3QgY2hhbmdlZFxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSB2YWx1ZVxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSBvbGRWYWx1ZVxuICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgKi9cbiAgICBhZnRlclNldEFsaWduKHZhbHVlLCBvbGRWYWx1ZSkge1xuICAgICAgICBsZXQgY2xzID0gdGhpcy5jbHM7XG5cbiAgICAgICAgTmVvQXJyYXlbdmFsdWUgPT09ICdzdGFydCcgPyAnYWRkJyA6ICdyZW1vdmUnXShjbHMsICduZW8tYWxpZ24tc3RhcnQnKTtcbiAgICAgICAgdGhpcy5jbHMgPSBjbHM7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogVHJpZ2dlcmVkIGFmdGVyIHRoZSBoaWRkZW4gY29uZmlnIGdvdCBjaGFuZ2VkXG4gICAgICogQHBhcmFtIHtCb29sZWFufSB2YWx1ZVxuICAgICAqIEBwYXJhbSB7Qm9vbGVhbn0gb2xkVmFsdWVcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICovXG4gICAgYWZ0ZXJTZXRIaWRkZW4odmFsdWUsIG9sZFZhbHVlKSB7XG4gICAgICAgIGxldCB2ZG9tICA9IHRoaXMudmRvbSxcbiAgICAgICAgICAgIHN0eWxlID0gdmRvbS5zdHlsZSB8fCB7fTtcblxuICAgICAgICBzdHlsZS5kaXNwbGF5ID0gdmFsdWUgPyAnbm9uZScgOiAnaW5saW5lLWJsb2NrJztcbiAgICAgICAgdGhpcy52ZG9tID0gdmRvbTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBUcmlnZ2VyZWQgYWZ0ZXIgdGhlIGljb25DbHMgY29uZmlnIGdvdCBjaGFuZ2VkXG4gICAgICogQHBhcmFtIHtTdHJpbmd9IHZhbHVlXG4gICAgICogQHBhcmFtIHtTdHJpbmd9IG9sZFZhbHVlXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIGFmdGVyU2V0SWNvbkNscyh2YWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgbGV0IGNscyA9IHRoaXMuY2xzO1xuXG4gICAgICAgIE5lb0FycmF5LnJlbW92ZShjbHMsIG9sZFZhbHVlKTtcblxuICAgICAgICBpZiAodmFsdWUgJiYgdmFsdWUgIT09ICcnKSB7XG4gICAgICAgICAgICBOZW9BcnJheS5hZGQoY2xzLCB2YWx1ZSk7XG4gICAgICAgIH1cblxuICAgICAgICB0aGlzLmNscyA9IGNscztcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBUcmlnZ2VyZWQgYmVmb3JlIHRoZSBhbGlnbiBjb25maWcgZ2V0cyBjaGFuZ2VkXG4gICAgICogQHBhcmFtIHtTdHJpbmd9IHZhbHVlXG4gICAgICogQHBhcmFtIHtTdHJpbmd9IG9sZFZhbHVlXG4gICAgICogQHByb3RlY3RlZFxuICAgICAqL1xuICAgIGJlZm9yZVNldEFsaWduKHZhbHVlLCBvbGRWYWx1ZSkge1xuICAgICAgICByZXR1cm4gdGhpcy5iZWZvcmVTZXRFbnVtVmFsdWUodmFsdWUsIG9sZFZhbHVlLCAnYWxpZ24nLCAnYWxpZ25WYWx1ZXMnKTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IHVwZGF0ZVBhcmVudFZkb21cbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IHNpbGVudFxuICAgICAqL1xuICAgIGRlc3Ryb3kodXBkYXRlUGFyZW50VmRvbSwgc2lsZW50KSB7XG4gICAgICAgIGxldCBtZSA9IHRoaXM7XG5cbiAgICAgICAgbWUucmVtb3ZlRG9tTGlzdGVuZXJzKHtjbGljazoge2ZuOiBtZS5vblRyaWdnZXJDbGljaywgc2NvcGU6IG1lfX0pO1xuXG4gICAgICAgIGRlbGV0ZSBtZS5maWVsZDtcblxuICAgICAgICBzdXBlci5kZXN0cm95KHVwZGF0ZVBhcmVudFZkb20sIHNpbGVudCk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICpcbiAgICAgKi9cbiAgICBvbk1vdXNlRW50ZXIoKSB7XG4gICAgICAgIHRoaXMuaXNIb3ZlcmVkID0gdHJ1ZTtcbiAgICAgICAgdGhpcy5oaWRkZW4gICAgPSBmYWxzZTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKlxuICAgICAqL1xuICAgIG9uTW91c2VMZWF2ZSgpIHtcbiAgICAgICAgdGhpcy5pc0hvdmVyZWQgPSBmYWxzZTtcbiAgICAgICAgdGhpcy5oaWRkZW4gICAgPSB0cnVlO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIGNsaWNrIGRvbUV2ZW50IGxpc3RlbmVyXG4gICAgICogQHBhcmFtIHtPYmplY3R9IGRhdGFcbiAgICAgKiBAcHJvdGVjdGVkXG4gICAgICovXG4gICAgb25UcmlnZ2VyQ2xpY2soZGF0YSkge1xuICAgICAgICBsZXQgbWUgICAgPSB0aGlzLFxuICAgICAgICAgICAgc2NvcGUgPSBtZS5zY29wZSB8fCBtZTtcblxuICAgICAgICBpZiAobWUuaGFuZGxlcikge1xuICAgICAgICAgICAgc2NvcGVbbWUuaGFuZGxlcl0uY2FsbChzY29wZSk7XG4gICAgICAgIH1cbiAgICB9XG59XG5cbk5lby5hcHBseUNsYXNzQ29uZmlnKEJhc2UpO1xuXG5leHBvcnQge0Jhc2UgYXMgZGVmYXVsdH07XG4iLCJpbXBvcnQgQmFzZSAgICAgZnJvbSAnLi9CYXNlLm1qcyc7XG5pbXBvcnQgTmVvQXJyYXkgZnJvbSAnLi4vLi4vLi4vdXRpbC9BcnJheS5tanMnO1xuXG4vKipcbiAqIENsZWFyIFRyaWdnZXIgdG8gcmVtb3ZlIHRoZSBpbnB1dCB2YWx1ZSBvZiBUZXh0RmllbGRzIG9yIHN1YmNsYXNzZXNcbiAqIEBjbGFzcyBOZW8uZm9ybS5maWVsZC50cmlnZ2VyLkNsZWFyXG4gKiBAZXh0ZW5kcyBOZW8uZm9ybS5maWVsZC50cmlnZ2VyLkJhc2VcbiAqL1xuY2xhc3MgQ2xlYXIgZXh0ZW5kcyBCYXNlIHtcbiAgICBzdGF0aWMgZ2V0Q29uZmlnKCkge3JldHVybiB7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtTdHJpbmd9IGNsYXNzTmFtZT0nTmVvLmZvcm0uZmllbGQudHJpZ2dlci5DbGVhcidcbiAgICAgICAgICogQHByb3RlY3RlZFxuICAgICAgICAgKi9cbiAgICAgICAgY2xhc3NOYW1lOiAnTmVvLmZvcm0uZmllbGQudHJpZ2dlci5DbGVhcicsXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtTdHJpbmd9IG50eXBlPSd0cmlnZ2VyLWNsZWFyJ1xuICAgICAgICAgKiBAcHJvdGVjdGVkXG4gICAgICAgICAqL1xuICAgICAgICBudHlwZTogJ3RyaWdnZXItY2xlYXInLFxuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nW119IGNscz1bJ25lby1maWVsZC10cmlnZ2VyJywgJ25lby10cmlnZ2VyLWNsZWFyJ11cbiAgICAgICAgICovXG4gICAgICAgIGNsczogWyduZW8tZmllbGQtdHJpZ2dlcicsICduZW8tdHJpZ2dlci1jbGVhciddLFxuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nfG51bGx9IGljb25DbHM9J2ZhIGZhLXRpbWVzJ1xuICAgICAgICAgKi9cbiAgICAgICAgaWNvbkNsczogJ2ZhIGZhLXRpbWVzJyxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEludGVybmFsIGZsYWcgdXNlZCBieSBmaWVsZC5nZXRUcmlnZ2VyKClcbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nfSB0eXBlPSdjbGVhcidcbiAgICAgICAgICogQHByb3RlY3RlZFxuICAgICAgICAgKi9cbiAgICAgICAgdHlwZTogJ2NsZWFyJyxcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge051bWJlcn0gd2VpZ2h0Xz0yMFxuICAgICAgICAgKi9cbiAgICAgICAgd2VpZ2h0OiAyMFxuICAgIH19XG5cbiAgICAvKipcbiAgICAgKiBUcmlnZ2VyZWQgYWZ0ZXIgdGhlIGhpZGRlbiBjb25maWcgZ290IGNoYW5nZWRcbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IHZhbHVlXG4gICAgICogQHBhcmFtIHtCb29sZWFufSBvbGRWYWx1ZVxuICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgKi9cbiAgICBhZnRlclNldEhpZGRlbih2YWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgbGV0IGNscyA9IHRoaXMuY2xzO1xuXG4gICAgICAgIE5lb0FycmF5W3ZhbHVlID8gJ2FkZCcgOiAncmVtb3ZlJ10oY2xzLCAnbmVvLWlzLWhpZGRlbicpO1xuICAgICAgICB0aGlzLmNscyA9IGNscztcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBUcmlnZ2VyZWQgYmVmb3JlIHRoZSBoaWRkZW4gY29uZmlnIGdldHMgY2hhbmdlZC5cbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IHZhbHVlXG4gICAgICogQHBhcmFtIHtCb29sZWFufSBvbGRWYWx1ZVxuICAgICAqIEBwcm90ZWN0ZWRcbiAgICAgKi9cbiAgICBiZWZvcmVTZXRIaWRkZW4odmFsdWUsIG9sZFZhbHVlKSB7XG4gICAgICAgIGlmICh0aGlzLnNob3dPbkhvdmVyICYmICF0aGlzLmlzSG92ZXJlZCkge1xuICAgICAgICAgICAgcmV0dXJuIHRydWU7XG4gICAgICAgIH1cblxuICAgICAgICByZXR1cm4gdmFsdWU7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICpcbiAgICAgKi9cbiAgICBkZXN0cm95KC4uLmFyZ3MpIHtcbiAgICAgICAgbGV0IG1lID0gdGhpcztcblxuICAgICAgICBtZS5maWVsZC51bih7XG4gICAgICAgICAgICBjaGFuZ2UgICAgICAgICAgICAgICAgICAgIDogbWUub25GaWVsZENoYW5nZSxcbiAgICAgICAgICAgIGNoYW5nZUNsZWFyVG9PcmlnaW5hbFZhbHVlOiBtZS5vbkZpZWxkQ2hhbmdlLFxuICAgICAgICAgICAgc2NvcGUgICAgICAgICAgICAgICAgICAgICA6IG1lXG4gICAgICAgIH0pO1xuXG4gICAgICAgIHN1cGVyLmRlc3Ryb3koLi4uYXJncyk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQHJldHVybnMge0Jvb2xlYW59IHRydWUgaW4gY2FzZSB0aGUgdHJpZ2dlciBzaG91bGQgYmUgaGlkZGVuXG4gICAgICovXG4gICAgZ2V0SGlkZGVuU3RhdGUoKSB7XG4gICAgICAgIGxldCBtZSAgICA9IHRoaXMsXG4gICAgICAgICAgICBmaWVsZCA9IG1lLmZpZWxkLFxuICAgICAgICAgICAgdmFsdWUgPSBmaWVsZC52YWx1ZTtcblxuICAgICAgICBpZiAoZmllbGQuY2xlYXJUb09yaWdpbmFsVmFsdWUpIHtcbiAgICAgICAgICAgIHJldHVybiB2YWx1ZSA9PT0gZmllbGQub3JpZ2luYWxDb25maWcudmFsdWU7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICBpZiAodmFsdWUgPT09IDApIHtcbiAgICAgICAgICAgICAgICB2YWx1ZSA9ICcwJztcbiAgICAgICAgICAgIH1cblxuICAgICAgICAgICAgcmV0dXJuICFmaWVsZC52YWx1ZSB8fCB2YWx1ZS50b1N0cmluZygpLmxlbmd0aCA8IDE7XG4gICAgICAgIH1cbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBAcGFyYW0ge09iamVjdH0gb3B0c1xuICAgICAqL1xuICAgIG9uRmllbGRDaGFuZ2Uob3B0cykge1xuICAgICAgICB0aGlzLmhpZGRlbiA9IHRoaXMuZ2V0SGlkZGVuU3RhdGUoKTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKlxuICAgICAqL1xuICAgIG9uQ29uc3RydWN0ZWQoKSB7XG4gICAgICAgIHN1cGVyLm9uQ29uc3RydWN0ZWQoKTtcblxuICAgICAgICBsZXQgbWUgPSB0aGlzO1xuXG4gICAgICAgIG1lLmZpZWxkLm9uKHtcbiAgICAgICAgICAgIGNoYW5nZSAgICAgICAgICAgICAgICAgICAgOiBtZS5vbkZpZWxkQ2hhbmdlLFxuICAgICAgICAgICAgY2hhbmdlQ2xlYXJUb09yaWdpbmFsVmFsdWU6IG1lLm9uRmllbGRDaGFuZ2UsXG4gICAgICAgICAgICBzY29wZSAgICAgICAgICAgICAgICAgICAgIDogbWVcbiAgICAgICAgfSk7XG5cbiAgICAgICAgbWUuaGlkZGVuID0gbWUuZ2V0SGlkZGVuU3RhdGUoKTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBAb3ZlcnJpZGVcbiAgICAgKi9cbiAgICBvbk1vdXNlRW50ZXIoKSB7XG4gICAgICAgIGxldCBtZSA9IHRoaXM7XG5cbiAgICAgICAgbWUuaXNIb3ZlcmVkID0gdHJ1ZTtcbiAgICAgICAgbWUuaGlkZGVuICAgID0gbWUuZ2V0SGlkZGVuU3RhdGUoKTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBAcGFyYW0ge09iamVjdH0gZGF0YVxuICAgICAqL1xuICAgIG9uVHJpZ2dlckNsaWNrKGRhdGEpIHtcbiAgICAgICAgdGhpcy5maWVsZC5jbGVhcigpO1xuICAgIH1cbn1cblxuTmVvLmFwcGx5Q2xhc3NDb25maWcoQ2xlYXIpO1xuXG5leHBvcnQge0NsZWFyIGFzIGRlZmF1bHR9O1xuIl0sIm5hbWVzIjpbXSwic291cmNlUm9vdCI6IiJ9
(function () { /*jshint esnext: true */ function noyield() { // https://github.com/jshint/jshint/issues/1123 /*jshint noyield: false */ // FAIL invalid option var of, run; run(function *() { return of(5); // not relaxed }); // not relaxed } function noyieldTrue() { /*jshint noyield: true */ // FAIL invalid option var of, run; run(function *() { return of(5); // relaxed }); // relaxed FAIL - still warns } noyield(); noyieldTrue(); })();
import React from 'react'; import ExpenseItem from './ExpenseItem'; import './ExpensesList.css'; const ExpensesList = props =>{ if (props.items.length === 0) { return <h2 className="expenses-list__fallback">Found no expenses.</h2>; }; return <ul className="expenses-list"> {props.items.map((expense) => ( <ExpenseItem key={expense.id} title={expense.title} amount={expense.amount} date={expense.date} /> ))} </ul> }; export default ExpensesList;
var ProTracker = function(){ var me = {}; me.load = function(file,name){ Tracker.setTrackerMode(TRACKERMODE.PROTRACKER); Tracker.useLinearFrequency = false; Tracker.clearInstruments(31); var song = { patterns:[], restartPosition: 1 }; var patternLength = 64; var instrumentCount = 31; var channelCount = 4; //see https://www.aes.id.au/modformat.html song.typeId = file.readString(4,1080); song.title = file.readString(20,0); if (song.typeId === "2CHN") channelCount = 2; if (song.typeId === "6CHN") channelCount = 6; if (song.typeId === "8CHN") channelCount = 8; if (song.typeId === "10CH") channelCount = 10; if (song.typeId === "12CH") channelCount = 12; if (song.typeId === "14CH") channelCount = 14; if (song.typeId === "16CH") channelCount = 16; if (song.typeId === "18CH") channelCount = 18; if (song.typeId === "20CH") channelCount = 20; if (song.typeId === "22CH") channelCount = 22; if (song.typeId === "24CH") channelCount = 24; if (song.typeId === "26CH") channelCount = 26; if (song.typeId === "28CH") channelCount = 28; if (song.typeId === "30CH") channelCount = 30; if (song.typeId === "32CH") channelCount = 32; song.channels = channelCount; var sampleDataOffset = 0; for (i = 1; i <= instrumentCount; ++i) { var instrumentName = file.readString(22); var sampleLength = file.readWord(); // in words var instrument = Instrument(); instrument.name = instrumentName; instrument.sample.length = instrument.sample.realLen = sampleLength << 1; var finetune = file.readUbyte(); if (finetune>7) finetune -= 16; instrument.setFineTune(finetune); instrument.sample.volume = file.readUbyte(); instrument.sample.loop.start = file.readWord() << 1; instrument.sample.loop.length = file.readWord() << 1; instrument.sample.loop.enabled = instrument.sample.loop.length>2; instrument.sample.loop.type = LOOPTYPE.FORWARD; instrument.pointer = sampleDataOffset; sampleDataOffset += instrument.sample.length; instrument.setSampleIndex(0); Tracker.setInstrument(i,instrument); } song.instruments = Tracker.getInstruments(); file.goto(950); song.length = file.readUbyte(); file.jump(1); // 127 byte var patternTable = []; var highestPattern = 0; for (var i = 0; i < 128; ++i) { patternTable[i] = file.readUbyte(); if (patternTable[i] > highestPattern) highestPattern = patternTable[i]; } song.patternTable = patternTable; file.goto(1084); // pattern data for (i = 0; i <= highestPattern; ++i) { var patternData = []; for (var step = 0; step<patternLength; step++){ var row = []; var channel; for (channel = 0; channel < channelCount; channel++){ var note = Note(); var trackStepInfo = file.readUint(); note.setPeriod((trackStepInfo >> 16) & 0x0fff); note.effect = (trackStepInfo >> 8) & 0x0f; note.instrument = (trackStepInfo >> 24) & 0xf0 | (trackStepInfo >> 12) & 0x0f; note.param = trackStepInfo & 0xff; row.push(note); } // fill with empty data for other channels // TODO: not needed anymore ? for (channel = channelCount; channel < Tracker.getTrackCount(); channel++){ row.push(Note()) } patternData.push(row); } song.patterns.push(patternData); //file.jump(1024); } var instrumentContainer = []; for(i=1; i <= instrumentCount; i++) { instrument = Tracker.getInstrument(i); if (instrument){ console.log( "Reading sample from 0x" + file.index + " with length of " + instrument.sample.length + " bytes and repeat length of " + instrument.sample.loop.length); var sampleEnd = instrument.sample.length; if (instrument.sample.loop.length>2 && SETTINGS.unrollShortLoops && instrument.sample.loop.length<1000){ // cut off trailing bytes for short looping samples sampleEnd = Math.min(sampleEnd,instrument.sample.loop.start + instrument.sample.loop.length); instrument.sample.length = sampleEnd; } for (j = 0; j<sampleEnd; j++){ var b = file.readByte(); // ignore first 2 bytes if (j<2)b=0; instrument.sample.data.push(b / 127) } // unroll short loops? // web audio loop start/end is in seconds // doesn't work that well with tiny loops if ((SETTINGS.unrollShortLoops || SETTINGS.unrollLoops) && instrument.sample.loop.length>2){ var loopCount = Math.ceil(40000 / instrument.sample.loop.length) + 1; if (!SETTINGS.unrollLoops) loopCount = 0; var resetLoopNumbers = false; var loopLength = 0; if (SETTINGS.unrollShortLoops && instrument.sample.loop.length<1600){ loopCount = Math.floor(1000/instrument.sample.loop.length); resetLoopNumbers = true; } for (var l=0;l<loopCount;l++){ var start = instrument.sample.loop.start; var end = start + instrument.sample.loop.length; for (j=start; j<end; j++){ instrument.sample.data.push(instrument.sample.data[j]); } loopLength += instrument.sample.loop.length; } if (resetLoopNumbers && loopLength){ instrument.sample.loop.length += loopLength; instrument.sample.length += loopLength; } } instrumentContainer.push({label: i + " " + instrument.name, data: i}); } } EventBus.trigger(EVENT.instrumentListChange,instrumentContainer); return song; }; //<!-- me.write = function(next){ var song = Tracker.getSong(); var instruments = Tracker.getInstruments(); var trackCount = Tracker.getTrackCount(); var patternLength = Tracker.getPatternLength(); // get filesize var fileSize = 20 + (31*30) + 1 + 1 + 128 + 4; var highestPattern = 0; for (i = 0;i<128;i++){ var p = song.patternTable[i] || 0; highestPattern = Math.max(highestPattern,p); } fileSize += ((highestPattern+1)* (trackCount * 256)); instruments.forEach(function(instrument){ if (instrument){ // reset to first sample in case we come from a XM file instrument.setSampleIndex(0); fileSize += instrument.sample.length; }else{ // +4 ? } }); var i; var arrayBuffer = new ArrayBuffer(fileSize); var file = new BinaryStream(arrayBuffer,true); // write title file.writeStringSection(song.title,20); // write instrument data instruments.forEach(function(instrument){ if (instrument){ // limit instrument size to 128k //TODO: show a warning when this is exceeded ... instrument.sample.length = Math.min(instrument.sample.length, 131070); // = FFFF * 2 file.writeStringSection(instrument.name,22); file.writeWord(instrument.sample.length >> 1); file.writeUByte(instrument.sample.finetune); file.writeUByte(instrument.sample.volume); file.writeWord(instrument.sample.loop.start >> 1); file.writeWord(instrument.sample.loop.length >> 1); }else{ file.clear(30); } }); file.writeUByte(song.length); file.writeUByte(127); // patternPos for (i = 0;i<128;i++){ var p = song.patternTable[i] || 0; file.writeUByte(p); } file.writeString( trackCount == 8 ? "8CHN" : "M.K."); // pattern Data for (i=0;i<=highestPattern;i++){ // TODO: patternData //file.clear(1024); var patternData = song.patterns[i]; // TODO - should be patternLength of pattnern; for (var step = 0; step<patternLength; step++){ var row = patternData[step]; for (var channel = 0; channel < trackCount; channel++){ var trackStep = row[channel]; var uIndex = 0; var lIndex = trackStep.instrument; if (lIndex>15){ uIndex = 16; // TODO: Why is this 16 and not 1 ? Nobody wanted 255 instruments instead of 31 ? lIndex = trackStep.instrument - 16; } var v = (uIndex << 24) + (trackStep.period << 16) + (lIndex << 12) + (trackStep.effect << 8) + trackStep.param; file.writeUint(v); } } } // sampleData; instruments.forEach(function(instrument){ if (instrument && instrument.sample.data && instrument.sample.length){ // should we put repeat info here? file.clear(2); var d; // instrument length is in word for (i = 0; i < instrument.sample.length-2; i++){ d = instrument.sample.data[i] || 0; file.writeByte(Math.round(d*127)); } console.log("write instrument with " + instrument.sample.length + " length"); }else{ // still write 4 bytes? } }); if (next) next(file); }; //--> return me; };
import React, { Component } from 'react'; import '../App.css'; import Home from './Home'; import Form from './Form'; import Projects from './Projects'; import Cv from './Cv'; import { FiPhoneCall } from 'react-icons/fi'; import { BsEnvelopeOpen } from 'react-icons/bs'; import { AiOutlineFileDone } from 'react-icons/ai'; class Dashboard extends Component { state ={ showHome: true, showForm: false, showProjects: false, showCv:false, } handleHomeClick = () => { this.setState(({ showHome: true, showProjects:false, showForm:false, showCv:false, }) ); } handleFormClick = () => { this.setState(({ showForm: true, showHome:false, showProjects:false, showCv:false, }) ); } handleProjectClick = () => { this.setState(({ showProjects: true, showHome:false, showForm:false, showCv:false, }) ); } handleCv = () => { this.setState(({ showProjects: false, showHome:false, showForm:false, showCv:true, }) ); } render() { let display if(this.state.showForm === true){ display = <Form /> }else if(this.state.showHome === true) { display = <Home /> }else if(this.state.showProjects === true) { display = <Projects /> }else if(this.state.showCv === true) { display = <Cv /> } return( <> <div className='dashboard'> <div className='picContainer'> <img className='picture' src='/images/profilePic.jpeg' alt='Me' /> <p>Hi my name is</p> <h3>Garin McCullick</h3> </div> <div className='bottom-wrapper'> <div className='navigation'> <div className='link' onClick={this.handleHomeClick}>Home</div> <div className='link' onClick={this.handleProjectClick}>Projects</div> <button className='call-to-actionBtn' onClick={this.handleFormClick}>Want to talk?</button> </div> <div className='personal-left'> <a href="tel:5736808460" rel="noreferrer" target="_blank"> <span className='phone-icon'><FiPhoneCall size={28} style={{color:'green'}}/></span> <p className="call-button">tel: (573) 680-8460</p> </a> <a href = "mailto: [email protected]" rel="noreferrer" target="_blank"> <span className='email-icon'><BsEnvelopeOpen size={28} style={{color:'goldenrod'}}/></span> <p className='email-button'>[email protected]</p> </a> <span className='Cv-link' onClick={this.handleCv}> <AiOutlineFileDone size={34 } className="file-icon" style={{color:'peru'}} /> <p>CV</p> </span> </div> </div> </div> <div className='right-side'> {display} </div> </> ) } } export default Dashboard
(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports", "@angular/core", "./soho-progress.component"], factory); } })(function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var i0 = require("@angular/core"); var i1 = require("./soho-progress.component"); var styles_SohoProgressComponent = []; var RenderType_SohoProgressComponent = i0.ɵcrt({ encapsulation: 2, styles: styles_SohoProgressComponent, data: {} }); exports.RenderType_SohoProgressComponent = RenderType_SohoProgressComponent; function View_SohoProgressComponent_0(_l) { return i0.ɵvid(2, [(_l()(), i0.ɵeld(0, 0, null, null, 0, "div", [], [[2, "progress-bar", null], [1, "data-value", 0]], null, null, null, null))], null, function (_ck, _v) { var _co = _v.component; var currVal_0 = true; var currVal_1 = _co.value; _ck(_v, 0, 0, currVal_0, currVal_1); }); } exports.View_SohoProgressComponent_0 = View_SohoProgressComponent_0; function View_SohoProgressComponent_Host_0(_l) { return i0.ɵvid(0, [(_l()(), i0.ɵeld(0, 0, null, null, 1, "soho-progress", [], [[2, "progress", null], [4, "display", null]], null, null, View_SohoProgressComponent_0, RenderType_SohoProgressComponent)), i0.ɵdid(1, 4374528, null, 0, i1.SohoProgressComponent, [i0.ElementRef], null, null)], null, function (_ck, _v) { var currVal_0 = i0.ɵnov(_v, 1).progressClass; var currVal_1 = i0.ɵnov(_v, 1).dispType; _ck(_v, 0, 0, currVal_0, currVal_1); }); } exports.View_SohoProgressComponent_Host_0 = View_SohoProgressComponent_Host_0; var SohoProgressComponentNgFactory = i0.ɵccf("soho-progress", i1.SohoProgressComponent, View_SohoProgressComponent_Host_0, { progressValue: "progressValue" }, { change: "change" }, []); exports.SohoProgressComponentNgFactory = SohoProgressComponentNgFactory; });
import readProxy from "./abis/readProxy.json"; import SNX from "./abis/snx.json"; export default { readProxy, tokens: { SNX, }, };
# stdlib from io import BytesIO from typing import Any from typing import Generator from typing import List # third party import boto3 from botocore.client import Config from pydantic import BaseSettings import requests from tqdm import tqdm # relative from ....grid import GridURL from ....util import get_fully_qualified_name from ....util import size_mb from ...common.serde.serialize import _serialize as serialize from ...common.uid import UID from ...store.proxy_dataset import ProxyDataset from .exceptions import DatasetUploadError MIN_BLOB_UPLOAD_SIZE_MB = 1 def read_chunks( fp: BytesIO, chunk_size: int = 1024**3 ) -> Generator[bytes, None, None]: """Read data in chunks from the file.""" while True: data = fp.read(chunk_size) if not data: break yield data def listify(x: Any) -> List[Any]: """turns x into a list. If x is a list or tuple, return as list. if x is not a list: return [x] if x is None: return [] Args: x (Any): some object Returns: List[Any]: x, as a list """ return list(x) if isinstance(x, (list, tuple)) else ([] if x is None else [x]) def upload_result_to_s3( asset_name: str, dataset_name: str, domain_id: UID, data: Any, settings: BaseSettings, ) -> ProxyDataset: """Upload data to Seaweed using boto3 client. - Serialize data to binary - Upload data to Seaweed using boto3 client - Create a ProxyDataset to store the metadata of the data uploaded to Seaweed Args: asset_name (str): name of the data being uploaded to Seaweed dataset_name (str): name of the dataset to which the data belongs domain_id (UID): unique id of the domain node data (Any): data to be uploaded to Seaweed settings (BaseSettings): base settings of the PyGrid server Returns: ProxyDataset: Class to store the metadata of the data being uploaded """ s3_client = get_s3_client(settings=settings) binary_dataset: bytes = serialize(data, to_bytes=True) # type: ignore # 1- Serialize the data to be uploaded to bytes. binary_buffer = BytesIO(binary_dataset) filename = f"{dataset_name}/{asset_name}" # 2 - Start to upload binary data into Seaweed. upload_response = s3_client.put_object( Bucket=domain_id.no_dash, Body=binary_buffer, Key=filename, ContentType="application/octet-stream", ) # TODO: Throw an exception if the response is not valid print("Upload Result") print(upload_response) # 3 - Create a ProxyDataset for the given data # Retrieve fully qualified name to use for pointer creation. data_fqn = str(get_fully_qualified_name(data)) data_dtype = str(type(data)) proxy_obj = ProxyDataset( asset_name=asset_name, dataset_name=dataset_name, node_id=domain_id, dtype=data_dtype, fqn=data_fqn, shape=data.shape, ) return proxy_obj def abort_s3_object_upload( client: boto3.client, upload_id: str, asset_name: str ) -> None: """Abort upload to s3 for the given asset. Args: client (boto3.client): boto3 client. upload_id (str): upload id generated for mutlipart upload. asset_name (str): name of the data/asset. """ # relative from .node_service.upload_service.upload_service_messages import ( AbortDataUploadMessage, ) # Send a message to PyGrid to abort the data being uploaded to s3. # TODO: make this call async -> could use celery .delay method to do _ = client.datasets.perform_api_request_generic( syft_msg=AbortDataUploadMessage, content={ "upload_id": upload_id, "asset_name": asset_name, }, ) def upload_to_s3_using_presigned( client: Any, data: Any, chunk_size: int, asset_name: str, dataset_name: str = "", ) -> ProxyDataset: """Perform a multipart upload of data to Seaweed using boto3 presigned urls. The main steps involve: - Converting the data to binary data - Chunking the binary into smaller chunks - Create presigned urls for each chunk - Upload data to Seaweed via PUT request - Send a acknowledge to Seaweed via PyGrid when all chunks are successfully uploaded - Create a ProxyDataset to store metadata of the uploaded data Args: client (Any): Client to send object to data (Any): Data to be uploaded to Seaweed chunk_size (int): smallest size of the data to be uploaded in bytes asset_name (str): name of the data being uploaded dataset_name Optional[(str)]: name of the dataset to which the data belongs Raises: Exception: If upload of data chunks to Seaweed fails. Returns: ProxyDataset: Class to store metadata about the data that is uploaded to Seaweed. """ data_upload_description = f"Uploading `{asset_name}`" # relative from .node_service.upload_service.upload_service_messages import ( UploadDataCompleteMessage, ) from .node_service.upload_service.upload_service_messages import UploadDataMessage dataset_name = str(dataset_name) # Step 1 - Convert data to be uploaded to binary binary_dataset: bytes = serialize(data, to_bytes=True) # type: ignore file_size = len(binary_dataset) # Step 2 - Send a message to PyGrid to inform of the data being uploaded, # and get presigned url for each chunk of data being uploaded. upload_response = client.datasets.perform_api_request_generic( syft_msg=UploadDataMessage, content={ "filename": f"{dataset_name}/{asset_name}", "file_size": file_size, "chunk_size": chunk_size, "address": client.address, "reply_to": client.address, }, ) try: # Step 3 - Starts to upload binary data into Seaweed. binary_buffer = BytesIO(binary_dataset) parts = sorted(upload_response.payload.parts, key=lambda x: x["part_no"]) etag_chunk_no_pairs = list() data_chunks = zip(read_chunks(binary_buffer, chunk_size), parts) for _ in tqdm( parts, desc=data_upload_description, colour="green", ncols=100, leave=True ): data_chunk, part = next(data_chunks) presigned_url = part["url"] part_no = part["part_no"] client_url = client.url_from_path(presigned_url) part["client_url"] = client_url res = requests.put(client_url, data=data_chunk) if not res.ok: # raise an error if upload fails error_message = ( f"\n\nFailed to upload `{asset_name}` to store\n" + f"Status code: {res.status_code} {res.reason}\n" + f"Error: {str(res.text)}" ) raise DatasetUploadError(message=error_message) etag = res.headers["ETag"] etag_chunk_no_pairs.append( {"ETag": etag, "PartNumber": part_no} ) # maintain list of part no and ETag # Step 4 - Send a message to PyGrid informing about dataset upload complete! upload_response = client.datasets.perform_request( syft_msg=UploadDataCompleteMessage, content={ "upload_id": upload_response.payload.upload_id, "filename": f"{dataset_name}/{asset_name}", "parts": etag_chunk_no_pairs, }, ) # Step 5 - Create a proxy dataset for the uploaded data. # Retrieve fully qualified name to use for pointer creation. obj_public_kwargs = getattr(data, "proxy_public_kwargs", None) data_fqn = str(get_fully_qualified_name(data)) data_dtype = str(type(data)) proxy_data = ProxyDataset( asset_name=asset_name, dataset_name=dataset_name, node_id=client.id, dtype=data_dtype, fqn=data_fqn, shape=data.shape, obj_public_kwargs=obj_public_kwargs, ) except (Exception, KeyboardInterrupt) as e: upload_id = upload_response.payload.upload_id abort_s3_object_upload( client=client, upload_id=upload_id, asset_name=asset_name ) raise e return proxy_data def get_s3_client(settings: BaseSettings) -> "boto3.client.S3": try: s3_endpoint = settings.S3_ENDPOINT s3_port = settings.S3_PORT s3_grid_url = GridURL(host_or_ip=s3_endpoint, port=s3_port) return boto3.client( "s3", endpoint_url=s3_grid_url.url, aws_access_key_id=settings.S3_ROOT_USER, aws_secret_access_key=settings.S3_ROOT_PWD, config=Config(signature_version="s3v4"), region_name=settings.S3_REGION, ) except Exception as e: print(f"Failed to create S3 Client with {s3_endpoint} {s3_port} {s3_grid_url}") raise e def check_send_to_blob_storage(obj: Any, use_blob_storage: bool = False) -> bool: """Check if the data needs to be send to Seaweed storage depending upon its size and type. Args: obj (Any): Data to be stored to Seaweed. use_blob_storage (bool, optional): Explicit flag to send the data to blob storage. Defaults to False. Returns: bool: Returns True if obj can be stored in blob store else returns False. """ # relative from ...tensor import Tensor from ...tensor.autodp.ndim_entity_phi import NDimEntityPhiTensor as NDEPT if use_blob_storage and ( isinstance(obj, (NDEPT, Tensor)) or size_mb(obj) > MIN_BLOB_UPLOAD_SIZE_MB ): return True return False
from project import motor from project import variables # My Blocks from lower_pen import lower_pen from lift_pen import lift_pen def print_v(size): seg4 = variables['Seg4'] lower_pen() motor['A+B'].on_for_degrees(10, -20, seg4) motor['A+B'].on_for_degrees(10, 20, seg4) lift_pen()
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.firebase=e()}(this,function(){"use strict";!function(t){if(!t.fetch){var e={searchParams:"URLSearchParams"in t,iterable:"Symbol"in t&&"iterator"in Symbol,blob:"FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in t,arrayBuffer:"ArrayBuffer"in t};if(e.arrayBuffer)var n=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],r=function(t){return t&&DataView.prototype.isPrototypeOf(t)},i=ArrayBuffer.isView||function(t){return t&&n.indexOf(Object.prototype.toString.call(t))>-1};h.prototype.append=function(t,e){t=s(t),e=u(e);var n=this.map[t];this.map[t]=n?n+","+e:e},h.prototype.delete=function(t){delete this.map[s(t)]},h.prototype.get=function(t){return t=s(t),this.has(t)?this.map[t]:null},h.prototype.has=function(t){return this.map.hasOwnProperty(s(t))},h.prototype.set=function(t,e){this.map[s(t)]=u(e)},h.prototype.forEach=function(t,e){for(var n in this.map)this.map.hasOwnProperty(n)&&t.call(e,this.map[n],n,this)},h.prototype.keys=function(){var t=[];return this.forEach(function(e,n){t.push(n)}),c(t)},h.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),c(t)},h.prototype.entries=function(){var t=[];return this.forEach(function(e,n){t.push([n,e])}),c(t)},e.iterable&&(h.prototype[Symbol.iterator]=h.prototype.entries);var o=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];y.prototype.clone=function(){return new y(this,{body:this._bodyInit})},v.call(y.prototype),v.call(g.prototype),g.prototype.clone=function(){return new g(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},g.error=function(){var t=new g(null,{status:0,statusText:""});return t.type="error",t};var a=[301,302,303,307,308];g.redirect=function(t,e){if(-1===a.indexOf(e))throw new RangeError("Invalid status code");return new g(null,{status:e,headers:{location:t}})},t.Headers=h,t.Request=y,t.Response=g,t.fetch=function(t,n){return new Promise(function(r,i){var o=new y(t,n),a=new XMLHttpRequest;a.onload=function(){var t,e,n={status:a.status,statusText:a.statusText,headers:(t=a.getAllResponseHeaders()||"",e=new h,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(t){var n=t.split(":"),r=n.shift().trim();if(r){var i=n.join(":").trim();e.append(r,i)}}),e)};n.url="responseURL"in a?a.responseURL:n.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;r(new g(i,n))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.open(o.method,o.url,!0),"include"===o.credentials?a.withCredentials=!0:"omit"===o.credentials&&(a.withCredentials=!1),"responseType"in a&&e.blob&&(a.responseType="blob"),o.headers.forEach(function(t,e){a.setRequestHeader(e,t)}),a.send(void 0===o._bodyInit?null:o._bodyInit)})},t.fetch.polyfill=!0}function s(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function u(t){return"string"!=typeof t&&(t=String(t)),t}function c(t){var n={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return e.iterable&&(n[Symbol.iterator]=function(){return n}),n}function h(t){this.map={},t instanceof h?t.forEach(function(t,e){this.append(e,t)},this):Array.isArray(t)?t.forEach(function(t){this.append(t[0],t[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}function l(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function p(t){return new Promise(function(e,n){t.onload=function(){e(t.result)},t.onerror=function(){n(t.error)}})}function f(t){var e=new FileReader,n=p(e);return e.readAsArrayBuffer(t),n}function d(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function v(){return this.bodyUsed=!1,this._initBody=function(t){if(this._bodyInit=t,t)if("string"==typeof t)this._bodyText=t;else if(e.blob&&Blob.prototype.isPrototypeOf(t))this._bodyBlob=t;else if(e.formData&&FormData.prototype.isPrototypeOf(t))this._bodyFormData=t;else if(e.searchParams&&URLSearchParams.prototype.isPrototypeOf(t))this._bodyText=t.toString();else if(e.arrayBuffer&&e.blob&&r(t))this._bodyArrayBuffer=d(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!e.arrayBuffer||!ArrayBuffer.prototype.isPrototypeOf(t)&&!i(t))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=d(t)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):e.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},e.blob&&(this.blob=function(){var t=l(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?l(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(f)}),this.text=function(){var t,e,n,r=l(this);if(r)return r;if(this._bodyBlob)return t=this._bodyBlob,e=new FileReader,n=p(e),e.readAsText(t),n;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),n=new Array(e.length),r=0;r<e.length;r++)n[r]=String.fromCharCode(e[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},e.formData&&(this.formData=function(){return this.text().then(_)}),this.json=function(){return this.text().then(JSON.parse)},this}function y(t,e){var n,r,i=(e=e||{}).body;if(t instanceof y){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new h(t.headers)),this.method=t.method,this.mode=t.mode,i||null==t._bodyInit||(i=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"omit",!e.headers&&this.headers||(this.headers=new h(e.headers)),this.method=(n=e.method||this.method||"GET",r=n.toUpperCase(),o.indexOf(r)>-1?r:n),this.mode=e.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function _(t){var e=new FormData;return t.trim().split("&").forEach(function(t){if(t){var n=t.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");e.append(decodeURIComponent(r),decodeURIComponent(i))}}),e}function g(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new h(e.headers),this.url=e.url||"",this._initBody(t)}}("undefined"!=typeof self?self:void 0);var t=setTimeout;function e(){}function n(t){if(!(this instanceof n))throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],s(t,this)}function r(t,e){for(;3===t._state;)t=t._value;0!==t._state?(t._handled=!0,n._immediateFn(function(){var n=1===t._state?e.onFulfilled:e.onRejected;if(null!==n){var r;try{r=n(t._value)}catch(t){return void o(e.promise,t)}i(e.promise,r)}else(1===t._state?i:o)(e.promise,t._value)})):t._deferreds.push(e)}function i(t,e){try{if(e===t)throw new TypeError("A promise cannot be resolved with itself.");if(e&&("object"==typeof e||"function"==typeof e)){var r=e.then;if(e instanceof n)return t._state=3,t._value=e,void a(t);if("function"==typeof r)return void s((i=r,u=e,function(){i.apply(u,arguments)}),t)}t._state=1,t._value=e,a(t)}catch(e){o(t,e)}var i,u}function o(t,e){t._state=2,t._value=e,a(t)}function a(t){2===t._state&&0===t._deferreds.length&&n._immediateFn(function(){t._handled||n._unhandledRejectionFn(t._value)});for(var e=0,i=t._deferreds.length;e<i;e++)r(t,t._deferreds[e]);t._deferreds=null}function s(t,e){var n=!1;try{t(function(t){n||(n=!0,i(e,t))},function(t){n||(n=!0,o(e,t))})}catch(t){if(n)return;n=!0,o(e,t)}}n.prototype.catch=function(t){return this.then(null,t)},n.prototype.then=function(t,n){var i=new this.constructor(e);return r(this,new function(t,e,n){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof e?e:null,this.promise=n}(t,n,i)),i},n.prototype.finally=function(t){var e=this.constructor;return this.then(function(n){return e.resolve(t()).then(function(){return n})},function(n){return e.resolve(t()).then(function(){return e.reject(n)})})},n.all=function(t){return new n(function(e,n){if(!t||void 0===t.length)throw new TypeError("Promise.all accepts an array");var r=Array.prototype.slice.call(t);if(0===r.length)return e([]);var i=r.length;function o(t,a){try{if(a&&("object"==typeof a||"function"==typeof a)){var s=a.then;if("function"==typeof s)return void s.call(a,function(e){o(t,e)},n)}r[t]=a,0==--i&&e(r)}catch(t){n(t)}}for(var a=0;a<r.length;a++)o(a,r[a])})},n.resolve=function(t){return t&&"object"==typeof t&&t.constructor===n?t:new n(function(e){e(t)})},n.reject=function(t){return new n(function(e,n){n(t)})},n.race=function(t){return new n(function(e,n){for(var r=0,i=t.length;r<i;r++)t[r].then(e,n)})},n._immediateFn="function"==typeof setImmediate&&function(t){setImmediate(t)}||function(e){t(e,0)},n._unhandledRejectionFn=function(t){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",t)};var u=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("unable to locate global object")}();function c(t,e){return t(e={exports:{}},e.exports),e.exports}u.Promise||(u.Promise=n);var h=c(function(t){var e=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=e)}),l=c(function(t){var e=t.exports={version:"2.5.5"};"number"==typeof __e&&(__e=e)}),p=(l.version,function(t){return"object"==typeof t?null!==t:"function"==typeof t}),f=function(t){if(!p(t))throw TypeError(t+" is not an object!");return t},d=function(t){try{return!!t()}catch(t){return!0}},v=!d(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),y=h.document,_=p(y)&&p(y.createElement),g=!v&&!d(function(){return 7!=Object.defineProperty((t="div",_?y.createElement(t):{}),"a",{get:function(){return 7}}).a;var t}),m=Object.defineProperty,b={f:v?Object.defineProperty:function(t,e,n){if(f(t),e=function(t,e){if(!p(t))return t;var n,r;if(e&&"function"==typeof(n=t.toString)&&!p(r=n.call(t)))return r;if("function"==typeof(n=t.valueOf)&&!p(r=n.call(t)))return r;if(!e&&"function"==typeof(n=t.toString)&&!p(r=n.call(t)))return r;throw TypeError("Can't convert object to primitive value")}(e,!0),f(n),g)try{return m(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}},w=v?function(t,e,n){return b.f(t,e,function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}(1,n))}:function(t,e,n){return t[e]=n,t},E={}.hasOwnProperty,T=function(t,e){return E.call(t,e)},C=0,S=Math.random(),I=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++C+S).toString(36))},N=c(function(t){var e=I("src"),n=Function.toString,r=(""+n).split("toString");l.inspectSource=function(t){return n.call(t)},(t.exports=function(t,n,i,o){var a="function"==typeof i;a&&(T(i,"name")||w(i,"name",n)),t[n]!==i&&(a&&(T(i,e)||w(i,e,t[n]?""+t[n]:r.join(String(n)))),t===h?t[n]=i:o?t[n]?t[n]=i:w(t,n,i):(delete t[n],w(t,n,i)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[e]||n.call(this)})}),R=function(t,e,n){if(function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!")}(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)}},A=function(t,e,n){var r,i,o,a,s=t&A.F,u=t&A.G,c=t&A.S,p=t&A.P,f=t&A.B,d=u?h:c?h[e]||(h[e]={}):(h[e]||{}).prototype,v=u?l:l[e]||(l[e]={}),y=v.prototype||(v.prototype={});for(r in u&&(n=e),n)o=((i=!s&&d&&void 0!==d[r])?d:n)[r],a=f&&i?R(o,h):p&&"function"==typeof o?R(Function.call,o):o,d&&N(d,r,o,t&A.U),v[r]!=o&&w(v,r,a),p&&y[r]!=o&&(y[r]=o)};h.core=l,A.F=1,A.G=2,A.S=4,A.P=8,A.B=16,A.W=32,A.U=64,A.R=128;var k=A,O={}.toString,P=function(t){return O.call(t).slice(8,-1)},D=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==P(t)?t.split(""):Object(t)},L=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t},x=Math.ceil,F=Math.floor,U=Math.min,M=function(t){return t>0?U(function(t){return isNaN(t=+t)?0:(t>0?F:x)(t)}(t),9007199254740991):0},W=Array.isArray||function(t){return"Array"==P(t)},B=h["__core-js_shared__"]||(h["__core-js_shared__"]={}),j=function(t){return B[t]||(B[t]={})},V=c(function(t){var e=j("wks"),n=h.Symbol,r="function"==typeof n;(t.exports=function(t){return e[t]||(e[t]=r&&n[t]||(r?n:I)("Symbol."+t))}).store=e}),q=V("species"),H=function(t,e){return new(function(t){var e;return W(t)&&("function"!=typeof(e=t.constructor)||e!==Array&&!W(e.prototype)||(e=void 0),p(e)&&null===(e=e[q])&&(e=void 0)),void 0===e?Array:e}(t))(e)},K=function(t,e){var n=1==t,r=2==t,i=3==t,o=4==t,a=6==t,s=5==t||a,u=e||H;return function(e,c,h){for(var l,p,f=Object(L(e)),d=D(f),v=R(c,h,3),y=M(d.length),_=0,g=n?u(e,y):r?u(e,0):void 0;y>_;_++)if((s||_ in d)&&(p=v(l=d[_],_,f),t))if(n)g[_]=p;else if(p)switch(t){case 3:return!0;case 5:return l;case 6:return _;case 2:g.push(l)}else if(o)return!1;return a?-1:i||o?o:g}},G=V("unscopables"),Q=Array.prototype;void 0==Q[G]&&w(Q,G,{});var z=function(t){Q[G][t]=!0},Y=K(5),X=!0;"find"in[]&&Array(1).find(function(){X=!1}),k(k.P+k.F*X,"Array",{find:function(t){return Y(this,t,arguments.length>1?arguments[1]:void 0)}}),z("find");l.Array.find;var $=K(6),J=!0;"findIndex"in[]&&Array(1).findIndex(function(){J=!1}),k(k.P+k.F*J,"Array",{findIndex:function(t){return $(this,t,arguments.length>1?arguments[1]:void 0)}}),z("findIndex");l.Array.findIndex;var Z=V("match"),tt=function(t,e,n){if(p(r=e)&&(void 0!==(i=r[Z])?i:"RegExp"==P(r)))throw TypeError("String#"+n+" doesn't accept regex!");var r,i;return String(L(t))},et=V("match"),nt="".startsWith;k(k.P+k.F*function(t){var e=/./;try{"/./"[t](e)}catch(n){try{return e[et]=!1,!"/./"[t](e)}catch(t){}}return!0}("startsWith"),"String",{startsWith:function(t){var e=tt(this,t,"startsWith"),n=M(Math.min(arguments.length>1?arguments[1]:void 0,e.length)),r=String(t);return nt?nt.call(e,r,n):e.slice(n,n+r.length)===r}});l.String.startsWith;var rt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};function it(t,e){function n(){this.constructor=t}rt(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var ot=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t};function at(t,e,n,r){return new(n||(n=Promise))(function(i,o){function a(t){try{u(r.next(t))}catch(t){o(t)}}function s(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(a,s)}u((r=r.apply(t,e||[])).next())})}function st(t,e){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=r[2&o[0]?"return":o[0]?"throw":"next"])&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[0,i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=e.call(t,a)}catch(t){o=[6,t],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}var ut=!1,ct=!1,ht="${JSCORE_VERSION}",lt=function(t,e){if(!t)throw pt(e)},pt=function(t){return new Error("Firebase Database ("+ht+") INTERNAL ASSERT FAILED: "+t)},ft=function(t){for(var e=[],n=0,r=0;r<t.length;r++){var i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=63&i|128):55296==(64512&i)&&r+1<t.length&&56320==(64512&t.charCodeAt(r+1))?(i=65536+((1023&i)<<10)+(1023&t.charCodeAt(++r)),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=63&i|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=63&i|128)}return e},dt={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray:function(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();for(var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[],i=0;i<t.length;i+=3){var o=t[i],a=i+1<t.length,s=a?t[i+1]:0,u=i+2<t.length,c=u?t[i+2]:0,h=o>>2,l=(3&o)<<4|s>>4,p=(15&s)<<2|c>>6,f=63&c;u||(f=64,a||(p=64)),r.push(n[h],n[l],n[p],n[f])}return r.join("")},encodeString:function(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(ft(t),e)},decodeString:function(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):function(t){for(var e=[],n=0,r=0;n<t.length;){var i=t[n++];if(i<128)e[r++]=String.fromCharCode(i);else if(i>191&&i<224){var o=t[n++];e[r++]=String.fromCharCode((31&i)<<6|63&o)}else if(i>239&&i<365){var a=((7&i)<<18|(63&(o=t[n++]))<<12|(63&(s=t[n++]))<<6|63&t[n++])-65536;e[r++]=String.fromCharCode(55296+(a>>10)),e[r++]=String.fromCharCode(56320+(1023&a))}else{o=t[n++];var s=t[n++];e[r++]=String.fromCharCode((15&i)<<12|(63&o)<<6|63&s)}}return e.join("")}(this.decodeStringToByteArray(t,e))},decodeStringToByteArray:function(t,e){this.init_();for(var n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[],i=0;i<t.length;){var o=n[t.charAt(i++)],a=i<t.length?n[t.charAt(i)]:0,s=++i<t.length?n[t.charAt(i)]:64,u=++i<t.length?n[t.charAt(i)]:64;if(++i,null==o||null==a||null==s||null==u)throw Error();var c=o<<2|a>>4;if(r.push(c),64!=s){var h=a<<4&240|s>>2;if(r.push(h),64!=u){var l=s<<6&192|u;r.push(l)}}}return r},init_:function(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(var t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}},vt=function(t){try{return dt.decodeString(t,!0)}catch(t){console.error("base64Decode failed: ",t)}return null};function yt(t){return _t(void 0,t)}function _t(t,e){if(!(e instanceof Object))return e;switch(e.constructor){case Date:return new Date(e.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return e}for(var n in e)e.hasOwnProperty(n)&&(t[n]=_t(t[n],e[n]));return t}function gt(t,e,n){t[e]=n}var mt=function(){function t(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}return t.prototype.wrapCallback=function(t){var e=this;return function(n,r){n?e.reject(n):e.resolve(r),"function"==typeof t&&(e.promise.catch(function(){}),1===t.length?t(n):t(n,r))}},t}(),bt=function(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test("undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"")},wt=function(){return!0===ut||!0===ct},Et="FirebaseError",Tt=Error.captureStackTrace,Ct=function(){return function(t,e){if(this.code=t,this.message=e,Tt)Tt(this,St.prototype.create);else{var n=Error.apply(this,arguments);this.name=Et,Object.defineProperty(this,"stack",{get:function(){return n.stack}})}}}();Ct.prototype=Object.create(Error.prototype),Ct.prototype.constructor=Ct,Ct.prototype.name=Et;var St=function(){function t(t,e,n){this.service=t,this.serviceName=e,this.errors=n,this.pattern=/\{\$([^}]+)}/g}return t.prototype.create=function(t,e){void 0===e&&(e={});var n,r=this.errors[t],i=this.service+"/"+t;n=void 0===r?"Error":r.replace(this.pattern,function(t,n){var r=e[n];return void 0!==r?r.toString():"<"+n+"?>"}),n=this.serviceName+": "+n+" ("+i+").";var o=new Ct(i,n);for(var a in e)e.hasOwnProperty(a)&&"_"!==a.slice(-1)&&(o[a]=e[a]);return o},t}();function It(t){return JSON.parse(t)}function Nt(t){return JSON.stringify(t)}var Rt=function(t){var e={},n={},r={},i="";try{var o=t.split(".");e=It(vt(o[0])||""),n=It(vt(o[1])||""),i=o[2],r=n.d||{},delete n.d}catch(t){}return{header:e,claims:n,data:r,signature:i}},At=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},kt=function(t,e){if(Object.prototype.hasOwnProperty.call(t,e))return t[e]},Ot=function(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(n,t[n])},Pt=function(t){return e={},Ot(t,function(t,n){e[t]=n}),e;var e},Dt=function(t){for(var e in t)return!1;return!0},Lt=function(t){var e=0;for(var n in t)e++;return e},xt=function(t,e,n){var r={};for(var i in t)r[i]=e.call(n,t[i],i,t);return r},Ft=function(t,e,n){for(var r in t)if(e.call(n,t[r],r,t))return r},Ut=function(t){for(var e in t)return e},Mt=function(t){function e(){var e=t.call(this)||this;e.chain_=[],e.buf_=[],e.W_=[],e.pad_=[],e.inbuf_=0,e.total_=0,e.blockSize=64,e.pad_[0]=128;for(var n=1;n<e.blockSize;++n)e.pad_[n]=0;return e.reset(),e}return it(e,t),e.prototype.reset=function(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0},e.prototype.compress_=function(t,e){e||(e=0);var n=this.W_;if("string"==typeof t)for(var r=0;r<16;r++)n[r]=t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|t.charCodeAt(e+3),e+=4;else for(r=0;r<16;r++)n[r]=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3],e+=4;for(r=16;r<80;r++){var i=n[r-3]^n[r-8]^n[r-14]^n[r-16];n[r]=4294967295&(i<<1|i>>>31)}var o,a,s=this.chain_[0],u=this.chain_[1],c=this.chain_[2],h=this.chain_[3],l=this.chain_[4];for(r=0;r<80;r++){r<40?r<20?(o=h^u&(c^h),a=1518500249):(o=u^c^h,a=1859775393):r<60?(o=u&c|h&(u|c),a=2400959708):(o=u^c^h,a=3395469782);i=(s<<5|s>>>27)+o+l+a+n[r]&4294967295;l=h,h=c,c=4294967295&(u<<30|u>>>2),u=s,s=i}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+u&4294967295,this.chain_[2]=this.chain_[2]+c&4294967295,this.chain_[3]=this.chain_[3]+h&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295},e.prototype.update=function(t,e){if(null!=t){void 0===e&&(e=t.length);for(var n=e-this.blockSize,r=0,i=this.buf_,o=this.inbuf_;r<e;){if(0==o)for(;r<=n;)this.compress_(t,r),r+=this.blockSize;if("string"==typeof t){for(;r<e;)if(i[o]=t.charCodeAt(r),++r,++o==this.blockSize){this.compress_(i),o=0;break}}else for(;r<e;)if(i[o]=t[r],++r,++o==this.blockSize){this.compress_(i),o=0;break}}this.inbuf_=o,this.total_+=e}},e.prototype.digest=function(){var t=[],e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(var n=this.blockSize-1;n>=56;n--)this.buf_[n]=255&e,e/=256;this.compress_(this.buf_);var r=0;for(n=0;n<5;n++)for(var i=24;i>=0;i-=8)t[r]=this.chain_[n]>>i&255,++r;return t},e}(function(){return function(){this.blockSize=-1}}());function Wt(t,e){var n=new Bt(t,e);return n.subscribe.bind(n)}var Bt=function(){function t(t,e){var n=this;this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=e,this.task.then(function(){t(n)}).catch(function(t){n.error(t)})}return t.prototype.next=function(t){this.forEachObserver(function(e){e.next(t)})},t.prototype.error=function(t){this.forEachObserver(function(e){e.error(t)}),this.close(t)},t.prototype.complete=function(){this.forEachObserver(function(t){t.complete()}),this.close()},t.prototype.subscribe=function(t,e,n){var r,i=this;if(void 0===t&&void 0===e&&void 0===n)throw new Error("Missing Observer.");void 0===(r=function(t,e){if("object"!=typeof t||null===t)return!1;for(var n=0,r=e;n<r.length;n++){var i=r[n];if(i in t&&"function"==typeof t[i])return!0}return!1}(t,["next","error","complete"])?t:{next:t,error:e,complete:n}).next&&(r.next=jt),void 0===r.error&&(r.error=jt),void 0===r.complete&&(r.complete=jt);var o=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(function(){try{i.finalError?r.error(i.finalError):r.complete()}catch(t){}}),this.observers.push(r),o},t.prototype.unsubscribeOne=function(t){void 0!==this.observers&&void 0!==this.observers[t]&&(delete this.observers[t],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))},t.prototype.forEachObserver=function(t){if(!this.finalized)for(var e=0;e<this.observers.length;e++)this.sendOne(e,t)},t.prototype.sendOne=function(t,e){var n=this;this.task.then(function(){if(void 0!==n.observers&&void 0!==n.observers[t])try{e(n.observers[t])}catch(t){"undefined"!=typeof console&&console.error&&console.error(t)}})},t.prototype.close=function(t){var e=this;this.finalized||(this.finalized=!0,void 0!==t&&(this.finalError=t),this.task.then(function(){e.observers=void 0,e.onNoObservers=void 0}))},t}();function jt(){}var Vt=function(t,e,n,r){var i;if(r<e?i="at least "+e:r>n&&(i=0===n?"none":"no more than "+n),i)throw new Error(t+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".")};function qt(t,e,n){var r="";switch(e){case 1:r=n?"first":"First";break;case 2:r=n?"second":"Second";break;case 3:r=n?"third":"Third";break;case 4:r=n?"fourth":"Fourth";break;default:throw new Error("errorPrefix called with argumentNumber > 4. Need to update it?")}var i=t+" failed: ";return i+=r+" argument "}function Ht(t,e,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(qt(t,e,r)+"must be a valid function.")}function Kt(t,e,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(qt(t,e,r)+"must be a valid context object.")}var Gt=function(t){for(var e=0,n=0;n<t.length;n++){var r=t.charCodeAt(n);r<128?e++:r<2048?e+=2:r>=55296&&r<=56319?(e+=4,n++):e+=3}return e},Qt=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},zt="[DEFAULT]",Yt=[],Xt=function(){function t(t,e,n){this.firebase_=n,this.isDeleted_=!1,this.services_={},this.name_=e.name,this._automaticDataCollectionEnabled=e.automaticDataCollectionEnabled||!1,this.options_=yt(t),this.INTERNAL={getUid:function(){return null},getToken:function(){return Promise.resolve(null)},addAuthTokenListener:function(t){Yt.push(t),setTimeout(function(){return t(null)},0)},removeAuthTokenListener:function(t){Yt=Yt.filter(function(e){return e!==t})}}}return Object.defineProperty(t.prototype,"automaticDataCollectionEnabled",{get:function(){return this.checkDestroyed_(),this._automaticDataCollectionEnabled},set:function(t){this.checkDestroyed_(),this._automaticDataCollectionEnabled=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return this.checkDestroyed_(),this.name_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return this.checkDestroyed_(),this.options_},enumerable:!0,configurable:!0}),t.prototype.delete=function(){var t=this;return new Promise(function(e){t.checkDestroyed_(),e()}).then(function(){t.firebase_.INTERNAL.removeApp(t.name_);var e=[];return Object.keys(t.services_).forEach(function(n){Object.keys(t.services_[n]).forEach(function(r){e.push(t.services_[n][r])})}),Promise.all(e.map(function(t){return t.INTERNAL.delete()}))}).then(function(){t.isDeleted_=!0,t.services_={}})},t.prototype._getService=function(t,e){if(void 0===e&&(e=zt),this.checkDestroyed_(),this.services_[t]||(this.services_[t]={}),!this.services_[t][e]){var n=e!==zt?e:void 0,r=this.firebase_.INTERNAL.factories[t](this,this.extendApp.bind(this),n);this.services_[t][e]=r}return this.services_[t][e]},t.prototype.extendApp=function(t){var e=this;_t(this,t),t.INTERNAL&&t.INTERNAL.addAuthTokenListener&&(Yt.forEach(function(t){e.INTERNAL.addAuthTokenListener(t)}),Yt=[])},t.prototype.checkDestroyed_=function(){this.isDeleted_&&$t("app-deleted",{name:this.name_})},t}();function $t(t,e){throw Zt.create(t,e)}Xt.prototype.name&&Xt.prototype.options||Xt.prototype.delete||console.log("dc");var Jt,Zt=new St("app","Firebase",{"no-app":"No Firebase App '{$name}' has been created - call Firebase App.initializeApp()","bad-app-name":"Illegal App name: '{$name}","duplicate-app":"Firebase App named '{$name}' already exists","app-deleted":"Firebase App named '{$name}' already deleted","duplicate-service":"Firebase service named '{$name}' already registered","sa-not-supported":"Initializing the Firebase SDK with a service account is only allowed in a Node.js environment. On client devices, you should instead initialize the SDK with an api key and auth domain","invalid-app-argument":"firebase.{$name}() takes either no argument or a Firebase App instance."}),te=function t(){var e={},n={},r={},i={__esModule:!0,initializeApp:function(t,n){if(void 0===n&&(n={}),"object"!=typeof n||null===n){var r=n;n={name:r}}var o=n;void 0===o.name&&(o.name=zt);var a=o.name;"string"==typeof a&&a||$t("bad-app-name",{name:a+""}),Qt(e,a)&&$t("duplicate-app",{name:a});var u=new Xt(t,o,i);return e[a]=u,s(u,"create"),u},app:o,apps:null,Promise:Promise,SDK_VERSION:"4.13.1",INTERNAL:{registerService:function(t,e,s,u,c){n[t]&&$t("duplicate-service",{name:t}),n[t]=e,u&&(r[t]=u,a().forEach(function(t){u("create",t)}));var h=function(e){return void 0===e&&(e=o()),"function"!=typeof e[t]&&$t("invalid-app-argument",{name:t}),e[t]()};return void 0!==s&&_t(h,s),i[t]=h,Xt.prototype[t]=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return this._getService.bind(this,t).apply(this,c?e:[])},h},createFirebaseNamespace:t,extendNamespace:function(t){_t(i,t)},createSubscribe:Wt,ErrorFactory:St,removeApp:function(t){s(e[t],"delete"),delete e[t]},factories:n,useAsService:u,Promise:Promise,deepExtend:_t}};function o(t){return Qt(e,t=t||zt)||$t("no-app",{name:t}),e[t]}function a(){return Object.keys(e).map(function(t){return e[t]})}function s(t,e){Object.keys(n).forEach(function(n){var i=u(t,n);null!==i&&r[i]&&r[i](e,t)})}function u(t,e){if("serverAuth"===e)return null;var n=e;return t.options,n}return gt(i,"default",i),Object.defineProperty(i,"apps",{get:a}),gt(o,"App",Xt),i}(),ee=Object.freeze({default:te,firebase:te}),ne=ee&&te||ee,re=ne.default,ie="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};(function(){var t,e=ne.default,n=n||{},r=this;function i(t){return"string"==typeof t}function o(t){return"boolean"==typeof t}function a(){}function s(t){var e=typeof t;if("object"==e){if(!t)return"null";if(t instanceof Array)return"array";if(t instanceof Object)return e;var n=Object.prototype.toString.call(t);if("[object Window]"==n)return"object";if("[object Array]"==n||"number"==typeof t.length&&void 0!==t.splice&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("splice"))return"array";if("[object Function]"==n||void 0!==t.call&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("call"))return"function"}else if("function"==e&&void 0===t.call)return"object";return e}function u(t){return null===t}function c(t){return"array"==s(t)}function h(t){var e=s(t);return"array"==e||"object"==e&&"number"==typeof t.length}function l(t){return"function"==s(t)}function p(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}var f="closure_uid_"+(1e9*Math.random()>>>0),d=0;function v(t,e,n){return t.call.apply(t.bind,arguments)}function y(t,e,n){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),t.apply(e,n)}}return function(){return t.apply(e,arguments)}}function _(t,e,n){return(_=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?v:y).apply(null,arguments)}function g(t,e){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}var m=Date.now||function(){return+new Date};function b(t,e){function n(){}n.prototype=e.prototype,t.lb=e.prototype,t.prototype=new n,t.prototype.constructor=t,t.ad=function(t,n,r){for(var i=Array(arguments.length-2),o=2;o<arguments.length;o++)i[o-2]=arguments[o];return e.prototype[n].apply(t,i)}}function w(t){t.prototype.then=t.prototype.then,t.prototype.$goog_Thenable=!0}function E(t){if(!t)return!1;try{return!!t.$goog_Thenable}catch(t){return!1}}function T(t){if(Error.captureStackTrace)Error.captureStackTrace(this,T);else{var e=Error().stack;e&&(this.stack=e)}t&&(this.message=String(t))}function C(t,e){for(var n="",r=(t=t.split("%s")).length-1,i=0;i<r;i++)n+=t[i]+(i<e.length?e[i]:"%s");T.call(this,n+t[r])}function S(t,e){throw new C("Failure"+(t?": "+t:""),Array.prototype.slice.call(arguments,1))}function I(t,e){this.c=t,this.f=e,this.b=0,this.a=null}function N(t,e){t.f(e),100>t.b&&(t.b++,e.next=t.a,t.a=e)}function R(){this.b=this.a=null}b(T,Error),T.prototype.name="CustomError",b(C,T),C.prototype.name="AssertionError",I.prototype.get=function(){if(0<this.b){this.b--;var t=this.a;this.a=t.next,t.next=null}else t=this.c();return t};var A=new I(function(){return new O},function(t){t.reset()});function k(){var t=ft,e=null;return t.a&&(e=t.a,t.a=t.a.next,t.a||(t.b=null),e.next=null),e}function O(){this.next=this.b=this.a=null}R.prototype.add=function(t,e){var n=A.get();n.set(t,e),this.b?this.b.next=n:this.a=n,this.b=n},O.prototype.set=function(t,e){this.a=t,this.b=e,this.next=null},O.prototype.reset=function(){this.next=this.b=this.a=null};var P=Array.prototype.indexOf?function(t,e){return Array.prototype.indexOf.call(t,e,void 0)}:function(t,e){if(i(t))return i(e)&&1==e.length?t.indexOf(e,0):-1;for(var n=0;n<t.length;n++)if(n in t&&t[n]===e)return n;return-1},D=Array.prototype.forEach?function(t,e,n){Array.prototype.forEach.call(t,e,n)}:function(t,e,n){for(var r=t.length,o=i(t)?t.split(""):t,a=0;a<r;a++)a in o&&e.call(n,o[a],a,t)};var L=Array.prototype.map?function(t,e){return Array.prototype.map.call(t,e,void 0)}:function(t,e){for(var n=t.length,r=Array(n),o=i(t)?t.split(""):t,a=0;a<n;a++)a in o&&(r[a]=e.call(void 0,o[a],a,t));return r},x=Array.prototype.some?function(t,e){return Array.prototype.some.call(t,e,void 0)}:function(t,e){for(var n=t.length,r=i(t)?t.split(""):t,o=0;o<n;o++)if(o in r&&e.call(void 0,r[o],o,t))return!0;return!1};function F(t,e){return 0<=P(t,e)}function U(t,e){var n;return(n=0<=(e=P(t,e)))&&Array.prototype.splice.call(t,e,1),n}function M(t,e){!function(t,e){var n=t.length,r=i(t)?t.split(""):t;for(--n;0<=n;--n)n in r&&e.call(void 0,r[n],n,t)}(t,function(n,r){e.call(void 0,n,r,t)&&1==Array.prototype.splice.call(t,r,1).length&&0})}function W(t){return Array.prototype.concat.apply([],arguments)}function B(t){var e=t.length;if(0<e){for(var n=Array(e),r=0;r<e;r++)n[r]=t[r];return n}return[]}function j(t,e){for(var n=t.split("%s"),r="",i=Array.prototype.slice.call(arguments,1);i.length&&1<n.length;)r+=n.shift()+i.shift();return r+n.join("%s")}var V=String.prototype.trim?function(t){return t.trim()}:function(t){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(t)[1]};function q(t){return $.test(t)?(-1!=t.indexOf("&")&&(t=t.replace(K,"&amp;")),-1!=t.indexOf("<")&&(t=t.replace(G,"&lt;")),-1!=t.indexOf(">")&&(t=t.replace(Q,"&gt;")),-1!=t.indexOf('"')&&(t=t.replace(z,"&quot;")),-1!=t.indexOf("'")&&(t=t.replace(Y,"&#39;")),-1!=t.indexOf("\0")&&(t=t.replace(X,"&#0;")),t):t}var H,K=/&/g,G=/</g,Q=/>/g,z=/"/g,Y=/'/g,X=/\x00/g,$=/[\x00&<>"']/;function J(t,e){return-1!=t.indexOf(e)}function Z(t,e){return t<e?-1:t>e?1:0}t:{var tt=r.navigator;if(tt){var et=tt.userAgent;if(et){H=et;break t}}H=""}function nt(t){return J(H,t)}function rt(t,e){for(var n in t)e.call(void 0,t[n],n,t)}function it(t){for(var e in t)return!1;return!0}function ot(t){var e,n={};for(e in t)n[e]=t[e];return n}var at,st,ut="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function ct(t,e){for(var n,r,i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(var o=0;o<ut.length;o++)n=ut[o],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function ht(t){r.setTimeout(function(){throw t},0)}function lt(t,e){st||function(){if(r.Promise&&r.Promise.resolve){var t=r.Promise.resolve(void 0);st=function(){t.then(dt)}}else st=function(){var t=dt;!l(r.setImmediate)||r.Window&&r.Window.prototype&&!nt("Edge")&&r.Window.prototype.setImmediate==r.setImmediate?(at||(at=function(){var t=r.MessageChannel;if(void 0===t&&"undefined"!=typeof window&&window.postMessage&&window.addEventListener&&!nt("Presto")&&(t=function(){var t=document.createElement("IFRAME");t.style.display="none",t.src="",document.documentElement.appendChild(t);var e=t.contentWindow;(t=e.document).open(),t.write(""),t.close();var n="callImmediate"+Math.random(),r="file:"==e.location.protocol?"*":e.location.protocol+"//"+e.location.host;t=_(function(t){"*"!=r&&t.origin!=r||t.data!=n||this.port1.onmessage()},this),e.addEventListener("message",t,!1),this.port1={},this.port2={postMessage:function(){e.postMessage(n,r)}}}),void 0!==t&&!nt("Trident")&&!nt("MSIE")){var e=new t,n={},i=n;return e.port1.onmessage=function(){if(void 0!==n.next){var t=(n=n.next).rb;n.rb=null,t()}},function(t){i.next={rb:t},i=i.next,e.port2.postMessage(0)}}return"undefined"!=typeof document&&"onreadystatechange"in document.createElement("SCRIPT")?function(t){var e=document.createElement("SCRIPT");e.onreadystatechange=function(){e.onreadystatechange=null,e.parentNode.removeChild(e),e=null,t(),t=null},document.documentElement.appendChild(e)}:function(t){r.setTimeout(t,0)}}()),at(t)):r.setImmediate(t)}}(),pt||(st(),pt=!0),ft.add(t,e)}var pt=!1,ft=new R;function dt(){for(var t;t=k();){try{t.a.call(t.b)}catch(t){ht(t)}N(A,t)}pt=!1}function vt(t,e){if(this.a=yt,this.j=void 0,this.f=this.b=this.c=null,this.g=this.h=!1,t!=a)try{var n=this;t.call(e,function(t){Nt(n,_t,t)},function(t){if(!(t instanceof Lt))try{if(t instanceof Error)throw t;throw Error("Promise rejected.")}catch(t){}Nt(n,gt,t)})}catch(t){Nt(this,gt,t)}}var yt=0,_t=2,gt=3;function mt(){this.next=this.f=this.b=this.g=this.a=null,this.c=!1}mt.prototype.reset=function(){this.f=this.b=this.g=this.a=null,this.c=!1};var bt=new I(function(){return new mt},function(t){t.reset()});function wt(t,e,n){var r=bt.get();return r.g=t,r.b=e,r.f=n,r}function Et(t){if(t instanceof vt)return t;var e=new vt(a);return Nt(e,_t,t),e}function Tt(t){return new vt(function(e,n){n(t)})}function Ct(t,e,n){Rt(t,e,n,null)||lt(g(e,t))}function St(t,e){t.b||t.a!=_t&&t.a!=gt||At(t),t.f?t.f.next=e:t.b=e,t.f=e}function It(t,e,n,r){var i=wt(null,null,null);return i.a=new vt(function(t,o){i.g=e?function(n){try{var i=e.call(r,n);t(i)}catch(t){o(t)}}:t,i.b=n?function(e){try{var i=n.call(r,e);void 0===i&&e instanceof Lt?o(e):t(i)}catch(t){o(t)}}:o}),i.a.c=t,St(t,i),i.a}function Nt(t,e,n){t.a==yt&&(t===n&&(e=gt,n=new TypeError("Promise cannot resolve to itself")),t.a=1,Rt(n,t.Kc,t.Lc,t)||(t.j=n,t.a=e,t.c=null,At(t),e!=gt||n instanceof Lt||function(t,e){t.g=!0,lt(function(){t.g&&Dt.call(null,e)})}(t,n)))}function Rt(t,e,n,r){if(t instanceof vt)return St(t,wt(e||a,n||null,r)),!0;if(E(t))return t.then(e,n,r),!0;if(p(t))try{var i=t.then;if(l(i))return function(t,e,n,r,i){function o(t){a||(a=!0,r.call(i,t))}var a=!1;try{e.call(t,function(t){a||(a=!0,n.call(i,t))},o)}catch(t){o(t)}}(t,i,e,n,r),!0}catch(t){return n.call(r,t),!0}return!1}function At(t){t.h||(t.h=!0,lt(t.Ub,t))}function kt(t){var e=null;return t.b&&(e=t.b,t.b=e.next,e.next=null),t.b||(t.f=null),e}function Ot(t,e,n,r){if(n==gt&&e.b&&!e.c)for(;t&&t.g;t=t.c)t.g=!1;if(e.a)e.a.c=null,Pt(e,n,r);else try{e.c?e.g.call(e.f):Pt(e,n,r)}catch(t){Dt.call(null,t)}N(bt,e)}function Pt(t,e,n){e==_t?t.g.call(t.f,n):t.b&&t.b.call(t.f,n)}vt.prototype.then=function(t,e,n){return It(this,l(t)?t:null,l(e)?e:null,n)},w(vt),(t=vt.prototype).ha=function(t,e){return(t=wt(t,t,e)).c=!0,St(this,t),this},t.m=function(t,e){return It(this,null,t,e)},t.cancel=function(t){this.a==yt&&lt(function(){!function t(e,n){if(e.a==yt)if(e.c){var r=e.c;if(r.b){for(var i=0,o=null,a=null,s=r.b;s&&(s.c||(i++,s.a==e&&(o=s),!(o&&1<i)));s=s.next)o||(a=s);o&&(r.a==yt&&1==i?t(r,n):(a?((i=a).next==r.f&&(r.f=i),i.next=i.next.next):kt(r),Ot(r,o,gt,n)))}e.c=null}else Nt(e,gt,n)}(this,new Lt(t))},this)},t.Kc=function(t){this.a=yt,Nt(this,_t,t)},t.Lc=function(t){this.a=yt,Nt(this,gt,t)},t.Ub=function(){for(var t;t=kt(this);)Ot(this,t,this.a,this.j);this.h=!1};var Dt=ht;function Lt(t){T.call(this,t)}function xt(){0!=Ft&&(Ut[this[f]||(this[f]=++d)]=this),this.pa=this.pa,this.oa=this.oa}b(Lt,T),Lt.prototype.name="cancel";var Ft=0,Ut={};function Mt(t){if(!t.pa&&(t.pa=!0,t.ua(),0!=Ft)){var e=t[f]||(t[f]=++d);if(0!=Ft&&t.oa&&0<t.oa.length)throw Error(t+" did not empty its onDisposeCallbacks queue. This probably means it overrode dispose() or disposeInternal() without calling the superclass' method.");delete Ut[e]}}function Wt(t){return Wt[" "](t),t}xt.prototype.pa=!1,xt.prototype.ua=function(){if(this.oa)for(;this.oa.length;)this.oa.shift()()},Wt[" "]=a;var Bt,jt,Vt=nt("Opera"),qt=nt("Trident")||nt("MSIE"),Ht=nt("Edge"),Kt=Ht||qt,Gt=nt("Gecko")&&!(J(H.toLowerCase(),"webkit")&&!nt("Edge"))&&!(nt("Trident")||nt("MSIE"))&&!nt("Edge"),Qt=J(H.toLowerCase(),"webkit")&&!nt("Edge");function zt(){var t=r.document;return t?t.documentMode:void 0}t:{var Yt="",Xt=(jt=H,Gt?/rv:([^\);]+)(\)|;)/.exec(jt):Ht?/Edge\/([\d\.]+)/.exec(jt):qt?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(jt):Qt?/WebKit\/(\S+)/.exec(jt):Vt?/(?:Version)[ \/]?(\S+)/.exec(jt):void 0);if(Xt&&(Yt=Xt?Xt[1]:""),qt){var $t=zt();if(null!=$t&&$t>parseFloat(Yt)){Bt=String($t);break t}}Bt=Yt}var Jt,Zt={};function te(t){return function(t,e){var n=Zt;return Object.prototype.hasOwnProperty.call(n,t)?n[t]:n[t]=e(t)}(t,function(){for(var e=0,n=V(String(Bt)).split("."),r=V(String(t)).split("."),i=Math.max(n.length,r.length),o=0;0==e&&o<i;o++){var a=n[o]||"",s=r[o]||"";do{if(a=/(\d*)(\D*)(.*)/.exec(a)||["","","",""],s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],0==a[0].length&&0==s[0].length)break;e=Z(0==a[1].length?0:parseInt(a[1],10),0==s[1].length?0:parseInt(s[1],10))||Z(0==a[2].length,0==s[2].length)||Z(a[2],s[2]),a=a[3],s=s[3]}while(0==e)}return 0<=e})}var ee=r.document;Jt=ee&&qt?zt()||("CSS1Compat"==ee.compatMode?parseInt(Bt,10):5):void 0;var re=Object.freeze||function(t){return t},ie=!qt||9<=Number(Jt),oe=qt&&!te("9"),ae=function(){if(!r.addEventListener||!Object.defineProperty)return!1;var t=!1,e=Object.defineProperty({},"passive",{get:function(){t=!0}});return r.addEventListener("test",a,e),r.removeEventListener("test",a,e),t}();function se(t,e){this.type=t,this.b=this.target=e,this.Eb=!0}function ue(t,e){if(se.call(this,t?t.type:""),this.relatedTarget=this.b=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.pointerId=0,this.pointerType="",this.a=null,t){var n=this.type=t.type,r=t.changedTouches?t.changedTouches[0]:null;if(this.target=t.target||t.srcElement,this.b=e,e=t.relatedTarget){if(Gt){t:{try{Wt(e.nodeName);var o=!0;break t}catch(t){}o=!1}o||(e=null)}}else"mouseover"==n?e=t.fromElement:"mouseout"==n&&(e=t.toElement);this.relatedTarget=e,null===r?(this.clientX=void 0!==t.clientX?t.clientX:t.pageX,this.clientY=void 0!==t.clientY?t.clientY:t.pageY,this.screenX=t.screenX||0,this.screenY=t.screenY||0):(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0),this.button=t.button,this.key=t.key||"",this.ctrlKey=t.ctrlKey,this.altKey=t.altKey,this.shiftKey=t.shiftKey,this.metaKey=t.metaKey,this.pointerId=t.pointerId||0,this.pointerType=i(t.pointerType)?t.pointerType:ce[t.pointerType]||"",this.a=t,t.defaultPrevented&&this.preventDefault()}}se.prototype.preventDefault=function(){this.Eb=!1},b(ue,se);var ce=re({2:"touch",3:"pen",4:"mouse"});ue.prototype.preventDefault=function(){ue.lb.preventDefault.call(this);var t=this.a;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,oe)try{(t.ctrlKey||112<=t.keyCode&&123>=t.keyCode)&&(t.keyCode=-1)}catch(t){}},ue.prototype.f=function(){return this.a};var he="closure_listenable_"+(1e6*Math.random()|0),le=0;function pe(t){t.ma=!0,t.listener=null,t.proxy=null,t.src=null,t.La=null}function fe(t){this.src=t,this.a={},this.b=0}function de(t,e){var n=e.type;n in t.a&&U(t.a[n],e)&&(pe(e),0==t.a[n].length&&(delete t.a[n],t.b--))}function ve(t,e,n,r){for(var i=0;i<t.length;++i){var o=t[i];if(!o.ma&&o.listener==e&&o.capture==!!n&&o.La==r)return i}return-1}fe.prototype.add=function(t,e,n,r,i){var o=t.toString();(t=this.a[o])||(t=this.a[o]=[],this.b++);var a=ve(t,e,r,i);return-1<a?(e=t[a],n||(e.Ha=!1)):((e=new function(t,e,n,r,i){this.listener=t,this.proxy=null,this.src=e,this.type=n,this.capture=!!r,this.La=i,this.key=++le,this.ma=this.Ha=!1}(e,this.src,o,!!r,i)).Ha=n,t.push(e)),e};var ye="closure_lm_"+(1e6*Math.random()|0),_e={};function ge(t,e,n,r,i){if(r&&r.once)be(t,e,n,r,i);else if(c(e))for(var o=0;o<e.length;o++)ge(t,e[o],n,r,i);else n=Ae(n),t&&t[he]?Oe(t,e,n,p(r)?!!r.capture:!!r,i):me(t,e,n,!1,r,i)}function me(t,e,n,r,i,o){if(!e)throw Error("Invalid event type");var a=p(i)?!!i.capture:!!i,s=Ne(t);if(s||(t[ye]=s=new fe(t)),!(n=s.add(e,n,r,a,o)).proxy)if(r=function(){var t=Ie,e=ie?function(n){return t.call(e.src,e.listener,n)}:function(n){if(!(n=t.call(e.src,e.listener,n)))return n};return e}(),n.proxy=r,r.src=t,r.listener=n,t.addEventListener)ae||(i=a),void 0===i&&(i=!1),t.addEventListener(e.toString(),r,i);else if(t.attachEvent)t.attachEvent(Te(e.toString()),r);else{if(!t.addListener||!t.removeListener)throw Error("addEventListener and attachEvent are unavailable.");t.addListener(r)}}function be(t,e,n,r,i){if(c(e))for(var o=0;o<e.length;o++)be(t,e[o],n,r,i);else n=Ae(n),t&&t[he]?Pe(t,e,n,p(r)?!!r.capture:!!r,i):me(t,e,n,!0,r,i)}function we(t,e,n,r,i){if(c(e))for(var o=0;o<e.length;o++)we(t,e[o],n,r,i);else r=p(r)?!!r.capture:!!r,n=Ae(n),t&&t[he]?(t=t.u,(e=String(e).toString())in t.a&&(-1<(n=ve(o=t.a[e],n,r,i))&&(pe(o[n]),Array.prototype.splice.call(o,n,1),0==o.length&&(delete t.a[e],t.b--)))):t&&(t=Ne(t))&&(e=t.a[e.toString()],t=-1,e&&(t=ve(e,n,r,i)),(n=-1<t?e[t]:null)&&Ee(n))}function Ee(t){if("number"!=typeof t&&t&&!t.ma){var e=t.src;if(e&&e[he])de(e.u,t);else{var n=t.type,r=t.proxy;e.removeEventListener?e.removeEventListener(n,r,t.capture):e.detachEvent?e.detachEvent(Te(n),r):e.addListener&&e.removeListener&&e.removeListener(r),(n=Ne(e))?(de(n,t),0==n.b&&(n.src=null,e[ye]=null)):pe(t)}}}function Te(t){return t in _e?_e[t]:_e[t]="on"+t}function Ce(t,e,n,r){var i=!0;if((t=Ne(t))&&(e=t.a[e.toString()]))for(e=e.concat(),t=0;t<e.length;t++){var o=e[t];o&&o.capture==n&&!o.ma&&(o=Se(o,r),i=i&&!1!==o)}return i}function Se(t,e){var n=t.listener,r=t.La||t.src;return t.Ha&&Ee(t),n.call(r,e)}function Ie(t,e){if(t.ma)return!0;if(!ie){if(!e)t:{e=["window","event"];for(var n=r,i=0;i<e.length;i++)if(null==(n=n[e[i]])){e=null;break t}e=n}if(e=new ue(i=e,this),n=!0,!(0>i.keyCode||void 0!=i.returnValue)){t:{var o=!1;if(0==i.keyCode)try{i.keyCode=-1;break t}catch(t){o=!0}(o||void 0==i.returnValue)&&(i.returnValue=!0)}for(i=[],o=e.b;o;o=o.parentNode)i.push(o);for(t=t.type,o=i.length-1;0<=o;o--){e.b=i[o];var a=Ce(i[o],t,!0,e);n=n&&a}for(o=0;o<i.length;o++)e.b=i[o],a=Ce(i[o],t,!1,e),n=n&&a}return n}return Se(t,new ue(e,this))}function Ne(t){return(t=t[ye])instanceof fe?t:null}var Re="__closure_events_fn_"+(1e9*Math.random()>>>0);function Ae(t){return l(t)?t:(t[Re]||(t[Re]=function(e){return t.handleEvent(e)}),t[Re])}function ke(){xt.call(this),this.u=new fe(this),this.Mb=this,this.Ta=null}function Oe(t,e,n,r,i){t.u.add(String(e),n,!1,r,i)}function Pe(t,e,n,r,i){t.u.add(String(e),n,!0,r,i)}function De(t,e,n,r){if(!(e=t.u.a[String(e)]))return!0;e=e.concat();for(var i=!0,o=0;o<e.length;++o){var a=e[o];if(a&&!a.ma&&a.capture==n){var s=a.listener,u=a.La||a.src;a.Ha&&de(t.u,a),i=!1!==s.call(u,r)&&i}}return i&&0!=r.Eb}function Le(t,e,n){if(l(t))n&&(t=_(t,n));else{if(!t||"function"!=typeof t.handleEvent)throw Error("Invalid listener argument");t=_(t.handleEvent,t)}return 2147483647<Number(e)?-1:r.setTimeout(t,e||0)}function xe(t){var e=null;return new vt(function(n,r){-1==(e=Le(function(){n(void 0)},t))&&r(Error("Failed to schedule timer."))}).m(function(t){throw r.clearTimeout(e),t})}function Fe(t){if(t.S&&"function"==typeof t.S)return t.S();if(i(t))return t.split("");if(h(t)){for(var e=[],n=t.length,r=0;r<n;r++)e.push(t[r]);return e}for(r in e=[],n=0,t)e[n++]=t[r];return e}function Ue(t){if(t.U&&"function"==typeof t.U)return t.U();if(!t.S||"function"!=typeof t.S){if(h(t)||i(t)){var e=[];t=t.length;for(var n=0;n<t;n++)e.push(n);return e}for(var r in e=[],n=0,t)e[n++]=r;return e}}function Me(t,e){this.b={},this.a=[],this.c=0;var n=arguments.length;if(1<n){if(n%2)throw Error("Uneven number of arguments");for(var r=0;r<n;r+=2)this.set(arguments[r],arguments[r+1])}else if(t)if(t instanceof Me)for(n=t.U(),r=0;r<n.length;r++)this.set(n[r],t.get(n[r]));else for(r in t)this.set(r,t[r])}function We(t){if(t.c!=t.a.length){for(var e=0,n=0;e<t.a.length;){var r=t.a[e];Be(t.b,r)&&(t.a[n++]=r),e++}t.a.length=n}if(t.c!=t.a.length){var i={};for(n=e=0;e<t.a.length;)Be(i,r=t.a[e])||(t.a[n++]=r,i[r]=1),e++;t.a.length=n}}function Be(t,e){return Object.prototype.hasOwnProperty.call(t,e)}b(ke,xt),ke.prototype[he]=!0,ke.prototype.addEventListener=function(t,e,n,r){ge(this,t,e,n,r)},ke.prototype.removeEventListener=function(t,e,n,r){we(this,t,e,n,r)},ke.prototype.dispatchEvent=function(t){var e,n=this.Ta;if(n)for(e=[];n;n=n.Ta)e.push(n);n=this.Mb;var r=t.type||t;if(i(t))t=new se(t,n);else if(t instanceof se)t.target=t.target||n;else{var o=t;ct(t=new se(r,n),o)}if(o=!0,e)for(var a=e.length-1;0<=a;a--){var s=t.b=e[a];o=De(s,r,!0,t)&&o}if(o=De(s=t.b=n,r,!0,t)&&o,o=De(s,r,!1,t)&&o,e)for(a=0;a<e.length;a++)o=De(s=t.b=e[a],r,!1,t)&&o;return o},ke.prototype.ua=function(){if(ke.lb.ua.call(this),this.u){var t,e=this.u;for(t in e.a){for(var n=e.a[t],r=0;r<n.length;r++)pe(n[r]);delete e.a[t],e.b--}}this.Ta=null},(t=Me.prototype).S=function(){We(this);for(var t=[],e=0;e<this.a.length;e++)t.push(this.b[this.a[e]]);return t},t.U=function(){return We(this),this.a.concat()},t.clear=function(){this.b={},this.c=this.a.length=0},t.get=function(t,e){return Be(this.b,t)?this.b[t]:e},t.set=function(t,e){Be(this.b,t)||(this.c++,this.a.push(t)),this.b[t]=e},t.forEach=function(t,e){for(var n=this.U(),r=0;r<n.length;r++){var i=n[r],o=this.get(i);t.call(e,o,i,this)}};var je=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function Ve(t,e){if(this.b=this.l=this.c="",this.j=null,this.h=this.g="",this.f=!1,t instanceof Ve){this.f=void 0!==e?e:t.f,qe(this,t.c),this.l=t.l,this.b=t.b,He(this,t.j),this.g=t.g,e=t.a;var n=new on;n.c=e.c,e.a&&(n.a=new Me(e.a),n.b=e.b),Ke(this,n),this.h=t.h}else t&&(n=String(t).match(je))?(this.f=!!e,qe(this,n[1]||"",!0),this.l=Xe(n[2]||""),this.b=Xe(n[3]||"",!0),He(this,n[4]),this.g=Xe(n[5]||"",!0),Ke(this,n[6]||"",!0),this.h=Xe(n[7]||"")):(this.f=!!e,this.a=new on(null,this.f))}function qe(t,e,n){t.c=n?Xe(e,!0):e,t.c&&(t.c=t.c.replace(/:$/,""))}function He(t,e){if(e){if(e=Number(e),isNaN(e)||0>e)throw Error("Bad port number "+e);t.j=e}else t.j=null}function Ke(t,e,n){e instanceof on?(t.a=e,function(t,e){e&&!t.f&&(an(t),t.c=null,t.a.forEach(function(t,e){var n=e.toLowerCase();e!=n&&(un(this,e),hn(this,n,t))},t)),t.f=e}(t.a,t.f)):(n||(e=$e(e,nn)),t.a=new on(e,t.f))}function Ge(t,e,n){t.a.set(e,n)}function Qe(t,e){return t.a.get(e)}function ze(t){return t instanceof Ve?new Ve(t):new Ve(t,void 0)}function Ye(t,e){var n=new Ve(null,void 0);return qe(n,"https"),t&&(n.b=t),e&&(n.g=e),n}function Xe(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function $e(t,e,n){return i(t)?(t=encodeURI(t).replace(e,Je),n&&(t=t.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),t):null}function Je(t){return"%"+((t=t.charCodeAt(0))>>4&15).toString(16)+(15&t).toString(16)}Ve.prototype.toString=function(){var t=[],e=this.c;e&&t.push($e(e,Ze,!0),":");var n=this.b;return(n||"file"==e)&&(t.push("//"),(e=this.l)&&t.push($e(e,Ze,!0),"@"),t.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.j)&&t.push(":",String(n))),(n=this.g)&&(this.b&&"/"!=n.charAt(0)&&t.push("/"),t.push($e(n,"/"==n.charAt(0)?en:tn,!0))),(n=this.a.toString())&&t.push("?",n),(n=this.h)&&t.push("#",$e(n,rn)),t.join("")};var Ze=/[#\/\?@]/g,tn=/[#\?:]/g,en=/[#\?]/g,nn=/[#\?@]/g,rn=/#/g;function on(t,e){this.b=this.a=null,this.c=t||null,this.f=!!e}function an(t){t.a||(t.a=new Me,t.b=0,t.c&&function(t,e){if(t){t=t.split("&");for(var n=0;n<t.length;n++){var r=t[n].indexOf("="),i=null;if(0<=r){var o=t[n].substring(0,r);i=t[n].substring(r+1)}else o=t[n];e(o,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(t.c,function(e,n){t.add(decodeURIComponent(e.replace(/\+/g," ")),n)}))}function sn(t){var e=Ue(t);if(void 0===e)throw Error("Keys are undefined");var n=new on(null,void 0);t=Fe(t);for(var r=0;r<e.length;r++){var i=e[r],o=t[r];c(o)?hn(n,i,o):n.add(i,o)}return n}function un(t,e){an(t),e=ln(t,e),Be(t.a.b,e)&&(t.c=null,t.b-=t.a.get(e).length,Be((t=t.a).b,e)&&(delete t.b[e],t.c--,t.a.length>2*t.c&&We(t)))}function cn(t,e){return an(t),e=ln(t,e),Be(t.a.b,e)}function hn(t,e,n){un(t,e),0<n.length&&(t.c=null,t.a.set(ln(t,e),B(n)),t.b+=n.length)}function ln(t,e){return e=String(e),t.f&&(e=e.toLowerCase()),e}(t=on.prototype).add=function(t,e){an(this),this.c=null,t=ln(this,t);var n=this.a.get(t);return n||this.a.set(t,n=[]),n.push(e),this.b+=1,this},t.clear=function(){this.a=this.c=null,this.b=0},t.forEach=function(t,e){an(this),this.a.forEach(function(n,r){D(n,function(n){t.call(e,n,r,this)},this)},this)},t.U=function(){an(this);for(var t=this.a.S(),e=this.a.U(),n=[],r=0;r<e.length;r++)for(var i=t[r],o=0;o<i.length;o++)n.push(e[r]);return n},t.S=function(t){an(this);var e=[];if(i(t))cn(this,t)&&(e=W(e,this.a.get(ln(this,t))));else{t=this.a.S();for(var n=0;n<t.length;n++)e=W(e,t[n])}return e},t.set=function(t,e){return an(this),this.c=null,cn(this,t=ln(this,t))&&(this.b-=this.a.get(t).length),this.a.set(t,[e]),this.b+=1,this},t.get=function(t,e){return 0<(t=t?this.S(t):[]).length?String(t[0]):e},t.toString=function(){if(this.c)return this.c;if(!this.a)return"";for(var t=[],e=this.a.U(),n=0;n<e.length;n++){var r=e[n],i=encodeURIComponent(String(r));r=this.S(r);for(var o=0;o<r.length;o++){var a=i;""!==r[o]&&(a+="="+encodeURIComponent(String(r[o]))),t.push(a)}}return this.c=t.join("&")};var pn=!qt||9<=Number(Jt);function fn(){this.a="",this.b=vn}function dn(t){return t instanceof fn&&t.constructor===fn&&t.b===vn?t.a:(S("expected object of type Const, got '"+t+"'"),"type_error:Const")}fn.prototype.la=!0,fn.prototype.ja=function(){return this.a},fn.prototype.toString=function(){return"Const{"+this.a+"}"};var vn={};function yn(t){var e=new fn;return e.a=t,e}function _n(){this.a="",this.b=En}function gn(t){return t instanceof _n&&t.constructor===_n&&t.b===En?t.a:(S("expected object of type TrustedResourceUrl, got '"+t+"' of type "+s(t)),"type_error:TrustedResourceUrl")}function mn(t,e){var n=dn(t);if(!wn.test(n))throw Error("Invalid TrustedResourceUrl format: "+n);return function(t){var e=new _n;return e.a=t,e}(t=n.replace(bn,function(t,r){if(!Object.prototype.hasOwnProperty.call(e,r))throw Error('Found marker, "'+r+'", in format string, "'+n+'", but no valid label mapping found in args: '+JSON.stringify(e));return(t=e[r])instanceof fn?dn(t):encodeURIComponent(String(t))}))}yn(""),_n.prototype.la=!0,_n.prototype.ja=function(){return this.a},_n.prototype.toString=function(){return"TrustedResourceUrl{"+this.a+"}"};var bn=/%{(\w+)}/g,wn=/^(?:https:)?\/\/[0-9a-z.:[\]-]+\/|^\/[^\/\\]|^about:blank#/i,En={};function Tn(){this.a="",this.b=Nn}function Cn(t){return t instanceof Tn&&t.constructor===Tn&&t.b===Nn?t.a:(S("expected object of type SafeUrl, got '"+t+"' of type "+s(t)),"type_error:SafeUrl")}Tn.prototype.la=!0,Tn.prototype.ja=function(){return this.a},Tn.prototype.toString=function(){return"SafeUrl{"+this.a+"}"};var Sn=/^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i;function In(t){return t instanceof Tn?t:(t=t.la?t.ja():String(t),Sn.test(t)||(t="about:invalid#zClosurez"),Rn(t))}var Nn={};function Rn(t){var e=new Tn;return e.a=t,e}function An(){this.a="",this.b=kn}Rn("about:blank"),An.prototype.la=!0,An.prototype.ja=function(){return this.a},An.prototype.toString=function(){return"SafeHtml{"+this.a+"}"};var kn={};function On(t){var e=new An;return e.a=t,e}function Pn(t){var e=document;return i(t)?e.getElementById(t):t}function Dn(t,e){rt(e,function(e,n){e&&e.la&&(e=e.ja()),"style"==n?t.style.cssText=e:"class"==n?t.className=e:"for"==n?t.htmlFor=e:Ln.hasOwnProperty(n)?t.setAttribute(Ln[n],e):0==n.lastIndexOf("aria-",0)||0==n.lastIndexOf("data-",0)?t.setAttribute(n,e):t[n]=e})}On("<!DOCTYPE html>"),On(""),On("<br>");var Ln={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",frameborder:"frameBorder",height:"height",maxlength:"maxLength",nonce:"nonce",role:"role",rowspan:"rowSpan",type:"type",usemap:"useMap",valign:"vAlign",width:"width"};function xn(t,e,n){var r=arguments,o=document,a=String(r[0]),s=r[1];if(!pn&&s&&(s.name||s.type)){if(a=["<",a],s.name&&a.push(' name="',q(s.name),'"'),s.type){a.push(' type="',q(s.type),'"');var u={};ct(u,s),delete u.type,s=u}a.push(">"),a=a.join("")}return a=o.createElement(a),s&&(i(s)?a.className=s:c(s)?a.className=s.join(" "):Dn(a,s)),2<r.length&&function(t,e,n){function r(n){n&&e.appendChild(i(n)?t.createTextNode(n):n)}for(var o=2;o<n.length;o++){var a=n[o];!h(a)||p(a)&&0<a.nodeType?r(a):D(Fn(a)?B(a):a,r)}}(o,a,r),a}function Fn(t){if(t&&"number"==typeof t.length){if(p(t))return"function"==typeof t.item||"string"==typeof t.item;if(l(t))return"function"==typeof t.item}return!1}function Un(t){var e=[];return function t(e,n,r){if(null==n)r.push("null");else{if("object"==typeof n){if(c(n)){var i=n;n=i.length,r.push("[");for(var o="",a=0;a<n;a++)r.push(o),t(e,i[a],r),o=",";return void r.push("]")}if(!(n instanceof String||n instanceof Number||n instanceof Boolean)){for(i in r.push("{"),o="",n)Object.prototype.hasOwnProperty.call(n,i)&&("function"!=typeof(a=n[i])&&(r.push(o),Bn(i,r),r.push(":"),t(e,a,r),o=","));return void r.push("}")}n=n.valueOf()}switch(typeof n){case"string":Bn(n,r);break;case"number":r.push(isFinite(n)&&!isNaN(n)?String(n):"null");break;case"boolean":r.push(String(n));break;case"function":r.push("null");break;default:throw Error("Unknown type: "+typeof n)}}}(new function(){},t,e),e.join("")}var Mn={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\u000b"},Wn=/\uffff/.test("￿")?/[\\"\x00-\x1f\x7f-\uffff]/g:/[\\"\x00-\x1f\x7f-\xff]/g;function Bn(t,e){e.push('"',t.replace(Wn,function(t){var e=Mn[t];return e||(e="\\u"+(65536|t.charCodeAt(0)).toString(16).substr(1),Mn[t]=e),e}),'"')}function jn(){var t=or();return qt&&!!Jt&&11==Jt||/Edge\/\d+/.test(t)}function Vn(){return r.window&&r.window.location.href||self&&self.location&&self.location.href||""}function qn(t,e){e=e||r.window;var n="about:blank";t&&(n=Cn(In(t))),e.location.href=n}function Hn(t){return!!((t=(t||or()).toLowerCase()).match(/android/)||t.match(/webos/)||t.match(/iphone|ipad|ipod/)||t.match(/blackberry/)||t.match(/windows phone/)||t.match(/iemobile/))}function Kn(t){t=t||r.window;try{t.close()}catch(t){}}function Gn(t,e,n){var r=Math.floor(1e9*Math.random()).toString();e=e||500,n=n||600;var i=(window.screen.availHeight-n)/2,o=(window.screen.availWidth-e)/2;for(a in e={width:e,height:n,top:0<i?i:0,left:0<o?o:0,location:!0,resizable:!0,statusbar:!0,toolbar:!1},n=or().toLowerCase(),r&&(e.target=r,J(n,"crios/")&&(e.target="_blank")),nr(or())==tr&&(t=t||"http://localhost",e.scrollbars=!0),n=t||"",(t=e)||(t={}),r=window,e=n instanceof Tn?n:In(void 0!==n.href?n.href:String(n)),n=t.target||n.target,i=[],t)switch(a){case"width":case"height":case"top":case"left":i.push(a+"="+t[a]);break;case"target":case"noopener":case"noreferrer":break;default:i.push(a+"="+(t[a]?1:0))}var a=i.join(",");if((nt("iPhone")&&!nt("iPod")&&!nt("iPad")||nt("iPad")||nt("iPod"))&&r.navigator&&r.navigator.standalone&&n&&"_self"!=n?(a=r.document.createElement("A"),e instanceof Tn||e instanceof Tn||(e=e.la?e.ja():String(e),Sn.test(e)||(e="about:invalid#zClosurez"),e=Rn(e)),a.href=Cn(e),a.setAttribute("target",n),t.noreferrer&&a.setAttribute("rel","noreferrer"),(t=document.createEvent("MouseEvent")).initMouseEvent("click",!0,!0,r,1),a.dispatchEvent(t),a={}):t.noreferrer?(a=r.open("",n,a),t=Cn(e),a&&(Kt&&J(t,";")&&(t="'"+t.replace(/'/g,"%27")+"'"),a.opener=null,yn("b/12014412, meta tag with sanitized URL"),t=On(t='<meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0; url='+q(t)+'">'),a.document.write(function(t){return t instanceof An&&t.constructor===An&&t.b===kn?t.a:(S("expected object of type SafeHtml, got '"+t+"' of type "+s(t)),"type_error:SafeHtml")}(t)),a.document.close())):(a=r.open(Cn(e),n,a))&&t.noopener&&(a.opener=null),a)try{a.focus()}catch(t){}return a}var Qn=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;function zn(){var t=null;return new vt(function(e){"complete"==r.document.readyState?e():(t=function(){e()},be(window,"load",t))}).m(function(e){throw we(window,"load",t),e})}function Yn(t){return t=t||or(),!("file:"!==hr()||!t.toLowerCase().match(/iphone|ipad|ipod|android/))}function Xn(){var t=r.window;try{return!(!t||t==t.top)}catch(t){return!1}}function $n(){return"object"!=typeof r.window&&"function"==typeof r.importScripts}function Jn(){return e.INTERNAL.hasOwnProperty("reactNative")?"ReactNative":e.INTERNAL.hasOwnProperty("node")?"Node":$n()?"Worker":"Browser"}function Zn(){var t=Jn();return"ReactNative"===t||"Node"===t}var tr="Firefox",er="Chrome";function nr(t){var e=t.toLowerCase();return J(e,"opera/")||J(e,"opr/")||J(e,"opios/")?"Opera":J(e,"iemobile")?"IEMobile":J(e,"msie")||J(e,"trident/")?"IE":J(e,"edge/")?"Edge":J(e,"firefox/")?tr:J(e,"silk/")?"Silk":J(e,"blackberry")?"Blackberry":J(e,"webos")?"Webos":!J(e,"safari/")||J(e,"chrome/")||J(e,"crios/")||J(e,"android")?!J(e,"chrome/")&&!J(e,"crios/")||J(e,"edge/")?J(e,"android")?"Android":(t=t.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))&&2==t.length?t[1]:"Other":er:"Safari"}var rr={Qc:"FirebaseCore-web",Sc:"FirebaseUI-web"};function ir(t,e){e=e||[];var n,r=[],i={};for(n in rr)i[rr[n]]=!0;for(n=0;n<e.length;n++)void 0!==i[e[n]]&&(delete i[e[n]],r.push(e[n]));return r.sort(),(e=r).length||(e=["FirebaseCore-web"]),"Browser"===(r=Jn())?r=nr(i=or()):"Worker"===r&&(r=nr(i=or())+"-"+r),r+"/JsCore/"+t+"/"+e.join(",")}function or(){return r.navigator&&r.navigator.userAgent||""}function ar(t,e){t=t.split("."),e=e||r;for(var n=0;n<t.length&&"object"==typeof e&&null!=e;n++)e=e[t[n]];return n!=t.length&&(e=void 0),e}function sr(){try{var t=r.localStorage,e=vr();if(t)return t.setItem(e,"1"),t.removeItem(e),!jn()||!!r.indexedDB}catch(t){return $n()&&!!r.indexedDB}return!1}function ur(){return(cr()||"chrome-extension:"===hr()||Yn())&&!Zn()&&sr()&&!$n()}function cr(){return"http:"===hr()||"https:"===hr()}function hr(){return r.location&&r.location.protocol||null}function lr(t){return!Hn(t=t||or())&&nr(t)!=tr}function pr(t){return void 0===t?null:Un(t)}function fr(t){var e,n={};for(e in t)t.hasOwnProperty(e)&&null!==t[e]&&void 0!==t[e]&&(n[e]=t[e]);return n}function dr(t){if(null!==t)return JSON.parse(t)}function vr(t){return t||Math.floor(1e9*Math.random()).toString()}function yr(t){return"Safari"!=nr(t=t||or())&&!t.toLowerCase().match(/iphone|ipad|ipod/)}function _r(){var t=r.___jsl;if(t&&t.H)for(var e in t.H)if(t.H[e].r=t.H[e].r||[],t.H[e].L=t.H[e].L||[],t.H[e].r=t.H[e].L.concat(),t.CP)for(var n=0;n<t.CP.length;n++)t.CP[n]=null}function gr(t,e){if(t>e)throw Error("Short delay should be less than long delay!");this.a=t,this.c=e,t=or(),e=Jn(),this.b=Hn(t)||"ReactNative"===e}function mr(){var t=r.document;return!t||void 0===t.visibilityState||"visible"==t.visibilityState}function br(t){try{var e=new Date(parseInt(t,10));if(!isNaN(e.getTime())&&!/[^0-9]/.test(t))return e.toUTCString()}catch(t){}return null}function wr(){return!(!ar("fireauth.oauthhelper",r)&&!ar("fireauth.iframe",r))}gr.prototype.get=function(){var t=r.navigator;return!t||"boolean"!=typeof t.onLine||!cr()&&"chrome-extension:"!==hr()&&void 0===t.connection||t.onLine?this.b?this.c:this.a:Math.min(5e3,this.a)};var Er,Tr={};try{var Cr={};Object.defineProperty(Cr,"abcd",{configurable:!0,enumerable:!0,value:1}),Object.defineProperty(Cr,"abcd",{configurable:!0,enumerable:!0,value:2}),Er=2==Cr.abcd}catch(jt){Er=!1}function Sr(t,e,n){Er?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n}):t[e]=n}function Ir(t,e){if(e)for(var n in e)e.hasOwnProperty(n)&&Sr(t,n,e[n])}function Nr(t){var e={};return Ir(e,t),e}function Rr(t){var e=t;if("object"==typeof t&&null!=t)for(var n in e="length"in t?[]:{},t)Sr(e,n,Rr(t[n]));return e}var Ar="EMAIL_SIGNIN",kr="email",Or="newEmail",Pr="requestType",Dr="email",Lr="fromEmail",xr="data",Fr="operation";function Ur(t,e){this.code=Wr+t,this.message=e||Br[t]||""}function Mr(t){var e=t&&t.code;return e?new Ur(e.substring(Wr.length),t.message):null}b(Ur,Error),Ur.prototype.C=function(){return{code:this.code,message:this.message}},Ur.prototype.toJSON=function(){return this.C()};var Wr="auth/",Br={"argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-already-in-use":"The email address is already in use by another account.","expired-action-code":"The action code has expired. ","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal error has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal error has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-email":"The email address is badly formatted.","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is malformed or has expired.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal error has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network error (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal error has occurred.","no-such-provider":"User was not linked to an account with the given provider.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","user-cancelled":"User did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled."};function jr(t){var e=t[Kr];if(void 0===e)throw new Ur("missing-continue-uri");if("string"!=typeof e||"string"==typeof e&&!e.length)throw new Ur("invalid-continue-uri");this.h=e,this.b=this.a=null,this.g=!1;var n=t[Vr];if(n&&"object"==typeof n){e=n[zr];var r=n[Gr];if(n=n[Qr],"string"==typeof e&&e.length){if(this.a=e,void 0!==r&&"boolean"!=typeof r)throw new Ur("argument-error",Gr+" property must be a boolean when specified.");if(this.g=!!r,void 0!==n&&("string"!=typeof n||"string"==typeof n&&!n.length))throw new Ur("argument-error",Qr+" property must be a non empty string when specified.");this.b=n||null}else{if(void 0!==e)throw new Ur("argument-error",zr+" property must be a non empty string when specified.");if(void 0!==r||void 0!==n)throw new Ur("missing-android-pkg-name")}}else if(void 0!==n)throw new Ur("argument-error",Vr+" property must be a non null object when specified.");if(this.f=null,(e=t[Hr])&&"object"==typeof e){if("string"==typeof(e=e[Yr])&&e.length)this.f=e;else if(void 0!==e)throw new Ur("argument-error",Yr+" property must be a non empty string when specified.")}else if(void 0!==e)throw new Ur("argument-error",Hr+" property must be a non null object when specified.");if(void 0!==(t=t[qr])&&"boolean"!=typeof t)throw new Ur("argument-error",qr+" property must be a boolean when specified.");this.c=!!t}var Vr="android",qr="handleCodeInApp",Hr="iOS",Kr="url",Gr="installApp",Qr="minimumVersion",zr="packageName",Yr="bundleId";function Xr(t){var e={};for(var n in e.continueUrl=t.h,e.canHandleCodeInApp=t.c,(e.androidPackageName=t.a)&&(e.androidMinimumVersion=t.b,e.androidInstallApp=t.g),e.iOSBundleId=t.f,e)null===e[n]&&delete e[n];return e}var $r=null,Jr=null;function Zr(t){var e="";return function(t,e){function n(e){for(;r<t.length;){var n=t.charAt(r++),i=Jr[n];if(null!=i)return i;if(!/^[\s\xa0]*$/.test(n))throw Error("Unknown base64 encoding at char: "+n)}return e}!function(){if(!$r){$r={},Jr={};for(var t=0;65>t;t++)$r[t]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(t),Jr[$r[t]]=t,62<=t&&(Jr["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(t)]=t)}}();for(var r=0;;){var i=n(-1),o=n(0),a=n(64),s=n(64);if(64===s&&-1===i)break;e(i<<2|o>>4),64!=a&&(e(o<<4&240|a>>2),64!=s&&e(a<<6&192|s))}}(t,function(t){e+=String.fromCharCode(t)}),e}function ti(t){this.c=t.sub,this.a=t.provider_id||t.firebase&&t.firebase.sign_in_provider||null,this.b=!!t.is_anonymous||"anonymous"==this.a}function ei(t){return(t=ni(t))&&t.sub&&t.iss&&t.aud&&t.exp?new ti(t):null}function ni(t){if(!t)return null;if(3!=(t=t.split(".")).length)return null;for(var e=(4-(t=t[1]).length%4)%4,n=0;n<e;n++)t+=".";try{return JSON.parse(Zr(t))}catch(t){}return null}ti.prototype.f=function(){return this.b};var ri="oauth_consumer_key oauth_nonce oauth_signature oauth_signature_method oauth_timestamp oauth_token oauth_version".split(" "),ii=["client_id","response_type","scope","redirect_uri","state"],oi={Rc:{Ma:"locale",Aa:500,za:600,Na:"facebook.com",cb:ii},Tc:{Ma:null,Aa:500,za:620,Na:"github.com",cb:ii},Uc:{Ma:"hl",Aa:515,za:680,Na:"google.com",cb:ii},$c:{Ma:"lang",Aa:485,za:705,Na:"twitter.com",cb:ri}};function ai(t){for(var e in oi)if(oi[e].Na==t)return oi[e];return null}function si(t){var e={};e["facebook.com"]=pi,e["google.com"]=di,e["github.com"]=fi,e["twitter.com"]=vi;var n=t&&t[ci];try{if(n)return e[n]?new e[n](t):new li(t);if(void 0!==t[ui])return new hi(t)}catch(t){}return null}var ui="idToken",ci="providerId";function hi(t){var e=t[ci];if(!e&&t[ui]){var n=ei(t[ui]);n&&n.a&&(e=n.a)}if(!e)throw Error("Invalid additional user info!");"anonymous"!=e&&"custom"!=e||(e=null),n=!1,void 0!==t.isNewUser?n=!!t.isNewUser:"identitytoolkit#SignupNewUserResponse"===t.kind&&(n=!0),Sr(this,"providerId",e),Sr(this,"isNewUser",n)}function li(t){hi.call(this,t),Sr(this,"profile",Rr((t=dr(t.rawUserInfo||"{}"))||{}))}function pi(t){if(li.call(this,t),"facebook.com"!=this.providerId)throw Error("Invalid provider ID!")}function fi(t){if(li.call(this,t),"github.com"!=this.providerId)throw Error("Invalid provider ID!");Sr(this,"username",this.profile&&this.profile.login||null)}function di(t){if(li.call(this,t),"google.com"!=this.providerId)throw Error("Invalid provider ID!")}function vi(t){if(li.call(this,t),"twitter.com"!=this.providerId)throw Error("Invalid provider ID!");Sr(this,"username",t.screenName||null)}function yi(t){var e=ze(t),n=Qe(e,"link"),r=Qe(ze(n),"link");return Qe(ze(e=Qe(e,"deep_link_id")),"link")||e||r||n||t}function _i(t,e){return t.then(function(t){if(t[$o]){var n=ei(t[$o]);if(!n||e!=n.c)throw new Ur("user-mismatch");return t}throw new Ur("user-mismatch")}).m(function(t){throw t&&t.code&&t.code==Wr+"user-not-found"?new Ur("user-mismatch"):t})}function gi(t,e,n){if(e.idToken||e.accessToken)e.idToken&&Sr(this,"idToken",e.idToken),e.accessToken&&Sr(this,"accessToken",e.accessToken);else{if(!e.oauthToken||!e.oauthTokenSecret)throw new Ur("internal-error","failed to construct a credential");Sr(this,"accessToken",e.oauthToken),Sr(this,"secret",e.oauthTokenSecret)}Sr(this,"providerId",t),Sr(this,"signInMethod",n)}function mi(t){var e={};return t.idToken&&(e.id_token=t.idToken),t.accessToken&&(e.access_token=t.accessToken),t.secret&&(e.oauth_token_secret=t.secret),e.providerId=t.providerId,{postBody:sn(e).toString(),requestUri:"http://localhost"}}function bi(t,e){this.Ac=e||[],Ir(this,{providerId:t,isOAuthProvider:!0}),this.tb={},this.Za=(ai(t)||{}).Ma||null,this.Xa=null}function wi(t){bi.call(this,t,ii),this.a=[]}function Ei(){wi.call(this,"facebook.com")}function Ti(t){if(!t)throw new Ur("argument-error","credential failed: expected 1 argument (the OAuth access token).");var e=t;return p(t)&&(e=t.accessToken),(new Ei).credential(null,e)}function Ci(){wi.call(this,"github.com")}function Si(t){if(!t)throw new Ur("argument-error","credential failed: expected 1 argument (the OAuth access token).");var e=t;return p(t)&&(e=t.accessToken),(new Ci).credential(null,e)}function Ii(){wi.call(this,"google.com"),this.ta("profile")}function Ni(t,e){var n=t;return p(t)&&(n=t.idToken,e=t.accessToken),(new Ii).credential(n,e)}function Ri(){bi.call(this,"twitter.com",ri)}function Ai(t,e){var n=t;if(p(n)||(n={oauthToken:t,oauthTokenSecret:e}),!n.oauthToken||!n.oauthTokenSecret)throw new Ur("argument-error","credential failed: expected 2 arguments (the OAuth access token and secret).");return new gi("twitter.com",n,"twitter.com")}function ki(t,e,n){this.a=t,this.b=e,Sr(this,"providerId","password"),Sr(this,"signInMethod",n===Oi.EMAIL_LINK_SIGN_IN_METHOD?Oi.EMAIL_LINK_SIGN_IN_METHOD:Oi.EMAIL_PASSWORD_SIGN_IN_METHOD)}function Oi(){Ir(this,{providerId:"password",isOAuthProvider:!1})}function Pi(t,e){if(!(e=Di(e)))throw new Ur("argument-error","Invalid email link!");return new ki(t,e,Oi.EMAIL_LINK_SIGN_IN_METHOD)}function Di(t){var e=Qe((t=new function(t){this.a=ze(t)}(t=yi(t))).a,"oobCode")||null;return"signIn"===(Qe(t.a,"mode")||null)&&e?e:null}function Li(t){if(!(t.Ra&&t.Qa||t.Ea&&t.Z))throw new Ur("internal-error");this.a=t,Sr(this,"providerId","phone"),Sr(this,"signInMethod","phone")}function xi(t){return t.a.Ea&&t.a.Z?{temporaryProof:t.a.Ea,phoneNumber:t.a.Z}:{sessionInfo:t.a.Ra,code:t.a.Qa}}function Fi(t){try{this.a=t||e.auth()}catch(t){throw new Ur("argument-error","Either an instance of firebase.auth.Auth must be passed as an argument to the firebase.auth.PhoneAuthProvider constructor, or the default firebase App instance must be initialized via firebase.initializeApp().")}Ir(this,{providerId:"phone",isOAuthProvider:!1})}function Ui(t,e){if(!t)throw new Ur("missing-verification-id");if(!e)throw new Ur("missing-verification-code");return new Li({Ra:t,Qa:e})}function Mi(t){if(t.temporaryProof&&t.phoneNumber)return new Li({Ea:t.temporaryProof,Z:t.phoneNumber});var e=t&&t.providerId;if(!e||"password"===e)return null;var n=t&&t.oauthAccessToken,r=t&&t.oauthTokenSecret;t=t&&t.oauthIdToken;try{switch(e){case"google.com":return Ni(t,n);case"facebook.com":return Ti(n);case"github.com":return Si(n);case"twitter.com":return Ai(n,r);default:return new wi(e).credential(t,n)}}catch(t){return null}}function Wi(t){if(!t.isOAuthProvider)throw new Ur("invalid-oauth-provider")}function Bi(t,e,n,r,i){if(this.b=t,this.c=e||null,this.f=n||null,this.g=r||null,this.a=i||null,!this.f&&!this.a)throw new Ur("invalid-auth-event");if(this.f&&this.a)throw new Ur("invalid-auth-event");if(this.f&&!this.g)throw new Ur("invalid-auth-event")}function ji(t){return(t=t||{}).type?new Bi(t.type,t.eventId,t.urlResponse,t.sessionId,t.error&&Mr(t.error)):null}function Vi(){this.b=null,this.a=[]}b(li,hi),b(pi,li),b(fi,li),b(di,li),b(vi,li),gi.prototype.xa=function(t){return da(t,mi(this))},gi.prototype.c=function(t,e){var n=mi(this);return n.idToken=e,va(t,n)},gi.prototype.f=function(t,e){return _i(ya(t,mi(this)),e)},gi.prototype.C=function(){var t={providerId:this.providerId,signInMethod:this.signInMethod};return this.idToken&&(t.oauthIdToken=this.idToken),this.accessToken&&(t.oauthAccessToken=this.accessToken),this.secret&&(t.oauthTokenSecret=this.secret),t},bi.prototype.Ca=function(t){return this.tb=ot(t),this},b(wi,bi),wi.prototype.ta=function(t){return F(this.a,t)||this.a.push(t),this},wi.prototype.yb=function(){return B(this.a)},wi.prototype.credential=function(t,e){if(!t&&!e)throw new Ur("argument-error","credential failed: must provide the ID token and/or the access token.");return new gi(this.providerId,{idToken:t||null,accessToken:e||null},this.providerId)},b(Ei,wi),Sr(Ei,"PROVIDER_ID","facebook.com"),Sr(Ei,"FACEBOOK_SIGN_IN_METHOD","facebook.com"),b(Ci,wi),Sr(Ci,"PROVIDER_ID","github.com"),Sr(Ci,"GITHUB_SIGN_IN_METHOD","github.com"),b(Ii,wi),Sr(Ii,"PROVIDER_ID","google.com"),Sr(Ii,"GOOGLE_SIGN_IN_METHOD","google.com"),b(Ri,bi),Sr(Ri,"PROVIDER_ID","twitter.com"),Sr(Ri,"TWITTER_SIGN_IN_METHOD","twitter.com"),ki.prototype.xa=function(t){return this.signInMethod==Oi.EMAIL_LINK_SIGN_IN_METHOD?Ka(t,Ca,{email:this.a,oobCode:this.b}):Ka(t,ja,{email:this.a,password:this.b})},ki.prototype.c=function(t,e){return this.signInMethod==Oi.EMAIL_LINK_SIGN_IN_METHOD?Ka(t,Sa,{idToken:e,email:this.a,oobCode:this.b}):Ka(t,xa,{idToken:e,email:this.a,password:this.b})},ki.prototype.f=function(t,e){return _i(this.xa(t),e)},ki.prototype.C=function(){return{email:this.a,password:this.b,signInMethod:this.signInMethod}},Ir(Oi,{PROVIDER_ID:"password"}),Ir(Oi,{EMAIL_LINK_SIGN_IN_METHOD:"emailLink"}),Ir(Oi,{EMAIL_PASSWORD_SIGN_IN_METHOD:"password"}),Li.prototype.xa=function(t){return t.Sa(xi(this))},Li.prototype.c=function(t,e){var n=xi(this);return n.idToken=e,Ka(t,qa,n)},Li.prototype.f=function(t,e){var n=xi(this);return n.operation="REAUTH",_i(t=Ka(t,Ha,n),e)},Li.prototype.C=function(){var t={providerId:"phone"};return this.a.Ra&&(t.verificationId=this.a.Ra),this.a.Qa&&(t.verificationCode=this.a.Qa),this.a.Ea&&(t.temporaryProof=this.a.Ea),this.a.Z&&(t.phoneNumber=this.a.Z),t},Fi.prototype.Sa=function(t,e){var n=this.a.b;return Et(e.verify()).then(function(r){if(!i(r))throw new Ur("argument-error","An implementation of firebase.auth.ApplicationVerifier.prototype.verify() must return a firebase.Promise that resolves with a string.");switch(e.type){case"recaptcha":return function(t,e){return Ka(t,Da,e)}(n,{phoneNumber:t,recaptchaToken:r}).then(function(t){return"function"==typeof e.reset&&e.reset(),t},function(t){throw"function"==typeof e.reset&&e.reset(),t});default:throw new Ur("argument-error",'Only firebase.auth.ApplicationVerifiers with type="recaptcha" are currently supported.')}})},Ir(Fi,{PROVIDER_ID:"phone"}),Ir(Fi,{PHONE_SIGN_IN_METHOD:"phone"}),Bi.prototype.C=function(){return{type:this.b,eventId:this.c,urlResponse:this.f,sessionId:this.g,error:this.a&&this.a.C()}};var qi=null;function Hi(t){var e="unauthorized-domain",n=void 0,r=ze(t);t=r.b,"chrome-extension"==(r=r.c)?n=j("This chrome extension ID (chrome-extension://%s) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.",t):"http"==r||"https"==r?n=j("This domain (%s) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.",t):e="operation-not-supported-in-this-environment",Ur.call(this,e,n)}function Ki(t,e,n){Ur.call(this,t,n),(t=e||{}).ub&&Sr(this,"email",t.ub),t.Z&&Sr(this,"phoneNumber",t.Z),t.credential&&Sr(this,"credential",t.credential)}function Gi(t){if(t.code){var e=t.code||"";0==e.indexOf(Wr)&&(e=e.substring(Wr.length));var n={credential:Mi(t)};if(t.email)n.ub=t.email;else{if(!t.phoneNumber)return new Ur(e,t.message||void 0);n.Z=t.phoneNumber}return new Ki(e,n,t.message)}return null}Vi.prototype.subscribe=function(t){var e=this;this.a.push(t),this.b||(this.b=function(t){for(var n=0;n<e.a.length;n++)e.a[n](t)},"function"==typeof(t=ar("universalLinks.subscribe",r))&&t(null,this.b))},Vi.prototype.unsubscribe=function(t){M(this.a,function(e){return e==t})},b(Hi,Ur),b(Ki,Ur),Ki.prototype.C=function(){var t={code:this.code,message:this.message};this.email&&(t.email=this.email),this.phoneNumber&&(t.phoneNumber=this.phoneNumber);var e=this.credential&&this.credential.C();return e&&ct(t,e),t},Ki.prototype.toJSON=function(){return this.C()};var Qi,zi=/^[+a-zA-Z0-9_.!#$%&'*\/=?^`{|}~-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,63}$/;function Yi(){}function Xi(t){return t.c||(t.c=t.b())}function $i(){}function Ji(t){if(!t.f&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var e=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],n=0;n<e.length;n++){var r=e[n];try{return new ActiveXObject(r),t.f=r}catch(t){}}throw Error("Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed")}return t.f}function Zi(){}function to(){this.a=new XDomainRequest,this.readyState=0,this.onreadystatechange=null,this.responseText="",this.status=-1,this.statusText="",this.a.onload=_(this.bc,this),this.a.onerror=_(this.zb,this),this.a.onprogress=_(this.cc,this),this.a.ontimeout=_(this.fc,this)}function eo(t,e){t.readyState=e,t.onreadystatechange&&t.onreadystatechange()}function no(t,e,n){this.reset(t,e,n,void 0,void 0)}function ro(t){this.f=t,this.b=this.c=this.a=null}function io(t,e){this.name=t,this.value=e}Yi.prototype.c=null,b($i,Yi),$i.prototype.a=function(){var t=Ji(this);return t?new ActiveXObject(t):new XMLHttpRequest},$i.prototype.b=function(){var t={};return Ji(this)&&(t[0]=!0,t[1]=!0),t},Qi=new $i,b(Zi,Yi),Zi.prototype.a=function(){var t=new XMLHttpRequest;if("withCredentials"in t)return t;if("undefined"!=typeof XDomainRequest)return new to;throw Error("Unsupported browser")},Zi.prototype.b=function(){return{}},(t=to.prototype).open=function(t,e,n){if(null!=n&&!n)throw Error("Only async requests are supported.");this.a.open(t,e)},t.send=function(t){if(t){if("string"!=typeof t)throw Error("Only string data is supported");this.a.send(t)}else this.a.send()},t.abort=function(){this.a.abort()},t.setRequestHeader=function(){},t.getResponseHeader=function(t){return"content-type"==t.toLowerCase()?this.a.contentType:""},t.bc=function(){this.status=200,this.responseText=this.a.responseText,eo(this,4)},t.zb=function(){this.status=500,this.responseText="",eo(this,4)},t.fc=function(){this.zb()},t.cc=function(){this.status=200,eo(this,1)},t.getAllResponseHeaders=function(){return"content-type: "+this.a.contentType},no.prototype.a=null,no.prototype.reset=function(t,e,n,r,i){delete this.a},io.prototype.toString=function(){return this.name};var oo=new io("SEVERE",1e3),ao=new io("WARNING",900),so=new io("CONFIG",700),uo=new io("FINE",500);ro.prototype.log=function(t,e,n){if(t.value>=function t(e){return e.c?e.c:e.a?t(e.a):(S("Root logger has no level set."),null)}(this).value)for(l(e)&&(e=e()),t=new no(t,String(e),this.f),n&&(t.a=n),n=this;n;)n=n.a};var co={},ho=null;function lo(t){var e;if(ho||(ho=new ro(""),co[""]=ho,ho.c=so),!(e=co[t])){e=new ro(t);var n=t.lastIndexOf("."),r=t.substr(n+1);(n=lo(t.substr(0,n))).b||(n.b={}),n.b[r]=e,e.a=n,co[t]=e}return e}function po(t,e){t&&t.log(uo,e,void 0)}function fo(t){this.f=t}function vo(t){ke.call(this),this.j=t,this.readyState=yo,this.status=0,this.responseText=this.statusText="",this.onreadystatechange=null,this.g=new Headers,this.b=null,this.h="GET",this.c="",this.a=!1,this.f=lo("goog.net.FetchXmlHttp")}b(fo,Yi),fo.prototype.a=function(){return new vo(this.f)},fo.prototype.b=function(t){return function(){return t}}({}),b(vo,ke);var yo=0;function _o(t){t.onreadystatechange&&t.onreadystatechange.call(t)}function go(t){ke.call(this),this.headers=new Me,this.D=t||null,this.c=!1,this.B=this.a=null,this.h=this.N=this.l="",this.f=this.I=this.j=this.G=!1,this.g=0,this.s=null,this.o=mo,this.v=this.O=!1}(t=vo.prototype).open=function(t,e){if(this.readyState!=yo)throw this.abort(),Error("Error reopening a connection");this.h=t,this.c=e,this.readyState=1,_o(this)},t.send=function(t){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.a=!0;var e={headers:this.g,method:this.h,credentials:void 0,cache:void 0};t&&(e.body=t),this.j.fetch(new Request(this.c,e)).then(this.ec.bind(this),this.Ab.bind(this))},t.abort=function(){this.responseText="",this.g=new Headers,this.status=0,1<=this.readyState&&this.a&&4!=this.readyState&&(this.readyState=4,this.a=!1,_o(this)),this.readyState=yo},t.ec=function(t){this.a&&(this.b||(this.b=t.headers,this.readyState=2,_o(this)),this.a&&(this.readyState=3,_o(this),this.a&&t.text().then(this.dc.bind(this,t),this.Ab.bind(this))))},t.dc=function(t,e){this.a&&(this.status=t.status,this.statusText=t.statusText,this.responseText=e,this.readyState=4,_o(this))},t.Ab=function(t){var e=this.f;e&&e.log(ao,"Failed to fetch url "+this.c,t instanceof Error?t:Error(t)),this.a&&(this.readyState=4,_o(this))},t.setRequestHeader=function(t,e){this.g.append(t,e)},t.getResponseHeader=function(t){return this.b?this.b.get(t.toLowerCase())||"":((t=this.f)&&t.log(ao,"Attempting to get response header but no headers have been received for url: "+this.c,void 0),"")},t.getAllResponseHeaders=function(){if(!this.b){var t=this.f;return t&&t.log(ao,"Attempting to get all response headers but no headers have been received for url: "+this.c,void 0),""}t=[];for(var e=this.b.entries(),n=e.next();!n.done;)n=n.value,t.push(n[0]+": "+n[1]),n=e.next();return t.join("\r\n")},b(go,ke);var mo="";go.prototype.b=lo("goog.net.XhrIo");var bo=/^https?$/i,wo=["POST","PUT"];function Eo(t,e,n,o,a){if(t.a)throw Error("[goog.net.XhrIo] Object is active with another request="+t.l+"; newUri="+e);n=n?n.toUpperCase():"GET",t.l=e,t.h="",t.N=n,t.G=!1,t.c=!0,t.a=t.D?t.D.a():Qi.a(),t.B=t.D?Xi(t.D):Xi(Qi),t.a.onreadystatechange=_(t.Db,t);try{po(t.b,Oo(t,"Opening Xhr")),t.I=!0,t.a.open(n,String(e),!0),t.I=!1}catch(e){return po(t.b,Oo(t,"Error opening Xhr: "+e.message)),void Co(t,e)}e=o||"";var s=new Me(t.headers);a&&function(t,e){if(t.forEach&&"function"==typeof t.forEach)t.forEach(e,void 0);else if(h(t)||i(t))D(t,e,void 0);else for(var n=Ue(t),r=Fe(t),o=r.length,a=0;a<o;a++)e.call(void 0,r[a],n&&n[a],t)}(a,function(t,e){s.set(e,t)}),a=function(t){t:{for(var e=To,n=t.length,r=i(t)?t.split(""):t,o=0;o<n;o++)if(o in r&&e.call(void 0,r[o],o,t)){e=o;break t}e=-1}return 0>e?null:i(t)?t.charAt(e):t[e]}(s.U()),o=r.FormData&&e instanceof r.FormData,!F(wo,n)||a||o||s.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),s.forEach(function(t,e){this.a.setRequestHeader(e,t)},t),t.o&&(t.a.responseType=t.o),"withCredentials"in t.a&&t.a.withCredentials!==t.O&&(t.a.withCredentials=t.O);try{Ro(t),0<t.g&&(t.v=function(t){return qt&&te(9)&&"number"==typeof t.timeout&&void 0!==t.ontimeout}(t.a),po(t.b,Oo(t,"Will abort after "+t.g+"ms if incomplete, xhr2 "+t.v)),t.v?(t.a.timeout=t.g,t.a.ontimeout=_(t.Fa,t)):t.s=Le(t.Fa,t.g,t)),po(t.b,Oo(t,"Sending request")),t.j=!0,t.a.send(e),t.j=!1}catch(e){po(t.b,Oo(t,"Send error: "+e.message)),Co(t,e)}}function To(t){return"content-type"==t.toLowerCase()}function Co(t,e){t.c=!1,t.a&&(t.f=!0,t.a.abort(),t.f=!1),t.h=e,So(t),No(t)}function So(t){t.G||(t.G=!0,t.dispatchEvent("complete"),t.dispatchEvent("error"))}function Io(t){if(t.c&&void 0!==n)if(t.B[1]&&4==Ao(t)&&2==ko(t))po(t.b,Oo(t,"Local request error detected and ignored"));else if(t.j&&4==Ao(t))Le(t.Db,0,t);else if(t.dispatchEvent("readystatechange"),4==Ao(t)){po(t.b,Oo(t,"Request complete")),t.c=!1;try{var e,i=ko(t);t:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var o=!0;break t;default:o=!1}if(!(e=o)){var a;if(a=0===i){var s=String(t.l).match(je)[1]||null;if(!s&&r.self&&r.self.location){var u=r.self.location.protocol;s=u.substr(0,u.length-1)}a=!bo.test(s?s.toLowerCase():"")}e=a}if(e)t.dispatchEvent("complete"),t.dispatchEvent("success");else{try{var c=2<Ao(t)?t.a.statusText:""}catch(e){po(t.b,"Can not get status: "+e.message),c=""}t.h=c+" ["+ko(t)+"]",So(t)}}finally{No(t)}}}function No(t,e){if(t.a){Ro(t);var n=t.a,r=t.B[0]?a:null;t.a=null,t.B=null,e||t.dispatchEvent("ready");try{n.onreadystatechange=r}catch(e){(t=t.b)&&t.log(oo,"Problem encountered resetting onreadystatechange: "+e.message,void 0)}}}function Ro(t){t.a&&t.v&&(t.a.ontimeout=null),t.s&&(r.clearTimeout(t.s),t.s=null)}function Ao(t){return t.a?t.a.readyState:0}function ko(t){try{return 2<Ao(t)?t.a.status:-1}catch(t){return-1}}function Oo(t,e){return e+" ["+t.N+" "+t.l+" "+ko(t)+"]"}function Po(t,e){this.g=[],this.v=t,this.s=e||null,this.f=this.a=!1,this.c=void 0,this.u=this.B=this.j=!1,this.h=0,this.b=null,this.l=0}function Do(t,e,n){t.a=!0,t.c=n,t.f=!e,Uo(t)}function Lo(t){if(t.a){if(!t.u)throw new Mo(t);t.u=!1}}function xo(t,e,n,r){t.g.push([e,n,r]),t.a&&Uo(t)}function Fo(t){return x(t.g,function(t){return l(t[1])})}function Uo(t){if(t.h&&t.a&&Fo(t)){var e=t.h,n=jo[e];n&&(r.clearTimeout(n.a),delete jo[e]),t.h=0}t.b&&(t.b.l--,delete t.b),e=t.c;for(var i=n=!1;t.g.length&&!t.j;){var o=t.g.shift(),a=o[0],s=o[1];if(o=o[2],a=t.f?s:a)try{var u=a.call(o||t.s,e);void 0!==u&&(t.f=t.f&&(u==e||u instanceof Error),t.c=e=u),(E(e)||"function"==typeof r.Promise&&e instanceof r.Promise)&&(i=!0,t.j=!0)}catch(r){e=r,t.f=!0,Fo(t)||(n=!0)}}t.c=e,i&&(u=_(t.o,t,!0),i=_(t.o,t,!1),e instanceof Po?(xo(e,u,i),e.B=!0):e.then(u,i)),n&&(e=new Bo(e),jo[e.a]=e,t.h=e.a)}function Mo(){T.call(this)}function Wo(){T.call(this)}function Bo(t){this.a=r.setTimeout(_(this.c,this),0),this.b=t}(t=go.prototype).Fa=function(){void 0!==n&&this.a&&(this.h="Timed out after "+this.g+"ms, aborting",po(this.b,Oo(this,this.h)),this.dispatchEvent("timeout"),this.abort(8))},t.abort=function(){this.a&&this.c&&(po(this.b,Oo(this,"Aborting")),this.c=!1,this.f=!0,this.a.abort(),this.f=!1,this.dispatchEvent("complete"),this.dispatchEvent("abort"),No(this))},t.ua=function(){this.a&&(this.c&&(this.c=!1,this.f=!0,this.a.abort(),this.f=!1),No(this,!0)),go.lb.ua.call(this)},t.Db=function(){this.pa||(this.I||this.j||this.f?Io(this):this.tc())},t.tc=function(){Io(this)},t.getResponse=function(){try{if(!this.a)return null;if("response"in this.a)return this.a.response;switch(this.o){case mo:case"text":return this.a.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in this.a)return this.a.mozResponseArrayBuffer}var t=this.b;return t&&t.log(oo,"Response type "+this.o+" is not supported on this browser",void 0),null}catch(t){return po(this.b,"Can not get response: "+t.message),null}},Po.prototype.cancel=function(t){if(this.a)this.c instanceof Po&&this.c.cancel();else{if(this.b){var e=this.b;delete this.b,t?e.cancel(t):(e.l--,0>=e.l&&e.cancel())}this.v?this.v.call(this.s,this):this.u=!0,this.a||(t=new Wo(this),Lo(this),Do(this,!1,t))}},Po.prototype.o=function(t,e){this.j=!1,Do(this,t,e)},Po.prototype.D=function(){Lo(this),Do(this,!0,null)},Po.prototype.then=function(t,e,n){var r,i,o=new vt(function(t,e){r=t,i=e});return xo(this,r,function(t){t instanceof Wo?o.cancel():i(t)}),o.then(t,e,n)},w(Po),b(Mo,T),Mo.prototype.message="Deferred has already fired",Mo.prototype.name="AlreadyCalledError",b(Wo,T),Wo.prototype.message="Deferred was canceled",Wo.prototype.name="CanceledError",Bo.prototype.c=function(){throw delete jo[this.a],this.b};var jo={};function Vo(t){var e={},n=e.document||document,r=gn(t),i=document.createElement("SCRIPT"),o={Fb:i,Fa:void 0},a=new Po(qo,o),s=null,u=null!=e.timeout?e.timeout:5e3;return 0<u&&(s=window.setTimeout(function(){Ho(i,!0);var t=new Qo(Go,"Timeout reached for loading script "+r);Lo(a),Do(a,!1,t)},u),o.Fa=s),i.onload=i.onreadystatechange=function(){i.readyState&&"loaded"!=i.readyState&&"complete"!=i.readyState||(Ho(i,e.bd||!1,s),a.D())},i.onerror=function(){Ho(i,!0,s);var t=new Qo(Ko,"Error while loading script "+r);Lo(a),Do(a,!1,t)},ct(o=e.attributes||{},{type:"text/javascript",charset:"UTF-8"}),Dn(i,o),i.src=gn(t),function(t){var e;return(e=(t||document).getElementsByTagName("HEAD"))&&0!=e.length?e[0]:t.documentElement}(n).appendChild(i),a}function qo(){if(this&&this.Fb){var t=this.Fb;t&&"SCRIPT"==t.tagName&&Ho(t,!0,this.Fa)}}function Ho(t,e,n){null!=n&&r.clearTimeout(n),t.onload=a,t.onerror=a,t.onreadystatechange=a,e&&window.setTimeout(function(){t&&t.parentNode&&t.parentNode.removeChild(t)},0)}var Ko=0,Go=1;function Qo(t,e){var n="Jsloader error (code #"+t+")";e&&(n+=": "+e),T.call(this,n),this.code=t}function zo(t){this.f=t}function Yo(t,n,i){if(this.b=t,t=n||{},this.j=t.secureTokenEndpoint||"https://securetoken.googleapis.com/v1/token",this.l=t.secureTokenTimeout||Jo,this.f=ot(t.secureTokenHeaders||Zo),this.g=t.firebaseEndpoint||"https://www.googleapis.com/identitytoolkit/v3/relyingparty/",this.h=t.firebaseTimeout||ta,this.a=ot(t.firebaseHeaders||ea),i&&(this.a["X-Client-Version"]=i,this.f["X-Client-Version"]=i),i="Node"==Jn(),!(i=r.XMLHttpRequest||i&&e.INTERNAL.node&&e.INTERNAL.node.XMLHttpRequest)&&!$n())throw new Ur("internal-error","The XMLHttpRequest compatibility library was not found.");this.c=void 0,$n()?this.c=new fo(self):Zn()?this.c=new zo(i):this.c=new Zi}b(Qo,T),b(zo,Yi),zo.prototype.a=function(){return new this.f},zo.prototype.b=function(){return{}};var Xo,$o="idToken",Jo=new gr(3e4,6e4),Zo={"Content-Type":"application/x-www-form-urlencoded"},ta=new gr(3e4,6e4),ea={"Content-Type":"application/json"};function na(t,e){e?t.a["X-Firebase-Locale"]=e:delete t.a["X-Firebase-Locale"]}function ra(t,e){e?(t.a["X-Client-Version"]=e,t.f["X-Client-Version"]=e):(delete t.a["X-Client-Version"],delete t.f["X-Client-Version"])}function ia(t,e,n,i,o,a,s){(function(){var t=or();return!((t=nr(t)!=er?null:(t=t.match(/\sChrome\/(\d+)/i))&&2==t.length?parseInt(t[1],10):null)&&30>t||qt&&Jt&&!(9<Jt))})()||$n()?t=_(t.o,t):(Xo||(Xo=new vt(function(t,e){!function(t,e){if(((window.gapi||{}).client||{}).request)t();else{r[aa]=function(){((window.gapi||{}).client||{}).request?t():e(Error("CORS_UNSUPPORTED"))};var n=mn(oa,{onload:aa});!function(t,e){xo(t,null,e,void 0)}(Vo(n),function(){e(Error("CORS_UNSUPPORTED"))})}}(t,e)})),t=_(t.u,t)),t(e,n,i,o,a,s)}Yo.prototype.o=function(t,e,n,i,o,a){if($n()&&(void 0===r.fetch||void 0===r.Headers||void 0===r.Request))throw new Ur("operation-not-supported-in-this-environment","fetch, Headers and Request native APIs or equivalent Polyfills must be available to support HTTP requests from a Worker environment.");var s=new go(this.c);if(a){s.g=Math.max(0,a);var u=setTimeout(function(){s.dispatchEvent("timeout")},a)}Oe(s,"complete",function(){u&&clearTimeout(u);var t=null;try{t=JSON.parse(function(t){try{return t.a?t.a.responseText:""}catch(e){return po(t.b,"Can not get responseText: "+e.message),""}}(this))||null}catch(e){t=null}e&&e(t)}),Pe(s,"ready",function(){u&&clearTimeout(u),Mt(this)}),Pe(s,"timeout",function(){u&&clearTimeout(u),Mt(this),e&&e(null)}),Eo(s,t,n,i,o)};var oa=yn("https://apis.google.com/js/client.js?onload=%{onload}"),aa="__fcb"+Math.floor(1e6*Math.random()).toString();function sa(t){if(!zi.test(t.email))throw new Ur("invalid-email")}function ua(t){"email"in t&&sa(t)}function ca(t){if(!t[$o])throw new Ur("internal-error")}function ha(t){if(t.phoneNumber||t.temporaryProof){if(!t.phoneNumber||!t.temporaryProof)throw new Ur("internal-error")}else{if(!t.sessionInfo)throw new Ur("missing-verification-id");if(!t.code)throw new Ur("missing-verification-code")}}Yo.prototype.u=function(t,e,n,r,i){var o=this;Xo.then(function(){window.gapi.client.setApiKey(o.b);var a=window.gapi.auth.getToken();window.gapi.auth.setToken(null),window.gapi.client.request({path:t,method:n,body:r,headers:i,authType:"none",callback:function(t){window.gapi.auth.setToken(a),e&&e(t)}})}).m(function(t){e&&e({error:{message:t&&t.message||"CORS_UNSUPPORTED"}})})},Yo.prototype.jb=function(){return Ka(this,Fa,{})},Yo.prototype.mb=function(t,e){return Ka(this,La,{idToken:t,email:e})},Yo.prototype.nb=function(t,e){return Ka(this,xa,{idToken:t,password:e})};var la={displayName:"DISPLAY_NAME",photoUrl:"PHOTO_URL"};function pa(t){if(!t.requestUri||!t.sessionId&&!t.postBody)throw new Ur("internal-error")}function fa(t){var e=null;if(t.needConfirmation?(t.code="account-exists-with-different-credential",e=Gi(t)):"FEDERATED_USER_ID_ALREADY_LINKED"==t.errorMessage?(t.code="credential-already-in-use",e=Gi(t)):"EMAIL_EXISTS"==t.errorMessage?(t.code="email-already-in-use",e=Gi(t)):t.errorMessage&&(e=Ga(t.errorMessage)),e)throw e;if(!t[$o])throw new Ur("internal-error")}function da(t,e){return e.returnIdpCredential=!0,Ka(t,Ua,e)}function va(t,e){return e.returnIdpCredential=!0,Ka(t,Wa,e)}function ya(t,e){return e.returnIdpCredential=!0,e.autoCreate=!1,Ka(t,Ma,e)}function _a(t){if(!t.oobCode)throw new Ur("invalid-action-code")}(t=Yo.prototype).ob=function(t,e){var n={idToken:t},r=[];return rt(la,function(t,i){var o=e[i];null===o?r.push(t):i in e&&(n[i]=o)}),r.length&&(n.deleteAttribute=r),Ka(this,La,n)},t.gb=function(t,e){return ct(t={requestType:"PASSWORD_RESET",email:t},e),Ka(this,Aa,t)},t.hb=function(t,e){return ct(t={requestType:"EMAIL_SIGNIN",email:t},e),Ka(this,Na,t)},t.fb=function(t,e){return ct(t={requestType:"VERIFY_EMAIL",idToken:t},e),Ka(this,Ra,t)},t.Sa=function(t){return Ka(this,Va,t)},t.Wa=function(t,e){return Ka(this,Pa,{oobCode:t,newPassword:e})},t.Ia=function(t){return Ka(this,ma,{oobCode:t})},t.Ua=function(t){return Ka(this,ga,{oobCode:t})};var ga={endpoint:"setAccountInfo",A:_a,ba:"email"},ma={endpoint:"resetPassword",A:_a,J:function(t){var e=t.requestType;if(!e||!t.email&&"EMAIL_SIGNIN"!=e)throw new Ur("internal-error")}},ba={endpoint:"signupNewUser",A:function(t){if(sa(t),!t.password)throw new Ur("weak-password")},J:ca,R:!0},wa={endpoint:"createAuthUri"},Ea={endpoint:"deleteAccount",T:["idToken"]},Ta={endpoint:"setAccountInfo",T:["idToken","deleteProvider"],A:function(t){if(!c(t.deleteProvider))throw new Ur("internal-error")}},Ca={endpoint:"emailLinkSignin",T:["email","oobCode"],A:sa,J:ca,R:!0},Sa={endpoint:"emailLinkSignin",T:["idToken","email","oobCode"],A:sa,J:ca,R:!0},Ia={endpoint:"getAccountInfo"},Na={endpoint:"getOobConfirmationCode",T:["requestType"],A:function(t){if("EMAIL_SIGNIN"!=t.requestType)throw new Ur("internal-error");sa(t)},ba:"email"},Ra={endpoint:"getOobConfirmationCode",T:["idToken","requestType"],A:function(t){if("VERIFY_EMAIL"!=t.requestType)throw new Ur("internal-error")},ba:"email"},Aa={endpoint:"getOobConfirmationCode",T:["requestType"],A:function(t){if("PASSWORD_RESET"!=t.requestType)throw new Ur("internal-error");sa(t)},ba:"email"},ka={pb:!0,endpoint:"getProjectConfig",Cb:"GET"},Oa={pb:!0,endpoint:"getRecaptchaParam",Cb:"GET",J:function(t){if(!t.recaptchaSiteKey)throw new Ur("internal-error")}},Pa={endpoint:"resetPassword",A:_a,ba:"email"},Da={endpoint:"sendVerificationCode",T:["phoneNumber","recaptchaToken"],ba:"sessionInfo"},La={endpoint:"setAccountInfo",T:["idToken"],A:ua,R:!0},xa={endpoint:"setAccountInfo",T:["idToken"],A:function(t){if(ua(t),!t.password)throw new Ur("weak-password")},J:ca,R:!0},Fa={endpoint:"signupNewUser",J:ca,R:!0},Ua={endpoint:"verifyAssertion",A:pa,J:fa,R:!0},Ma={endpoint:"verifyAssertion",A:pa,J:function(t){if(t.errorMessage&&"USER_NOT_FOUND"==t.errorMessage)throw new Ur("user-not-found");if(t.errorMessage)throw Ga(t.errorMessage);if(!t[$o])throw new Ur("internal-error")},R:!0},Wa={endpoint:"verifyAssertion",A:function(t){if(pa(t),!t.idToken)throw new Ur("internal-error")},J:fa,R:!0},Ba={endpoint:"verifyCustomToken",A:function(t){if(!t.token)throw new Ur("invalid-custom-token")},J:ca,R:!0},ja={endpoint:"verifyPassword",A:function(t){if(sa(t),!t.password)throw new Ur("wrong-password")},J:ca,R:!0},Va={endpoint:"verifyPhoneNumber",A:ha,J:ca},qa={endpoint:"verifyPhoneNumber",A:function(t){if(!t.idToken)throw new Ur("internal-error");ha(t)},J:function(t){if(t.temporaryProof)throw t.code="credential-already-in-use",Gi(t);ca(t)}},Ha={Tb:{USER_NOT_FOUND:"user-not-found"},endpoint:"verifyPhoneNumber",A:ha,J:ca};function Ka(t,e,n){if(!function(t,e){if(!e||!e.length)return!0;if(!t)return!1;for(var n=0;n<e.length;n++){var r=t[e[n]];if(void 0===r||null===r||""===r)return!1}return!0}(n,e.T))return Tt(new Ur("internal-error"));var r,i=e.Cb||"POST";return Et(n).then(e.A).then(function(){return e.R&&(n.returnSecureToken=!0),function(t,e,n,r,i,o){var a=ze(t.g+e);Ge(a,"key",t.b),o&&Ge(a,"cb",m().toString());var s="GET"==n;if(s)for(var u in r)r.hasOwnProperty(u)&&Ge(a,u,r[u]);return new vt(function(e,o){ia(t,a.toString(),function(t){t?t.error?o(Qa(t,i||{})):e(t):o(new Ur("network-request-failed"))},n,s?void 0:Un(fr(r)),t.a,t.h.get())})}(t,e.endpoint,i,n,e.Tb,e.pb||!1)}).then(function(t){return r=t}).then(e.J).then(function(){if(!e.ba)return r;if(!(e.ba in r))throw new Ur("internal-error");return r[e.ba]})}function Ga(t){return Qa({error:{errors:[{message:t}],code:400,message:t}})}function Qa(t,e){var n=(t.error&&t.error.errors&&t.error.errors[0]||{}).reason||"",r={keyInvalid:"invalid-api-key",ipRefererBlocked:"app-not-authorized"};if(n=r[n]?new Ur(r[n]):null)return n;for(var i in n=t.error&&t.error.message||"",ct(r={INVALID_CUSTOM_TOKEN:"invalid-custom-token",CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_EMAIL:"invalid-email",INVALID_PASSWORD:"wrong-password",USER_DISABLED:"user-disabled",MISSING_PASSWORD:"internal-error",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",INVALID_MESSAGE_PAYLOAD:"invalid-message-payload",INVALID_RECIPIENT_EMAIL:"invalid-recipient-email",INVALID_SENDER:"invalid-sender",EMAIL_NOT_FOUND:"user-not-found",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",CORS_UNSUPPORTED:"cors-unsupported",DYNAMIC_LINK_NOT_ACTIVATED:"dynamic-link-not-activated",INVALID_APP_ID:"invalid-app-id",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",WEAK_PASSWORD:"weak-password",OPERATION_NOT_ALLOWED:"operation-not-allowed",USER_CANCELLED:"user-cancelled",CAPTCHA_CHECK_FAILED:"captcha-check-failed",INVALID_APP_CREDENTIAL:"invalid-app-credential",INVALID_CODE:"invalid-verification-code",INVALID_PHONE_NUMBER:"invalid-phone-number",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_APP_CREDENTIAL:"missing-app-credential",MISSING_CODE:"missing-verification-code",MISSING_PHONE_NUMBER:"missing-phone-number",MISSING_SESSION_INFO:"missing-verification-id",QUOTA_EXCEEDED:"quota-exceeded",SESSION_EXPIRED:"code-expired",INVALID_CONTINUE_URI:"invalid-continue-uri",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",MISSING_IOS_BUNDLE_ID:"missing-ios-bundle-id",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",INVALID_CERT_HASH:"invalid-cert-hash"},e||{}),e=(e=n.match(/^[^\s]+\s*:\s*(.*)$/))&&1<e.length?e[1]:void 0,r)if(0===n.indexOf(i))return new Ur(r[i],e);return!e&&t&&(e=pr(t)),new Ur("internal-error",e)}var za,Ya={Wc:{Ya:"https://www.googleapis.com/identitytoolkit/v3/relyingparty/",eb:"https://securetoken.googleapis.com/v1/token",id:"p"},Yc:{Ya:"https://staging-www.sandbox.googleapis.com/identitytoolkit/v3/relyingparty/",eb:"https://staging-securetoken.sandbox.googleapis.com/v1/token",id:"s"},Zc:{Ya:"https://www-googleapis-test.sandbox.google.com/identitytoolkit/v3/relyingparty/",eb:"https://test-securetoken.sandbox.googleapis.com/v1/token",id:"t"}};function Xa(t){for(var e in Ya)if(Ya[e].id===t)return{firebaseEndpoint:(t=Ya[e]).Ya,secureTokenEndpoint:t.eb};return null}function $a(t){this.b=t,this.a=null,this.ab=function(t){return(ns||(ns=new vt(function(t,e){function n(){_r(),ar("gapi.load")("gapi.iframes",{callback:t,ontimeout:function(){_r(),e(Error("Network Error"))},timeout:ts.get()})}if(ar("gapi.iframes.Iframe"))t();else if(ar("gapi.load"))n();else{var i="__iframefcb"+Math.floor(1e6*Math.random()).toString();r[i]=function(){ar("gapi.load")?n():e(Error("Network Error"))},Et(Vo(i=mn(Za,{onload:i}))).m(function(){e(Error("Network Error"))})}}).m(function(t){throw ns=null,t}))).then(function(){return new vt(function(e,n){ar("gapi.iframes.getContext")().open({where:document.body,url:t.b,messageHandlersFilter:ar("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"),attributes:{style:{position:"absolute",top:"-100px",width:"1px",height:"1px"}},dontclear:!0},function(r){function i(){clearTimeout(o),e()}t.a=r,t.a.restyle({setHideOnLeave:!1});var o=setTimeout(function(){n(Error("Network Error"))},es.get());r.ping(i).then(i,function(){n(Error("Network Error"))})})})})}(this)}za=Xa("__EID__")?"__EID__":void 0;var Ja,Za=yn("https://apis.google.com/js/api.js?onload=%{onload}"),ts=new gr(3e4,6e4),es=new gr(5e3,15e3),ns=null;function rs(t,e,n){this.j=t,this.g=e,this.h=n,this.f=null,this.a=Ye(this.j,"/__/auth/iframe"),Ge(this.a,"apiKey",this.g),Ge(this.a,"appName",this.h),this.b=null,this.c=[]}function is(t,e,n,r,i){this.o=t,this.u=e,this.c=n,this.l=r,this.h=this.g=this.j=null,this.a=i,this.f=null}function os(t){try{return e.app(t).auth().Ka()}catch(t){return[]}}function as(t,e,n,r,i){this.u=t,this.f=e,this.b=n,this.c=r||null,this.h=i||null,this.o=this.s=this.v=null,this.g=[],this.l=this.a=null}function ss(t){var e=Vn();return function(t){return Ka(t,ka,{}).then(function(t){return t.authorizedDomains||[]})}(t).then(function(t){t:{var n=ze(e),r=n.c;n=n.b;for(var i=0;i<t.length;i++){var o=t[i],a=n,s=r;if(0==o.indexOf("chrome-extension://")?a=ze(o).b==a&&"chrome-extension"==s:"http"!=s&&"https"!=s?a=!1:Qn.test(o)?a=a==o:(o=o.split(".").join("\\."),a=new RegExp("^(.+\\."+o+"|"+o+")$","i").test(a)),a){t=!0;break t}}t=!1}if(!t)throw new Hi(Vn())})}function us(t){return t.l?t.l:(t.l=zn().then(function(){if(!t.s){var e=t.c,n=t.h,r=os(t.b),i=new rs(t.u,t.f,t.b);i.f=e,i.b=n,i.c=B(r||[]),t.s=i.toString()}t.j=new $a(t.s),function(t){if(!t.j)throw Error("IfcHandler must be initialized!");!function(t,e){t.ab.then(function(){t.a.register("authEvent",e,ar("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"))})}(t.j,function(e){var n={};if(e&&e.authEvent){var r=!1;for(e=ji(e.authEvent),n=0;n<t.g.length;n++)r=t.g[n](e)||r;return(n={}).status=r?"ACK":"ERROR",Et(n)}return n.status="ERROR",Et(n)})}(t)}),t.l)}function cs(t){return t.o||(t.v=t.c?ir(t.c,os(t.b)):null,t.o=new Yo(t.f,Xa(t.h),t.v)),t.o}function hs(t,e,n,r,i,o,a,s,u,c){return(t=new is(t,e,n,r,i)).j=o,t.g=a,t.h=s,t.b=ot(u||null),t.f=c,t.toString()}function ls(t){if(this.a=t||e.INTERNAL.reactNative&&e.INTERNAL.reactNative.AsyncStorage,!this.a)throw new Ur("internal-error","The React Native compatibility library was not found.");this.type="asyncStorage"}function ps(){if(!vs())throw new Ur("web-storage-unsupported");this.f={},this.a=[],this.b=0,this.g=r.indexedDB,this.type="indexedDB"}function fs(t){return new vt(function(e,n){var r=t.g.open("firebaseLocalStorageDb",1);r.onerror=function(t){try{t.preventDefault()}catch(t){}n(Error(t.target.error))},r.onupgradeneeded=function(t){t=t.target.result;try{t.createObjectStore("firebaseLocalStorage",{keyPath:"fbase_key"})}catch(t){n(t)}},r.onsuccess=function(r){(r=r.target.result).objectStoreNames.contains("firebaseLocalStorage")?e(r):function(t){return new vt(function(e,n){var r=t.g.deleteDatabase("firebaseLocalStorageDb");r.onsuccess=function(){e()},r.onerror=function(t){n(Error(t.target.error))}})}(t).then(function(){return fs(t)}).then(function(t){e(t)}).m(function(t){n(t)})}})}function ds(t){return t.h||(t.h=fs(t)),t.h}function vs(){try{return!!r.indexedDB}catch(t){return!1}}function ys(t){return t.objectStore("firebaseLocalStorage")}function _s(t,e){return t.transaction(["firebaseLocalStorage"],e?"readwrite":"readonly")}function gs(t){return new vt(function(e,n){t.onsuccess=function(t){t&&t.target?e(t.target.result):e()},t.onerror=function(t){n(Error(t.target.errorCode))}})}function ms(t){var e=this,n=null;this.a=[],this.type="indexedDB",this.c=t,this.b=Et().then(function(){return vs()?(Ja||(Ja=new ps),(n=Ja).set("__sak","!").then(function(){return n.get("__sak")}).then(function(t){if("!"!==t)throw Error("indexedDB not supported!");return n.P("__sak")}).then(function(){return n}).m(function(){return e.c})):e.c}).then(function(t){return e.type=t.type,t.Y(function(t){D(e.a,function(e){e(t)})}),t})}function bs(){this.a={},this.type="inMemory"}function ws(){if(!function(){var t="Node"==Jn();if(!(t=Es()||t&&e.INTERNAL.node&&e.INTERNAL.node.localStorage))return!1;try{return t.setItem("__sak","1"),t.removeItem("__sak"),!0}catch(t){return!1}}()){if("Node"==Jn())throw new Ur("internal-error","The LocalStorage compatibility library was not found.");throw new Ur("web-storage-unsupported")}this.a=Es()||e.INTERNAL.node.localStorage,this.type="localStorage"}function Es(){try{var t=r.localStorage,e=vr();return t&&(t.setItem(e,"1"),t.removeItem(e)),t}catch(t){return null}}function Ts(){this.type="nullStorage"}function Cs(){if(!function(){var t="Node"==Jn();if(!(t=Ss()||t&&e.INTERNAL.node&&e.INTERNAL.node.sessionStorage))return!1;try{return t.setItem("__sak","1"),t.removeItem("__sak"),!0}catch(t){return!1}}()){if("Node"==Jn())throw new Ur("internal-error","The SessionStorage compatibility library was not found.");throw new Ur("web-storage-unsupported")}this.a=Ss()||e.INTERNAL.node.sessionStorage,this.type="sessionStorage"}function Ss(){try{var t=r.sessionStorage,e=vr();return t&&(t.setItem(e,"1"),t.removeItem(e)),t}catch(t){return null}}rs.prototype.toString=function(){return this.f?Ge(this.a,"v",this.f):un(this.a.a,"v"),this.b?Ge(this.a,"eid",this.b):un(this.a.a,"eid"),this.c.length?Ge(this.a,"fw",this.c.join(",")):un(this.a.a,"fw"),this.a.toString()},is.prototype.toString=function(){var t=Ye(this.o,"/__/auth/handler");if(Ge(t,"apiKey",this.u),Ge(t,"appName",this.c),Ge(t,"authType",this.l),this.a.isOAuthProvider){var n=this.a;try{var r=e.app(this.c).auth().ca()}catch(t){r=null}for(var i in n.Xa=r,Ge(t,"providerId",this.a.providerId),r=fr((n=this.a).tb))r[i]=r[i].toString();i=n.Ac,r=ot(r);for(var o=0;o<i.length;o++){var a=i[o];a in r&&delete r[a]}n.Za&&n.Xa&&!r[n.Za]&&(r[n.Za]=n.Xa),it(r)||Ge(t,"customParameters",pr(r))}if("function"==typeof this.a.yb&&((n=this.a.yb()).length&&Ge(t,"scopes",n.join(","))),this.j?Ge(t,"redirectUrl",this.j):un(t.a,"redirectUrl"),this.g?Ge(t,"eventId",this.g):un(t.a,"eventId"),this.h?Ge(t,"v",this.h):un(t.a,"v"),this.b)for(var s in this.b)this.b.hasOwnProperty(s)&&!Qe(t,s)&&Ge(t,s,this.b[s]);return this.f?Ge(t,"eid",this.f):un(t.a,"eid"),(s=os(this.c)).length&&Ge(t,"fw",s.join(",")),t.toString()},(t=as.prototype).Da=function(t,e,n){var r=new Ur("popup-closed-by-user"),i=new Ur("web-storage-unsupported"),o=this,a=!1;return this.ea().then(function(){(function(t){var e={type:"webStorageSupport"};return us(t).then(function(){return function(t,e){return t.ab.then(function(){return new vt(function(n){t.a.send(e.type,e,n,ar("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"))})})}(t.j,e)}).then(function(t){if(t&&t.length&&void 0!==t[0].webStorageSupport)return t[0].webStorageSupport;throw Error()})})(o).then(function(n){n||(t&&Kn(t),e(i),a=!0)})}).m(function(){}).then(function(){if(!a)return function(t){return new vt(function(e){return function n(){xe(2e3).then(function(){if(t&&!t.closed)return n();e()})}()})}(t)}).then(function(){if(!a)return xe(n).then(function(){e(r)})})},t.Gb=function(){var t=or();return!lr(t)&&!yr(t)},t.Bb=function(){return!1},t.xb=function(t,e,n,r,i,o,a){if(!t)return Tt(new Ur("popup-blocked"));if(a&&!lr())return this.ea().m(function(e){Kn(t),i(e)}),r(),Et();this.a||(this.a=ss(cs(this)));var s=this;return this.a.then(function(){var e=s.ea().m(function(e){throw Kn(t),i(e),e});return r(),e}).then(function(){(Wi(n),a)||qn(hs(s.u,s.f,s.b,e,n,null,o,s.c,void 0,s.h),t)}).m(function(t){throw"auth/network-request-failed"==t.code&&(s.a=null),t})},t.Ba=function(t,e,n){this.a||(this.a=ss(cs(this)));var r=this;return this.a.then(function(){Wi(e),qn(hs(r.u,r.f,r.b,t,e,Vn(),n,r.c,void 0,r.h))}).m(function(t){throw"auth/network-request-failed"==t.code&&(r.a=null),t})},t.ea=function(){var t=this;return us(this).then(function(){return t.j.ab}).m(function(){throw t.a=null,new Ur("network-request-failed")})},t.Lb=function(){return!0},t.va=function(t){this.g.push(t)},t.Ja=function(t){M(this.g,function(e){return e==t})},(t=ls.prototype).get=function(t){return Et(this.a.getItem(t)).then(function(t){return t&&dr(t)})},t.set=function(t,e){return Et(this.a.setItem(t,pr(e)))},t.P=function(t){return Et(this.a.removeItem(t))},t.Y=function(){},t.aa=function(){},(t=ps.prototype).set=function(t,e){var n,r=!1,i=this;return ds(this).then(function(e){return gs((e=ys(_s(n=e,!0))).get(t))}).then(function(o){var a=ys(_s(n,!0));return o?(o.value=e,gs(a.put(o))):(i.b++,r=!0,(o={}).fbase_key=t,o.value=e,gs(a.add(o)))}).then(function(){i.f[t]=e}).ha(function(){r&&i.b--})},t.get=function(t){return ds(this).then(function(e){return gs(ys(_s(e,!1)).get(t))}).then(function(t){return t&&t.value})},t.P=function(t){var e=!1,n=this;return ds(this).then(function(r){return e=!0,n.b++,gs(ys(_s(r,!0)).delete(t))}).then(function(){delete n.f[t]}).ha(function(){e&&n.b--})},t.Jc=function(){var t=this;return ds(this).then(function(t){var e=ys(_s(t,!1));return e.getAll?gs(e.getAll()):new vt(function(t,n){var r=[],i=e.openCursor();i.onsuccess=function(e){(e=e.target.result)?(r.push(e.value),e.continue()):t(r)},i.onerror=function(t){n(Error(t.target.errorCode))}})}).then(function(e){var n={},r=[];if(0==t.b){for(r=0;r<e.length;r++)n[e[r].fbase_key]=e[r].value;r=function t(e,n){var r,i=[];for(r in e)if(r in n)if(typeof e[r]!=typeof n[r])i.push(r);else if(c(e[r])){t:{var o=void 0,a=e[r],s=n[r];for(o in a)if(!(o in s)||a[o]!==s[o]){o=!1;break t}for(o in s)if(!(o in a)){o=!1;break t}o=!0}o||i.push(r)}else"object"==typeof e[r]&&null!=e[r]&&null!=n[r]?0<t(e[r],n[r]).length&&i.push(r):e[r]!==n[r]&&i.push(r);else i.push(r);for(r in n)r in e||i.push(r);return i}(t.f,n),t.f=n}return r})},t.Y=function(t){0==this.a.length&&function(t){t.c&&t.c.cancel("STOP_EVENT"),function e(){t.c=xe(800).then(_(t.Jc,t)).then(function(e){0<e.length&&D(t.a,function(t){t(e)})}).then(e).m(function(t){"STOP_EVENT"!=t.message&&e()});return t.c}()}(this),this.a.push(t)},t.aa=function(t){M(this.a,function(e){return e==t}),0==this.a.length&&this.c&&this.c.cancel("STOP_EVENT")},(t=ms.prototype).get=function(t){return this.b.then(function(e){return e.get(t)})},t.set=function(t,e){return this.b.then(function(n){return n.set(t,e)})},t.P=function(t){return this.b.then(function(e){return e.P(t)})},t.Y=function(t){this.a.push(t)},t.aa=function(t){M(this.a,function(e){return e==t})},(t=bs.prototype).get=function(t){return Et(this.a[t])},t.set=function(t,e){return this.a[t]=e,Et()},t.P=function(t){return delete this.a[t],Et()},t.Y=function(){},t.aa=function(){},(t=ws.prototype).get=function(t){var e=this;return Et().then(function(){return dr(e.a.getItem(t))})},t.set=function(t,e){var n=this;return Et().then(function(){var r=pr(e);null===r?n.P(t):n.a.setItem(t,r)})},t.P=function(t){var e=this;return Et().then(function(){e.a.removeItem(t)})},t.Y=function(t){r.window&&ge(r.window,"storage",t)},t.aa=function(t){r.window&&we(r.window,"storage",t)},(t=Ts.prototype).get=function(){return Et(null)},t.set=function(){return Et()},t.P=function(){return Et()},t.Y=function(){},t.aa=function(){},(t=Cs.prototype).get=function(t){var e=this;return Et().then(function(){return dr(e.a.getItem(t))})},t.set=function(t,e){var n=this;return Et().then(function(){var r=pr(e);null===r?n.P(t):n.a.setItem(t,r)})},t.P=function(t){var e=this;return Et().then(function(){e.a.removeItem(t)})},t.Y=function(){},t.aa=function(){};var Is,Ns,Rs={w:ws,Pa:Cs},As={w:ws,Pa:Cs},ks={w:ls,Pa:Ts},Os={w:ws,Pa:Ts},Ps={Vc:"local",NONE:"none",Xc:"session"};function Ds(){var t=!(yr(or())||!Xn()),e=lr(),n=sr();this.o=t,this.h=e,this.l=n,this.a={},Is||(Is=new function(){var t={};t.Browser=Rs,t.Node=As,t.ReactNative=ks,t.Worker=Os,this.a=t[Jn()]}),t=Is;try{this.g=!jn()&&wr()||!r.indexedDB?new t.a.w:new ms($n()?new bs:new t.a.w)}catch(t){this.g=new bs,this.h=!0}try{this.j=new t.a.Pa}catch(t){this.j=new bs}this.u=new bs,this.f=_(this.Kb,this),this.b={}}function Ls(){return Ns||(Ns=new Ds),Ns}function xs(t,e){switch(e){case"session":return t.j;case"none":return t.u;default:return t.g}}function Fs(t,e){return"firebase:"+t.name+(e?":"+e:"")}function Us(t,e,n){return n=Fs(e,n),"local"==e.w&&(t.b[n]=null),xs(t,e.w).P(n)}function Ms(t){t.c&&(clearInterval(t.c),t.c=null)}(t=Ds.prototype).get=function(t,e){return xs(this,t.w).get(Fs(t,e))},t.set=function(t,e,n){var r=Fs(t,n),i=this,o=xs(this,t.w);return o.set(r,e).then(function(){return o.get(r)}).then(function(e){"local"==t.w&&(i.b[r]=e)})},t.addListener=function(t,e,n){t=Fs(t,e),this.l&&(this.b[t]=r.localStorage.getItem(t)),it(this.a)&&(xs(this,"local").Y(this.f),this.h||(jn()||!wr())&&r.indexedDB||!this.l||function(t){Ms(t),t.c=setInterval(function(){for(var e in t.a){var n=r.localStorage.getItem(e),i=t.b[e];n!=i&&(t.b[e]=n,n=new ue({type:"storage",key:e,target:window,oldValue:i,newValue:n,a:!0}),t.Kb(n))}},1e3)}(this)),this.a[t]||(this.a[t]=[]),this.a[t].push(n)},t.removeListener=function(t,e,n){t=Fs(t,e),this.a[t]&&(M(this.a[t],function(t){return t==n}),0==this.a[t].length&&delete this.a[t]),it(this.a)&&(xs(this,"local").aa(this.f),Ms(this))},t.Kb=function(t){if(t&&t.f){var e=t.a.key;if(null==e)for(var n in this.a){var i=this.b[n];void 0===i&&(i=null);var o=r.localStorage.getItem(n);o!==i&&(this.b[n]=o,this.Va(n))}else if(0==e.indexOf("firebase:")&&this.a[e]){if(void 0!==t.a.a?xs(this,"local").aa(this.f):Ms(this),this.o)if(n=r.localStorage.getItem(e),(i=t.a.newValue)!==n)null!==i?r.localStorage.setItem(e,i):r.localStorage.removeItem(e);else if(this.b[e]===i&&void 0===t.a.a)return;var a=this;n=function(){void 0===t.a.a&&a.b[e]===r.localStorage.getItem(e)||(a.b[e]=r.localStorage.getItem(e),a.Va(e))},qt&&Jt&&10==Jt&&r.localStorage.getItem(e)!==t.a.newValue&&t.a.newValue!==t.a.oldValue?setTimeout(n,10):n()}}else D(t,_(this.Va,this))},t.Va=function(t){this.a[t]&&D(this.a[t],function(t){t()})};var Ws,Bs={name:"authEvent",w:"local"};function js(t,e){this.b=-1,this.b=Vs,this.f=r.Uint8Array?new Uint8Array(this.b):Array(this.b),this.g=this.c=0,this.a=[],this.j=t,this.h=e,this.l=r.Int32Array?new Int32Array(64):Array(64),void 0!==Ws||(Ws=r.Int32Array?new Int32Array(Ys):Ys),this.reset()}b(js,function(){this.b=-1});for(var Vs=64,qs=Vs-1,Hs=[],Ks=0;Ks<qs;Ks++)Hs[Ks]=0;var Gs=W(128,Hs);function Qs(t){for(var e=t.f,n=t.l,r=0,i=0;i<e.length;)n[r++]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3],i=4*r;for(e=16;64>e;e++){i=0|n[e-15],r=0|n[e-2];var o=(0|n[e-16])+((i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3)|0,a=(0|n[e-7])+((r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10)|0;n[e]=o+a|0}r=0|t.a[0],i=0|t.a[1];var s=0|t.a[2],u=0|t.a[3],c=0|t.a[4],h=0|t.a[5],l=0|t.a[6];for(o=0|t.a[7],e=0;64>e;e++){var p=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&i^r&s^i&s)|0;a=(o=o+((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))|0)+((a=(a=c&h^~c&l)+(0|Ws[e])|0)+(0|n[e])|0)|0,o=l,l=h,h=c,c=u+a|0,u=s,s=i,i=r,r=a+p|0}t.a[0]=t.a[0]+r|0,t.a[1]=t.a[1]+i|0,t.a[2]=t.a[2]+s|0,t.a[3]=t.a[3]+u|0,t.a[4]=t.a[4]+c|0,t.a[5]=t.a[5]+h|0,t.a[6]=t.a[6]+l|0,t.a[7]=t.a[7]+o|0}function zs(t,e,n){void 0===n&&(n=e.length);var r=0,o=t.c;if(i(e))for(;r<n;)t.f[o++]=e.charCodeAt(r++),o==t.b&&(Qs(t),o=0);else{if(!h(e))throw Error("message must be string or array");for(;r<n;){var a=e[r++];if(!("number"==typeof a&&0<=a&&255>=a&&a==(0|a)))throw Error("message must be a byte array");t.f[o++]=a,o==t.b&&(Qs(t),o=0)}}t.c=o,t.g+=n}js.prototype.reset=function(){this.g=this.c=0,this.a=r.Int32Array?new Int32Array(this.h):B(this.h)};var Ys=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Xs(){js.call(this,8,$s)}b(Xs,js);var $s=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function Js(t,e,n,r,i){this.u=t,this.j=e,this.l=n,this.o=r||null,this.s=i||null,this.h=e+":"+n,this.v=new function(){this.a=Ls()},this.g=new function(t){this.a=t,this.b=Ls()}(this.h),this.f=null,this.b=[],this.a=this.c=null}function Zs(t){return new Ur("invalid-cordova-configuration",t)}function tu(t){var e=new Xs;zs(e,t),t=[];var n=8*e.g;56>e.c?zs(e,Gs,56-e.c):zs(e,Gs,e.b-(e.c-56));for(var r=63;56<=r;r--)e.f[r]=255&n,n/=256;for(Qs(e),r=n=0;r<e.j;r++)for(var i=24;0<=i;i-=8)t[n++]=e.a[r]>>i&255;return function(t){return L(t,function(t){return 1<(t=t.toString(16)).length?t:"0"+t}).join("")}(t)}function eu(t,e){for(var n=0;n<t.b.length;n++)try{t.b[n](e)}catch(t){}}function nu(t){return t.f||(t.f=t.ea().then(function(){return new vt(function(e){t.va(function n(r){return e(r),t.Ja(n),!1}),function(t){function e(e){i=!0,o&&o.cancel(),ru(t).then(function(r){var i=n;if(r&&e&&e.url){var o=null;-1!=(i=yi(e.url)).indexOf("/__/auth/callback")&&(o=(o="object"==typeof(o=dr(Qe(o=ze(i),"firebaseError")||null))?Mr(o):null)?new Bi(r.b,r.c,null,null,o):new Bi(r.b,r.c,i,r.g)),i=o||n}eu(t,i)})}var n=new Bi("unknown",null,null,null,new Ur("no-auth-event")),i=!1,o=xe(500).then(function(){return ru(t).then(function(){i||eu(t,n)})}),a=r.handleOpenURL;r.handleOpenURL=function(t){if(0==t.toLowerCase().indexOf(ar("BuildInfo.packageName",r).toLowerCase()+"://")&&e({url:t}),"function"==typeof a)try{a(t)}catch(t){console.error(t)}},qi||(qi=new Vi),qi.subscribe(e)}(t)})})),t.f}function ru(t){var e=null;return function(t){return t.b.get(Bs,t.a).then(function(t){return ji(t)})}(t.g).then(function(n){return e=n,Us((n=t.g).b,Bs,n.a)}).then(function(){return e})}(t=Js.prototype).ea=function(){return this.ya?this.ya:this.ya=(Yn(void 0)?zn().then(function(){return new vt(function(t,e){var n=r.document,i=setTimeout(function(){e(Error("Cordova framework is not ready."))},1e3);n.addEventListener("deviceready",function(){clearTimeout(i),t()},!1)})}):Tt(Error("Cordova must run in an Android or iOS file scheme."))).then(function(){if("function"!=typeof ar("universalLinks.subscribe",r))throw Zs("cordova-universal-links-plugin is not installed");if(void 0===ar("BuildInfo.packageName",r))throw Zs("cordova-plugin-buildinfo is not installed");if("function"!=typeof ar("cordova.plugins.browsertab.openUrl",r))throw Zs("cordova-plugin-browsertab is not installed");if("function"!=typeof ar("cordova.InAppBrowser.open",r))throw Zs("cordova-plugin-inappbrowser is not installed")},function(){throw new Ur("cordova-not-ready")})},t.Da=function(t,e){return e(new Ur("operation-not-supported-in-this-environment")),Et()},t.xb=function(){return Tt(new Ur("operation-not-supported-in-this-environment"))},t.Lb=function(){return!1},t.Gb=function(){return!0},t.Bb=function(){return!0},t.Ba=function(t,e,n){if(this.c)return Tt(new Ur("redirect-operation-pending"));var i=this,o=r.document,a=null,s=null,u=null,c=null;return this.c=Et().then(function(){return Wi(e),nu(i)}).then(function(){return function(t,e,n,i){var o=function(){for(var t=20,e=[];0<t;)e.push("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Math.floor(62*Math.random()))),t--;return e.join("")}(),a=new Bi(e,i,null,o,new Ur("no-auth-event")),s=ar("BuildInfo.packageName",r);if("string"!=typeof s)throw new Ur("invalid-cordova-configuration");var u=ar("BuildInfo.displayName",r),c={};if(or().toLowerCase().match(/iphone|ipad|ipod/))c.ibi=s;else{if(!or().toLowerCase().match(/android/))return Tt(new Ur("operation-not-supported-in-this-environment"));c.apn=s}u&&(c.appDisplayName=u),o=tu(o),c.sessionId=o;var h=hs(t.u,t.j,t.l,e,n,null,i,t.o,c,t.s);return t.ea().then(function(){var e=t.h;return t.v.a.set(Bs,a.C(),e)}).then(function(){var e=ar("cordova.plugins.browsertab.isAvailable",r);if("function"!=typeof e)throw new Ur("invalid-cordova-configuration");var n=null;e(function(e){if(e){if("function"!=typeof(n=ar("cordova.plugins.browsertab.openUrl",r)))throw new Ur("invalid-cordova-configuration");n(h)}else{if("function"!=typeof(n=ar("cordova.InAppBrowser.open",r)))throw new Ur("invalid-cordova-configuration");e=!(!(e=or()).match(/(iPad|iPhone|iPod).*OS 7_\d/i)&&!e.match(/(iPad|iPhone|iPod).*OS 8_\d/i)),t.a=n(h,e?"_blank":"_system","location=yes")}})})}(i,t,e,n)}).then(function(){return new vt(function(t,e){s=function(){var e=ar("cordova.plugins.browsertab.close",r);return t(),"function"==typeof e&&e(),i.a&&"function"==typeof i.a.close&&(i.a.close(),i.a=null),!1},i.va(s),u=function(){a||(a=xe(2e3).then(function(){e(new Ur("redirect-cancelled-by-user"))}))},c=function(){mr()&&u()},o.addEventListener("resume",u,!1),or().toLowerCase().match(/android/)||o.addEventListener("visibilitychange",c,!1)}).m(function(t){return ru(i).then(function(){throw t})})}).ha(function(){u&&o.removeEventListener("resume",u,!1),c&&o.removeEventListener("visibilitychange",c,!1),a&&a.cancel(),s&&i.Ja(s),i.c=null})},t.va=function(t){this.b.push(t),nu(this).m(function(e){"auth/invalid-cordova-configuration"===e.code&&(e=new Bi("unknown",null,null,null,new Ur("no-auth-event")),t(e))})},t.Ja=function(t){M(this.b,function(e){return e==t})};var iu={name:"pendingRedirect",w:"session"};function ou(t){return Us(t.b,iu,t.a)}function au(t,e,n){this.v=t,this.l=e,this.u=n,this.h=[],this.f=!1,this.j=_(this.o,this),this.c=new yu,this.s=new bu,this.g=new function(t){this.a=t,this.b=Ls()}(this.l+":"+this.u),this.b={},this.b.unknown=this.c,this.b.signInViaRedirect=this.c,this.b.linkViaRedirect=this.c,this.b.reauthViaRedirect=this.c,this.b.signInViaPopup=this.s,this.b.linkViaPopup=this.s,this.b.reauthViaPopup=this.s,this.a=su(this.v,this.l,this.u,za)}function su(t,n,r,i){var o=e.SDK_VERSION||null;return Yn()?new Js(t,n,r,o,i):new as(t,n,r,o,i)}function uu(t){t.f||(t.f=!0,t.a.va(t.j));var e=t.a;return t.a.ea().m(function(n){throw t.a==e&&t.reset(),n})}function cu(t){t.a.Gb()&&uu(t).m(function(e){var n=new Bi("unknown",null,null,null,new Ur("operation-not-supported-in-this-environment"));fu(e)&&t.o(n)}),t.a.Bb()||_u(t.c)}au.prototype.reset=function(){this.f=!1,this.a.Ja(this.j),this.a=su(this.v,this.l,this.u)},au.prototype.subscribe=function(t){if(F(this.h,t)||this.h.push(t),!this.f){var e=this;(function(t){return t.b.get(iu,t.a).then(function(t){return"pending"==t})})(this.g).then(function(t){t?ou(e.g).then(function(){uu(e).m(function(t){var n=new Bi("unknown",null,null,null,new Ur("operation-not-supported-in-this-environment"));fu(t)&&e.o(n)})}):cu(e)}).m(function(){cu(e)})}},au.prototype.unsubscribe=function(t){M(this.h,function(e){return e==t})},au.prototype.o=function(t){if(!t)throw new Ur("invalid-auth-event");for(var e=!1,n=0;n<this.h.length;n++){var r=this.h[n];if(r.qb(t.b,t.c)){(e=this.b[t.b])&&e.h(t,r),e=!0;break}}return _u(this.c),e};var hu=new gr(2e3,1e4),lu=new gr(3e4,6e4);function pu(t,e,n,r,i,o){return t.a.xb(e,n,r,function(){t.f||(t.f=!0,t.a.va(t.j))},function(){t.reset()},i,o)}function fu(t){return!(!t||"auth/cordova-not-ready"!=t.code)}au.prototype.da=function(){return this.c.da()},au.prototype.Ba=function(t,e,n){var r,i=this;return function(t){return t.b.set(iu,"pending",t.a)}(this.g).then(function(){return i.a.Ba(t,e,n).m(function(t){if(fu(t))throw new Ur("operation-not-supported-in-this-environment");return r=t,ou(i.g).then(function(){throw r})}).then(function(){return i.a.Lb()?new vt(function(){}):ou(i.g).then(function(){return i.da()}).then(function(){}).m(function(){})})})},au.prototype.Da=function(t,e,n,r){return this.a.Da(n,function(n){t.ga(e,null,n,r)},hu.get())};var du={};function vu(t,e,n){var r=e+":"+n;return du[r]||(du[r]=new au(t,e,n)),du[r]}function yu(){this.b=null,this.f=[],this.c=[],this.a=null,this.g=!1}function _u(t){t.g||(t.g=!0,mu(t,!1,null,null))}function gu(t,e){if(t.b=function(){return Et(e)},t.f.length)for(var n=0;n<t.f.length;n++)t.f[n](e)}function mu(t,e,n,r){e?r?function(t,e){if(t.b=function(){return Tt(e)},t.c.length)for(var n=0;n<t.c.length;n++)t.c[n](e)}(t,r):gu(t,n):gu(t,{user:null}),t.f=[],t.c=[]}function bu(){}function wu(t,e){this.a=e,Sr(this,"verificationId",t)}function Eu(t,e,n,r){return new Fi(t).Sa(e,n).then(function(t){return new wu(t,r)})}function Tu(t,e,n){if(this.h=t,this.j=e,this.g=n,this.c=3e4,this.f=96e4,this.b=null,this.a=this.c,this.f<this.c)throw Error("Proactive refresh lower bound greater than upper bound!")}function Cu(t){this.f=t,this.b=this.a=null,this.c=0}function Su(t,e){var n=e[$o],r=e.refreshToken;e=Iu(e.expiresIn),t.b=n,t.c=e,t.a=r}function Iu(t){return m()+1e3*parseInt(t,10)}function Nu(t,e){return function(t,e){return new vt(function(n,r){"refresh_token"==e.grant_type&&e.refresh_token||"authorization_code"==e.grant_type&&e.code?ia(t,t.j+"?key="+encodeURIComponent(t.b),function(t){t?t.error?r(Qa(t)):t.access_token&&t.refresh_token?n(t):r(new Ur("internal-error")):r(new Ur("network-request-failed"))},"POST",sn(e).toString(),t.f,t.l.get()):r(new Ur("internal-error"))})}(t.f,e).then(function(e){return t.b=e.access_token,t.c=Iu(e.expires_in),t.a=e.refresh_token,{accessToken:t.b,expirationTime:t.c,refreshToken:t.a}}).m(function(e){throw"auth/user-token-expired"==e.code&&(t.a=null),e})}function Ru(t,e){this.a=t||null,this.b=e||null,Ir(this,{lastSignInTime:br(e||null),creationTime:br(t||null)})}function Au(t,e){for(var n in se.call(this,t),e)this[n]=e[n]}function ku(t,n,r){this.D=[],this.G=t.apiKey,this.s=t.appName,this.B=t.authDomain||null,t=e.SDK_VERSION?ir(e.SDK_VERSION):null,this.b=new Yo(this.G,Xa(za),t),this.h=new Cu(this.b),Uu(this,n[$o]),Su(this.h,n),Sr(this,"refreshToken",this.h.a),Bu(this,r||{}),ke.call(this),this.I=!1,this.B&&ur()&&(this.a=vu(this.B,this.G,this.s)),this.N=[],this.j=null,this.l=function(t){return new Tu(function(){return t.F(!0)},function(t){return!(!t||"auth/network-request-failed"!=t.code)},function(){var e=t.h.c-m()-3e5;return 0<e?e:0})}(this),this.V=_(this.Ga,this);var i=this;this.ia=null,this.sa=function(t){i.na(t.g)},this.X=null,this.O=[],this.ra=function(t){Pu(i,t.c)},this.W=null}function Ou(t,e){t.X&&we(t.X,"languageCodeChanged",t.sa),(t.X=e)&&ge(e,"languageCodeChanged",t.sa)}function Pu(t,n){t.O=n,ra(t.b,e.SDK_VERSION?ir(e.SDK_VERSION,t.O):null)}function Du(t,e){t.W&&we(t.W,"frameworkChanged",t.ra),(t.W=e)&&ge(e,"frameworkChanged",t.ra)}function Lu(t){try{return e.app(t.s).auth()}catch(e){throw new Ur("internal-error","No firebase.auth.Auth instance is available for the Firebase App '"+t.s+"'!")}}function xu(t){t.o||t.l.b||(t.l.start(),we(t,"tokenChanged",t.V),ge(t,"tokenChanged",t.V))}function Fu(t){we(t,"tokenChanged",t.V),t.l.stop()}function Uu(t,e){t.qa=e,Sr(t,"_lat",e)}function Mu(t){for(var e=[],n=0;n<t.N.length;n++)e.push(t.N[n](t));return function(t){return new vt(function(e){var n=t.length,r=[];if(n)for(var i=function(t,i,o){n--,r[t]=i?{Zb:!0,value:o}:{Zb:!1,reason:o},0==n&&e(r)},o=0;o<t.length;o++)Ct(t[o],g(i,o,!0),g(i,o,!1));else e(r)})}(e).then(function(){return t})}function Wu(t){t.a&&!t.I&&(t.I=!0,t.a.subscribe(t))}function Bu(t,e){Ir(t,{uid:e.uid,displayName:e.displayName||null,photoURL:e.photoURL||null,email:e.email||null,emailVerified:e.emailVerified||!1,phoneNumber:e.phoneNumber||null,isAnonymous:e.isAnonymous||!1,metadata:new Ru(e.createdAt,e.lastLoginAt),providerData:[]})}function ju(){}function Vu(t){return Et().then(function(){if(t.o)throw new Ur("app-deleted")})}function qu(t){return L(t.providerData,function(t){return t.providerId})}function Hu(t,e){e&&(Ku(t,e.providerId),t.providerData.push(e))}function Ku(t,e){M(t.providerData,function(t){return t.providerId==e})}function Gu(t,e,n){("uid"!=e||n)&&t.hasOwnProperty(e)&&Sr(t,e,n)}function Qu(t,e){t!=e&&(Ir(t,{uid:e.uid,displayName:e.displayName,photoURL:e.photoURL,email:e.email,emailVerified:e.emailVerified,phoneNumber:e.phoneNumber,isAnonymous:e.isAnonymous,providerData:[]}),e.metadata?Sr(t,"metadata",function(t){return new Ru(t.a,t.b)}(e.metadata)):Sr(t,"metadata",new Ru),D(e.providerData,function(e){Hu(t,e)}),t.h=e.h,Sr(t,"refreshToken",t.h.a))}function zu(t){return t.F().then(function(e){var n=t.isAnonymous;return function(t,e){return Ka(t.b,Ia,{idToken:e}).then(_(t.uc,t))}(t,e).then(function(){return n||Gu(t,"isAnonymous",!1),e})})}function Yu(t,e){e[$o]&&t.qa!=e[$o]&&(Su(t.h,e),t.dispatchEvent(new Au("tokenChanged")),Uu(t,e[$o]),Gu(t,"refreshToken",t.h.a))}function Xu(t,e){return zu(t).then(function(){if(F(qu(t),e))return Mu(t).then(function(){throw new Ur("provider-already-linked")})})}function $u(t,e,n){return Nr({user:t,credential:Mi(e),additionalUserInfo:e=si(e),operationType:n})}function Ju(t,e){return Yu(t,e),t.reload().then(function(){return t})}function Zu(t,n,r,i,o){if(!ur())return Tt(new Ur("operation-not-supported-in-this-environment"));if(t.j&&!o)return Tt(t.j);var a=ai(r.providerId),s=vr(t.uid+":::"),u=null;(!lr()||Xn())&&t.B&&r.isOAuthProvider&&(u=hs(t.B,t.G,t.s,n,r,null,s,e.SDK_VERSION||null));var c=Gn(u,a&&a.Aa,a&&a.za);return i=i().then(function(){if(ec(t),!o)return t.F().then(function(){})}).then(function(){return pu(t.a,c,n,r,s,!!u)}).then(function(){return new vt(function(e,r){t.ga(n,null,new Ur("cancelled-popup-request"),t.g||null),t.f=e,t.v=r,t.g=s,t.c=t.a.Da(t,n,c,s)})}).then(function(t){return c&&Kn(c),t?Nr(t):null}).m(function(t){throw c&&Kn(c),t}),nc(t,i,o)}function tc(t,e,n,r,i){if(!ur())return Tt(new Ur("operation-not-supported-in-this-environment"));if(t.j&&!i)return Tt(t.j);var o=null,a=vr(t.uid+":::");return r=r().then(function(){if(ec(t),!i)return t.F().then(function(){})}).then(function(){return t.$=a,Mu(t)}).then(function(e){return t.fa&&(e=(e=t.fa).b.set(ic,t.C(),e.a)),e}).then(function(){return t.a.Ba(e,n,a)}).m(function(e){if(o=e,t.fa)return oc(t.fa);throw o}).then(function(){if(o)throw o}),nc(t,r,i)}function ec(t){if(!t.a||!t.I){if(t.a&&!t.I)throw new Ur("internal-error");throw new Ur("auth-domain-config-required")}}function nc(t,e,n){var r=function(t,e,n){return t.j&&!n?(e.cancel(),Tt(t.j)):e.m(function(e){throw!e||"auth/user-disabled"!=e.code&&"auth/user-token-expired"!=e.code||(t.j||t.dispatchEvent(new Au("userInvalidated")),t.j=e),e})}(t,e,n);return t.D.push(r),r.ha(function(){U(t.D,r)}),r}function rc(t){if(!t.apiKey)return null;var e={apiKey:t.apiKey,authDomain:t.authDomain,appName:t.appName},n={};if(!(t.stsTokenManager&&t.stsTokenManager.accessToken&&t.stsTokenManager.expirationTime))return null;n[$o]=t.stsTokenManager.accessToken,n.refreshToken=t.stsTokenManager.refreshToken||null,n.expiresIn=(t.stsTokenManager.expirationTime-m())/1e3;var r=new ku(e,n,t);return t.providerData&&D(t.providerData,function(t){t&&Hu(r,Nr(t))}),t.redirectEventId&&(r.$=t.redirectEventId),r}yu.prototype.reset=function(){this.b=null,this.a&&(this.a.cancel(),this.a=null)},yu.prototype.h=function(t,e){if(t){this.reset(),this.g=!0;var n=t.b,r=t.c,i=t.a&&"auth/web-storage-unsupported"==t.a.code,o=t.a&&"auth/operation-not-supported-in-this-environment"==t.a.code;"unknown"!=n||i||o?t.a?(mu(this,!0,null,t.a),Et()):e.wa(n,r)?function(t,e,n){n=n.wa(e.b,e.c);var r=e.f,i=e.g,o=!!e.b.match(/Redirect$/);n(r,i).then(function(e){mu(t,o,e,null)}).m(function(e){mu(t,o,null,e)})}(this,t,e):Tt(new Ur("invalid-auth-event")):(mu(this,!1,null,null),Et())}else Tt(new Ur("invalid-auth-event"))},yu.prototype.da=function(){var t=this;return new vt(function(e,n){t.b?t.b().then(e,n):(t.f.push(e),t.c.push(n),function(t){var e=new Ur("timeout");t.a&&t.a.cancel(),t.a=xe(lu.get()).then(function(){t.b||mu(t,!0,null,e)})}(t))})},bu.prototype.h=function(t,e){if(t){var n=t.b,r=t.c;t.a?(e.ga(t.b,null,t.a,t.c),Et()):e.wa(n,r)?function(t,e){var n=t.c,r=t.b;e.wa(r,n)(t.f,t.g).then(function(t){e.ga(r,t,null,n)}).m(function(t){e.ga(r,null,t,n)})}(t,e):Tt(new Ur("invalid-auth-event"))}else Tt(new Ur("invalid-auth-event"))},wu.prototype.confirm=function(t){return t=Ui(this.verificationId,t),this.a(t)},Tu.prototype.start=function(){this.a=this.c,function t(e,n){e.stop();e.b=xe(function(t,e){return e?(t.a=t.c,t.g()):(e=t.a,t.a*=2,t.a>t.f&&(t.a=t.f),e)}(e,n)).then(function(){return t=r.document,e=null,mr()||!t?Et():new vt(function(n){e=function(){mr()&&(t.removeEventListener("visibilitychange",e,!1),n())},t.addEventListener("visibilitychange",e,!1)}).m(function(n){throw t.removeEventListener("visibilitychange",e,!1),n});var t,e}).then(function(){return e.h()}).then(function(){t(e,!0)}).m(function(n){e.j(n)&&t(e,!1)})}(this,!0)},Tu.prototype.stop=function(){this.b&&(this.b.cancel(),this.b=null)},Cu.prototype.C=function(){return{apiKey:this.f.b,refreshToken:this.a,accessToken:this.b,expirationTime:this.c}},Cu.prototype.getToken=function(t){return t=!!t,this.b&&!this.a?Tt(new Ur("user-token-expired")):t||!this.b||m()>this.c-3e4?this.a?Nu(this,{grant_type:"refresh_token",refresh_token:this.a}):Et(null):Et({accessToken:this.b,expirationTime:this.c,refreshToken:this.a})},Ru.prototype.C=function(){return{lastLoginAt:this.b,createdAt:this.a}},b(Au,se),b(ku,ke),ku.prototype.na=function(t){this.ia=t,na(this.b,t)},ku.prototype.ca=function(){return this.ia},ku.prototype.Ka=function(){return B(this.O)},ku.prototype.Ga=function(){this.l.b&&(this.l.stop(),this.l.start())},Sr(ku.prototype,"providerId","firebase"),(t=ku.prototype).reload=function(){var t=this;return nc(this,Vu(this).then(function(){return zu(t).then(function(){return Mu(t)}).then(ju)}))},t.ac=function(t){return this.F(t).then(function(t){return new function(t){var e=ni(t);if(!(e&&e.exp&&e.auth_time&&e.iat))throw new Ur("internal-error","An internal error occurred. The token obtained by Firebase appears to be malformed. Please retry the operation.");Ir(this,{token:t,expirationTime:br(1e3*e.exp),authTime:br(1e3*e.auth_time),issuedAtTime:br(1e3*e.iat),signInProvider:e.firebase&&e.firebase.sign_in_provider?e.firebase.sign_in_provider:null,claims:e})}(t)})},t.F=function(t){var e=this;return nc(this,Vu(this).then(function(){return e.h.getToken(t)}).then(function(t){if(!t)throw new Ur("internal-error");return t.accessToken!=e.qa&&(Uu(e,t.accessToken),e.dispatchEvent(new Au("tokenChanged"))),Gu(e,"refreshToken",t.refreshToken),t.accessToken}))},t.getToken=function(t){return Tr["firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead."]||(Tr["firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead."]=!0,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn("firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead.")),this.F(t)},t.uc=function(t){if(!(t=t.users)||!t.length)throw new Ur("internal-error");Bu(this,{uid:(t=t[0]).localId,displayName:t.displayName,photoURL:t.photoUrl,email:t.email,emailVerified:!!t.emailVerified,phoneNumber:t.phoneNumber,lastLoginAt:t.lastLoginAt,createdAt:t.createdAt});for(var e=function(t){return(t=t.providerUserInfo)&&t.length?L(t,function(t){return new function(t,e,n,r,i,o){Ir(this,{uid:t,displayName:r||null,photoURL:i||null,email:n||null,phoneNumber:o||null,providerId:e})}(t.rawId,t.providerId,t.email,t.displayName,t.photoUrl,t.phoneNumber)}):[]}(t),n=0;n<e.length;n++)Hu(this,e[n]);Gu(this,"isAnonymous",!(this.email&&t.passwordHash||this.providerData&&this.providerData.length))},t.bb=function(t){var e=this,n=null;return nc(this,t.f(this.b,this.uid).then(function(t){return Yu(e,t),n=$u(e,t,"reauthenticate"),e.j=null,e.reload()}).then(function(){return n}),!0)},t.vc=function(t){return this.bb(t).then(function(){})},t.$a=function(t){var e=this,n=null;return nc(this,Xu(this,t.providerId).then(function(){return e.F()}).then(function(n){return t.c(e.b,n)}).then(function(t){return n=$u(e,t,"link"),Ju(e,t)}).then(function(){return n}))},t.mc=function(t){return this.$a(t).then(function(t){return t.user})},t.nc=function(t,e){var n=this;return nc(this,Xu(this,"phone").then(function(){return Eu(Lu(n),t,e,_(n.$a,n))}))},t.wc=function(t,e){var n=this;return nc(this,Et().then(function(){return Eu(Lu(n),t,e,_(n.bb,n))}),!0)},t.mb=function(t){var e=this;return nc(this,this.F().then(function(n){return e.b.mb(n,t)}).then(function(t){return Yu(e,t),e.reload()}))},t.Nc=function(t){var e=this;return nc(this,this.F().then(function(n){return t.c(e.b,n)}).then(function(t){return Yu(e,t),e.reload()}))},t.nb=function(t){var e=this;return nc(this,this.F().then(function(n){return e.b.nb(n,t)}).then(function(t){return Yu(e,t),e.reload()}))},t.ob=function(t){if(void 0===t.displayName&&void 0===t.photoURL)return Vu(this);var e=this;return nc(this,this.F().then(function(n){return e.b.ob(n,{displayName:t.displayName,photoUrl:t.photoURL})}).then(function(t){return Yu(e,t),Gu(e,"displayName",t.displayName||null),Gu(e,"photoURL",t.photoUrl||null),D(e.providerData,function(t){"password"===t.providerId&&(Sr(t,"displayName",e.displayName),Sr(t,"photoURL",e.photoURL))}),Mu(e)}).then(ju))},t.Mc=function(t){var e=this;return nc(this,zu(this).then(function(n){return F(qu(e),t)?function(t,e,n){return Ka(t,Ta,{idToken:e,deleteProvider:n})}(e.b,n,[t]).then(function(t){var n={};return D(t.providerUserInfo||[],function(t){n[t.providerId]=!0}),D(qu(e),function(t){n[t]||Ku(e,t)}),n[Fi.PROVIDER_ID]||Sr(e,"phoneNumber",null),Mu(e)}):Mu(e).then(function(){throw new Ur("no-such-provider")})}))},t.delete=function(){var t=this;return nc(this,this.F().then(function(e){return Ka(t.b,Ea,{idToken:e})}).then(function(){t.dispatchEvent(new Au("userDeleted"))})).then(function(){for(var e=0;e<t.D.length;e++)t.D[e].cancel("app-deleted");Ou(t,null),Du(t,null),t.D=[],t.o=!0,Fu(t),Sr(t,"refreshToken",null),t.a&&t.a.unsubscribe(t)})},t.qb=function(t,e){return!!("linkViaPopup"==t&&(this.g||null)==e&&this.f||"reauthViaPopup"==t&&(this.g||null)==e&&this.f||"linkViaRedirect"==t&&(this.$||null)==e||"reauthViaRedirect"==t&&(this.$||null)==e)},t.ga=function(t,e,n,r){"linkViaPopup"!=t&&"reauthViaPopup"!=t||r!=(this.g||null)||(n&&this.v?this.v(n):e&&!n&&this.f&&this.f(e),this.c&&(this.c.cancel(),this.c=null),delete this.f,delete this.v)},t.wa=function(t,e){return"linkViaPopup"==t&&e==(this.g||null)?_(this.vb,this):"reauthViaPopup"==t&&e==(this.g||null)?_(this.wb,this):"linkViaRedirect"==t&&(this.$||null)==e?_(this.vb,this):"reauthViaRedirect"==t&&(this.$||null)==e?_(this.wb,this):null},t.oc=function(t){var e=this;return Zu(this,"linkViaPopup",t,function(){return Xu(e,t.providerId).then(function(){return Mu(e)})},!1)},t.xc=function(t){return Zu(this,"reauthViaPopup",t,function(){return Et()},!0)},t.pc=function(t){var e=this;return tc(this,"linkViaRedirect",t,function(){return Xu(e,t.providerId)},!1)},t.yc=function(t){return tc(this,"reauthViaRedirect",t,function(){return Et()},!0)},t.vb=function(t,e){var n=this;this.c&&(this.c.cancel(),this.c=null);var r=null;return nc(this,this.F().then(function(r){return va(n.b,{requestUri:t,sessionId:e,idToken:r})}).then(function(t){return r=$u(n,t,"link"),Ju(n,t)}).then(function(){return r}))},t.wb=function(t,e){var n=this;this.c&&(this.c.cancel(),this.c=null);var r=null;return nc(this,Et().then(function(){return _i(ya(n.b,{requestUri:t,sessionId:e}),n.uid)}).then(function(t){return r=$u(n,t,"reauthenticate"),Yu(n,t),n.j=null,n.reload()}).then(function(){return r}),!0)},t.fb=function(t){var e=this,n=null;return nc(this,this.F().then(function(e){return n=e,void 0===t||it(t)?{}:Xr(new jr(t))}).then(function(t){return e.b.fb(n,t)}).then(function(t){if(e.email!=t)return e.reload()}).then(function(){}))},t.toJSON=function(){return this.C()},t.C=function(){var t={uid:this.uid,displayName:this.displayName,photoURL:this.photoURL,email:this.email,emailVerified:this.emailVerified,phoneNumber:this.phoneNumber,isAnonymous:this.isAnonymous,providerData:[],apiKey:this.G,appName:this.s,authDomain:this.B,stsTokenManager:this.h.C(),redirectEventId:this.$||null};return this.metadata&&ct(t,this.metadata.C()),D(this.providerData,function(e){t.providerData.push(function(t){var e,n={};for(e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);return n}(e))}),t};var ic={name:"redirectUser",w:"session"};function oc(t){return Us(t.b,ic,t.a)}function ac(t){this.a=t,this.b=Ls(),this.c=null,this.f=function(t){var e=cc("local"),n=cc("session"),i=cc("none");return function(t,e,n){var i=Fs(e,n),o=xs(t,e.w);return t.get(e,n).then(function(a){var s=null;try{s=dr(r.localStorage.getItem(i))}catch(t){}if(s&&!a)return r.localStorage.removeItem(i),t.set(e,s,n);s&&a&&"localStorage"!=o.type&&r.localStorage.removeItem(i)})}(t.b,e,t.a).then(function(){return t.b.get(n,t.a)}).then(function(r){return r?n:t.b.get(i,t.a).then(function(n){return n?i:t.b.get(e,t.a).then(function(n){return n?e:t.b.get(uc,t.a).then(function(t){return t?cc(t):e})})})}).then(function(e){return t.c=e,sc(t,e.w)}).m(function(){t.c||(t.c=e)})}(this),this.b.addListener(cc("local"),this.a,_(this.g,this))}function sc(t,e){var n,r=[];for(n in Ps)Ps[n]!==e&&r.push(Us(t.b,cc(Ps[n]),t.a));return r.push(Us(t.b,uc,t.a)),function(t){return new vt(function(e,n){var r=t.length,i=[];if(r)for(var o=function(t,n){r--,i[t]=n,0==r&&e(i)},a=function(t){n(t)},s=0;s<t.length;s++)Ct(t[s],g(o,s),a);else e(i)})}(r)}ac.prototype.g=function(){var t=this,e=cc("local");fc(this,function(){return Et().then(function(){return t.c&&"local"!=t.c.w?t.b.get(e,t.a):null}).then(function(n){if(n)return sc(t,"local").then(function(){t.c=e})})})};var uc={name:"persistence",w:"session"};function cc(t){return{name:"authUser",w:t}}function hc(t,e){return fc(t,function(){return t.b.set(t.c,e.C(),t.a)})}function lc(t){return fc(t,function(){return Us(t.b,t.c,t.a)})}function pc(t,e){return fc(t,function(){return t.b.get(t.c,t.a).then(function(t){return t&&e&&(t.authDomain=e),rc(t||{})})})}function fc(t,e){return t.f=t.f.then(e,e),t.f}function dc(t){if(this.l=!1,Sr(this,"app",t),!wc(this).options||!wc(this).options.apiKey)throw new Ur("invalid-api-key");t=e.SDK_VERSION?ir(e.SDK_VERSION):null,this.b=new Yo(wc(this).options&&wc(this).options.apiKey,Xa(za),t),this.N=[],this.o=[],this.I=[],this.Ob=e.INTERNAL.createSubscribe(_(this.ic,this)),this.O=void 0,this.Pb=e.INTERNAL.createSubscribe(_(this.jc,this)),mc(this,null),this.h=new ac(wc(this).options.apiKey+":"+wc(this).name),this.G=new function(t){this.a=t,this.b=Ls()}(wc(this).options.apiKey+":"+wc(this).name),this.V=Sc(this,function(t){var e=wc(t).options.authDomain,n=function(t){var e=function(t,e){return t.b.get(ic,t.a).then(function(t){return t&&e&&(t.authDomain=e),rc(t||{})})}(t.G,wc(t).options.authDomain).then(function(e){return(t.B=e)&&(e.fa=t.G),oc(t.G)});return Sc(t,e)}(t).then(function(){return pc(t.h,e)}).then(function(e){return e?(e.fa=t.G,t.B&&(t.B.$||null)==(e.$||null)?e:e.reload().then(function(){return hc(t.h,e).then(function(){return e})}).m(function(n){return"auth/network-request-failed"==n.code?e:lc(t.h)})):null}).then(function(e){mc(t,e||null)});return Sc(t,n)}(this)),this.j=Sc(this,function(t){return t.V.then(function(){return t.da()}).m(function(){}).then(function(){if(!t.l)return t.ia()}).m(function(){}).then(function(){if(!t.l){t.X=!0;var e=t.h;e.b.addListener(cc("local"),e.a,t.ia)}})}(this)),this.X=!1,this.ia=_(this.Ic,this),this.Ga=_(this.ka,this),this.qa=_(this.Yb,this),this.ra=_(this.gc,this),this.sa=_(this.hc,this),function(t){var e=wc(t).options.authDomain,n=wc(t).options.apiKey;e&&ur()&&(t.Nb=t.V.then(function(){if(!t.l){if(t.a=vu(e,n,wc(t).name),t.a.subscribe(t),Ec(t)&&Wu(Ec(t)),t.B){Wu(t.B);var r=t.B;r.na(t.ca()),Ou(r,t),Pu(r=t.B,t.D),Du(r,t),t.B=null}return t.a}}))}(this),this.INTERNAL={},this.INTERNAL.delete=_(this.delete,this),this.INTERNAL.logFramework=_(this.qc,this),this.s=0,ke.call(this),function(t){Object.defineProperty(t,"lc",{get:function(){return this.ca()},set:function(t){this.na(t)},enumerable:!1}),t.W=null}(this),this.D=[]}function vc(t){se.call(this,"languageCodeChanged"),this.g=t}function yc(t){se.call(this,"frameworkChanged"),this.c=t}function _c(t){return t.Nb||Tt(new Ur("auth-domain-config-required"))}function gc(t,e){var n={};return n.apiKey=wc(t).options.apiKey,n.authDomain=wc(t).options.authDomain,n.appName=wc(t).name,t.V.then(function(){return function(t,e,n,r){var i=new ku(t,e);return n&&(i.fa=n),r&&Pu(i,r),i.reload().then(function(){return i})}(n,e,t.G,t.Ka())}).then(function(e){return Ec(t)&&e.uid==Ec(t).uid?(Qu(Ec(t),e),t.ka(e)):(mc(t,e),Wu(e),t.ka(e))}).then(function(){Cc(t)})}function mc(t,e){Ec(t)&&(function(t,e){M(t.N,function(t){return t==e})}(Ec(t),t.Ga),we(Ec(t),"tokenChanged",t.qa),we(Ec(t),"userDeleted",t.ra),we(Ec(t),"userInvalidated",t.sa),Fu(Ec(t))),e&&(e.N.push(t.Ga),ge(e,"tokenChanged",t.qa),ge(e,"userDeleted",t.ra),ge(e,"userInvalidated",t.sa),0<t.s&&xu(e)),Sr(t,"currentUser",e),e&&(e.na(t.ca()),Ou(e,t),Pu(e,t.D),Du(e,t))}function bc(t,e){var n=null,r=null;return Sc(t,e.then(function(e){return n=Mi(e),r=si(e),gc(t,e)}).then(function(){return Nr({user:Ec(t),credential:n,additionalUserInfo:r,operationType:"signIn"})}))}function wc(t){return t.app}function Ec(t){return t.currentUser}function Tc(t){return Ec(t)&&Ec(t)._lat||null}function Cc(t){if(t.X){for(var e=0;e<t.o.length;e++)t.o[e]&&t.o[e](Tc(t));if(t.O!==t.getUid()&&t.I.length)for(t.O=t.getUid(),e=0;e<t.I.length;e++)t.I[e]&&t.I[e](Tc(t))}}function Sc(t,e){return t.N.push(e),e.ha(function(){U(t.N,e)}),e}function Ic(t,e,n,i,o,a){if(Sr(this,"type","recaptcha"),this.b=this.c=null,this.o=!1,this.l=e,this.a=n||{theme:"light",type:"image"},this.g=[],this.a[Ac])throw new Ur("argument-error","sitekey should not be provided for reCAPTCHA as one is automatically provisioned for the current project.");if(this.h="invisible"===this.a[kc],!r.document)throw new Ur("operation-not-supported-in-this-environment","RecaptchaVerifier is only supported in a browser HTTP/HTTPS environment with DOM support.");if(!Pn(e)||!this.h&&Pn(e).hasChildNodes())throw new Ur("argument-error","reCAPTCHA container is either not found or already contains inner elements!");this.u=new Yo(t,a||null,o||null),this.s=i||function(){return null};var s=this;this.j=[];var u=this.a[Nc];this.a[Nc]=function(t){if(Oc(s,t),"function"==typeof u)u(t);else if("string"==typeof u){var e=ar(u,r);"function"==typeof e&&e(t)}};var c=this.a[Rc];this.a[Rc]=function(){if(Oc(s,null),"function"==typeof c)c();else if("string"==typeof c){var t=ar(c,r);"function"==typeof t&&t()}}}ac.prototype.ib=function(t){var e=null,n=this;return function(t){var e=new Ur("invalid-persistence-type"),n=new Ur("unsupported-persistence-type");t:{for(r in Ps)if(Ps[r]==t){var r=!0;break t}r=!1}if(!r||"string"!=typeof t)throw e;switch(Jn()){case"ReactNative":if("session"===t)throw n;break;case"Node":if("none"!==t)throw n;break;default:if(!sr()&&"none"!==t)throw n}}(t),fc(this,function(){return t!=n.c.w?n.b.get(n.c,n.a).then(function(r){return e=r,sc(n,t)}).then(function(){if(n.c=cc(t),e)return n.b.set(n.c,e,n.a)}):Et()})},b(dc,ke),b(vc,se),b(yc,se),(t=dc.prototype).ib=function(t){return Sc(this,t=this.h.ib(t))},t.na=function(t){this.W===t||this.l||(this.W=t,na(this.b,this.W),this.dispatchEvent(new vc(this.ca())))},t.ca=function(){return this.W},t.Oc=function(){var t=r.navigator;this.na(t&&(t.languages&&t.languages[0]||t.language||t.userLanguage)||null)},t.qc=function(t){this.D.push(t),ra(this.b,e.SDK_VERSION?ir(e.SDK_VERSION,this.D):null),this.dispatchEvent(new yc(this.D))},t.Ka=function(){return B(this.D)},t.toJSON=function(){return{apiKey:wc(this).options.apiKey,authDomain:wc(this).options.authDomain,appName:wc(this).name,currentUser:Ec(this)&&Ec(this).C()}},t.qb=function(t,e){switch(t){case"unknown":case"signInViaRedirect":return!0;case"signInViaPopup":return this.g==e&&!!this.f;default:return!1}},t.ga=function(t,e,n,r){"signInViaPopup"==t&&this.g==r&&(n&&this.v?this.v(n):e&&!n&&this.f&&this.f(e),this.c&&(this.c.cancel(),this.c=null),delete this.f,delete this.v)},t.wa=function(t,e){return"signInViaRedirect"==t||"signInViaPopup"==t&&this.g==e&&this.f?_(this.Xb,this):null},t.Xb=function(t,e){var n=this;t={requestUri:t,sessionId:e},this.c&&(this.c.cancel(),this.c=null);var r=null,i=null,o=da(n.b,t).then(function(t){return r=Mi(t),i=si(t),t});return Sc(this,t=n.V.then(function(){return o}).then(function(t){return gc(n,t)}).then(function(){return Nr({user:Ec(n),credential:r,additionalUserInfo:i,operationType:"signIn"})}))},t.Gc=function(t){if(!ur())return Tt(new Ur("operation-not-supported-in-this-environment"));var n=this,r=ai(t.providerId),i=vr(),o=null;(!lr()||Xn())&&wc(this).options.authDomain&&t.isOAuthProvider&&(o=hs(wc(this).options.authDomain,wc(this).options.apiKey,wc(this).name,"signInViaPopup",t,null,i,e.SDK_VERSION||null));var a=Gn(o,r&&r.Aa,r&&r.za);return Sc(this,r=_c(this).then(function(e){return pu(e,a,"signInViaPopup",t,i,!!o)}).then(function(){return new vt(function(t,e){n.ga("signInViaPopup",null,new Ur("cancelled-popup-request"),n.g),n.f=t,n.v=e,n.g=i,n.c=n.a.Da(n,"signInViaPopup",a,i)})}).then(function(t){return a&&Kn(a),t?Nr(t):null}).m(function(t){throw a&&Kn(a),t}))},t.Hc=function(t){if(!ur())return Tt(new Ur("operation-not-supported-in-this-environment"));var e=this;return Sc(this,_c(this).then(function(){return fc(t=e.h,function(){return t.b.set(uc,t.c.w,t.a)});var t}).then(function(){return e.a.Ba("signInViaRedirect",t)}))},t.da=function(){if(!ur())return Tt(new Ur("operation-not-supported-in-this-environment"));var t=this;return Sc(this,_c(this).then(function(){return t.a.da()}).then(function(t){return t?Nr(t):null}))},t.kb=function(){var t=this;return Sc(this,this.j.then(function(){return Ec(t)?(mc(t,null),lc(t.h).then(function(){Cc(t)})):Et()}))},t.Ic=function(){var t=this;return pc(this.h,wc(this).options.authDomain).then(function(e){if(!t.l){var n;if(n=Ec(t)&&e){n=Ec(t).uid;var r=e.uid;n=void 0!==n&&null!==n&&""!==n&&void 0!==r&&null!==r&&""!==r&&n==r}if(n)return Qu(Ec(t),e),Ec(t).F();(Ec(t)||e)&&(mc(t,e),e&&(Wu(e),e.fa=t.G),t.a&&t.a.subscribe(t),Cc(t))}})},t.ka=function(t){return hc(this.h,t)},t.Yb=function(){Cc(this),this.ka(Ec(this))},t.gc=function(){this.kb()},t.hc=function(){this.kb()},t.ic=function(t){var e=this;this.addAuthTokenListener(function(){t.next(Ec(e))})},t.jc=function(t){var e=this;!function(t,e){t.I.push(e),Sc(t,t.j.then(function(){!t.l&&F(t.I,e)&&t.O!==t.getUid()&&(t.O=t.getUid(),e(Tc(t)))}))}(this,function(){t.next(Ec(e))})},t.sc=function(t,n,r){var i=this;return this.X&&e.Promise.resolve().then(function(){l(t)?t(Ec(i)):l(t.next)&&t.next(Ec(i))}),this.Ob(t,n,r)},t.rc=function(t,n,r){var i=this;return this.X&&e.Promise.resolve().then(function(){i.O=i.getUid(),l(t)?t(Ec(i)):l(t.next)&&t.next(Ec(i))}),this.Pb(t,n,r)},t.$b=function(t){var e=this;return Sc(this,this.j.then(function(){return Ec(e)?Ec(e).F(t).then(function(t){return{accessToken:t}}):null}))},t.Cc=function(t){return this.Hb(t).then(function(t){return t.user})},t.Hb=function(t){var e=this;return this.j.then(function(){return bc(e,Ka(e.b,Ba,{token:t}))}).then(function(t){var n=t.user;return Gu(n,"isAnonymous",!1),e.ka(n),t})},t.Ib=function(t,e){var n=this;return this.j.then(function(){return bc(n,Ka(n.b,ja,{email:t,password:e}))})},t.Dc=function(t,e){return this.Ib(t,e).then(function(t){return t.user})},t.Sb=function(t,e){return this.sb(t,e).then(function(t){return t.user})},t.sb=function(t,e){var n=this;return this.j.then(function(){return bc(n,Ka(n.b,ba,{email:t,password:e}))})},t.Bc=function(t){return this.Oa(t).then(function(t){return t.user})},t.Oa=function(t){var e=this;return this.j.then(function(){return bc(e,t.xa(e.b))})},t.jb=function(){return this.Jb().then(function(t){return t.user})},t.Jb=function(){var t=this;return this.j.then(function(){var e=Ec(t);return e&&e.isAnonymous?Nr({user:e,credential:null,additionalUserInfo:Nr({providerId:null,isNewUser:!1}),operationType:"signIn"}):bc(t,t.b.jb()).then(function(e){var n=e.user;return Gu(n,"isAnonymous",!0),t.ka(n),e})})},t.getUid=function(){return Ec(this)&&Ec(this).uid||null},t.Qb=function(t){this.addAuthTokenListener(t),this.s++,0<this.s&&Ec(this)&&xu(Ec(this))},t.zc=function(t){var e=this;D(this.o,function(n){n==t&&e.s--}),0>this.s&&(this.s=0),0==this.s&&Ec(this)&&Fu(Ec(this)),this.removeAuthTokenListener(t)},t.addAuthTokenListener=function(t){var e=this;this.o.push(t),Sc(this,this.j.then(function(){e.l||F(e.o,t)&&t(Tc(e))}))},t.removeAuthTokenListener=function(t){M(this.o,function(e){return e==t})},t.delete=function(){this.l=!0;for(var t=0;t<this.N.length;t++)this.N[t].cancel("app-deleted");return this.N=[],this.h&&(t=this.h).b.removeListener(cc("local"),t.a,this.ia),this.a&&this.a.unsubscribe(this),e.Promise.resolve()},t.Vb=function(t){return Sc(this,function(t,e){return Ka(t,wa,{identifier:e,continueUri:cr()?Vn():"http://localhost"}).then(function(t){return t.allProviders||[]})}(this.b,t))},t.Wb=function(t){return Sc(this,function(t,e){return Ka(t,wa,{identifier:e,continueUri:cr()?Vn():"http://localhost"}).then(function(t){return t.signinMethods||[]})}(this.b,t))},t.kc=function(t){return!!Di(t)},t.hb=function(t,e){var n=this;return Sc(this,Et().then(function(){var t=new jr(e);if(!t.c)throw new Ur("argument-error",qr+" must be true when sending sign in link to email");return Xr(t)}).then(function(e){return n.b.hb(t,e)}).then(function(){}))},t.Pc=function(t){return this.Ia(t).then(function(t){return t.data.email})},t.Wa=function(t,e){return Sc(this,this.b.Wa(t,e).then(function(){}))},t.Ia=function(t){return Sc(this,this.b.Ia(t).then(function(t){return new function(t){var e={},n=t[kr],r=t[Or];if(!(t=t[Pr])||t!=Ar&&!n)throw Error("Invalid provider user info!");e[Lr]=r||null,e[Dr]=n||null,Sr(this,Fr,t),Sr(this,xr,Rr(e))}(t)}))},t.Ua=function(t){return Sc(this,this.b.Ua(t).then(function(){}))},t.gb=function(t,e){var n=this;return Sc(this,Et().then(function(){return void 0===e||it(e)?{}:Xr(new jr(e))}).then(function(e){return n.b.gb(t,e)}).then(function(){}))},t.Fc=function(t,e){return Sc(this,Eu(this,t,e,_(this.Oa,this)))},t.Ec=function(t,e){var n=this;return Sc(this,Et().then(function(){var r=Pi(t,e||Vn());return n.Oa(r)}))};var Nc="callback",Rc="expired-callback",Ac="sitekey",kc="size";function Oc(t,e){for(var n=0;n<t.j.length;n++)try{t.j[n](e)}catch(t){}}function Pc(t,e){return t.g.push(e),e.ha(function(){U(t.g,e)}),e}function Dc(t){if(t.o)throw new Ur("internal-error","RecaptchaVerifier instance has been destroyed.")}(t=Ic.prototype).ya=function(){var t=this;return this.c?this.c:this.c=Pc(this,Et().then(function(){if(cr()&&!$n())return zn();throw new Ur("operation-not-supported-in-this-environment","RecaptchaVerifier is only supported in a browser HTTP/HTTPS environment.")}).then(function(){return function(t,e){return new vt(function(n,i){var o=setTimeout(function(){i(new Ur("network-request-failed"))},xc.get());if(!r.grecaptcha||e!==t.c&&!t.b){r[t.a]=function(){if(r.grecaptcha){t.c=e;var a=r.grecaptcha.render;r.grecaptcha.render=function(e,n){return e=a(e,n),t.b++,e},clearTimeout(o),n()}else clearTimeout(o),i(new Ur("internal-error"));delete r[t.a]};var a=mn(Lc,{onload:t.a,hl:e||""});Et(Vo(a)).m(function(){clearTimeout(o),i(new Ur("internal-error","Unable to load external reCAPTCHA dependencies!"))})}else clearTimeout(o),n()})}(Uc(),t.s())}).then(function(){return Ka(t.u,Oa,{})}).then(function(e){t.a[Ac]=e.recaptchaSiteKey}).m(function(e){throw t.c=null,e}))},t.render=function(){Dc(this);var t=this;return Pc(this,this.ya().then(function(){if(null===t.b){var e=t.l;if(!t.h){var n=Pn(e);e=xn("DIV"),n.appendChild(e)}t.b=grecaptcha.render(e,t.a)}return t.b}))},t.verify=function(){Dc(this);var t=this;return Pc(this,this.render().then(function(e){return new vt(function(n){var r=grecaptcha.getResponse(e);if(r)n(r);else{var i=function(e){e&&(function(t,e){M(t.j,function(t){return t==e})}(t,i),n(e))};t.j.push(i),t.h&&grecaptcha.execute(t.b)}})}))},t.reset=function(){Dc(this),null!==this.b&&grecaptcha.reset(this.b)},t.clear=function(){Dc(this),this.o=!0,Uc().b--;for(var t=0;t<this.g.length;t++)this.g[t].cancel("RecaptchaVerifier instance has been destroyed.");if(!this.h){t=Pn(this.l);for(var e;e=t.firstChild;)t.removeChild(e)}};var Lc=yn("https://www.google.com/recaptcha/api.js?onload=%{onload}&render=explicit&hl=%{hl}");var xc=new gr(3e4,6e4);var Fc=null;function Uc(){return Fc||(Fc=new function(){this.b=r.grecaptcha?1/0:0,this.c=null,this.a="__rcb"+Math.floor(1e6*Math.random()).toString()}),Fc}function Mc(t,n,r){try{this.f=r||e.app()}catch(t){throw new Ur("argument-error","No firebase.app.App instance is currently initialized.")}if(!this.f.options||!this.f.options.apiKey)throw new Ur("invalid-api-key");r=this.f.options.apiKey;var i=this,o=null;try{o=this.f.auth().Ka()}catch(t){}o=e.SDK_VERSION?ir(e.SDK_VERSION,o):null,Ic.call(this,r,t,n,function(){try{var t=i.f.auth().ca()}catch(e){t=null}return t},o,Xa(za))}function Wc(t,e,n,r){t:{n=Array.prototype.slice.call(n);for(var i=0,o=!1,a=0;a<e.length;a++)if(e[a].optional)o=!0;else{if(o)throw new Ur("internal-error","Argument validator encountered a required argument after an optional argument.");i++}if(o=e.length,n.length<i||o<n.length)r="Expected "+(i==o?1==i?"1 argument":i+" arguments":i+"-"+o+" arguments")+" but got "+n.length+".";else{for(i=0;i<n.length;i++)if(o=e[i].optional&&void 0===n[i],!e[i].M(n[i])&&!o){if(e=e[i],0>i||i>=Bc.length)throw new Ur("internal-error","Argument validator received an unsupported number of arguments.");n=Bc[i],r=(r?"":n+" argument ")+(e.name?'"'+e.name+'" ':"")+"must be "+e.K+".";break t}r=null}}if(r)throw new Ur("argument-error",t+" failed: "+r)}b(Mc,Ic);var Bc="First Second Third Fourth Fifth Sixth Seventh Eighth Ninth".split(" ");function jc(t,e){return{name:t||"",K:"a valid string",optional:!!e,M:i}}function Vc(){return{name:"opt_forceRefresh",K:"a boolean",optional:!0,M:o}}function qc(t,e){return{name:t||"",K:"a valid object",optional:!!e,M:p}}function Hc(t,e){return{name:t||"",K:"a function",optional:!!e,M:l}}function Kc(t,e){return{name:t||"",K:"null",optional:!!e,M:u}}function Gc(t){return{name:t?t+"Credential":"credential",K:t?"a valid "+t+" credential":"a valid credential",optional:!1,M:function(e){if(!e)return!1;var n=!t||e.providerId===t;return!(!e.xa||!n)}}}function Qc(){return{name:"applicationVerifier",K:"an implementation of firebase.auth.ApplicationVerifier",optional:!1,M:function(t){return!!(t&&i(t.type)&&l(t.verify))}}}function zc(t,e,n,r){return{name:n||"",K:t.K+" or "+e.K,optional:!!r,M:function(n){return t.M(n)||e.M(n)}}}function Yc(t,e){for(var n in e){var r=e[n].name;t[r]=$c(r,t[n],e[n].i)}}function Xc(t,e,n,r){t[e]=$c(e,n,r)}function $c(t,e,n){function r(){var t=Array.prototype.slice.call(arguments);return Wc(o,n,t),e.apply(this,t)}if(!n)return e;var i,o=function(t){return(t=t.split("."))[t.length-1]}(t);for(i in e)r[i]=e[i];for(i in e.prototype)r.prototype[i]=e.prototype[i];return r}Yc(dc.prototype,{Ua:{name:"applyActionCode",i:[jc("code")]},Ia:{name:"checkActionCode",i:[jc("code")]},Wa:{name:"confirmPasswordReset",i:[jc("code"),jc("newPassword")]},Sb:{name:"createUserWithEmailAndPassword",i:[jc("email"),jc("password")]},sb:{name:"createUserAndRetrieveDataWithEmailAndPassword",i:[jc("email"),jc("password")]},Vb:{name:"fetchProvidersForEmail",i:[jc("email")]},Wb:{name:"fetchSignInMethodsForEmail",i:[jc("email")]},da:{name:"getRedirectResult",i:[]},kc:{name:"isSignInWithEmailLink",i:[jc("emailLink")]},rc:{name:"onAuthStateChanged",i:[zc(qc(),Hc(),"nextOrObserver"),Hc("opt_error",!0),Hc("opt_completed",!0)]},sc:{name:"onIdTokenChanged",i:[zc(qc(),Hc(),"nextOrObserver"),Hc("opt_error",!0),Hc("opt_completed",!0)]},gb:{name:"sendPasswordResetEmail",i:[jc("email"),zc(qc("opt_actionCodeSettings",!0),Kc(null,!0),"opt_actionCodeSettings",!0)]},hb:{name:"sendSignInLinkToEmail",i:[jc("email"),qc("actionCodeSettings")]},ib:{name:"setPersistence",i:[jc("persistence")]},Oa:{name:"signInAndRetrieveDataWithCredential",i:[Gc()]},jb:{name:"signInAnonymously",i:[]},Jb:{name:"signInAnonymouslyAndRetrieveData",i:[]},Bc:{name:"signInWithCredential",i:[Gc()]},Cc:{name:"signInWithCustomToken",i:[jc("token")]},Hb:{name:"signInAndRetrieveDataWithCustomToken",i:[jc("token")]},Dc:{name:"signInWithEmailAndPassword",i:[jc("email"),jc("password")]},Ec:{name:"signInWithEmailLink",i:[jc("email"),jc("emailLink",!0)]},Ib:{name:"signInAndRetrieveDataWithEmailAndPassword",i:[jc("email"),jc("password")]},Fc:{name:"signInWithPhoneNumber",i:[jc("phoneNumber"),Qc()]},Gc:{name:"signInWithPopup",i:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},Hc:{name:"signInWithRedirect",i:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},kb:{name:"signOut",i:[]},toJSON:{name:"toJSON",i:[jc(null,!0)]},Oc:{name:"useDeviceLanguage",i:[]},Pc:{name:"verifyPasswordResetCode",i:[jc("code")]}}),function(t,e){for(var n in e){var r=e[n].name;if(r!==n){var i=e[n].Rb;Object.defineProperty(t,r,{get:function(){return this[n]},set:function(t){Wc(r,[i],[t],!0),this[n]=t},enumerable:!0})}}}(dc.prototype,{lc:{name:"languageCode",Rb:zc(jc(),Kc(),"languageCode")}}),dc.Persistence=Ps,dc.Persistence.LOCAL="local",dc.Persistence.SESSION="session",dc.Persistence.NONE="none",Yc(ku.prototype,{delete:{name:"delete",i:[]},ac:{name:"getIdTokenResult",i:[Vc()]},F:{name:"getIdToken",i:[Vc()]},getToken:{name:"getToken",i:[Vc()]},$a:{name:"linkAndRetrieveDataWithCredential",i:[Gc()]},mc:{name:"linkWithCredential",i:[Gc()]},nc:{name:"linkWithPhoneNumber",i:[jc("phoneNumber"),Qc()]},oc:{name:"linkWithPopup",i:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},pc:{name:"linkWithRedirect",i:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},bb:{name:"reauthenticateAndRetrieveDataWithCredential",i:[Gc()]},vc:{name:"reauthenticateWithCredential",i:[Gc()]},wc:{name:"reauthenticateWithPhoneNumber",i:[jc("phoneNumber"),Qc()]},xc:{name:"reauthenticateWithPopup",i:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},yc:{name:"reauthenticateWithRedirect",i:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},reload:{name:"reload",i:[]},fb:{name:"sendEmailVerification",i:[zc(qc("opt_actionCodeSettings",!0),Kc(null,!0),"opt_actionCodeSettings",!0)]},toJSON:{name:"toJSON",i:[jc(null,!0)]},Mc:{name:"unlink",i:[jc("provider")]},mb:{name:"updateEmail",i:[jc("email")]},nb:{name:"updatePassword",i:[jc("password")]},Nc:{name:"updatePhoneNumber",i:[Gc("phone")]},ob:{name:"updateProfile",i:[qc("profile")]}}),Yc(vt.prototype,{ha:{name:"finally"},m:{name:"catch"},then:{name:"then"}}),Yc(wu.prototype,{confirm:{name:"confirm",i:[jc("verificationCode")]}}),Xc(Oi,"credential",function(t,e){return new ki(t,e)},[jc("email"),jc("password")]),Yc(Ei.prototype,{ta:{name:"addScope",i:[jc("scope")]},Ca:{name:"setCustomParameters",i:[qc("customOAuthParameters")]}}),Xc(Ei,"credential",Ti,[zc(jc(),qc(),"token")]),Xc(Oi,"credentialWithLink",Pi,[jc("email"),jc("emailLink")]),Yc(Ci.prototype,{ta:{name:"addScope",i:[jc("scope")]},Ca:{name:"setCustomParameters",i:[qc("customOAuthParameters")]}}),Xc(Ci,"credential",Si,[zc(jc(),qc(),"token")]),Yc(Ii.prototype,{ta:{name:"addScope",i:[jc("scope")]},Ca:{name:"setCustomParameters",i:[qc("customOAuthParameters")]}}),Xc(Ii,"credential",Ni,[zc(jc(),zc(qc(),Kc()),"idToken"),zc(jc(),Kc(),"accessToken",!0)]),Yc(Ri.prototype,{Ca:{name:"setCustomParameters",i:[qc("customOAuthParameters")]}}),Xc(Ri,"credential",Ai,[zc(jc(),qc(),"token"),jc("secret",!0)]),Yc(wi.prototype,{ta:{name:"addScope",i:[jc("scope")]},credential:{name:"credential",i:[zc(jc(),Kc(),"idToken",!0),zc(jc(),Kc(),"accessToken",!0)]},Ca:{name:"setCustomParameters",i:[qc("customOAuthParameters")]}}),Xc(Fi,"credential",Ui,[jc("verificationId"),jc("verificationCode")]),Yc(Fi.prototype,{Sa:{name:"verifyPhoneNumber",i:[jc("phoneNumber"),Qc()]}}),Yc(Ur.prototype,{toJSON:{name:"toJSON",i:[jc(null,!0)]}}),Yc(Ki.prototype,{toJSON:{name:"toJSON",i:[jc(null,!0)]}}),Yc(Hi.prototype,{toJSON:{name:"toJSON",i:[jc(null,!0)]}}),Yc(Mc.prototype,{clear:{name:"clear",i:[]},render:{name:"render",i:[]},verify:{name:"verify",i:[]}}),function(){if(void 0===e||!e.INTERNAL||!e.INTERNAL.registerService)throw Error("Cannot find the firebase namespace; be sure to include firebase-app.js before this library.");var t={Auth:dc,Error:Ur};Xc(t,"EmailAuthProvider",Oi,[]),Xc(t,"FacebookAuthProvider",Ei,[]),Xc(t,"GithubAuthProvider",Ci,[]),Xc(t,"GoogleAuthProvider",Ii,[]),Xc(t,"TwitterAuthProvider",Ri,[]),Xc(t,"OAuthProvider",wi,[jc("providerId")]),Xc(t,"PhoneAuthProvider",Fi,[{name:"auth",K:"an instance of Firebase Auth",optional:!0,M:function(t){return!!(t&&t instanceof dc)}}]),Xc(t,"RecaptchaVerifier",Mc,[zc(jc(),{name:"",K:"an HTML element",optional:!1,M:function(t){return!!(t&&t instanceof Element)}},"recaptchaContainer"),qc("recaptchaParameters",!0),{name:"app",K:"an instance of Firebase App",optional:!0,M:function(t){return!!(t&&t instanceof e.app.App)}}]),e.INTERNAL.registerService("auth",function(t,e){return e({INTERNAL:{getUid:_((t=new dc(t)).getUid,t),getToken:_(t.$b,t),addAuthTokenListener:_(t.Qb,t),removeAuthTokenListener:_(t.zc,t)}}),t},t,function(t,e){if("create"===t)try{e.auth()}catch(t){}}),e.INTERNAL.extendNamespace({User:ku})}()}).call(void 0!==ie?ie:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"}(Jt||(Jt={}));var oe=Jt.INFO,ae=function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(!(e<t.logLevel)){var i=(new Date).toISOString();switch(e){case Jt.DEBUG:case Jt.VERBOSE:console.log.apply(console,["["+i+"] "+t.name+":"].concat(n));break;case Jt.INFO:console.info.apply(console,["["+i+"] "+t.name+":"].concat(n));break;case Jt.WARN:console.warn.apply(console,["["+i+"] "+t.name+":"].concat(n));break;case Jt.ERROR:console.error.apply(console,["["+i+"] "+t.name+":"].concat(n));break;default:throw new Error("Attempted to log a message with an invalid logType (value: "+e+")")}}},se=function(){function t(t){this.name=t,this._logLevel=oe,this._logHandler=ae}return Object.defineProperty(t.prototype,"logLevel",{get:function(){return this._logLevel},set:function(t){if(!(t in Jt))throw new TypeError("Invalid value assigned to `logLevel`");this._logLevel=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"logHandler",{get:function(){return this._logHandler},set:function(t){if("function"!=typeof t)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=t},enumerable:!0,configurable:!0}),t.prototype.debug=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,Jt.DEBUG].concat(t))},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,Jt.VERBOSE].concat(t))},t.prototype.info=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,Jt.INFO].concat(t))},t.prototype.warn=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,Jt.WARN].concat(t))},t.prototype.error=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,Jt.ERROR].concat(t))},t}(),ue=function(){function t(t){this.domStorage_=t,this.prefix_="firebase:"}return t.prototype.set=function(t,e){null==e?this.domStorage_.removeItem(this.prefixedName_(t)):this.domStorage_.setItem(this.prefixedName_(t),Nt(e))},t.prototype.get=function(t){var e=this.domStorage_.getItem(this.prefixedName_(t));return null==e?null:It(e)},t.prototype.remove=function(t){this.domStorage_.removeItem(this.prefixedName_(t))},t.prototype.prefixedName_=function(t){return this.prefix_+t},t.prototype.toString=function(){return this.domStorage_.toString()},t}(),ce=function(){function t(){this.cache_={},this.isInMemoryStorage=!0}return t.prototype.set=function(t,e){null==e?delete this.cache_[t]:this.cache_[t]=e},t.prototype.get=function(t){return At(this.cache_,t)?this.cache_[t]:null},t.prototype.remove=function(t){delete this.cache_[t]},t}(),he=function(t){try{if("undefined"!=typeof window&&void 0!==window[t]){var e=window[t];return e.setItem("firebase:sentinel","cache"),e.removeItem("firebase:sentinel"),new ue(e)}}catch(t){}return new ce},le=he("localStorage"),pe=he("sessionStorage"),fe=new se("@firebase/database"),de=function(){var t=1;return function(){return t++}}(),ve=function(t){var e=function(t){for(var e=[],n=0,r=0;r<t.length;r++){var i=t.charCodeAt(r);if(i>=55296&&i<=56319){var o=i-55296;lt(++r<t.length,"Surrogate pair missing trail surrogate."),i=65536+(o<<10)+(t.charCodeAt(r)-56320)}i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=63&i|128):i<65536?(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=63&i|128):(e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=63&i|128)}return e}(t),n=new Mt;n.update(e);var r=n.digest();return dt.encodeByteArray(r)},ye=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];for(var n="",r=0;r<t.length;r++)Array.isArray(t[r])||t[r]&&"object"==typeof t[r]&&"number"==typeof t[r].length?n+=ye.apply(null,t[r]):"object"==typeof t[r]?n+=Nt(t[r]):n+=t[r],n+=" ";return n},_e=null,ge=!0,me=function(t,e){lt(!e||!0===t||!1===t,"Can't turn on custom loggers persistently."),!0===t?(fe.logLevel=Jt.VERBOSE,_e=fe.log.bind(fe),e&&pe.set("logging_enabled",!0)):"function"==typeof t?_e=t:(_e=null,pe.remove("logging_enabled"))},be=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(!0===ge&&(ge=!1,null===_e&&!0===pe.get("logging_enabled")&&me(!0)),_e){var n=ye.apply(null,t);_e(n)}},we=function(t){return function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];be.apply(void 0,[t].concat(e))}},Ee=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n="FIREBASE INTERNAL ERROR: "+ye.apply(void 0,t);fe.error(n)},Te=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n="FIREBASE FATAL ERROR: "+ye.apply(void 0,t);throw fe.error(n),new Error(n)},Ce=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n="FIREBASE WARNING: "+ye.apply(void 0,t);fe.warn(n)},Se=function(t){return"number"==typeof t&&(t!=t||t==Number.POSITIVE_INFINITY||t==Number.NEGATIVE_INFINITY)},Ie="[MIN_NAME]",Ne="[MAX_NAME]",Re=function(t,e){if(t===e)return 0;if(t===Ie||e===Ne)return-1;if(e===Ie||t===Ne)return 1;var n=Fe(t),r=Fe(e);return null!==n?null!==r?n-r==0?t.length-e.length:n-r:-1:null!==r?1:t<e?-1:1},Ae=function(t,e){return t===e?0:t<e?-1:1},ke=function(t,e){if(e&&t in e)return e[t];throw new Error("Missing required key ("+t+") in object: "+Nt(e))},Oe=function(t){if("object"!=typeof t||null===t)return Nt(t);var e=[];for(var n in t)e.push(n);e.sort();for(var r="{",i=0;i<e.length;i++)0!==i&&(r+=","),r+=Nt(e[i]),r+=":",r+=Oe(t[e[i]]);return r+="}"},Pe=function(t,e){var n=t.length;if(n<=e)return[t];for(var r=[],i=0;i<n;i+=e)i+e>n?r.push(t.substring(i,n)):r.push(t.substring(i,i+e));return r},De=function(t,e){if(Array.isArray(t))for(var n=0;n<t.length;++n)e(n,t[n]);else Ot(t,function(t,n){return e(n,t)})},Le=function(t){lt(!Se(t),"Invalid JSON number");var e,n,r,i,o,a,s;for(0===t?(n=0,r=0,e=1/t==-1/0?1:0):(e=t<0,(t=Math.abs(t))>=Math.pow(2,-1022)?(n=(i=Math.min(Math.floor(Math.log(t)/Math.LN2),1023))+1023,r=Math.round(t*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,r=Math.round(t/Math.pow(2,-1074)))),a=[],o=52;o;o-=1)a.push(r%2?1:0),r=Math.floor(r/2);for(o=11;o;o-=1)a.push(n%2?1:0),n=Math.floor(n/2);a.push(e?1:0),a.reverse(),s=a.join("");var u="";for(o=0;o<64;o+=8){var c=parseInt(s.substr(o,8),2).toString(16);1===c.length&&(c="0"+c),u+=c}return u.toLowerCase()},xe=new RegExp("^-?\\d{1,10}$"),Fe=function(t){if(xe.test(t)){var e=Number(t);if(e>=-2147483648&&e<=2147483647)return e}return null},Ue=function(t){try{t()}catch(t){setTimeout(function(){var e=t.stack||"";throw Ce("Exception was thrown by user callback.",e),t},Math.floor(0))}},Me=function(){return("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},We=function(t,e){var n=setTimeout(t,e);return"object"==typeof n&&n.unref&&n.unref(),n},Be=function(){function t(t,e){if(void 0===e){this.pieces_=t.split("/");for(var n=0,r=0;r<this.pieces_.length;r++)this.pieces_[r].length>0&&(this.pieces_[n]=this.pieces_[r],n++);this.pieces_.length=n,this.pieceNum_=0}else this.pieces_=t,this.pieceNum_=e}return Object.defineProperty(t,"Empty",{get:function(){return new t("")},enumerable:!0,configurable:!0}),t.prototype.getFront=function(){return this.pieceNum_>=this.pieces_.length?null:this.pieces_[this.pieceNum_]},t.prototype.getLength=function(){return this.pieces_.length-this.pieceNum_},t.prototype.popFront=function(){var e=this.pieceNum_;return e<this.pieces_.length&&e++,new t(this.pieces_,e)},t.prototype.getBack=function(){return this.pieceNum_<this.pieces_.length?this.pieces_[this.pieces_.length-1]:null},t.prototype.toString=function(){for(var t="",e=this.pieceNum_;e<this.pieces_.length;e++)""!==this.pieces_[e]&&(t+="/"+this.pieces_[e]);return t||"/"},t.prototype.toUrlEncodedString=function(){for(var t="",e=this.pieceNum_;e<this.pieces_.length;e++)""!==this.pieces_[e]&&(t+="/"+encodeURIComponent(String(this.pieces_[e])));return t||"/"},t.prototype.slice=function(t){return void 0===t&&(t=0),this.pieces_.slice(this.pieceNum_+t)},t.prototype.parent=function(){if(this.pieceNum_>=this.pieces_.length)return null;for(var e=[],n=this.pieceNum_;n<this.pieces_.length-1;n++)e.push(this.pieces_[n]);return new t(e,0)},t.prototype.child=function(e){for(var n=[],r=this.pieceNum_;r<this.pieces_.length;r++)n.push(this.pieces_[r]);if(e instanceof t)for(r=e.pieceNum_;r<e.pieces_.length;r++)n.push(e.pieces_[r]);else{var i=e.split("/");for(r=0;r<i.length;r++)i[r].length>0&&n.push(i[r])}return new t(n,0)},t.prototype.isEmpty=function(){return this.pieceNum_>=this.pieces_.length},t.relativePath=function(e,n){var r=e.getFront(),i=n.getFront();if(null===r)return n;if(r===i)return t.relativePath(e.popFront(),n.popFront());throw new Error("INTERNAL ERROR: innerPath ("+n+") is not within outerPath ("+e+")")},t.comparePaths=function(t,e){for(var n=t.slice(),r=e.slice(),i=0;i<n.length&&i<r.length;i++){var o=Re(n[i],r[i]);if(0!==o)return o}return n.length===r.length?0:n.length<r.length?-1:1},t.prototype.equals=function(t){if(this.getLength()!==t.getLength())return!1;for(var e=this.pieceNum_,n=t.pieceNum_;e<=this.pieces_.length;e++,n++)if(this.pieces_[e]!==t.pieces_[n])return!1;return!0},t.prototype.contains=function(t){var e=this.pieceNum_,n=t.pieceNum_;if(this.getLength()>t.getLength())return!1;for(;e<this.pieces_.length;){if(this.pieces_[e]!==t.pieces_[n])return!1;++e,++n}return!0},t}(),je=function(){function t(t,e){this.errorPrefix_=e,this.parts_=t.slice(),this.byteLength_=Math.max(1,this.parts_.length);for(var n=0;n<this.parts_.length;n++)this.byteLength_+=Gt(this.parts_[n]);this.checkValid_()}return Object.defineProperty(t,"MAX_PATH_DEPTH",{get:function(){return 32},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MAX_PATH_LENGTH_BYTES",{get:function(){return 768},enumerable:!0,configurable:!0}),t.prototype.push=function(t){this.parts_.length>0&&(this.byteLength_+=1),this.parts_.push(t),this.byteLength_+=Gt(t),this.checkValid_()},t.prototype.pop=function(){var t=this.parts_.pop();this.byteLength_-=Gt(t),this.parts_.length>0&&(this.byteLength_-=1)},t.prototype.checkValid_=function(){if(this.byteLength_>t.MAX_PATH_LENGTH_BYTES)throw new Error(this.errorPrefix_+"has a key path longer than "+t.MAX_PATH_LENGTH_BYTES+" bytes ("+this.byteLength_+").");if(this.parts_.length>t.MAX_PATH_DEPTH)throw new Error(this.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+t.MAX_PATH_DEPTH+") or object contains a cycle "+this.toErrorString())},t.prototype.toErrorString=function(){return 0==this.parts_.length?"":"in property '"+this.parts_.join(".")+"'"},t}(),Ve="long_polling",qe=function(){function t(t,e,n,r,i){void 0===i&&(i=""),this.secure=e,this.namespace=n,this.webSocketOnly=r,this.persistenceKey=i,this.host=t.toLowerCase(),this.domain=this.host.substr(this.host.indexOf(".")+1),this.internalHost=le.get("host:"+t)||this.host}return t.prototype.needsQueryParam=function(){return this.host!==this.internalHost||this.isCustomHost()},t.prototype.isCacheableHost=function(){return"s-"===this.internalHost.substr(0,2)},t.prototype.isDemoHost=function(){return"firebaseio-demo.com"===this.domain},t.prototype.isCustomHost=function(){return"firebaseio.com"!==this.domain&&"firebaseio-demo.com"!==this.domain},t.prototype.updateHost=function(t){t!==this.internalHost&&(this.internalHost=t,this.isCacheableHost()&&le.set("host:"+this.host,this.internalHost))},t.prototype.connectionURL=function(t,e){var n;if(lt("string"==typeof t,"typeof type must == string"),lt("object"==typeof e,"typeof params must == object"),"websocket"===t)n=(this.secure?"wss://":"ws://")+this.internalHost+"/.ws?";else{if(t!==Ve)throw new Error("Unknown connection type: "+t);n=(this.secure?"https://":"http://")+this.internalHost+"/.lp?"}this.needsQueryParam()&&(e.ns=this.namespace);var r=[];return Ot(e,function(t,e){r.push(t+"="+e)}),n+r.join("&")},t.prototype.toString=function(){var t=this.toURLString();return this.persistenceKey&&(t+="<"+this.persistenceKey+">"),t},t.prototype.toURLString=function(){return(this.secure?"https://":"http://")+this.host},t}();var He,Ke,Ge,Qe,ze,Ye=function(t){var e=Xe(t),n=e.subdomain;"firebase"===e.domain&&Te(e.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),n&&"undefined"!=n||"localhost"===e.domain||Te("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),e.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&Ce("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");var r="ws"===e.scheme||"wss"===e.scheme;return{repoInfo:new qe(e.host,e.secure,n,r),path:new Be(e.pathString)}},Xe=function(t){var e="",n="",r="",i="",o=!0,a="https",s=443;if("string"==typeof t){var u=t.indexOf("//");u>=0&&(a=t.substring(0,u-1),t=t.substring(u+2));var c=t.indexOf("/");-1===c&&(c=t.length);var h=t.indexOf("?");-1===h&&(h=t.length),e=t.substring(0,Math.min(c,h)),c<h&&(i=function(t){for(var e="",n=t.split("/"),r=0;r<n.length;r++)if(n[r].length>0){var i=n[r];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(t){}e+="/"+i}return e}(t.substring(c,h)));var l=function(t){var e={};t.startsWith("?")&&(t=t.substring(1));for(var n=0,r=t.split("&");n<r.length;n++){var i=r[n];if(0!==i.length){var o=i.split("=");2===o.length?e[decodeURIComponent(o[0])]=decodeURIComponent(o[1]):Ce("Invalid query segment '"+i+"' in query '"+t+"'")}}return e}(t.substring(Math.min(t.length,h)));(u=e.indexOf(":"))>=0?(o="https"===a||"wss"===a,s=parseInt(e.substring(u+1),10)):u=t.length;var p=e.split(".");3===p.length?(n=p[1],r=p[0].toLowerCase()):2===p.length?n=p[0]:"localhost"===p[0].slice(0,u).toLowerCase()&&(n="localhost"),""===r&&"ns"in l&&(r=l.ns)}return{host:e,port:s,domain:n,subdomain:r,secure:o,scheme:a,pathString:i}},$e=/[\[\].#$\/\u0000-\u001F\u007F]/,Je=/[\[\].#$\u0000-\u001F\u007F]/,Ze=function(t){return"string"==typeof t&&0!==t.length&&!$e.test(t)},tn=function(t){return"string"==typeof t&&0!==t.length&&!Je.test(t)},en=function(t){return null===t||"string"==typeof t||"number"==typeof t&&!Se(t)||t&&"object"==typeof t&&At(t,".sv")},nn=function(t,e,n,r,i){i&&void 0===n||rn(qt(t,e,i),n,r)},rn=function(t,e,n){var r=n instanceof Be?new je(n,t):n;if(void 0===e)throw new Error(t+"contains undefined "+r.toErrorString());if("function"==typeof e)throw new Error(t+"contains a function "+r.toErrorString()+" with contents = "+e.toString());if(Se(e))throw new Error(t+"contains "+e.toString()+" "+r.toErrorString());if("string"==typeof e&&e.length>10485760/3&&Gt(e)>10485760)throw new Error(t+"contains a string greater than 10485760 utf8 bytes "+r.toErrorString()+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){var i=!1,o=!1;if(Ot(e,function(e,n){if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(o=!0,!Ze(e)))throw new Error(t+" contains an invalid key ("+e+") "+r.toErrorString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');r.push(e),rn(t,n,r),r.pop()}),i&&o)throw new Error(t+' contains ".value" child '+r.toErrorString()+" in addition to actual children.")}},on=function(t,e,n,r,i){if(!i||void 0!==n){var o=qt(t,e,i);if(!n||"object"!=typeof n||Array.isArray(n))throw new Error(o+" must be an object containing the children to replace.");var a=[];Ot(n,function(t,e){var n=new Be(t);if(rn(o,e,r.child(n)),".priority"===n.getBack()&&!en(e))throw new Error(o+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");a.push(n)}),function(t,e){var n,r;for(n=0;n<e.length;n++)for(var i=(r=e[n]).slice(),o=0;o<i.length;o++)if(".priority"===i[o]&&o===i.length-1);else if(!Ze(i[o]))throw new Error(t+"contains an invalid key ("+i[o]+") in path "+r.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');e.sort(Be.comparePaths);var a=null;for(n=0;n<e.length;n++){if(r=e[n],null!==a&&a.contains(r))throw new Error(t+"contains a path "+a.toString()+" that is ancestor of another path "+r.toString());a=r}}(o,a)}},an=function(t,e,n,r){if(!r||void 0!==n){if(Se(n))throw new Error(qt(t,e,r)+"is "+n.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!en(n))throw new Error(qt(t,e,r)+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},sn=function(t,e,n,r){if(!r||void 0!==n)switch(n){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(qt(t,e,r)+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}},un=function(t,e,n,r){if(!(r&&void 0===n||Ze(n)))throw new Error(qt(t,e,r)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},cn=function(t,e,n,r){if(!(r&&void 0===n||tn(n)))throw new Error(qt(t,e,r)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},hn=function(t,e){if(".info"===e.getFront())throw new Error(t+" failed = Can't modify data under /.info/")},ln=function(t,e,n){var r=n.path.toString();if("string"!=typeof n.repoInfo.host||0===n.repoInfo.host.length||!Ze(n.repoInfo.namespace)&&"localhost"!==n.repoInfo.host.split(":")[0]||0!==r.length&&!function(t){return t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),tn(t)}(r))throw new Error(qt(t,e,!1)+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')},pn=function(){function t(t,e){this.repo_=t,this.path_=e}return t.prototype.cancel=function(t){Vt("OnDisconnect.cancel",0,1,arguments.length),Ht("OnDisconnect.cancel",1,t,!0);var e=new mt;return this.repo_.onDisconnectCancel(this.path_,e.wrapCallback(t)),e.promise},t.prototype.remove=function(t){Vt("OnDisconnect.remove",0,1,arguments.length),hn("OnDisconnect.remove",this.path_),Ht("OnDisconnect.remove",1,t,!0);var e=new mt;return this.repo_.onDisconnectSet(this.path_,null,e.wrapCallback(t)),e.promise},t.prototype.set=function(t,e){Vt("OnDisconnect.set",1,2,arguments.length),hn("OnDisconnect.set",this.path_),nn("OnDisconnect.set",1,t,this.path_,!1),Ht("OnDisconnect.set",2,e,!0);var n=new mt;return this.repo_.onDisconnectSet(this.path_,t,n.wrapCallback(e)),n.promise},t.prototype.setWithPriority=function(t,e,n){Vt("OnDisconnect.setWithPriority",2,3,arguments.length),hn("OnDisconnect.setWithPriority",this.path_),nn("OnDisconnect.setWithPriority",1,t,this.path_,!1),an("OnDisconnect.setWithPriority",2,e,!1),Ht("OnDisconnect.setWithPriority",3,n,!0);var r=new mt;return this.repo_.onDisconnectSetWithPriority(this.path_,t,e,r.wrapCallback(n)),r.promise},t.prototype.update=function(t,e){if(Vt("OnDisconnect.update",1,2,arguments.length),hn("OnDisconnect.update",this.path_),Array.isArray(t)){for(var n={},r=0;r<t.length;++r)n[""+r]=t[r];t=n,Ce("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}on("OnDisconnect.update",1,t,this.path_,!1),Ht("OnDisconnect.update",2,e,!0);var i=new mt;return this.repo_.onDisconnectUpdate(this.path_,t,i.wrapCallback(e)),i.promise},t}(),fn=function(){function t(t,e){this.committed=t,this.snapshot=e}return t.prototype.toJSON=function(){return Vt("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}},t}(),dn=(He="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Ke=0,Ge=[],function(t){var e,n=t===Ke;Ke=t;var r=new Array(8);for(e=7;e>=0;e--)r[e]=He.charAt(t%64),t=Math.floor(t/64);lt(0===t,"Cannot push at time == 0");var i=r.join("");if(n){for(e=11;e>=0&&63===Ge[e];e--)Ge[e]=0;Ge[e]++}else for(e=0;e<12;e++)Ge[e]=Math.floor(64*Math.random());for(e=0;e<12;e++)i+=He.charAt(Ge[e]);return lt(20===i.length,"nextPushId: Length should be 20."),i}),vn=function(){function t(t,e){this.name=t,this.node=e}return t.Wrap=function(e,n){return new t(e,n)},t}(),yn=function(){function t(){}return t.prototype.getCompare=function(){return this.compare.bind(this)},t.prototype.indexedValueChanged=function(t,e){var n=new vn(Ie,t),r=new vn(Ie,e);return 0!==this.compare(n,r)},t.prototype.minPost=function(){return vn.MIN},t}(),_n=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return it(e,t),Object.defineProperty(e,"__EMPTY_NODE",{get:function(){return Qe},set:function(t){Qe=t},enumerable:!0,configurable:!0}),e.prototype.compare=function(t,e){return Re(t.name,e.name)},e.prototype.isDefinedOn=function(t){throw pt("KeyIndex.isDefinedOn not expected to be called.")},e.prototype.indexedValueChanged=function(t,e){return!1},e.prototype.minPost=function(){return vn.MIN},e.prototype.maxPost=function(){return new vn(Ne,Qe)},e.prototype.makePost=function(t,e){return lt("string"==typeof t,"KeyIndex indexValue must always be a string."),new vn(t,Qe)},e.prototype.toString=function(){return".key"},e}(yn),gn=new _n;var mn,bn,wn,En=function(t){return"number"==typeof t?"number:"+Le(t):"string:"+t},Tn=function(t){if(t.isLeafNode()){var e=t.val();lt("string"==typeof e||"number"==typeof e||"object"==typeof e&&At(e,".sv"),"Priority must be a string or number.")}else lt(t===ze||t.isEmpty(),"priority of unexpected type.");lt(t===ze||t.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")},Cn=function(){function t(e,n){void 0===n&&(n=t.__childrenNodeConstructor.EMPTY_NODE),this.value_=e,this.priorityNode_=n,this.lazyHash_=null,lt(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),Tn(this.priorityNode_)}return Object.defineProperty(t,"__childrenNodeConstructor",{get:function(){return mn},set:function(t){mn=t},enumerable:!0,configurable:!0}),t.prototype.isLeafNode=function(){return!0},t.prototype.getPriority=function(){return this.priorityNode_},t.prototype.updatePriority=function(e){return new t(this.value_,e)},t.prototype.getImmediateChild=function(e){return".priority"===e?this.priorityNode_:t.__childrenNodeConstructor.EMPTY_NODE},t.prototype.getChild=function(e){return e.isEmpty()?this:".priority"===e.getFront()?this.priorityNode_:t.__childrenNodeConstructor.EMPTY_NODE},t.prototype.hasChild=function(){return!1},t.prototype.getPredecessorChildName=function(t,e){return null},t.prototype.updateImmediateChild=function(e,n){return".priority"===e?this.updatePriority(n):n.isEmpty()&&".priority"!==e?this:t.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,n).updatePriority(this.priorityNode_)},t.prototype.updateChild=function(e,n){var r=e.getFront();return null===r?n:n.isEmpty()&&".priority"!==r?this:(lt(".priority"!==r||1===e.getLength(),".priority must be the last token in a path"),this.updateImmediateChild(r,t.__childrenNodeConstructor.EMPTY_NODE.updateChild(e.popFront(),n)))},t.prototype.isEmpty=function(){return!1},t.prototype.numChildren=function(){return 0},t.prototype.forEachChild=function(t,e){return!1},t.prototype.val=function(t){return t&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()},t.prototype.hash=function(){if(null===this.lazyHash_){var t="";this.priorityNode_.isEmpty()||(t+="priority:"+En(this.priorityNode_.val())+":");var e=typeof this.value_;t+=e+":",t+="number"===e?Le(this.value_):this.value_,this.lazyHash_=ve(t)}return this.lazyHash_},t.prototype.getValue=function(){return this.value_},t.prototype.compareTo=function(e){return e===t.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof t.__childrenNodeConstructor?-1:(lt(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))},t.prototype.compareToLeafNode_=function(e){var n=typeof e.value_,r=typeof this.value_,i=t.VALUE_TYPE_ORDER.indexOf(n),o=t.VALUE_TYPE_ORDER.indexOf(r);return lt(i>=0,"Unknown leaf type: "+n),lt(o>=0,"Unknown leaf type: "+r),i===o?"object"===r?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:o-i},t.prototype.withIndex=function(){return this},t.prototype.isIndexed=function(){return!0},t.prototype.equals=function(t){if(t===this)return!0;if(t.isLeafNode()){var e=t;return this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_)}return!1},t.VALUE_TYPE_ORDER=["object","boolean","number","string"],t}();var Sn,In,Nn=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return it(e,t),e.prototype.compare=function(t,e){var n=t.node.getPriority(),r=e.node.getPriority(),i=n.compareTo(r);return 0===i?Re(t.name,e.name):i},e.prototype.isDefinedOn=function(t){return!t.getPriority().isEmpty()},e.prototype.indexedValueChanged=function(t,e){return!t.getPriority().equals(e.getPriority())},e.prototype.minPost=function(){return vn.MIN},e.prototype.maxPost=function(){return new vn(Ne,new Cn("[PRIORITY-POST]",wn))},e.prototype.makePost=function(t,e){var n=bn(t);return new vn(e,new Cn("[PRIORITY-POST]",n))},e.prototype.toString=function(){return".priority"},e}(yn)),Rn=function(){function t(t,e,n,r,i){void 0===i&&(i=null),this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];for(var o=1;!t.isEmpty();)if(t=t,o=e?n(t.key,e):1,r&&(o*=-1),o<0)t=this.isReverse_?t.left:t.right;else{if(0===o){this.nodeStack_.push(t);break}this.nodeStack_.push(t),t=this.isReverse_?t.right:t.left}}return t.prototype.getNext=function(){if(0===this.nodeStack_.length)return null;var t,e=this.nodeStack_.pop();if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t},t.prototype.hasNext=function(){return this.nodeStack_.length>0},t.prototype.peek=function(){if(0===this.nodeStack_.length)return null;var t=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value}},t}(),An=function(){function t(e,n,r,i,o){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=i?i:On.EMPTY_NODE,this.right=null!=o?o:On.EMPTY_NODE}return t.prototype.copy=function(e,n,r,i,o){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right)},t.prototype.count=function(){return this.left.count()+1+this.right.count()},t.prototype.isEmpty=function(){return!1},t.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},t.prototype.min_=function(){return this.left.isEmpty()?this:this.left.min_()},t.prototype.minKey=function(){return this.min_().key},t.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},t.prototype.insert=function(t,e,n){var r,i;return(i=(r=n(t,(i=this).key))<0?i.copy(null,null,null,i.left.insert(t,e,n),null):0===r?i.copy(null,e,null,null,null):i.copy(null,null,null,null,i.right.insert(t,e,n))).fixUp_()},t.prototype.removeMin_=function(){if(this.left.isEmpty())return On.EMPTY_NODE;var t=this;return t.left.isRed_()||t.left.left.isRed_()||(t=t.moveRedLeft_()),(t=t.copy(null,null,null,t.left.removeMin_(),null)).fixUp_()},t.prototype.remove=function(t,e){var n,r;if(e(t,(n=this).key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(t,e),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===e(t,n.key)){if(n.right.isEmpty())return On.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(t,e))}return n.fixUp_()},t.prototype.isRed_=function(){return this.color},t.prototype.fixUp_=function(){var t=this;return t.right.isRed_()&&!t.left.isRed_()&&(t=t.rotateLeft_()),t.left.isRed_()&&t.left.left.isRed_()&&(t=t.rotateRight_()),t.left.isRed_()&&t.right.isRed_()&&(t=t.colorFlip_()),t},t.prototype.moveRedLeft_=function(){var t=this.colorFlip_();return t.right.left.isRed_()&&(t=(t=(t=t.copy(null,null,null,null,t.right.rotateRight_())).rotateLeft_()).colorFlip_()),t},t.prototype.moveRedRight_=function(){var t=this.colorFlip_();return t.left.left.isRed_()&&(t=(t=t.rotateRight_()).colorFlip_()),t},t.prototype.rotateLeft_=function(){var e=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)},t.prototype.rotateRight_=function(){var e=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)},t.prototype.colorFlip_=function(){var t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)},t.prototype.checkMaxDepth_=function(){var t=this.check_();return Math.pow(2,t)<=this.count()+1},t.prototype.check_=function(){var t;if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");if((t=this.left.check_())!==this.right.check_())throw new Error("Black depths differ");return t+(this.isRed_()?0:1)},t.RED=!0,t.BLACK=!1,t}(),kn=function(){function t(){}return t.prototype.copy=function(t,e,n,r,i){return this},t.prototype.insert=function(t,e,n){return new An(t,e,null)},t.prototype.remove=function(t,e){return this},t.prototype.count=function(){return 0},t.prototype.isEmpty=function(){return!0},t.prototype.inorderTraversal=function(t){return!1},t.prototype.reverseTraversal=function(t){return!1},t.prototype.minKey=function(){return null},t.prototype.maxKey=function(){return null},t.prototype.check_=function(){return 0},t.prototype.isRed_=function(){return!1},t}(),On=function(){function t(e,n){void 0===n&&(n=t.EMPTY_NODE),this.comparator_=e,this.root_=n}return t.prototype.insert=function(e,n){return new t(this.comparator_,this.root_.insert(e,n,this.comparator_).copy(null,null,An.BLACK,null,null))},t.prototype.remove=function(e){return new t(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,An.BLACK,null,null))},t.prototype.get=function(t){for(var e,n=this.root_;!n.isEmpty();){if(0===(e=this.comparator_(t,n.key)))return n.value;e<0?n=n.left:e>0&&(n=n.right)}return null},t.prototype.getPredecessorKey=function(t){for(var e,n=this.root_,r=null;!n.isEmpty();){if(0===(e=this.comparator_(t,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}e<0?n=n.left:e>0&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")},t.prototype.isEmpty=function(){return this.root_.isEmpty()},t.prototype.count=function(){return this.root_.count()},t.prototype.minKey=function(){return this.root_.minKey()},t.prototype.maxKey=function(){return this.root_.maxKey()},t.prototype.inorderTraversal=function(t){return this.root_.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.root_.reverseTraversal(t)},t.prototype.getIterator=function(t){return new Rn(this.root_,null,this.comparator_,!1,t)},t.prototype.getIteratorFrom=function(t,e){return new Rn(this.root_,t,this.comparator_,!1,e)},t.prototype.getReverseIteratorFrom=function(t,e){return new Rn(this.root_,t,this.comparator_,!0,e)},t.prototype.getReverseIterator=function(t){return new Rn(this.root_,null,this.comparator_,!0,t)},t.EMPTY_NODE=new kn,t}(),Pn=Math.log(2),Dn=function(){function t(t){var e;this.count=(e=t+1,parseInt(Math.log(e)/Pn,10)),this.current_=this.count-1;var n,r=(n=this.count,parseInt(Array(n+1).join("1"),2));this.bits_=t+1&r}return t.prototype.nextBitIsOne=function(){var t=!(this.bits_&1<<this.current_);return this.current_--,t},t}(),Ln=function(t,e,n,r){t.sort(e);var i=function(e,r){var o,a,s=r-e;if(0==s)return null;if(1==s)return o=t[e],a=n?n(o):o,new An(a,o.node,An.BLACK,null,null);var u=parseInt(s/2,10)+e,c=i(e,u),h=i(u+1,r);return o=t[u],a=n?n(o):o,new An(a,o.node,An.BLACK,c,h)},o=function(e){for(var r=null,o=null,a=t.length,s=function(e,r){var o=a-e,s=a;a-=e;var c=i(o+1,s),h=t[o],l=n?n(h):h;u(new An(l,h.node,r,null,c))},u=function(t){r?(r.left=t,r=t):(o=t,r=t)},c=0;c<e.count;++c){var h=e.nextBitIsOne(),l=Math.pow(2,e.count-(c+1));h?s(l,An.BLACK):(s(l,An.BLACK),s(l,An.RED))}return o}(new Dn(t.length));return new On(r||e,o)},xn={},Fn=function(){function t(t,e){this.indexes_=t,this.indexSet_=e}return Object.defineProperty(t,"Default",{get:function(){return lt(xn&&Nn,"ChildrenNode.ts has not been loaded"),Sn=Sn||new t({".priority":xn},{".priority":Nn})},enumerable:!0,configurable:!0}),t.prototype.get=function(t){var e=kt(this.indexes_,t);if(!e)throw new Error("No index defined for "+t);return e===xn?null:e},t.prototype.hasIndex=function(t){return At(this.indexSet_,t.toString())},t.prototype.addIndex=function(e,n){lt(e!==gn,"KeyIndex always exists and isn't meant to be added to the IndexMap.");for(var r,i=[],o=!1,a=n.getIterator(vn.Wrap),s=a.getNext();s;)o=o||e.isDefinedOn(s.node),i.push(s),s=a.getNext();r=o?Ln(i,e.getCompare()):xn;var u=e.toString(),c=Pt(this.indexSet_);c[u]=e;var h=Pt(this.indexes_);return h[u]=r,new t(h,c)},t.prototype.addToIndexes=function(e,n){var r=this;return new t(xt(this.indexes_,function(t,i){var o=kt(r.indexSet_,i);if(lt(o,"Missing index implementation for "+i),t===xn){if(o.isDefinedOn(e.node)){for(var a=[],s=n.getIterator(vn.Wrap),u=s.getNext();u;)u.name!=e.name&&a.push(u),u=s.getNext();return a.push(e),Ln(a,o.getCompare())}return xn}var c=n.get(e.name),h=t;return c&&(h=h.remove(new vn(e.name,c))),h.insert(e,e.node)}),this.indexSet_)},t.prototype.removeFromIndexes=function(e,n){return new t(xt(this.indexes_,function(t){if(t===xn)return t;var r=n.get(e.name);return r?t.remove(new vn(e.name,r)):t}),this.indexSet_)},t}();function Un(t,e){return Re(t.name,e.name)}function Mn(t,e){return Re(t,e)}var Wn=function(){function t(t,e,n){this.children_=t,this.priorityNode_=e,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&Tn(this.priorityNode_),this.children_.isEmpty()&&lt(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}return Object.defineProperty(t,"EMPTY_NODE",{get:function(){return In||(In=new t(new On(Mn),null,Fn.Default))},enumerable:!0,configurable:!0}),t.prototype.isLeafNode=function(){return!1},t.prototype.getPriority=function(){return this.priorityNode_||In},t.prototype.updatePriority=function(e){return this.children_.isEmpty()?this:new t(this.children_,e,this.indexMap_)},t.prototype.getImmediateChild=function(t){if(".priority"===t)return this.getPriority();var e=this.children_.get(t);return null===e?In:e},t.prototype.getChild=function(t){var e=t.getFront();return null===e?this:this.getImmediateChild(e).getChild(t.popFront())},t.prototype.hasChild=function(t){return null!==this.children_.get(t)},t.prototype.updateImmediateChild=function(e,n){if(lt(n,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(n);var r=new vn(e,n),i=void 0,o=void 0;return n.isEmpty()?(i=this.children_.remove(e),o=this.indexMap_.removeFromIndexes(r,this.children_)):(i=this.children_.insert(e,n),o=this.indexMap_.addToIndexes(r,this.children_)),new t(i,i.isEmpty()?In:this.priorityNode_,o)},t.prototype.updateChild=function(t,e){var n=t.getFront();if(null===n)return e;lt(".priority"!==t.getFront()||1===t.getLength(),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(t.popFront(),e);return this.updateImmediateChild(n,r)},t.prototype.isEmpty=function(){return this.children_.isEmpty()},t.prototype.numChildren=function(){return this.children_.count()},t.prototype.val=function(e){if(this.isEmpty())return null;var n={},r=0,i=0,o=!0;if(this.forEachChild(Nn,function(a,s){n[a]=s.val(e),r++,o&&t.INTEGER_REGEXP_.test(a)?i=Math.max(i,Number(a)):o=!1}),!e&&o&&i<2*r){var a=[];for(var s in n)a[s]=n[s];return a}return e&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n},t.prototype.hash=function(){if(null===this.lazyHash_){var t="";this.getPriority().isEmpty()||(t+="priority:"+En(this.getPriority().val())+":"),this.forEachChild(Nn,function(e,n){var r=n.hash();""!==r&&(t+=":"+e+":"+r)}),this.lazyHash_=""===t?"":ve(t)}return this.lazyHash_},t.prototype.getPredecessorChildName=function(t,e,n){var r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new vn(t,e));return i?i.name:null}return this.children_.getPredecessorKey(t)},t.prototype.getFirstChildName=function(t){var e=this.resolveIndex_(t);if(e){var n=e.minKey();return n&&n.name}return this.children_.minKey()},t.prototype.getFirstChild=function(t){var e=this.getFirstChildName(t);return e?new vn(e,this.children_.get(e)):null},t.prototype.getLastChildName=function(t){var e=this.resolveIndex_(t);if(e){var n=e.maxKey();return n&&n.name}return this.children_.maxKey()},t.prototype.getLastChild=function(t){var e=this.getLastChildName(t);return e?new vn(e,this.children_.get(e)):null},t.prototype.forEachChild=function(t,e){var n=this.resolveIndex_(t);return n?n.inorderTraversal(function(t){return e(t.name,t.node)}):this.children_.inorderTraversal(e)},t.prototype.getIterator=function(t){return this.getIteratorFrom(t.minPost(),t)},t.prototype.getIteratorFrom=function(t,e){var n=this.resolveIndex_(e);if(n)return n.getIteratorFrom(t,function(t){return t});for(var r=this.children_.getIteratorFrom(t.name,vn.Wrap),i=r.peek();null!=i&&e.compare(i,t)<0;)r.getNext(),i=r.peek();return r},t.prototype.getReverseIterator=function(t){return this.getReverseIteratorFrom(t.maxPost(),t)},t.prototype.getReverseIteratorFrom=function(t,e){var n=this.resolveIndex_(e);if(n)return n.getReverseIteratorFrom(t,function(t){return t});for(var r=this.children_.getReverseIteratorFrom(t.name,vn.Wrap),i=r.peek();null!=i&&e.compare(i,t)>0;)r.getNext(),i=r.peek();return r},t.prototype.compareTo=function(t){return this.isEmpty()?t.isEmpty()?0:-1:t.isLeafNode()||t.isEmpty()?1:t===Bn?-1:0},t.prototype.withIndex=function(e){if(e===gn||this.indexMap_.hasIndex(e))return this;var n=this.indexMap_.addIndex(e,this.children_);return new t(this.children_,this.priorityNode_,n)},t.prototype.isIndexed=function(t){return t===gn||this.indexMap_.hasIndex(t)},t.prototype.equals=function(t){if(t===this)return!0;if(t.isLeafNode())return!1;var e=t;if(this.getPriority().equals(e.getPriority())){if(this.children_.count()===e.children_.count()){for(var n=this.getIterator(Nn),r=e.getIterator(Nn),i=n.getNext(),o=r.getNext();i&&o;){if(i.name!==o.name||!i.node.equals(o.node))return!1;i=n.getNext(),o=r.getNext()}return null===i&&null===o}return!1}return!1},t.prototype.resolveIndex_=function(t){return t===gn?null:this.indexMap_.get(t.toString())},t.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/,t}(),Bn=new(function(t){function e(){return t.call(this,new On(Mn),Wn.EMPTY_NODE,Fn.Default)||this}return it(e,t),e.prototype.compareTo=function(t){return t===this?0:1},e.prototype.equals=function(t){return t===this},e.prototype.getPriority=function(){return this},e.prototype.getImmediateChild=function(t){return Wn.EMPTY_NODE},e.prototype.isEmpty=function(){return!1},e}(Wn));Object.defineProperties(vn,{MIN:{value:new vn(Ie,Wn.EMPTY_NODE)},MAX:{value:new vn(Ne,Bn)}}),_n.__EMPTY_NODE=Wn.EMPTY_NODE,Cn.__childrenNodeConstructor=Wn,ze=Bn,function(t){wn=t}(Bn);var jn=!0;function Vn(t,e){if(void 0===e&&(e=null),null===t)return Wn.EMPTY_NODE;if("object"==typeof t&&".priority"in t&&(e=t[".priority"]),lt(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"==typeof t&&".value"in t&&null!==t[".value"]&&(t=t[".value"]),"object"!=typeof t||".sv"in t)return new Cn(t,Vn(e));if(t instanceof Array||!jn){var n=Wn.EMPTY_NODE,r=t;return Ot(r,function(t,e){if(At(r,t)&&"."!==t.substring(0,1)){var i=Vn(e);!i.isLeafNode()&&i.isEmpty()||(n=n.updateImmediateChild(t,i))}}),n.updatePriority(Vn(e))}var i=[],o=!1,a=t;if(Ot(a,function(t,e){if("string"!=typeof t||"."!==t.substring(0,1)){var n=Vn(a[t]);n.isEmpty()||(o=o||!n.getPriority().isEmpty(),i.push(new vn(t,n)))}}),0==i.length)return Wn.EMPTY_NODE;var s=Ln(i,Un,function(t){return t.name},Mn);if(o){var u=Ln(i,Nn.getCompare());return new Wn(s,Vn(e),new Fn({".priority":u},{".priority":Nn}))}return new Wn(s,Vn(e),Fn.Default)}!function(t){bn=t}(Vn);var qn,Hn,Kn=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return it(e,t),e.prototype.compare=function(t,e){var n=t.node.compareTo(e.node);return 0===n?Re(t.name,e.name):n},e.prototype.isDefinedOn=function(t){return!0},e.prototype.indexedValueChanged=function(t,e){return!t.equals(e)},e.prototype.minPost=function(){return vn.MIN},e.prototype.maxPost=function(){return vn.MAX},e.prototype.makePost=function(t,e){var n=Vn(t);return new vn(e,n)},e.prototype.toString=function(){return".value"},e}(yn)),Gn=function(t){function e(e){var n=t.call(this)||this;return n.indexPath_=e,lt(!e.isEmpty()&&".priority"!==e.getFront(),"Can't create PathIndex with empty path or .priority key"),n}return it(e,t),e.prototype.extractChild=function(t){return t.getChild(this.indexPath_)},e.prototype.isDefinedOn=function(t){return!t.getChild(this.indexPath_).isEmpty()},e.prototype.compare=function(t,e){var n=this.extractChild(t.node),r=this.extractChild(e.node),i=n.compareTo(r);return 0===i?Re(t.name,e.name):i},e.prototype.makePost=function(t,e){var n=Vn(t),r=Wn.EMPTY_NODE.updateChild(this.indexPath_,n);return new vn(e,r)},e.prototype.maxPost=function(){var t=Wn.EMPTY_NODE.updateChild(this.indexPath_,Bn);return new vn(Ne,t)},e.prototype.toString=function(){return this.indexPath_.slice().join("/")},e}(yn),Qn=function(){function t(t,e,n){this.node_=t,this.ref_=e,this.index_=n}return t.prototype.val=function(){return Vt("DataSnapshot.val",0,0,arguments.length),this.node_.val()},t.prototype.exportVal=function(){return Vt("DataSnapshot.exportVal",0,0,arguments.length),this.node_.val(!0)},t.prototype.toJSON=function(){return Vt("DataSnapshot.toJSON",0,1,arguments.length),this.exportVal()},t.prototype.exists=function(){return Vt("DataSnapshot.exists",0,0,arguments.length),!this.node_.isEmpty()},t.prototype.child=function(e){Vt("DataSnapshot.child",0,1,arguments.length),e=String(e),cn("DataSnapshot.child",1,e,!1);var n=new Be(e),r=this.ref_.child(n);return new t(this.node_.getChild(n),r,Nn)},t.prototype.hasChild=function(t){Vt("DataSnapshot.hasChild",1,1,arguments.length),cn("DataSnapshot.hasChild",1,t,!1);var e=new Be(t);return!this.node_.getChild(e).isEmpty()},t.prototype.getPriority=function(){return Vt("DataSnapshot.getPriority",0,0,arguments.length),this.node_.getPriority().val()},t.prototype.forEach=function(e){var n=this;return Vt("DataSnapshot.forEach",1,1,arguments.length),Ht("DataSnapshot.forEach",1,e,!1),!this.node_.isLeafNode()&&!!this.node_.forEachChild(this.index_,function(r,i){return e(new t(i,n.ref_.child(r),Nn))})},t.prototype.hasChildren=function(){return Vt("DataSnapshot.hasChildren",0,0,arguments.length),!this.node_.isLeafNode()&&!this.node_.isEmpty()},Object.defineProperty(t.prototype,"key",{get:function(){return this.ref_.getKey()},enumerable:!0,configurable:!0}),t.prototype.numChildren=function(){return Vt("DataSnapshot.numChildren",0,0,arguments.length),this.node_.numChildren()},t.prototype.getRef=function(){return Vt("DataSnapshot.ref",0,0,arguments.length),this.ref_},Object.defineProperty(t.prototype,"ref",{get:function(){return this.getRef()},enumerable:!0,configurable:!0}),t}(),zn=function(){function t(t,e,n,r){this.eventType=t,this.eventRegistration=e,this.snapshot=n,this.prevName=r}return t.prototype.getPath=function(){var t=this.snapshot.getRef();return"value"===this.eventType?t.path:t.getParent().path},t.prototype.getEventType=function(){return this.eventType},t.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},t.prototype.toString=function(){return this.getPath().toString()+":"+this.eventType+":"+Nt(this.snapshot.exportVal())},t}(),Yn=function(){function t(t,e,n){this.eventRegistration=t,this.error=e,this.path=n}return t.prototype.getPath=function(){return this.path},t.prototype.getEventType=function(){return"cancel"},t.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},t.prototype.toString=function(){return this.path.toString()+":cancel"},t}(),Xn=function(){function t(t,e,n){this.callback_=t,this.cancelCallback_=e,this.context_=n}return t.prototype.respondsTo=function(t){return"value"===t},t.prototype.createEvent=function(t,e){var n=e.getQueryParams().getIndex();return new zn("value",this,new Qn(t.snapshotNode,e.getRef(),n))},t.prototype.getEventRunner=function(t){var e=this.context_;if("cancel"===t.getEventType()){lt(this.cancelCallback_,"Raising a cancel event on a listener with no cancel callback");var n=this.cancelCallback_;return function(){n.call(e,t.error)}}var r=this.callback_;return function(){r.call(e,t.snapshot)}},t.prototype.createCancelEvent=function(t,e){return this.cancelCallback_?new Yn(this,t,e):null},t.prototype.matches=function(e){return e instanceof t&&(!e.callback_||!this.callback_||e.callback_===this.callback_&&e.context_===this.context_)},t.prototype.hasAnyCallback=function(){return null!==this.callback_},t}(),$n=function(){function t(t,e,n){this.callbacks_=t,this.cancelCallback_=e,this.context_=n}return t.prototype.respondsTo=function(t){var e="children_added"===t?"child_added":t;return e="children_removed"===e?"child_removed":e,At(this.callbacks_,e)},t.prototype.createCancelEvent=function(t,e){return this.cancelCallback_?new Yn(this,t,e):null},t.prototype.createEvent=function(t,e){lt(null!=t.childName,"Child events should have a childName.");var n=e.getRef().child(t.childName),r=e.getQueryParams().getIndex();return new zn(t.type,this,new Qn(t.snapshotNode,n,r),t.prevName)},t.prototype.getEventRunner=function(t){var e=this.context_;if("cancel"===t.getEventType()){lt(this.cancelCallback_,"Raising a cancel event on a listener with no cancel callback");var n=this.cancelCallback_;return function(){n.call(e,t.error)}}var r=this.callbacks_[t.eventType];return function(){r.call(e,t.snapshot,t.prevName)}},t.prototype.matches=function(e){if(e instanceof t){if(!this.callbacks_||!e.callbacks_)return!0;if(this.context_===e.context_){var n=Lt(e.callbacks_);if(n===Lt(this.callbacks_)){if(1===n){var r=Ut(e.callbacks_),i=Ut(this.callbacks_);return!(i!==r||e.callbacks_[r]&&this.callbacks_[i]&&e.callbacks_[r]!==this.callbacks_[i])}return function(t,e){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&!e(n,t[n]))return!1;return!0}(this.callbacks_,function(t,n){return e.callbacks_[t]===n})}}}return!1},t.prototype.hasAnyCallback=function(){return null!==this.callbacks_},t}(),Jn=function(){function t(t,e,n,r){this.repo=t,this.path=e,this.queryParams_=n,this.orderByCalled_=r}return Object.defineProperty(t,"__referenceConstructor",{get:function(){return lt(qn,"Reference.ts has not been loaded"),qn},set:function(t){qn=t},enumerable:!0,configurable:!0}),t.validateQueryEndpoints_=function(t){var e=null,n=null;if(t.hasStart()&&(e=t.getIndexStartValue()),t.hasEnd()&&(n=t.getIndexEndValue()),t.getIndex()===gn){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), endAt(),or equalTo() must be a string.";if(t.hasStart()){if(t.getIndexStartName()!=Ie)throw new Error(r);if("string"!=typeof e)throw new Error(i)}if(t.hasEnd()){if(t.getIndexEndName()!=Ne)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(t.getIndex()===Nn){if(null!=e&&!en(e)||null!=n&&!en(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), endAt(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(lt(t.getIndex()instanceof Gn||t.getIndex()===Kn,"unknown index type."),null!=e&&"object"==typeof e||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), endAt(), or equalTo() cannot be an object.")},t.validateLimit_=function(t){if(t.hasStart()&&t.hasEnd()&&t.hasLimit()&&!t.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.")},t.prototype.validateNoPreviousOrderByCall_=function(t){if(!0===this.orderByCalled_)throw new Error(t+": You can't combine multiple orderBy calls.")},t.prototype.getQueryParams=function(){return this.queryParams_},t.prototype.getRef=function(){return Vt("Query.ref",0,0,arguments.length),new t.__referenceConstructor(this.repo,this.path)},t.prototype.on=function(e,n,r,i){Vt("Query.on",2,4,arguments.length),sn("Query.on",1,e,!1),Ht("Query.on",2,n,!1);var o=t.getCancelAndContextArgs_("Query.on",r,i);if("value"===e)this.onValueEvent(n,o.cancel,o.context);else{var a={};a[e]=n,this.onChildEvent(a,o.cancel,o.context)}return n},t.prototype.onValueEvent=function(t,e,n){var r=new Xn(t,e||null,n||null);this.repo.addEventCallbackForQuery(this,r)},t.prototype.onChildEvent=function(t,e,n){var r=new $n(t,e,n);this.repo.addEventCallbackForQuery(this,r)},t.prototype.off=function(t,e,n){Vt("Query.off",0,3,arguments.length),sn("Query.off",1,t,!0),Ht("Query.off",2,e,!0),Kt("Query.off",3,n,!0);var r=null,i=null;"value"===t?r=new Xn(e||null,null,n||null):t&&(e&&((i={})[t]=e),r=new $n(i,null,n||null));this.repo.removeEventCallbackForQuery(this,r)},t.prototype.once=function(e,n,r,i){var o=this;Vt("Query.once",1,4,arguments.length),sn("Query.once",1,e,!1),Ht("Query.once",2,n,!0);var a=t.getCancelAndContextArgs_("Query.once",r,i),s=!0,u=new mt;u.promise.catch(function(){});var c=function(t){s&&(s=!1,o.off(e,c),n&&n.bind(a.context)(t),u.resolve(t))};return this.on(e,c,function(t){o.off(e,c),a.cancel&&a.cancel.bind(a.context)(t),u.reject(t)}),u.promise},t.prototype.limitToFirst=function(e){if(Vt("Query.limitToFirst",1,1,arguments.length),"number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("Query.limitToFirst: First argument must be a positive integer.");if(this.queryParams_.hasLimit())throw new Error("Query.limitToFirst: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new t(this.repo,this.path,this.queryParams_.limitToFirst(e),this.orderByCalled_)},t.prototype.limitToLast=function(e){if(Vt("Query.limitToLast",1,1,arguments.length),"number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("Query.limitToLast: First argument must be a positive integer.");if(this.queryParams_.hasLimit())throw new Error("Query.limitToLast: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new t(this.repo,this.path,this.queryParams_.limitToLast(e),this.orderByCalled_)},t.prototype.orderByChild=function(e){if(Vt("Query.orderByChild",1,1,arguments.length),"$key"===e)throw new Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKey() instead.');if("$priority"===e)throw new Error('Query.orderByChild: "$priority" is invalid. Use Query.orderByPriority() instead.');if("$value"===e)throw new Error('Query.orderByChild: "$value" is invalid. Use Query.orderByValue() instead.');cn("Query.orderByChild",1,e,!1),this.validateNoPreviousOrderByCall_("Query.orderByChild");var n=new Be(e);if(n.isEmpty())throw new Error("Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.");var r=new Gn(n),i=this.queryParams_.orderBy(r);return t.validateQueryEndpoints_(i),new t(this.repo,this.path,i,!0)},t.prototype.orderByKey=function(){Vt("Query.orderByKey",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByKey");var e=this.queryParams_.orderBy(gn);return t.validateQueryEndpoints_(e),new t(this.repo,this.path,e,!0)},t.prototype.orderByPriority=function(){Vt("Query.orderByPriority",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByPriority");var e=this.queryParams_.orderBy(Nn);return t.validateQueryEndpoints_(e),new t(this.repo,this.path,e,!0)},t.prototype.orderByValue=function(){Vt("Query.orderByValue",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByValue");var e=this.queryParams_.orderBy(Kn);return t.validateQueryEndpoints_(e),new t(this.repo,this.path,e,!0)},t.prototype.startAt=function(e,n){void 0===e&&(e=null),Vt("Query.startAt",0,2,arguments.length),nn("Query.startAt",1,e,this.path,!0),un("Query.startAt",2,n,!0);var r=this.queryParams_.startAt(e,n);if(t.validateLimit_(r),t.validateQueryEndpoints_(r),this.queryParams_.hasStart())throw new Error("Query.startAt: Starting point was already set (by another call to startAt or equalTo).");return void 0===e&&(e=null,n=null),new t(this.repo,this.path,r,this.orderByCalled_)},t.prototype.endAt=function(e,n){void 0===e&&(e=null),Vt("Query.endAt",0,2,arguments.length),nn("Query.endAt",1,e,this.path,!0),un("Query.endAt",2,n,!0);var r=this.queryParams_.endAt(e,n);if(t.validateLimit_(r),t.validateQueryEndpoints_(r),this.queryParams_.hasEnd())throw new Error("Query.endAt: Ending point was already set (by another call to endAt or equalTo).");return new t(this.repo,this.path,r,this.orderByCalled_)},t.prototype.equalTo=function(t,e){if(Vt("Query.equalTo",1,2,arguments.length),nn("Query.equalTo",1,t,this.path,!1),un("Query.equalTo",2,e,!0),this.queryParams_.hasStart())throw new Error("Query.equalTo: Starting point was already set (by another call to startAt or equalTo).");if(this.queryParams_.hasEnd())throw new Error("Query.equalTo: Ending point was already set (by another call to endAt or equalTo).");return this.startAt(t,e).endAt(t,e)},t.prototype.toString=function(){return Vt("Query.toString",0,0,arguments.length),this.repo.toString()+this.path.toUrlEncodedString()},t.prototype.toJSON=function(){return Vt("Query.toJSON",0,1,arguments.length),this.toString()},t.prototype.queryObject=function(){return this.queryParams_.getQueryObject()},t.prototype.queryIdentifier=function(){var t=this.queryObject(),e=Oe(t);return"{}"===e?"default":e},t.prototype.isEqual=function(e){if(Vt("Query.isEqual",1,1,arguments.length),!(e instanceof t)){throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}var n=this.repo===e.repo,r=this.path.equals(e.path),i=this.queryIdentifier()===e.queryIdentifier();return n&&r&&i},t.getCancelAndContextArgs_=function(t,e,n){var r={cancel:null,context:null};if(e&&n)r.cancel=e,Ht(t,3,r.cancel,!0),r.context=n,Kt(t,4,r.context,!0);else if(e)if("object"==typeof e&&null!==e)r.context=e;else{if("function"!=typeof e)throw new Error(qt(t,3,!0)+" must either be a cancel callback or a context object.");r.cancel=e}return r},Object.defineProperty(t.prototype,"ref",{get:function(){return this.getRef()},enumerable:!0,configurable:!0}),t}(),Zn=function(){function t(){this.set={}}return t.prototype.add=function(t,e){this.set[t]=null===e||e},t.prototype.contains=function(t){return At(this.set,t)},t.prototype.get=function(t){return this.contains(t)?this.set[t]:void 0},t.prototype.remove=function(t){delete this.set[t]},t.prototype.clear=function(){this.set={}},t.prototype.isEmpty=function(){return Dt(this.set)},t.prototype.count=function(){return Lt(this.set)},t.prototype.each=function(t){Ot(this.set,function(e,n){return t(e,n)})},t.prototype.keys=function(){var t=[];return Ot(this.set,function(e){t.push(e)}),t},t}(),tr=function(){function t(){this.value_=null,this.children_=null}return t.prototype.find=function(t){if(null!=this.value_)return this.value_.getChild(t);if(t.isEmpty()||null==this.children_)return null;var e=t.getFront();return t=t.popFront(),this.children_.contains(e)?this.children_.get(e).find(t):null},t.prototype.remember=function(e,n){if(e.isEmpty())this.value_=n,this.children_=null;else if(null!==this.value_)this.value_=this.value_.updateChild(e,n);else{null==this.children_&&(this.children_=new Zn);var r=e.getFront();this.children_.contains(r)||this.children_.add(r,new t);var i=this.children_.get(r);e=e.popFront(),i.remember(e,n)}},t.prototype.forget=function(t){if(t.isEmpty())return this.value_=null,this.children_=null,!0;if(null!==this.value_){if(this.value_.isLeafNode())return!1;var e=this.value_;this.value_=null;var n=this;return e.forEachChild(Nn,function(t,e){n.remember(new Be(t),e)}),this.forget(t)}if(null!==this.children_){var r=t.getFront();if(t=t.popFront(),this.children_.contains(r))this.children_.get(r).forget(t)&&this.children_.remove(r);return!!this.children_.isEmpty()&&(this.children_=null,!0)}return!0},t.prototype.forEachTree=function(t,e){null!==this.value_?e(t,this.value_):this.forEachChild(function(n,r){var i=new Be(t.toString()+"/"+n);r.forEachTree(i,e)})},t.prototype.forEachChild=function(t){null!==this.children_&&this.children_.each(function(e,n){t(e,n)})},t}(),er=function(t,e){return t&&"object"==typeof t?(lt(".sv"in t,"Unexpected leaf node or priority contents"),e[t[".sv"]]):t},nr=function(t,e){var n,r=t.getPriority().val(),i=er(r,e);if(t.isLeafNode()){var o=t,a=er(o.getValue(),e);return a!==o.getValue()||i!==o.getPriority().val()?new Cn(a,Vn(i)):t}var s=t;return n=s,i!==s.getPriority().val()&&(n=n.updatePriority(new Cn(i))),s.forEachChild(Nn,function(t,r){var i=nr(r,e);i!==r&&(n=n.updateImmediateChild(t,i))}),n};!function(t){t[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(Hn||(Hn={}));var rr,ir,or=function(){function t(t,e,n,r){this.fromUser=t,this.fromServer=e,this.queryId=n,this.tagged=r,lt(!r||e,"Tagged queries must be from server.")}return t.User=new t(!0,!1,null,!1),t.Server=new t(!1,!0,null,!1),t.forServerTaggedQuery=function(e){return new t(!1,!0,e,!0)},t}(),ar=function(){function t(t,e,n){this.path=t,this.affectedTree=e,this.revert=n,this.type=Hn.ACK_USER_WRITE,this.source=or.User}return t.prototype.operationForChild=function(e){if(this.path.isEmpty()){if(null!=this.affectedTree.value)return lt(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var n=this.affectedTree.subtree(new Be(e));return new t(Be.Empty,n,this.revert)}return lt(this.path.getFront()===e,"operationForChild called for unrelated child."),new t(this.path.popFront(),this.affectedTree,this.revert)},t}(),sr=function(){return rr||(rr=new On(Ae)),rr},ur=function(){function t(t,e){void 0===e&&(e=sr()),this.value=t,this.children=e}return t.fromObject=function(e){var n=t.Empty;return Ot(e,function(t,e){n=n.set(new Be(t),e)}),n},t.prototype.isEmpty=function(){return null===this.value&&this.children.isEmpty()},t.prototype.findRootMostMatchingPathAndValue=function(t,e){if(null!=this.value&&e(this.value))return{path:Be.Empty,value:this.value};if(t.isEmpty())return null;var n=t.getFront(),r=this.children.get(n);if(null!==r){var i=r.findRootMostMatchingPathAndValue(t.popFront(),e);return null!=i?{path:new Be(n).child(i.path),value:i.value}:null}return null},t.prototype.findRootMostValueAndPath=function(t){return this.findRootMostMatchingPathAndValue(t,function(){return!0})},t.prototype.subtree=function(e){if(e.isEmpty())return this;var n=e.getFront(),r=this.children.get(n);return null!==r?r.subtree(e.popFront()):t.Empty},t.prototype.set=function(e,n){if(e.isEmpty())return new t(n,this.children);var r=e.getFront(),i=(this.children.get(r)||t.Empty).set(e.popFront(),n),o=this.children.insert(r,i);return new t(this.value,o)},t.prototype.remove=function(e){if(e.isEmpty())return this.children.isEmpty()?t.Empty:new t(null,this.children);var n=e.getFront(),r=this.children.get(n);if(r){var i=r.remove(e.popFront()),o=void 0;return o=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&o.isEmpty()?t.Empty:new t(this.value,o)}return this},t.prototype.get=function(t){if(t.isEmpty())return this.value;var e=t.getFront(),n=this.children.get(e);return n?n.get(t.popFront()):null},t.prototype.setTree=function(e,n){if(e.isEmpty())return n;var r=e.getFront(),i=(this.children.get(r)||t.Empty).setTree(e.popFront(),n),o=void 0;return o=i.isEmpty()?this.children.remove(r):this.children.insert(r,i),new t(this.value,o)},t.prototype.fold=function(t){return this.fold_(Be.Empty,t)},t.prototype.fold_=function(t,e){var n={};return this.children.inorderTraversal(function(r,i){n[r]=i.fold_(t.child(r),e)}),e(t,this.value,n)},t.prototype.findOnPath=function(t,e){return this.findOnPath_(t,Be.Empty,e)},t.prototype.findOnPath_=function(t,e,n){var r=!!this.value&&n(e,this.value);if(r)return r;if(t.isEmpty())return null;var i=t.getFront(),o=this.children.get(i);return o?o.findOnPath_(t.popFront(),e.child(i),n):null},t.prototype.foreachOnPath=function(t,e){return this.foreachOnPath_(t,Be.Empty,e)},t.prototype.foreachOnPath_=function(e,n,r){if(e.isEmpty())return this;this.value&&r(n,this.value);var i=e.getFront(),o=this.children.get(i);return o?o.foreachOnPath_(e.popFront(),n.child(i),r):t.Empty},t.prototype.foreach=function(t){this.foreach_(Be.Empty,t)},t.prototype.foreach_=function(t,e){this.children.inorderTraversal(function(n,r){r.foreach_(t.child(n),e)}),this.value&&e(t,this.value)},t.prototype.foreachChild=function(t){this.children.inorderTraversal(function(e,n){n.value&&t(e,n.value)})},t.Empty=new t(null),t}(),cr=function(){function t(t,e){this.source=t,this.path=e,this.type=Hn.LISTEN_COMPLETE}return t.prototype.operationForChild=function(e){return this.path.isEmpty()?new t(this.source,Be.Empty):new t(this.source,this.path.popFront())},t}(),hr=function(){function t(t,e,n){this.source=t,this.path=e,this.snap=n,this.type=Hn.OVERWRITE}return t.prototype.operationForChild=function(e){return this.path.isEmpty()?new t(this.source,Be.Empty,this.snap.getImmediateChild(e)):new t(this.source,this.path.popFront(),this.snap)},t}(),lr=function(){function t(t,e,n){this.source=t,this.path=e,this.children=n,this.type=Hn.MERGE}return t.prototype.operationForChild=function(e){if(this.path.isEmpty()){var n=this.children.subtree(new Be(e));return n.isEmpty()?null:n.value?new hr(this.source,Be.Empty,n.value):new t(this.source,Be.Empty,n)}return lt(this.path.getFront()===e,"Can't get a merge for a child not on the path of the operation"),new t(this.source,this.path.popFront(),this.children)},t.prototype.toString=function(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"},t}(),pr=function(){function t(t,e,n){this.node_=t,this.fullyInitialized_=e,this.filtered_=n}return t.prototype.isFullyInitialized=function(){return this.fullyInitialized_},t.prototype.isFiltered=function(){return this.filtered_},t.prototype.isCompleteForPath=function(t){if(t.isEmpty())return this.isFullyInitialized()&&!this.filtered_;var e=t.getFront();return this.isCompleteForChild(e)},t.prototype.isCompleteForChild=function(t){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(t)},t.prototype.getNode=function(){return this.node_},t}(),fr=function(){function t(t,e){this.eventCache_=t,this.serverCache_=e}return t.prototype.updateEventSnap=function(e,n,r){return new t(new pr(e,n,r),this.serverCache_)},t.prototype.updateServerSnap=function(e,n,r){return new t(this.eventCache_,new pr(e,n,r))},t.prototype.getEventCache=function(){return this.eventCache_},t.prototype.getCompleteEventSnap=function(){return this.eventCache_.isFullyInitialized()?this.eventCache_.getNode():null},t.prototype.getServerCache=function(){return this.serverCache_},t.prototype.getCompleteServerSnap=function(){return this.serverCache_.isFullyInitialized()?this.serverCache_.getNode():null},t.Empty=new t(new pr(Wn.EMPTY_NODE,!1,!1),new pr(Wn.EMPTY_NODE,!1,!1)),t}(),dr=function(){function t(t,e,n,r,i){this.type=t,this.snapshotNode=e,this.childName=n,this.oldSnap=r,this.prevName=i}return t.valueChange=function(e){return new t(t.VALUE,e)},t.childAddedChange=function(e,n){return new t(t.CHILD_ADDED,n,e)},t.childRemovedChange=function(e,n){return new t(t.CHILD_REMOVED,n,e)},t.childChangedChange=function(e,n,r){return new t(t.CHILD_CHANGED,n,e,r)},t.childMovedChange=function(e,n){return new t(t.CHILD_MOVED,n,e)},t.CHILD_ADDED="child_added",t.CHILD_REMOVED="child_removed",t.CHILD_CHANGED="child_changed",t.CHILD_MOVED="child_moved",t.VALUE="value",t}(),vr=function(){function t(t){this.index_=t}return t.prototype.updateChild=function(t,e,n,r,i,o){lt(t.isIndexed(this.index_),"A node must be indexed if only a child is updated");var a=t.getImmediateChild(e);return a.getChild(r).equals(n.getChild(r))&&a.isEmpty()==n.isEmpty()?t:(null!=o&&(n.isEmpty()?t.hasChild(e)?o.trackChildChange(dr.childRemovedChange(e,a)):lt(t.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(dr.childAddedChange(e,n)):o.trackChildChange(dr.childChangedChange(e,n,a))),t.isLeafNode()&&n.isEmpty()?t:t.updateImmediateChild(e,n).withIndex(this.index_))},t.prototype.updateFullNode=function(t,e,n){return null!=n&&(t.isLeafNode()||t.forEachChild(Nn,function(t,r){e.hasChild(t)||n.trackChildChange(dr.childRemovedChange(t,r))}),e.isLeafNode()||e.forEachChild(Nn,function(e,r){if(t.hasChild(e)){var i=t.getImmediateChild(e);i.equals(r)||n.trackChildChange(dr.childChangedChange(e,r,i))}else n.trackChildChange(dr.childAddedChange(e,r))})),e.withIndex(this.index_)},t.prototype.updatePriority=function(t,e){return t.isEmpty()?Wn.EMPTY_NODE:t.updatePriority(e)},t.prototype.filtersNodes=function(){return!1},t.prototype.getIndexedFilter=function(){return this},t.prototype.getIndex=function(){return this.index_},t}(),yr=function(){function t(){this.changeMap_={}}return t.prototype.trackChildChange=function(t){var e=t.type,n=t.childName;lt(e==dr.CHILD_ADDED||e==dr.CHILD_CHANGED||e==dr.CHILD_REMOVED,"Only child changes supported for tracking"),lt(".priority"!==n,"Only non-priority child changes can be tracked.");var r=kt(this.changeMap_,n);if(r){var i=r.type;if(e==dr.CHILD_ADDED&&i==dr.CHILD_REMOVED)this.changeMap_[n]=dr.childChangedChange(n,t.snapshotNode,r.snapshotNode);else if(e==dr.CHILD_REMOVED&&i==dr.CHILD_ADDED)delete this.changeMap_[n];else if(e==dr.CHILD_REMOVED&&i==dr.CHILD_CHANGED)this.changeMap_[n]=dr.childRemovedChange(n,r.oldSnap);else if(e==dr.CHILD_CHANGED&&i==dr.CHILD_ADDED)this.changeMap_[n]=dr.childAddedChange(n,t.snapshotNode);else{if(e!=dr.CHILD_CHANGED||i!=dr.CHILD_CHANGED)throw pt("Illegal combination of changes: "+t+" occurred after "+r);this.changeMap_[n]=dr.childChangedChange(n,t.snapshotNode,r.oldSnap)}}else this.changeMap_[n]=t},t.prototype.getChanges=function(){return function(t){var e=[],n=0;for(var r in t)e[n++]=t[r];return e}(this.changeMap_)},t}(),_r=new(function(){function t(){}return t.prototype.getCompleteChild=function(t){return null},t.prototype.getChildAfterChild=function(t,e,n){return null},t}()),gr=function(){function t(t,e,n){void 0===n&&(n=null),this.writes_=t,this.viewCache_=e,this.optCompleteServerCache_=n}return t.prototype.getCompleteChild=function(t){var e=this.viewCache_.getEventCache();if(e.isCompleteForChild(t))return e.getNode().getImmediateChild(t);var n=null!=this.optCompleteServerCache_?new pr(this.optCompleteServerCache_,!0,!1):this.viewCache_.getServerCache();return this.writes_.calcCompleteChild(t,n)},t.prototype.getChildAfterChild=function(t,e,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:this.viewCache_.getCompleteServerSnap(),i=this.writes_.calcIndexedSlice(r,e,1,n,t);return 0===i.length?null:i[0]},t}(),mr=function(){return function(t,e){this.viewCache=t,this.changes=e}}(),br=function(){function t(t){this.filter_=t}return t.prototype.assertIndexed=function(t){lt(t.getEventCache().getNode().isIndexed(this.filter_.getIndex()),"Event snap not indexed"),lt(t.getServerCache().getNode().isIndexed(this.filter_.getIndex()),"Server snap not indexed")},t.prototype.applyOperation=function(e,n,r,i){var o,a,s=new yr;if(n.type===Hn.OVERWRITE){var u=n;u.source.fromUser?o=this.applyUserOverwrite_(e,u.path,u.snap,r,i,s):(lt(u.source.fromServer,"Unknown source."),a=u.source.tagged||e.getServerCache().isFiltered()&&!u.path.isEmpty(),o=this.applyServerOverwrite_(e,u.path,u.snap,r,i,a,s))}else if(n.type===Hn.MERGE){var c=n;c.source.fromUser?o=this.applyUserMerge_(e,c.path,c.children,r,i,s):(lt(c.source.fromServer,"Unknown source."),a=c.source.tagged||e.getServerCache().isFiltered(),o=this.applyServerMerge_(e,c.path,c.children,r,i,a,s))}else if(n.type===Hn.ACK_USER_WRITE){var h=n;o=h.revert?this.revertUserWrite_(e,h.path,r,i,s):this.ackUserWrite_(e,h.path,h.affectedTree,r,i,s)}else{if(n.type!==Hn.LISTEN_COMPLETE)throw pt("Unknown operation type: "+n.type);o=this.listenComplete_(e,n.path,r,s)}var l=s.getChanges();return t.maybeAddValueEvent_(e,o,l),new mr(o,l)},t.maybeAddValueEvent_=function(t,e,n){var r=e.getEventCache();if(r.isFullyInitialized()){var i=r.getNode().isLeafNode()||r.getNode().isEmpty(),o=t.getCompleteEventSnap();(n.length>0||!t.getEventCache().isFullyInitialized()||i&&!r.getNode().equals(o)||!r.getNode().getPriority().equals(o.getPriority()))&&n.push(dr.valueChange(e.getCompleteEventSnap()))}},t.prototype.generateEventCacheAfterServerEvent_=function(t,e,n,r,i){var o=t.getEventCache();if(null!=n.shadowingWrite(e))return t;var a=void 0,s=void 0;if(e.isEmpty())if(lt(t.getServerCache().isFullyInitialized(),"If change path is empty, we must have complete server data"),t.getServerCache().isFiltered()){var u=t.getCompleteServerSnap(),c=u instanceof Wn?u:Wn.EMPTY_NODE,h=n.calcCompleteEventChildren(c);a=this.filter_.updateFullNode(t.getEventCache().getNode(),h,i)}else{var l=n.calcCompleteEventCache(t.getCompleteServerSnap());a=this.filter_.updateFullNode(t.getEventCache().getNode(),l,i)}else{var p=e.getFront();if(".priority"==p){lt(1==e.getLength(),"Can't have a priority with additional path components");var f=o.getNode();s=t.getServerCache().getNode();var d=n.calcEventCacheAfterServerOverwrite(e,f,s);a=null!=d?this.filter_.updatePriority(f,d):o.getNode()}else{var v=e.popFront(),y=void 0;if(o.isCompleteForChild(p)){s=t.getServerCache().getNode();var _=n.calcEventCacheAfterServerOverwrite(e,o.getNode(),s);y=null!=_?o.getNode().getImmediateChild(p).updateChild(v,_):o.getNode().getImmediateChild(p)}else y=n.calcCompleteChild(p,t.getServerCache());a=null!=y?this.filter_.updateChild(o.getNode(),p,y,v,r,i):o.getNode()}}return t.updateEventSnap(a,o.isFullyInitialized()||e.isEmpty(),this.filter_.filtersNodes())},t.prototype.applyServerOverwrite_=function(t,e,n,r,i,o,a){var s,u=t.getServerCache(),c=o?this.filter_:this.filter_.getIndexedFilter();if(e.isEmpty())s=c.updateFullNode(u.getNode(),n,null);else if(c.filtersNodes()&&!u.isFiltered()){var h=u.getNode().updateChild(e,n);s=c.updateFullNode(u.getNode(),h,null)}else{var l=e.getFront();if(!u.isCompleteForPath(e)&&e.getLength()>1)return t;var p=e.popFront(),f=u.getNode().getImmediateChild(l).updateChild(p,n);s=".priority"==l?c.updatePriority(u.getNode(),f):c.updateChild(u.getNode(),l,f,p,_r,null)}var d=t.updateServerSnap(s,u.isFullyInitialized()||e.isEmpty(),c.filtersNodes()),v=new gr(r,d,i);return this.generateEventCacheAfterServerEvent_(d,e,r,v,a)},t.prototype.applyUserOverwrite_=function(t,e,n,r,i,o){var a,s,u=t.getEventCache(),c=new gr(r,t,i);if(e.isEmpty())s=this.filter_.updateFullNode(t.getEventCache().getNode(),n,o),a=t.updateEventSnap(s,!0,this.filter_.filtersNodes());else{var h=e.getFront();if(".priority"===h)s=this.filter_.updatePriority(t.getEventCache().getNode(),n),a=t.updateEventSnap(s,u.isFullyInitialized(),u.isFiltered());else{var l=e.popFront(),p=u.getNode().getImmediateChild(h),f=void 0;if(l.isEmpty())f=n;else{var d=c.getCompleteChild(h);f=null!=d?".priority"===l.getBack()&&d.getChild(l.parent()).isEmpty()?d:d.updateChild(l,n):Wn.EMPTY_NODE}if(p.equals(f))a=t;else{var v=this.filter_.updateChild(u.getNode(),h,f,l,c,o);a=t.updateEventSnap(v,u.isFullyInitialized(),this.filter_.filtersNodes())}}}return a},t.cacheHasChild_=function(t,e){return t.getEventCache().isCompleteForChild(e)},t.prototype.applyUserMerge_=function(e,n,r,i,o,a){var s=this,u=e;return r.foreach(function(r,c){var h=n.child(r);t.cacheHasChild_(e,h.getFront())&&(u=s.applyUserOverwrite_(u,h,c,i,o,a))}),r.foreach(function(r,c){var h=n.child(r);t.cacheHasChild_(e,h.getFront())||(u=s.applyUserOverwrite_(u,h,c,i,o,a))}),u},t.prototype.applyMerge_=function(t,e){return e.foreach(function(e,n){t=t.updateChild(e,n)}),t},t.prototype.applyServerMerge_=function(t,e,n,r,i,o,a){var s=this;if(t.getServerCache().getNode().isEmpty()&&!t.getServerCache().isFullyInitialized())return t;var u,c=t;u=e.isEmpty()?n:ur.Empty.setTree(e,n);var h=t.getServerCache().getNode();return u.children.inorderTraversal(function(e,n){if(h.hasChild(e)){var u=t.getServerCache().getNode().getImmediateChild(e),l=s.applyMerge_(u,n);c=s.applyServerOverwrite_(c,new Be(e),l,r,i,o,a)}}),u.children.inorderTraversal(function(e,n){var u=!t.getServerCache().isCompleteForChild(e)&&null==n.value;if(!h.hasChild(e)&&!u){var l=t.getServerCache().getNode().getImmediateChild(e),p=s.applyMerge_(l,n);c=s.applyServerOverwrite_(c,new Be(e),p,r,i,o,a)}}),c},t.prototype.ackUserWrite_=function(t,e,n,r,i,o){if(null!=r.shadowingWrite(e))return t;var a=t.getServerCache().isFiltered(),s=t.getServerCache();if(null!=n.value){if(e.isEmpty()&&s.isFullyInitialized()||s.isCompleteForPath(e))return this.applyServerOverwrite_(t,e,s.getNode().getChild(e),r,i,a,o);if(e.isEmpty()){var u=ur.Empty;return s.getNode().forEachChild(gn,function(t,e){u=u.set(new Be(t),e)}),this.applyServerMerge_(t,e,u,r,i,a,o)}return t}var c=ur.Empty;return n.foreach(function(t,n){var r=e.child(t);s.isCompleteForPath(r)&&(c=c.set(t,s.getNode().getChild(r)))}),this.applyServerMerge_(t,e,c,r,i,a,o)},t.prototype.listenComplete_=function(t,e,n,r){var i=t.getServerCache(),o=t.updateServerSnap(i.getNode(),i.isFullyInitialized()||e.isEmpty(),i.isFiltered());return this.generateEventCacheAfterServerEvent_(o,e,n,_r,r)},t.prototype.revertUserWrite_=function(t,e,n,r,i){var o;if(null!=n.shadowingWrite(e))return t;var a=new gr(n,t,r),s=t.getEventCache().getNode(),u=void 0;if(e.isEmpty()||".priority"===e.getFront()){var c=void 0;if(t.getServerCache().isFullyInitialized())c=n.calcCompleteEventCache(t.getCompleteServerSnap());else{var h=t.getServerCache().getNode();lt(h instanceof Wn,"serverChildren would be complete if leaf node"),c=n.calcCompleteEventChildren(h)}c=c,u=this.filter_.updateFullNode(s,c,i)}else{var l=e.getFront(),p=n.calcCompleteChild(l,t.getServerCache());null==p&&t.getServerCache().isCompleteForChild(l)&&(p=s.getImmediateChild(l)),(u=null!=p?this.filter_.updateChild(s,l,p,e.popFront(),a,i):t.getEventCache().getNode().hasChild(l)?this.filter_.updateChild(s,l,Wn.EMPTY_NODE,e.popFront(),a,i):s).isEmpty()&&t.getServerCache().isFullyInitialized()&&(o=n.calcCompleteEventCache(t.getCompleteServerSnap())).isLeafNode()&&(u=this.filter_.updateFullNode(u,o,i))}return o=t.getServerCache().isFullyInitialized()||null!=n.shadowingWrite(Be.Empty),t.updateEventSnap(u,o,this.filter_.filtersNodes())},t}(),wr=function(){function t(t){this.query_=t,this.index_=this.query_.getQueryParams().getIndex()}return t.prototype.generateEventsForChanges=function(t,e,n){var r=this,i=[],o=[];return t.forEach(function(t){t.type===dr.CHILD_CHANGED&&r.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&o.push(dr.childMovedChange(t.childName,t.snapshotNode))}),this.generateEventsForType_(i,dr.CHILD_REMOVED,t,n,e),this.generateEventsForType_(i,dr.CHILD_ADDED,t,n,e),this.generateEventsForType_(i,dr.CHILD_MOVED,o,n,e),this.generateEventsForType_(i,dr.CHILD_CHANGED,t,n,e),this.generateEventsForType_(i,dr.VALUE,t,n,e),i},t.prototype.generateEventsForType_=function(t,e,n,r,i){var o=this,a=n.filter(function(t){return t.type===e});a.sort(this.compareChanges_.bind(this)),a.forEach(function(e){var n=o.materializeSingleChange_(e,i);r.forEach(function(r){r.respondsTo(e.type)&&t.push(r.createEvent(n,o.query_))})})},t.prototype.materializeSingleChange_=function(t,e){return"value"===t.type||"child_removed"===t.type?t:(t.prevName=e.getPredecessorChildName(t.childName,t.snapshotNode,this.index_),t)},t.prototype.compareChanges_=function(t,e){if(null==t.childName||null==e.childName)throw pt("Should only compare child_ events.");var n=new vn(t.childName,t.snapshotNode),r=new vn(e.childName,e.snapshotNode);return this.index_.compare(n,r)},t}(),Er=function(){function t(t,e){this.query_=t,this.eventRegistrations_=[];var n=this.query_.getQueryParams(),r=new vr(n.getIndex()),i=n.getNodeFilter();this.processor_=new br(i);var o=e.getServerCache(),a=e.getEventCache(),s=r.updateFullNode(Wn.EMPTY_NODE,o.getNode(),null),u=i.updateFullNode(Wn.EMPTY_NODE,a.getNode(),null),c=new pr(s,o.isFullyInitialized(),r.filtersNodes()),h=new pr(u,a.isFullyInitialized(),i.filtersNodes());this.viewCache_=new fr(h,c),this.eventGenerator_=new wr(this.query_)}return t.prototype.getQuery=function(){return this.query_},t.prototype.getServerCache=function(){return this.viewCache_.getServerCache().getNode()},t.prototype.getCompleteServerCache=function(t){var e=this.viewCache_.getCompleteServerSnap();return e&&(this.query_.getQueryParams().loadsAllData()||!t.isEmpty()&&!e.getImmediateChild(t.getFront()).isEmpty())?e.getChild(t):null},t.prototype.isEmpty=function(){return 0===this.eventRegistrations_.length},t.prototype.addEventRegistration=function(t){this.eventRegistrations_.push(t)},t.prototype.removeEventRegistration=function(t,e){var n=[];if(e){lt(null==t,"A cancel should cancel all event registrations.");var r=this.query_.path;this.eventRegistrations_.forEach(function(t){e=e;var i=t.createCancelEvent(e,r);i&&n.push(i)})}if(t){for(var i=[],o=0;o<this.eventRegistrations_.length;++o){var a=this.eventRegistrations_[o];if(a.matches(t)){if(t.hasAnyCallback()){i=i.concat(this.eventRegistrations_.slice(o+1));break}}else i.push(a)}this.eventRegistrations_=i}else this.eventRegistrations_=[];return n},t.prototype.applyOperation=function(t,e,n){t.type===Hn.MERGE&&null!==t.source.queryId&&(lt(this.viewCache_.getCompleteServerSnap(),"We should always have a full cache before handling merges"),lt(this.viewCache_.getCompleteEventSnap(),"Missing event cache, even though we have a server cache"));var r=this.viewCache_,i=this.processor_.applyOperation(r,t,e,n);return this.processor_.assertIndexed(i.viewCache),lt(i.viewCache.getServerCache().isFullyInitialized()||!r.getServerCache().isFullyInitialized(),"Once a server snap is complete, it should never go back"),this.viewCache_=i.viewCache,this.generateEventsForChanges_(i.changes,i.viewCache.getEventCache().getNode(),null)},t.prototype.getInitialEvents=function(t){var e=this.viewCache_.getEventCache(),n=[];e.getNode().isLeafNode()||e.getNode().forEachChild(Nn,function(t,e){n.push(dr.childAddedChange(t,e))});return e.isFullyInitialized()&&n.push(dr.valueChange(e.getNode())),this.generateEventsForChanges_(n,e.getNode(),t)},t.prototype.generateEventsForChanges_=function(t,e,n){var r=n?[n]:this.eventRegistrations_;return this.eventGenerator_.generateEventsForChanges(t,e,r)},t}(),Tr=function(){function t(){this.views_={}}return Object.defineProperty(t,"__referenceConstructor",{get:function(){return lt(ir,"Reference.ts has not been loaded"),ir},set:function(t){lt(!ir,"__referenceConstructor has already been defined"),ir=t},enumerable:!0,configurable:!0}),t.prototype.isEmpty=function(){return Dt(this.views_)},t.prototype.applyOperation=function(t,e,n){var r=t.source.queryId;if(null!==r){var i=kt(this.views_,r);return lt(null!=i,"SyncTree gave us an op for an invalid query."),i.applyOperation(t,e,n)}var o=[];return Ot(this.views_,function(r,i){o=o.concat(i.applyOperation(t,e,n))}),o},t.prototype.addEventRegistration=function(t,e,n,r,i){var o=t.queryIdentifier(),a=kt(this.views_,o);if(!a){var s=n.calcCompleteEventCache(i?r:null),u=!1;s?u=!0:r instanceof Wn?(s=n.calcCompleteEventChildren(r),u=!1):(s=Wn.EMPTY_NODE,u=!1);var c=new fr(new pr(s,u,!1),new pr(r,i,!1));a=new Er(t,c),this.views_[o]=a}return a.addEventRegistration(e),a.getInitialEvents(e)},t.prototype.removeEventRegistration=function(e,n,r){var i=e.queryIdentifier(),o=[],a=[],s=this.hasCompleteView();if("default"===i){var u=this;Ot(this.views_,function(t,e){a=a.concat(e.removeEventRegistration(n,r)),e.isEmpty()&&(delete u.views_[t],e.getQuery().getQueryParams().loadsAllData()||o.push(e.getQuery()))})}else{var c=kt(this.views_,i);c&&(a=a.concat(c.removeEventRegistration(n,r)),c.isEmpty()&&(delete this.views_[i],c.getQuery().getQueryParams().loadsAllData()||o.push(c.getQuery())))}return s&&!this.hasCompleteView()&&o.push(new t.__referenceConstructor(e.repo,e.path)),{removed:o,events:a}},t.prototype.getQueryViews=function(){var t=this;return Object.keys(this.views_).map(function(e){return t.views_[e]}).filter(function(t){return!t.getQuery().getQueryParams().loadsAllData()})},t.prototype.getCompleteServerCache=function(t){var e=null;return Ot(this.views_,function(n,r){e=e||r.getCompleteServerCache(t)}),e},t.prototype.viewForQuery=function(t){if(t.getQueryParams().loadsAllData())return this.getCompleteView();var e=t.queryIdentifier();return kt(this.views_,e)},t.prototype.viewExistsForQuery=function(t){return null!=this.viewForQuery(t)},t.prototype.hasCompleteView=function(){return null!=this.getCompleteView()},t.prototype.getCompleteView=function(){var t,e,n;return(t=this.views_,(n=Ft(t,function(t){return t.getQuery().getQueryParams().loadsAllData()},e))&&t[n])||null},t}(),Cr=function(){function t(t){this.writeTree_=t}return t.prototype.addWrite=function(e,n){if(e.isEmpty())return new t(new ur(n));var r=this.writeTree_.findRootMostValueAndPath(e);if(null!=r){var i=r.path,o=r.value,a=Be.relativePath(i,e);return o=o.updateChild(a,n),new t(this.writeTree_.set(i,o))}var s=new ur(n);return new t(this.writeTree_.setTree(e,s))},t.prototype.addWrites=function(t,e){var n=this;return Ot(e,function(e,r){n=n.addWrite(t.child(e),r)}),n},t.prototype.removeWrite=function(e){return e.isEmpty()?t.Empty:new t(this.writeTree_.setTree(e,ur.Empty))},t.prototype.hasCompleteWrite=function(t){return null!=this.getCompleteNode(t)},t.prototype.getCompleteNode=function(t){var e=this.writeTree_.findRootMostValueAndPath(t);return null!=e?this.writeTree_.get(e.path).getChild(Be.relativePath(e.path,t)):null},t.prototype.getCompleteChildren=function(){var t=[],e=this.writeTree_.value;return null!=e?e.isLeafNode()||e.forEachChild(Nn,function(e,n){t.push(new vn(e,n))}):this.writeTree_.children.inorderTraversal(function(e,n){null!=n.value&&t.push(new vn(e,n.value))}),t},t.prototype.childCompoundWrite=function(e){if(e.isEmpty())return this;var n=this.getCompleteNode(e);return new t(null!=n?new ur(n):this.writeTree_.subtree(e))},t.prototype.isEmpty=function(){return this.writeTree_.isEmpty()},t.prototype.apply=function(e){return t.applySubtreeWrite_(Be.Empty,this.writeTree_,e)},t.Empty=new t(new ur(null)),t.applySubtreeWrite_=function(e,n,r){if(null!=n.value)return r.updateChild(e,n.value);var i=null;return n.children.inorderTraversal(function(n,o){".priority"===n?(lt(null!==o.value,"Priority writes must always be leaf nodes"),i=o.value):r=t.applySubtreeWrite_(e.child(n),o,r)}),r.getChild(e).isEmpty()||null===i||(r=r.updateChild(e.child(".priority"),i)),r},t}(),Sr=function(){function t(){this.visibleWrites_=Cr.Empty,this.allWrites_=[],this.lastWriteId_=-1}return t.prototype.childWrites=function(t){return new Ir(t,this)},t.prototype.addOverwrite=function(t,e,n,r){lt(n>this.lastWriteId_,"Stacking an older write on top of newer ones"),void 0===r&&(r=!0),this.allWrites_.push({path:t,snap:e,writeId:n,visible:r}),r&&(this.visibleWrites_=this.visibleWrites_.addWrite(t,e)),this.lastWriteId_=n},t.prototype.addMerge=function(t,e,n){lt(n>this.lastWriteId_,"Stacking an older merge on top of newer ones"),this.allWrites_.push({path:t,children:e,writeId:n,visible:!0}),this.visibleWrites_=this.visibleWrites_.addWrites(t,e),this.lastWriteId_=n},t.prototype.getWrite=function(t){for(var e=0;e<this.allWrites_.length;e++){var n=this.allWrites_[e];if(n.writeId===t)return n}return null},t.prototype.removeWrite=function(t){var e=this,n=this.allWrites_.findIndex(function(e){return e.writeId===t});lt(n>=0,"removeWrite called with nonexistent writeId.");var r=this.allWrites_[n];this.allWrites_.splice(n,1);for(var i=r.visible,o=!1,a=this.allWrites_.length-1;i&&a>=0;){var s=this.allWrites_[a];s.visible&&(a>=n&&this.recordContainsPath_(s,r.path)?i=!1:r.path.contains(s.path)&&(o=!0)),a--}if(i){if(o)return this.resetTree_(),!0;if(r.snap)this.visibleWrites_=this.visibleWrites_.removeWrite(r.path);else{var u=r.children;Ot(u,function(t){e.visibleWrites_=e.visibleWrites_.removeWrite(r.path.child(t))})}return!0}return!1},t.prototype.getCompleteWriteData=function(t){return this.visibleWrites_.getCompleteNode(t)},t.prototype.calcCompleteEventCache=function(e,n,r,i){if(r||i){var o=this.visibleWrites_.childCompoundWrite(e);if(!i&&o.isEmpty())return n;if(i||null!=n||o.hasCompleteWrite(Be.Empty)){var a=t.layerTree_(this.allWrites_,function(t){return(t.visible||i)&&(!r||!~r.indexOf(t.writeId))&&(t.path.contains(e)||e.contains(t.path))},e);c=n||Wn.EMPTY_NODE;return a.apply(c)}return null}var s=this.visibleWrites_.getCompleteNode(e);if(null!=s)return s;var u=this.visibleWrites_.childCompoundWrite(e);if(u.isEmpty())return n;if(null!=n||u.hasCompleteWrite(Be.Empty)){var c=n||Wn.EMPTY_NODE;return u.apply(c)}return null},t.prototype.calcCompleteEventChildren=function(t,e){var n=Wn.EMPTY_NODE,r=this.visibleWrites_.getCompleteNode(t);if(r)return r.isLeafNode()||r.forEachChild(Nn,function(t,e){n=n.updateImmediateChild(t,e)}),n;if(e){var i=this.visibleWrites_.childCompoundWrite(t);return e.forEachChild(Nn,function(t,e){var r=i.childCompoundWrite(new Be(t)).apply(e);n=n.updateImmediateChild(t,r)}),i.getCompleteChildren().forEach(function(t){n=n.updateImmediateChild(t.name,t.node)}),n}return this.visibleWrites_.childCompoundWrite(t).getCompleteChildren().forEach(function(t){n=n.updateImmediateChild(t.name,t.node)}),n},t.prototype.calcEventCacheAfterServerOverwrite=function(t,e,n,r){lt(n||r,"Either existingEventSnap or existingServerSnap must exist");var i=t.child(e);if(this.visibleWrites_.hasCompleteWrite(i))return null;var o=this.visibleWrites_.childCompoundWrite(i);return o.isEmpty()?r.getChild(e):o.apply(r.getChild(e))},t.prototype.calcCompleteChild=function(t,e,n){var r=t.child(e),i=this.visibleWrites_.getCompleteNode(r);return null!=i?i:n.isCompleteForChild(e)?this.visibleWrites_.childCompoundWrite(r).apply(n.getNode().getImmediateChild(e)):null},t.prototype.shadowingWrite=function(t){return this.visibleWrites_.getCompleteNode(t)},t.prototype.calcIndexedSlice=function(t,e,n,r,i,o){var a,s=this.visibleWrites_.childCompoundWrite(t),u=s.getCompleteNode(Be.Empty);if(null!=u)a=u;else{if(null==e)return[];a=s.apply(e)}if((a=a.withIndex(o)).isEmpty()||a.isLeafNode())return[];for(var c=[],h=o.getCompare(),l=i?a.getReverseIteratorFrom(n,o):a.getIteratorFrom(n,o),p=l.getNext();p&&c.length<r;)0!==h(p,n)&&c.push(p),p=l.getNext();return c},t.prototype.recordContainsPath_=function(t,e){return t.snap?t.path.contains(e):!!Ft(t.children,function(n,r){return t.path.child(r).contains(e)})},t.prototype.resetTree_=function(){this.visibleWrites_=t.layerTree_(this.allWrites_,t.DefaultFilter_,Be.Empty),this.allWrites_.length>0?this.lastWriteId_=this.allWrites_[this.allWrites_.length-1].writeId:this.lastWriteId_=-1},t.DefaultFilter_=function(t){return t.visible},t.layerTree_=function(t,e,n){for(var r=Cr.Empty,i=0;i<t.length;++i){var o=t[i];if(e(o)){var a=o.path,s=void 0;if(o.snap)n.contains(a)?(s=Be.relativePath(n,a),r=r.addWrite(s,o.snap)):a.contains(n)&&(s=Be.relativePath(a,n),r=r.addWrite(Be.Empty,o.snap.getChild(s)));else{if(!o.children)throw pt("WriteRecord should have .snap or .children");if(n.contains(a))s=Be.relativePath(n,a),r=r.addWrites(s,o.children);else if(a.contains(n))if((s=Be.relativePath(a,n)).isEmpty())r=r.addWrites(Be.Empty,o.children);else{var u=kt(o.children,s.getFront());if(u){var c=u.getChild(s.popFront());r=r.addWrite(Be.Empty,c)}}}}}return r},t}(),Ir=function(){function t(t,e){this.treePath_=t,this.writeTree_=e}return t.prototype.calcCompleteEventCache=function(t,e,n){return this.writeTree_.calcCompleteEventCache(this.treePath_,t,e,n)},t.prototype.calcCompleteEventChildren=function(t){return this.writeTree_.calcCompleteEventChildren(this.treePath_,t)},t.prototype.calcEventCacheAfterServerOverwrite=function(t,e,n){return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_,t,e,n)},t.prototype.shadowingWrite=function(t){return this.writeTree_.shadowingWrite(this.treePath_.child(t))},t.prototype.calcIndexedSlice=function(t,e,n,r,i){return this.writeTree_.calcIndexedSlice(this.treePath_,t,e,n,r,i)},t.prototype.calcCompleteChild=function(t,e){return this.writeTree_.calcCompleteChild(this.treePath_,t,e)},t.prototype.child=function(e){return new t(this.treePath_.child(e),this.writeTree_)},t}(),Nr=function(){function t(t){this.listenProvider_=t,this.syncPointTree_=ur.Empty,this.pendingWriteTree_=new Sr,this.tagToQueryMap_={},this.queryToTagMap_={}}return t.prototype.applyUserOverwrite=function(t,e,n,r){return this.pendingWriteTree_.addOverwrite(t,e,n,r),r?this.applyOperationToSyncPoints_(new hr(or.User,t,e)):[]},t.prototype.applyUserMerge=function(t,e,n){this.pendingWriteTree_.addMerge(t,e,n);var r=ur.fromObject(e);return this.applyOperationToSyncPoints_(new lr(or.User,t,r))},t.prototype.ackUserWrite=function(t,e){void 0===e&&(e=!1);var n=this.pendingWriteTree_.getWrite(t);if(this.pendingWriteTree_.removeWrite(t)){var r=ur.Empty;return null!=n.snap?r=r.set(Be.Empty,!0):Ot(n.children,function(t,e){r=r.set(new Be(t),e)}),this.applyOperationToSyncPoints_(new ar(n.path,r,e))}return[]},t.prototype.applyServerOverwrite=function(t,e){return this.applyOperationToSyncPoints_(new hr(or.Server,t,e))},t.prototype.applyServerMerge=function(t,e){var n=ur.fromObject(e);return this.applyOperationToSyncPoints_(new lr(or.Server,t,n))},t.prototype.applyListenComplete=function(t){return this.applyOperationToSyncPoints_(new cr(or.Server,t))},t.prototype.applyTaggedQueryOverwrite=function(e,n,r){var i=this.queryKeyForTag_(r);if(null!=i){var o=t.parseQueryKey_(i),a=o.path,s=o.queryId,u=Be.relativePath(a,e),c=new hr(or.forServerTaggedQuery(s),u,n);return this.applyTaggedOperation_(a,c)}return[]},t.prototype.applyTaggedQueryMerge=function(e,n,r){var i=this.queryKeyForTag_(r);if(i){var o=t.parseQueryKey_(i),a=o.path,s=o.queryId,u=Be.relativePath(a,e),c=ur.fromObject(n),h=new lr(or.forServerTaggedQuery(s),u,c);return this.applyTaggedOperation_(a,h)}return[]},t.prototype.applyTaggedListenComplete=function(e,n){var r=this.queryKeyForTag_(n);if(r){var i=t.parseQueryKey_(r),o=i.path,a=i.queryId,s=Be.relativePath(o,e),u=new cr(or.forServerTaggedQuery(a),s);return this.applyTaggedOperation_(o,u)}return[]},t.prototype.addEventRegistration=function(e,n){var r=e.path,i=null,o=!1;this.syncPointTree_.foreachOnPath(r,function(t,e){var n=Be.relativePath(t,r);i=i||e.getCompleteServerCache(n),o=o||e.hasCompleteView()});var a,s=this.syncPointTree_.get(r);(s?(o=o||s.hasCompleteView(),i=i||s.getCompleteServerCache(Be.Empty)):(s=new Tr,this.syncPointTree_=this.syncPointTree_.set(r,s)),null!=i)?a=!0:(a=!1,i=Wn.EMPTY_NODE,this.syncPointTree_.subtree(r).foreachChild(function(t,e){var n=e.getCompleteServerCache(Be.Empty);n&&(i=i.updateImmediateChild(t,n))}));var u=s.viewExistsForQuery(e);if(!u&&!e.getQueryParams().loadsAllData()){var c=t.makeQueryKey_(e);lt(!(c in this.queryToTagMap_),"View does not exist, but we have a tag");var h=t.getNextQueryTag_();this.queryToTagMap_[c]=h,this.tagToQueryMap_["_"+h]=c}var l=this.pendingWriteTree_.childWrites(r),p=s.addEventRegistration(e,n,l,i,a);if(!u&&!o){var f=s.viewForQuery(e);p=p.concat(this.setupListener_(e,f))}return p},t.prototype.removeEventRegistration=function(e,n,r){var i=this,o=e.path,a=this.syncPointTree_.get(o),s=[];if(a&&("default"===e.queryIdentifier()||a.viewExistsForQuery(e))){var u=a.removeEventRegistration(e,n,r);a.isEmpty()&&(this.syncPointTree_=this.syncPointTree_.remove(o));var c=u.removed;s=u.events;var h=-1!==c.findIndex(function(t){return t.getQueryParams().loadsAllData()}),l=this.syncPointTree_.findOnPath(o,function(t,e){return e.hasCompleteView()});if(h&&!l){var p=this.syncPointTree_.subtree(o);if(!p.isEmpty())for(var f=this.collectDistinctViewsForSubTree_(p),d=0;d<f.length;++d){var v=f[d],y=v.getQuery(),_=this.createListenerForView_(v);this.listenProvider_.startListening(t.queryForListening_(y),this.tagForQuery_(y),_.hashFn,_.onComplete)}}if(!l&&c.length>0&&!r)if(h){this.listenProvider_.stopListening(t.queryForListening_(e),null)}else c.forEach(function(e){var n=i.queryToTagMap_[t.makeQueryKey_(e)];i.listenProvider_.stopListening(t.queryForListening_(e),n)});this.removeTags_(c)}return s},t.prototype.calcCompleteEventCache=function(t,e){var n=this.pendingWriteTree_,r=this.syncPointTree_.findOnPath(t,function(e,n){var r=Be.relativePath(e,t),i=n.getCompleteServerCache(r);if(i)return i});return n.calcCompleteEventCache(t,r,e,!0)},t.prototype.collectDistinctViewsForSubTree_=function(t){return t.fold(function(t,e,n){if(e&&e.hasCompleteView())return[e.getCompleteView()];var r=[];return e&&(r=e.getQueryViews()),Ot(n,function(t,e){r=r.concat(e)}),r})},t.prototype.removeTags_=function(e){for(var n=0;n<e.length;++n){var r=e[n];if(!r.getQueryParams().loadsAllData()){var i=t.makeQueryKey_(r),o=this.queryToTagMap_[i];delete this.queryToTagMap_[i],delete this.tagToQueryMap_["_"+o]}}},t.queryForListening_=function(t){return t.getQueryParams().loadsAllData()&&!t.getQueryParams().isDefault()?t.getRef():t},t.prototype.setupListener_=function(e,n){var r=e.path,i=this.tagForQuery_(e),o=this.createListenerForView_(n),a=this.listenProvider_.startListening(t.queryForListening_(e),i,o.hashFn,o.onComplete),s=this.syncPointTree_.subtree(r);if(i)lt(!s.value.hasCompleteView(),"If we're adding a query, it shouldn't be shadowed");else for(var u=s.fold(function(t,e,n){if(!t.isEmpty()&&e&&e.hasCompleteView())return[e.getCompleteView().getQuery()];var r=[];return e&&(r=r.concat(e.getQueryViews().map(function(t){return t.getQuery()}))),Ot(n,function(t,e){r=r.concat(e)}),r}),c=0;c<u.length;++c){var h=u[c];this.listenProvider_.stopListening(t.queryForListening_(h),this.tagForQuery_(h))}return a},t.prototype.createListenerForView_=function(t){var e=this,n=t.getQuery(),r=this.tagForQuery_(n);return{hashFn:function(){return(t.getServerCache()||Wn.EMPTY_NODE).hash()},onComplete:function(t){if("ok"===t)return r?e.applyTaggedListenComplete(n.path,r):e.applyListenComplete(n.path);var i=function(t,e){var n="Unknown Error";"too_big"===t?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"==t?n="Client doesn't have permission to access the desired data.":"unavailable"==t&&(n="The service is unavailable");var r=new Error(t+" at "+e.path.toString()+": "+n);return r.code=t.toUpperCase(),r}(t,n);return e.removeEventRegistration(n,null,i)}}},t.makeQueryKey_=function(t){return t.path.toString()+"$"+t.queryIdentifier()},t.parseQueryKey_=function(t){var e=t.indexOf("$");return lt(-1!==e&&e<t.length-1,"Bad queryKey."),{queryId:t.substr(e+1),path:new Be(t.substr(0,e))}},t.prototype.queryKeyForTag_=function(t){return this.tagToQueryMap_["_"+t]},t.prototype.tagForQuery_=function(e){var n=t.makeQueryKey_(e);return kt(this.queryToTagMap_,n)},t.getNextQueryTag_=function(){return t.nextQueryTag_++},t.prototype.applyTaggedOperation_=function(t,e){var n=this.syncPointTree_.get(t);lt(n,"Missing sync point for query tag that we're tracking");var r=this.pendingWriteTree_.childWrites(t);return n.applyOperation(e,r,null)},t.prototype.applyOperationToSyncPoints_=function(t){return this.applyOperationHelper_(t,this.syncPointTree_,null,this.pendingWriteTree_.childWrites(Be.Empty))},t.prototype.applyOperationHelper_=function(t,e,n,r){if(t.path.isEmpty())return this.applyOperationDescendantsHelper_(t,e,n,r);var i=e.get(Be.Empty);null==n&&null!=i&&(n=i.getCompleteServerCache(Be.Empty));var o=[],a=t.path.getFront(),s=t.operationForChild(a),u=e.children.get(a);if(u&&s){var c=n?n.getImmediateChild(a):null,h=r.child(a);o=o.concat(this.applyOperationHelper_(s,u,c,h))}return i&&(o=o.concat(i.applyOperation(t,r,n))),o},t.prototype.applyOperationDescendantsHelper_=function(t,e,n,r){var i=this,o=e.get(Be.Empty);null==n&&null!=o&&(n=o.getCompleteServerCache(Be.Empty));var a=[];return e.children.inorderTraversal(function(e,o){var s=n?n.getImmediateChild(e):null,u=r.child(e),c=t.operationForChild(e);c&&(a=a.concat(i.applyOperationDescendantsHelper_(c,o,s,u)))}),o&&(a=a.concat(o.applyOperation(t,r,n))),a},t.nextQueryTag_=1,t}(),Rr=function(){function t(){this.rootNode_=Wn.EMPTY_NODE}return t.prototype.getNode=function(t){return this.rootNode_.getChild(t)},t.prototype.updateSnapshot=function(t,e){this.rootNode_=this.rootNode_.updateChild(t,e)},t}(),Ar=function(){function t(t){this.app_=t}return t.prototype.getToken=function(t){return this.app_.INTERNAL.getToken(t).then(null,function(t){return t&&"auth/token-not-initialized"===t.code?(be("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(t)})},t.prototype.addTokenChangeListener=function(t){this.app_.INTERNAL.addAuthTokenListener(t)},t.prototype.removeTokenChangeListener=function(t){this.app_.INTERNAL.removeAuthTokenListener(t)},t.prototype.notifyForInvalidToken=function(){var t='Provided authentication credentials for the app named "'+this.app_.name+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.app_.options?t+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.app_.options?t+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':t+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',Ce(t)},t}(),kr=function(){function t(){this.counters_={}}return t.prototype.incrementCounter=function(t,e){void 0===e&&(e=1),At(this.counters_,t)||(this.counters_[t]=0),this.counters_[t]+=e},t.prototype.get=function(){return yt(this.counters_)},t}(),Or=function(){function t(){}return t.getCollection=function(t){var e=t.toString();return this.collections_[e]||(this.collections_[e]=new kr),this.collections_[e]},t.getOrCreateReporter=function(t,e){var n=t.toString();return this.reporters_[n]||(this.reporters_[n]=e()),this.reporters_[n]},t.collections_={},t.reporters_={},t}(),Pr=function(){function t(t){this.collection_=t,this.last_=null}return t.prototype.get=function(){var t=this.collection_.get(),e=Pt(t);return this.last_&&Ot(this.last_,function(t,n){e[t]=e[t]-n}),this.last_=t,e},t}(),Dr=1e4,Lr=3e4,xr=function(){function t(t,e){this.server_=e,this.statsToReport_={},this.statsListener_=new Pr(t);var n=Dr+(Lr-Dr)*Math.random();We(this.reportStats_.bind(this),Math.floor(n))}return t.prototype.includeStat=function(t){this.statsToReport_[t]=!0},t.prototype.reportStats_=function(){var t=this,e=this.statsListener_.get(),n={},r=!1;Ot(e,function(e,i){i>0&&At(t.statsToReport_,e)&&(n[e]=i,r=!0)}),r&&this.server_.reportStats(n),We(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))},t}(),Fr=function(){function t(){this.eventLists_=[],this.recursionDepth_=0}return t.prototype.queueEvents=function(t){for(var e=null,n=0;n<t.length;n++){var r=t[n],i=r.getPath();null===e||i.equals(e.getPath())||(this.eventLists_.push(e),e=null),null===e&&(e=new Ur(i)),e.add(r)}e&&this.eventLists_.push(e)},t.prototype.raiseEventsAtPath=function(t,e){this.queueEvents(e),this.raiseQueuedEventsMatchingPredicate_(function(e){return e.equals(t)})},t.prototype.raiseEventsForChangedPath=function(t,e){this.queueEvents(e),this.raiseQueuedEventsMatchingPredicate_(function(e){return e.contains(t)||t.contains(e)})},t.prototype.raiseQueuedEventsMatchingPredicate_=function(t){this.recursionDepth_++;for(var e=!0,n=0;n<this.eventLists_.length;n++){var r=this.eventLists_[n];if(r)t(r.getPath())?(this.eventLists_[n].raise(),this.eventLists_[n]=null):e=!1}e&&(this.eventLists_=[]),this.recursionDepth_--},t}(),Ur=function(){function t(t){this.path_=t,this.events_=[]}return t.prototype.add=function(t){this.events_.push(t)},t.prototype.raise=function(){for(var t=0;t<this.events_.length;t++){var e=this.events_[t];if(null!==e){this.events_[t]=null;var n=e.getEventRunner();_e&&be("event: "+e.toString()),Ue(n)}}},t.prototype.getPath=function(){return this.path_},t}(),Mr=function(){function t(t){this.allowedEvents_=t,this.listeners_={},lt(Array.isArray(t)&&t.length>0,"Requires a non-empty array")}return t.prototype.trigger=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(Array.isArray(this.listeners_[t]))for(var r=this.listeners_[t].slice(),i=0;i<r.length;i++)r[i].callback.apply(r[i].context,e)},t.prototype.on=function(t,e,n){this.validateEventType_(t),this.listeners_[t]=this.listeners_[t]||[],this.listeners_[t].push({callback:e,context:n});var r=this.getInitialEvent(t);r&&e.apply(n,r)},t.prototype.off=function(t,e,n){this.validateEventType_(t);for(var r=this.listeners_[t]||[],i=0;i<r.length;i++)if(r[i].callback===e&&(!n||n===r[i].context))return void r.splice(i,1)},t.prototype.validateEventType_=function(t){lt(this.allowedEvents_.find(function(e){return e===t}),"Unknown event: "+t)},t}(),Wr=function(t){function e(){var e,n,r=t.call(this,["visible"])||this;return"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(n="visibilitychange",e="hidden"):void 0!==document.mozHidden?(n="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(n="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(n="webkitvisibilitychange",e="webkitHidden")),r.visible_=!0,n&&document.addEventListener(n,function(){var t=!document[e];t!==r.visible_&&(r.visible_=t,r.trigger("visible",t))},!1),r}return it(e,t),e.getInstance=function(){return new e},e.prototype.getInitialEvent=function(t){return lt("visible"===t,"Unknown event type: "+t),[this.visible_]},e}(Mr),Br=function(t){function e(){var e=t.call(this,["online"])||this;return e.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||bt()||(window.addEventListener("online",function(){e.online_||(e.online_=!0,e.trigger("online",!0))},!1),window.addEventListener("offline",function(){e.online_&&(e.online_=!1,e.trigger("online",!1))},!1)),e}return it(e,t),e.getInstance=function(){return new e},e.prototype.getInitialEvent=function(t){return lt("online"===t,"Unknown event type: "+t),[this.online_]},e.prototype.currentlyOnline=function(){return this.online_},e}(Mr),jr=function(){function t(t){this.onMessage_=t,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}return t.prototype.closeAfter=function(t,e){this.closeAfterResponse=t,this.onClose=e,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)},t.prototype.handleResponse=function(t,e){var n=this;this.pendingResponses[t]=e;for(var r=function(){var t=i.pendingResponses[i.currentResponseNum];delete i.pendingResponses[i.currentResponseNum];for(var e=function(e){t[e]&&Ue(function(){n.onMessage_(t[e])})},r=0;r<t.length;++r)e(r);if(i.currentResponseNum===i.closeAfterResponse)return i.onClose&&(i.onClose(),i.onClose=null),"break";i.currentResponseNum++},i=this;this.pendingResponses[this.currentResponseNum];){if("break"===r())break}},t}(),Vr="pLPCommand",qr="pRTLPCB",Hr=function(){function t(t,e,n,r){this.connId=t,this.repoInfo=e,this.transportSessionId=n,this.lastSessionId=r,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=we(t),this.stats_=Or.getCollection(e),this.urlFn=function(t){return e.connectionURL(Ve,t)}}return t.prototype.open=function(t,e){var n=this;this.curSegmentNum=0,this.onDisconnect_=e,this.myPacketOrderer=new jr(t),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(function(){n.log_("Timed out trying to connect."),n.onClosed_(),n.connectTimeoutTimer_=null},Math.floor(3e4)),function(t){if(wt()||"complete"===document.readyState)t();else{var e=!1,n=function(){document.body?e||(e=!0,t()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",function(){"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}}(function(){if(!n.isClosed_){n.scriptTagHolder=new Kr(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=t[0],i=t[1],o=t[2];if(n.incrementIncomingBytes_(t),n.scriptTagHolder)if(n.connectTimeoutTimer_&&(clearTimeout(n.connectTimeoutTimer_),n.connectTimeoutTimer_=null),n.everConnected_=!0,"start"==r)n.id=i,n.password=o;else{if("close"!==r)throw new Error("Unrecognized command received: "+r);i?(n.scriptTagHolder.sendNewPolls=!1,n.myPacketOrderer.closeAfter(i,function(){n.onClosed_()})):n.onClosed_()}},function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=t[0],i=t[1];n.incrementIncomingBytes_(t),n.myPacketOrderer.handleResponse(r,i)},function(){n.onClosed_()},n.urlFn);var t={start:"t"};t.ser=Math.floor(1e8*Math.random()),n.scriptTagHolder.uniqueCallbackIdentifier&&(t.cb=n.scriptTagHolder.uniqueCallbackIdentifier),t.v="5",n.transportSessionId&&(t.s=n.transportSessionId),n.lastSessionId&&(t.ls=n.lastSessionId),!wt()&&"undefined"!=typeof location&&location.href&&-1!==location.href.indexOf("firebaseio.com")&&(t.r="f");var e=n.urlFn(t);n.log_("Connecting via long-poll to "+e),n.scriptTagHolder.addTag(e,function(){})}})},t.prototype.start=function(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)},t.forceAllow=function(){t.forceAllow_=!0},t.forceDisallow=function(){t.forceDisallow_=!0},t.isAvailable=function(){return t.forceAllow_||!t.forceDisallow_&&"undefined"!=typeof document&&null!=document.createElement&&!("object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))&&!("object"==typeof Windows&&"object"==typeof Windows.UI)&&!wt()},t.prototype.markConnectionHealthy=function(){},t.prototype.shutdown_=function(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)},t.prototype.onClosed_=function(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))},t.prototype.close=function(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())},t.prototype.send=function(t){var e=Nt(t);this.bytesSent+=e.length,this.stats_.incrementCounter("bytes_sent",e.length);for(var n,r=(n=ft(e),dt.encodeByteArray(n,!0)),i=Pe(r,1840),o=0;o<i.length;o++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,i.length,i[o]),this.curSegmentNum++},t.prototype.addDisconnectPingFrame=function(t,e){if(!wt()){this.myDisconnFrame=document.createElement("iframe");var n={dframe:"t"};n.id=t,n.pw=e,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}},t.prototype.incrementIncomingBytes_=function(t){var e=Nt(t).length;this.bytesReceived+=e,this.stats_.incrementCounter("bytes_received",e)},t}(),Kr=function(){function t(e,n,r,i){if(this.onDisconnect=r,this.urlFn=i,this.outstandingRequests=new Zn,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0,wt())this.commandCB=e,this.onMessageCB=n;else{this.uniqueCallbackIdentifier=de(),window[Vr+this.uniqueCallbackIdentifier]=e,window[qr+this.uniqueCallbackIdentifier]=n,this.myIFrame=t.createIFrame_();var o="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length))o='<script>document.domain="'+document.domain+'";<\/script>';var a="<html><body>"+o+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(a),this.myIFrame.doc.close()}catch(t){be("frame writing exception"),t.stack&&be(t.stack),be(t)}}}return t.createIFrame_=function(){var t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||be("No IE domain setting required")}catch(n){var e=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+e+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t},t.prototype.close=function(){var e=this;if(this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(function(){null!==e.myIFrame&&(document.body.removeChild(e.myIFrame),e.myIFrame=null)},Math.floor(0))),wt()&&this.myID){var n={disconn:"t"};n.id=this.myID,n.pw=this.myPW;var r=this.urlFn(n);t.nodeRestRequest(r)}var i=this.onDisconnect;i&&(this.onDisconnect=null,i())},t.prototype.startLongPoll=function(t,e){for(this.myID=t,this.myPW=e,this.alive=!0;this.newRequest_(););},t.prototype.newRequest_=function(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.count()<(this.pendingSegs.length>0?2:1)){this.currentSerial++;var t={};t.id=this.myID,t.pw=this.myPW,t.ser=this.currentSerial;for(var e=this.urlFn(t),n="",r=0;this.pendingSegs.length>0;){if(!(this.pendingSegs[0].d.length+30+n.length<=1870))break;var i=this.pendingSegs.shift();n=n+"&seg"+r+"="+i.seg+"&ts"+r+"="+i.ts+"&d"+r+"="+i.d,r++}return e+=n,this.addLongPollTag_(e,this.currentSerial),!0}return!1},t.prototype.enqueueSegment=function(t,e,n){this.pendingSegs.push({seg:t,ts:e,d:n}),this.alive&&this.newRequest_()},t.prototype.addLongPollTag_=function(t,e){var n=this;this.outstandingRequests.add(e,1);var r=function(){n.outstandingRequests.remove(e),n.newRequest_()},i=setTimeout(r,Math.floor(25e3));this.addTag(t,function(){clearTimeout(i),r()})},t.prototype.addTag=function(t,e){var n=this;wt()?this.doNodeLongPoll(t,e):setTimeout(function(){try{if(!n.sendNewPolls)return;var r=n.myIFrame.doc.createElement("script");r.type="text/javascript",r.async=!0,r.src=t,r.onload=r.onreadystatechange=function(){var t=r.readyState;t&&"loaded"!==t&&"complete"!==t||(r.onload=r.onreadystatechange=null,r.parentNode&&r.parentNode.removeChild(r),e())},r.onerror=function(){be("Long-poll script failed to load: "+t),n.sendNewPolls=!1,n.close()},n.myIFrame.doc.body.appendChild(r)}catch(t){}},Math.floor(1))},t}(),Gr=null;"undefined"!=typeof MozWebSocket?Gr=MozWebSocket:"undefined"!=typeof WebSocket&&(Gr=WebSocket);var Qr=function(){function t(e,n,r,i){this.connId=e,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=we(this.connId),this.stats_=Or.getCollection(n),this.connURL=t.connectionURL_(n,r,i)}return t.connectionURL_=function(t,e,n){var r={v:"5"};return!wt()&&"undefined"!=typeof location&&location.href&&-1!==location.href.indexOf("firebaseio.com")&&(r.r="f"),e&&(r.s=e),n&&(r.ls=n),t.connectionURL("websocket",r)},t.prototype.open=function(t,e){var n=this;this.onDisconnect=e,this.onMessage=t,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,le.set("previous_websocket_failure",!0);try{if(wt()){var r=ct?"AdminNode":"Node",i={headers:{"User-Agent":"Firebase/5/"+te.SDK_VERSION+"/"+process.platform+"/"+r}},o=process.env,a=0==this.connURL.indexOf("wss://")?o.HTTPS_PROXY||o.https_proxy:o.HTTP_PROXY||o.http_proxy;a&&(i.proxy={origin:a}),this.mySock=new Gr(this.connURL,[],i)}else this.mySock=new Gr(this.connURL)}catch(t){this.log_("Error instantiating WebSocket.");var s=t.message||t.data;return s&&this.log_(s),void this.onClosed_()}this.mySock.onopen=function(){n.log_("Websocket connected."),n.everConnected_=!0},this.mySock.onclose=function(){n.log_("Websocket connection was disconnected."),n.mySock=null,n.onClosed_()},this.mySock.onmessage=function(t){n.handleIncomingFrame(t)},this.mySock.onerror=function(t){n.log_("WebSocket error. Closing connection.");var e=t.message||t.data;e&&n.log_(e),n.onClosed_()}},t.prototype.start=function(){},t.forceDisallow=function(){t.forceDisallow_=!0},t.isAvailable=function(){var e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){var n=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==Gr&&!t.forceDisallow_},t.previouslyFailed=function(){return le.isInMemoryStorage||!0===le.get("previous_websocket_failure")},t.prototype.markConnectionHealthy=function(){le.remove("previous_websocket_failure")},t.prototype.appendFrame_=function(t){if(this.frames.push(t),this.frames.length==this.totalFrames){var e=this.frames.join("");this.frames=null;var n=It(e);this.onMessage(n)}},t.prototype.handleNewFrameCount_=function(t){this.totalFrames=t,this.frames=[]},t.prototype.extractFrameCount_=function(t){if(lt(null===this.frames,"We already have a frame buffer"),t.length<=6){var e=Number(t);if(!isNaN(e))return this.handleNewFrameCount_(e),null}return this.handleNewFrameCount_(1),t},t.prototype.handleIncomingFrame=function(t){if(null!==this.mySock){var e=t.data;if(this.bytesReceived+=e.length,this.stats_.incrementCounter("bytes_received",e.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(e);else{var n=this.extractFrameCount_(e);null!==n&&this.appendFrame_(n)}}},t.prototype.send=function(t){this.resetKeepAlive();var e=Nt(t);this.bytesSent+=e.length,this.stats_.incrementCounter("bytes_sent",e.length);var n=Pe(e,16384);n.length>1&&this.sendString_(String(n.length));for(var r=0;r<n.length;r++)this.sendString_(n[r])},t.prototype.shutdown_=function(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)},t.prototype.onClosed_=function(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))},t.prototype.close=function(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())},t.prototype.resetKeepAlive=function(){var t=this;clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(function(){t.mySock&&t.sendString_("0"),t.resetKeepAlive()},Math.floor(45e3))},t.prototype.sendString_=function(t){try{this.mySock.send(t)}catch(t){this.log_("Exception thrown from WebSocket.send():",t.message||t.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}},t.responsesRequiredToBeHealthy=2,t.healthyTimeout=3e4,t}(),zr=function(){function t(t){this.initTransports_(t)}return Object.defineProperty(t,"ALL_TRANSPORTS",{get:function(){return[Hr,Qr]},enumerable:!0,configurable:!0}),t.prototype.initTransports_=function(e){var n=Qr&&Qr.isAvailable(),r=n&&!Qr.previouslyFailed();if(e.webSocketOnly&&(n||Ce("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),r=!0),r)this.transports_=[Qr];else{var i=this.transports_=[];De(t.ALL_TRANSPORTS,function(t,e){e&&e.isAvailable()&&i.push(e)})}},t.prototype.initialTransport=function(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")},t.prototype.upgradeTransport=function(){return this.transports_.length>1?this.transports_[1]:null},t}(),Yr=function(){function t(t,e,n,r,i,o,a){this.id=t,this.repoInfo_=e,this.onMessage_=n,this.onReady_=r,this.onDisconnect_=i,this.onKill_=o,this.lastSessionId=a,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=we("c:"+this.id+":"),this.transportManager_=new zr(e),this.log_("Connection created"),this.start_()}return t.prototype.start_=function(){var t=this,e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,void 0,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var n=this.connReceiver_(this.conn_),r=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(function(){t.conn_&&t.conn_.open(n,r)},Math.floor(0));var i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=We(function(){t.healthyTimeout_=null,t.isHealthy_||(t.conn_&&t.conn_.bytesReceived>102400?(t.log_("Connection exceeded healthy timeout but has received "+t.conn_.bytesReceived+" bytes. Marking connection healthy."),t.isHealthy_=!0,t.conn_.markConnectionHealthy()):t.conn_&&t.conn_.bytesSent>10240?t.log_("Connection exceeded healthy timeout but has sent "+t.conn_.bytesSent+" bytes. Leaving connection alive."):(t.log_("Closing unhealthy connection after timeout."),t.close()))},Math.floor(i)))},t.prototype.nextTransportId_=function(){return"c:"+this.id+":"+this.connectionCount++},t.prototype.disconnReceiver_=function(t){var e=this;return function(n){t===e.conn_?e.onConnectionLost_(n):t===e.secondaryConn_?(e.log_("Secondary connection lost."),e.onSecondaryConnectionLost_()):e.log_("closing an old connection")}},t.prototype.connReceiver_=function(t){var e=this;return function(n){2!=e.state_&&(t===e.rx_?e.onPrimaryMessageReceived_(n):t===e.secondaryConn_?e.onSecondaryMessageReceived_(n):e.log_("message on old connection"))}},t.prototype.sendRequest=function(t){var e={t:"d",d:t};this.sendData_(e)},t.prototype.tryCleanupConnection=function(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)},t.prototype.onSecondaryControl_=function(t){if("t"in t){var e=t.t;"a"===e?this.upgradeIfSecondaryHealthy_():"r"===e?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===e&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}},t.prototype.onSecondaryMessageReceived_=function(t){var e=ke("t",t),n=ke("d",t);if("c"==e)this.onSecondaryControl_(n);else{if("d"!=e)throw new Error("Unknown protocol layer: "+e);this.pendingDataMessages.push(n)}},t.prototype.upgradeIfSecondaryHealthy_=function(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))},t.prototype.proceedWithUpgrade_=function(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()},t.prototype.onPrimaryMessageReceived_=function(t){var e=ke("t",t),n=ke("d",t);"c"==e?this.onControl_(n):"d"==e&&this.onDataMessage_(n)},t.prototype.onDataMessage_=function(t){this.onPrimaryResponse_(),this.onMessage_(t)},t.prototype.onPrimaryResponse_=function(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))},t.prototype.onControl_=function(t){var e=ke("t",t);if("d"in t){var n=t.d;if("h"===e)this.onHandshake_(n);else if("n"===e){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(var r=0;r<this.pendingDataMessages.length;++r)this.onDataMessage_(this.pendingDataMessages[r]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===e?this.onConnectionShutdown_(n):"r"===e?this.onReset_(n):"e"===e?Ee("Server Error: "+n):"o"===e?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):Ee("Unknown control packet command: "+e)}},t.prototype.onHandshake_=function(t){var e=t.ts,n=t.v,r=t.h;this.sessionId=t.s,this.repoInfo_.updateHost(r),0==this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,e),"5"!==n&&Ce("Protocol version mismatch detected"),this.tryStartUpgrade_())},t.prototype.tryStartUpgrade_=function(){var t=this.transportManager_.upgradeTransport();t&&this.startUpgrade_(t)},t.prototype.startUpgrade_=function(t){var e=this;this.secondaryConn_=new t(this.nextTransportId_(),this.repoInfo_,this.sessionId),this.secondaryResponsesRequired_=t.responsesRequiredToBeHealthy||0;var n=this.connReceiver_(this.secondaryConn_),r=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(n,r),We(function(){e.secondaryConn_&&(e.log_("Timed out trying to upgrade."),e.secondaryConn_.close())},Math.floor(6e4))},t.prototype.onReset_=function(t){this.log_("Reset packet received. New host: "+t),this.repoInfo_.updateHost(t),1===this.state_?this.close():(this.closeConnections_(),this.start_())},t.prototype.onConnectionEstablished_=function(t,e){var n=this;this.log_("Realtime connection established."),this.conn_=t,this.state_=1,this.onReady_&&(this.onReady_(e,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):We(function(){n.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))},t.prototype.sendPingOnPrimaryIfNecessary_=function(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))},t.prototype.onSecondaryConnectionLost_=function(){var t=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==t&&this.rx_!==t||this.close()},t.prototype.onConnectionLost_=function(t){this.conn_=null,t||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(le.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()},t.prototype.onConnectionShutdown_=function(t){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(t),this.onKill_=null),this.onDisconnect_=null,this.close()},t.prototype.sendData_=function(t){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(t)},t.prototype.close=function(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))},t.prototype.closeConnections_=function(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)},t}(),Xr=function(){function t(){}return t.prototype.put=function(t,e,n,r){},t.prototype.merge=function(t,e,n,r){},t.prototype.refreshAuthToken=function(t){},t.prototype.onDisconnectPut=function(t,e,n){},t.prototype.onDisconnectMerge=function(t,e,n){},t.prototype.onDisconnectCancel=function(t,e){},t.prototype.reportStats=function(t){},t}(),$r=1e3,Jr=3e5,Zr=function(t){function e(n,r,i,o,a,s){var u=t.call(this)||this;if(u.repoInfo_=n,u.onDataUpdate_=r,u.onConnectStatus_=i,u.onServerInfoUpdate_=o,u.authTokenProvider_=a,u.authOverride_=s,u.id=e.nextPersistentConnectionId_++,u.log_=we("p:"+u.id+":"),u.interruptReasons_={},u.listens_={},u.outstandingPuts_=[],u.outstandingPutCount_=0,u.onDisconnectRequestQueue_=[],u.connected_=!1,u.reconnectDelay_=$r,u.maxReconnectDelay_=Jr,u.securityDebugCallback_=null,u.lastSessionId=null,u.establishConnectionTimer_=null,u.visible_=!1,u.requestCBHash_={},u.requestNumber_=0,u.realtime_=null,u.authToken_=null,u.forceTokenRefresh_=!1,u.invalidAuthTokenCount_=0,u.firstConnection_=!0,u.lastConnectionAttemptTime_=null,u.lastConnectionEstablishedTime_=null,s&&!wt())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");return u.scheduleConnect_(0),Wr.getInstance().on("visible",u.onVisible_,u),-1===n.host.indexOf("fblocal")&&Br.getInstance().on("online",u.onOnline_,u),u}return it(e,t),e.prototype.sendRequest=function(t,e,n){var r=++this.requestNumber_,i={r:r,a:t,b:e};this.log_(Nt(i)),lt(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)},e.prototype.listen=function(t,e,n,r){var i=t.queryIdentifier(),o=t.path.toString();this.log_("Listen called for "+o+" "+i),this.listens_[o]=this.listens_[o]||{},lt(t.getQueryParams().isDefault()||!t.getQueryParams().loadsAllData(),"listen() called for non-default but complete query"),lt(!this.listens_[o][i],"listen() called twice for same path/queryId.");var a={onComplete:r,hashFn:e,query:t,tag:n};this.listens_[o][i]=a,this.connected_&&this.sendListen_(a)},e.prototype.sendListen_=function(t){var n=this,r=t.query,i=r.path.toString(),o=r.queryIdentifier();this.log_("Listen on "+i+" for "+o);var a={p:i};t.tag&&(a.q=r.queryObject(),a.t=t.tag),a.h=t.hashFn(),this.sendRequest("q",a,function(a){var s=a.d,u=a.s;e.warnOnListenWarnings_(s,r),(n.listens_[i]&&n.listens_[i][o])===t&&(n.log_("listen response",a),"ok"!==u&&n.removeListen_(i,o),t.onComplete&&t.onComplete(u,s))})},e.warnOnListenWarnings_=function(t,e){if(t&&"object"==typeof t&&At(t,"w")){var n=kt(t,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){var r='".indexOn": "'+e.getQueryParams().getIndex().toString()+'"',i=e.path.toString();Ce("Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding "+r+" at "+i+" to your security rules for better performance.")}}},e.prototype.refreshAuthToken=function(t){this.authToken_=t,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},function(){}),this.reduceReconnectDelayIfAdminCredential_(t)},e.prototype.reduceReconnectDelayIfAdminCredential_=function(t){var e;(t&&40===t.length||"object"==typeof(e=Rt(t).claims)&&!0===e.admin)&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)},e.prototype.tryAuth=function(){var t,e,n=this;if(this.connected_&&this.authToken_){var r=this.authToken_,i=(t=Rt(r),e=t.claims,t.signature&&e&&"object"==typeof e&&e.hasOwnProperty("iat")?"auth":"gauth"),o={cred:r};null===this.authOverride_?o.noauth=!0:"object"==typeof this.authOverride_&&(o.authvar=this.authOverride_),this.sendRequest(i,o,function(t){var e=t.s,i=t.d||"error";n.authToken_===r&&("ok"===e?n.invalidAuthTokenCount_=0:n.onAuthRevoked_(e,i))})}},e.prototype.unlisten=function(t,e){var n=t.path.toString(),r=t.queryIdentifier();this.log_("Unlisten called for "+n+" "+r),lt(t.getQueryParams().isDefault()||!t.getQueryParams().loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,t.queryObject(),e)},e.prototype.sendUnlisten_=function(t,e,n,r){this.log_("Unlisten on "+t+" for "+e);var i={p:t};r&&(i.q=n,i.t=r),this.sendRequest("n",i)},e.prototype.onDisconnectPut=function(t,e,n){this.connected_?this.sendOnDisconnect_("o",t,e,n):this.onDisconnectRequestQueue_.push({pathString:t,action:"o",data:e,onComplete:n})},e.prototype.onDisconnectMerge=function(t,e,n){this.connected_?this.sendOnDisconnect_("om",t,e,n):this.onDisconnectRequestQueue_.push({pathString:t,action:"om",data:e,onComplete:n})},e.prototype.onDisconnectCancel=function(t,e){this.connected_?this.sendOnDisconnect_("oc",t,null,e):this.onDisconnectRequestQueue_.push({pathString:t,action:"oc",data:null,onComplete:e})},e.prototype.sendOnDisconnect_=function(t,e,n,r){var i={p:e,d:n};this.log_("onDisconnect "+t,i),this.sendRequest(t,i,function(t){r&&setTimeout(function(){r(t.s,t.d)},Math.floor(0))})},e.prototype.put=function(t,e,n,r){this.putInternal("p",t,e,n,r)},e.prototype.merge=function(t,e,n,r){this.putInternal("m",t,e,n,r)},e.prototype.putInternal=function(t,e,n,r,i){var o={p:e,d:n};void 0!==i&&(o.h=i),this.outstandingPuts_.push({action:t,request:o,onComplete:r}),this.outstandingPutCount_++;var a=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(a):this.log_("Buffering put: "+e)},e.prototype.sendPut_=function(t){var e=this,n=this.outstandingPuts_[t].action,r=this.outstandingPuts_[t].request,i=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,r,function(r){e.log_(n+" response",r),delete e.outstandingPuts_[t],e.outstandingPutCount_--,0===e.outstandingPutCount_&&(e.outstandingPuts_=[]),i&&i(r.s,r.d)})},e.prototype.reportStats=function(t){var e=this;if(this.connected_){var n={c:t};this.log_("reportStats",n),this.sendRequest("s",n,function(t){if("ok"!==t.s){var n=t.d;e.log_("reportStats","Error sending stats: "+n)}})}},e.prototype.onDataMessage_=function(t){if("r"in t){this.log_("from server: "+Nt(t));var e=t.r,n=this.requestCBHash_[e];n&&(delete this.requestCBHash_[e],n(t.b))}else{if("error"in t)throw"A server-side error has occurred: "+t.error;"a"in t&&this.onDataPush_(t.a,t.b)}},e.prototype.onDataPush_=function(t,e){this.log_("handleServerMessage",t,e),"d"===t?this.onDataUpdate_(e.p,e.d,!1,e.t):"m"===t?this.onDataUpdate_(e.p,e.d,!0,e.t):"c"===t?this.onListenRevoked_(e.p,e.q):"ac"===t?this.onAuthRevoked_(e.s,e.d):"sd"===t?this.onSecurityDebugPacket_(e):Ee("Unrecognized action received from server: "+Nt(t)+"\nAre you using the latest client?")},e.prototype.onReady_=function(t,e){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(t),this.lastSessionId=e,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)},e.prototype.scheduleConnect_=function(t){var e=this;lt(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(function(){e.establishConnectionTimer_=null,e.establishConnection_()},Math.floor(t))},e.prototype.onVisible_=function(t){t&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=$r,this.realtime_||this.scheduleConnect_(0)),this.visible_=t},e.prototype.onOnline_=function(t){t?(this.log_("Browser went online."),this.reconnectDelay_=$r,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())},e.prototype.onRealtimeDisconnect_=function(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){if(this.visible_){if(this.lastConnectionEstablishedTime_){(new Date).getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=$r),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();var t=(new Date).getTime()-this.lastConnectionAttemptTime_,e=Math.max(0,this.reconnectDelay_-t);e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)},e.prototype.establishConnection_=function(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;var t=this.onDataMessage_.bind(this),n=this.onReady_.bind(this),r=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+e.nextConnectionId_++,o=this,a=this.lastSessionId,s=!1,u=null,c=function(){u?u.close():(s=!0,r())};this.realtime_={close:c,sendRequest:function(t){lt(u,"sendRequest call when we're not connected not allowed."),u.sendRequest(t)}};var h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1,this.authTokenProvider_.getToken(h).then(function(e){s?be("getToken() completed but was canceled"):(be("getToken() completed. Creating connection."),o.authToken_=e&&e.accessToken,u=new Yr(i,o.repoInfo_,t,n,r,function(t){Ce(t+" ("+o.repoInfo_.toString()+")"),o.interrupt("server_kill")},a))}).then(null,function(t){o.log_("Failed to get token: "+t),s||(ct&&Ce(t),c())})}},e.prototype.interrupt=function(t){be("Interrupting connection for reason: "+t),this.interruptReasons_[t]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())},e.prototype.resume=function(t){be("Resuming connection for reason: "+t),delete this.interruptReasons_[t],Dt(this.interruptReasons_)&&(this.reconnectDelay_=$r,this.realtime_||this.scheduleConnect_(0))},e.prototype.handleTimestamp_=function(t){var e=t-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:e})},e.prototype.cancelSentTransactions_=function(){for(var t=0;t<this.outstandingPuts_.length;t++){var e=this.outstandingPuts_[t];e&&"h"in e.request&&e.queued&&(e.onComplete&&e.onComplete("disconnect"),delete this.outstandingPuts_[t],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])},e.prototype.onListenRevoked_=function(t,e){var n;n=e?e.map(function(t){return Oe(t)}).join("$"):"default";var r=this.removeListen_(t,n);r&&r.onComplete&&r.onComplete("permission_denied")},e.prototype.removeListen_=function(t,e){var n,r=new Be(t).toString();return void 0!==this.listens_[r]?(n=this.listens_[r][e],delete this.listens_[r][e],0===Lt(this.listens_[r])&&delete this.listens_[r]):n=void 0,n},e.prototype.onAuthRevoked_=function(t,e){be("Auth token revoked: "+t+"/"+e),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==t&&"permission_denied"!==t||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))},e.prototype.onSecurityDebugPacket_=function(t){this.securityDebugCallback_?this.securityDebugCallback_(t):"msg"in t&&console.log("FIREBASE: "+t.msg.replace("\n","\nFIREBASE: "))},e.prototype.restoreState_=function(){var t=this;this.tryAuth(),Ot(this.listens_,function(e,n){Ot(n,function(e,n){t.sendListen_(n)})});for(var e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){var n=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(n.action,n.pathString,n.data,n.onComplete)}},e.prototype.sendConnectStats_=function(){var t={},e="js";ct?e="admin_node":ut&&(e="node"),t["sdk."+e+"."+te.SDK_VERSION.replace(/\./g,"-")]=1,bt()?t["framework.cordova"]=1:"object"==typeof navigator&&"ReactNative"===navigator.product&&(t["framework.reactnative"]=1),this.reportStats(t)},e.prototype.shouldReconnect_=function(){var t=Br.getInstance().currentlyOnline();return Dt(this.interruptReasons_)&&t},e.nextPersistentConnectionId_=0,e.nextConnectionId_=0,e}(Xr),ti=function(t){function e(e,n,r){var i=t.call(this)||this;return i.repoInfo_=e,i.onDataUpdate_=n,i.authTokenProvider_=r,i.log_=we("p:rest:"),i.listens_={},i}return it(e,t),e.prototype.reportStats=function(t){throw new Error("Method not implemented.")},e.getListenId_=function(t,e){return void 0!==e?"tag$"+e:(lt(t.getQueryParams().isDefault(),"should have a tag if it's not a default query."),t.path.toString())},e.prototype.listen=function(t,n,r,i){var o=this,a=t.path.toString();this.log_("Listen called for "+a+" "+t.queryIdentifier());var s=e.getListenId_(t,r),u={};this.listens_[s]=u;var c=t.getQueryParams().toRestQueryStringParameters();this.restRequest_(a+".json",c,function(t,e){var n=e;(404===t&&(n=null,t=null),null===t&&o.onDataUpdate_(a,n,!1,r),kt(o.listens_,s)===u)&&i(t?401==t?"permission_denied":"rest_error:"+t:"ok",null)})},e.prototype.unlisten=function(t,n){var r=e.getListenId_(t,n);delete this.listens_[r]},e.prototype.refreshAuthToken=function(t){},e.prototype.restRequest_=function(t,e,n){var r=this;void 0===e&&(e={}),e.format="export",this.authTokenProvider_.getToken(!1).then(function(i){var o=i&&i.accessToken;o&&(e.auth=o);var a,s=(r.repoInfo_.secure?"https://":"http://")+r.repoInfo_.host+t+"?"+(a=[],Ot(e,function(t,e){Array.isArray(e)?e.forEach(function(e){a.push(encodeURIComponent(t)+"="+encodeURIComponent(e))}):a.push(encodeURIComponent(t)+"="+encodeURIComponent(e))}),a.length?"&"+a.join("&"):"");r.log_("Sending REST request for "+s);var u=new XMLHttpRequest;u.onreadystatechange=function(){if(n&&4===u.readyState){r.log_("REST Response for "+s+" received. status:",u.status,"response:",u.responseText);var t=null;if(u.status>=200&&u.status<300){try{t=It(u.responseText)}catch(t){Ce("Failed to parse JSON response for "+s+": "+u.responseText)}n(null,t)}else 401!==u.status&&404!==u.status&&Ce("Got unsuccessful REST response for "+s+" Status: "+u.status),n(u.status);n=null}},u.open("GET",s,!0),u.send()})},e}(Xr),ei=function(){function t(t,e,n){var r=this;this.repoInfo_=t,this.app=n,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Fr,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=new tr,this.persistentConnection_=null;var i=new Ar(n);if(this.stats_=Or.getCollection(t),e||Me())this.server_=new ti(this.repoInfo_,this.onDataUpdate_.bind(this),i),setTimeout(this.onConnectStatus_.bind(this,!0),0);else{var o=n.options.databaseAuthVariableOverride;if(void 0!==o&&null!==o){if("object"!=typeof o)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{Nt(o)}catch(t){throw new Error("Invalid authOverride provided: "+t)}}this.persistentConnection_=new Zr(this.repoInfo_,this.onDataUpdate_.bind(this),this.onConnectStatus_.bind(this),this.onServerInfoUpdate_.bind(this),i,o),this.server_=this.persistentConnection_}i.addTokenChangeListener(function(t){r.server_.refreshAuthToken(t)}),this.statsReporter_=Or.getOrCreateReporter(t,function(){return new xr(r.stats_,r.server_)}),this.transactions_init_(),this.infoData_=new Rr,this.infoSyncTree_=new Nr({startListening:function(t,e,n,i){var o=[],a=r.infoData_.getNode(t.path);return a.isEmpty()||(o=r.infoSyncTree_.applyServerOverwrite(t.path,a),setTimeout(function(){i("ok")},0)),o},stopListening:function(){}}),this.updateInfo_("connected",!1),this.serverSyncTree_=new Nr({startListening:function(t,e,n,i){return r.server_.listen(t,n,e,function(e,n){var o=i(e,n);r.eventQueue_.raiseEventsForChangedPath(t.path,o)}),[]},stopListening:function(t,e){r.server_.unlisten(t,e)}})}return t.prototype.toString=function(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host},t.prototype.name=function(){return this.repoInfo_.namespace},t.prototype.serverTime=function(){var t=this.infoData_.getNode(new Be(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t},t.prototype.generateServerValues=function(){return(t=(t={timestamp:this.serverTime()})||{}).timestamp=t.timestamp||(new Date).getTime(),t;var t},t.prototype.onDataUpdate_=function(t,e,n,r){this.dataUpdateCount++;var i=new Be(t);e=this.interceptServerDataCallback_?this.interceptServerDataCallback_(t,e):e;var o=[];if(r)if(n){var a=xt(e,function(t){return Vn(t)});o=this.serverSyncTree_.applyTaggedQueryMerge(i,a,r)}else{var s=Vn(e);o=this.serverSyncTree_.applyTaggedQueryOverwrite(i,s,r)}else if(n){var u=xt(e,function(t){return Vn(t)});o=this.serverSyncTree_.applyServerMerge(i,u)}else{var c=Vn(e);o=this.serverSyncTree_.applyServerOverwrite(i,c)}var h=i;o.length>0&&(h=this.rerunTransactions_(i)),this.eventQueue_.raiseEventsForChangedPath(h,o)},t.prototype.interceptServerData_=function(t){this.interceptServerDataCallback_=t},t.prototype.onConnectStatus_=function(t){this.updateInfo_("connected",t),!1===t&&this.runOnDisconnectEvents_()},t.prototype.onServerInfoUpdate_=function(t){var e=this;De(t,function(t,n){e.updateInfo_(n,t)})},t.prototype.updateInfo_=function(t,e){var n=new Be("/.info/"+t),r=Vn(e);this.infoData_.updateSnapshot(n,r);var i=this.infoSyncTree_.applyServerOverwrite(n,r);this.eventQueue_.raiseEventsForChangedPath(n,i)},t.prototype.getNextWriteId_=function(){return this.nextWriteId_++},t.prototype.setWithPriority=function(t,e,n,r){var i=this;this.log_("set",{path:t.toString(),value:e,priority:n});var o=this.generateServerValues(),a=Vn(e,n),s=nr(a,o),u=this.getNextWriteId_(),c=this.serverSyncTree_.applyUserOverwrite(t,s,u,!0);this.eventQueue_.queueEvents(c),this.server_.put(t.toString(),a.val(!0),function(e,n){var o="ok"===e;o||Ce("set at "+t+" failed: "+e);var a=i.serverSyncTree_.ackUserWrite(u,!o);i.eventQueue_.raiseEventsForChangedPath(t,a),i.callOnCompleteCallback(r,e,n)});var h=this.abortTransactions_(t);this.rerunTransactions_(h),this.eventQueue_.raiseEventsForChangedPath(h,[])},t.prototype.update=function(t,e,n){var r=this;this.log_("update",{path:t.toString(),value:e});var i=!0,o=this.generateServerValues(),a={};if(Ot(e,function(t,e){i=!1;var n=Vn(e);a[t]=nr(n,o)}),i)be("update() called with empty data. Don't do anything."),this.callOnCompleteCallback(n,"ok");else{var s=this.getNextWriteId_(),u=this.serverSyncTree_.applyUserMerge(t,a,s);this.eventQueue_.queueEvents(u),this.server_.merge(t.toString(),e,function(e,i){var o="ok"===e;o||Ce("update at "+t+" failed: "+e);var a=r.serverSyncTree_.ackUserWrite(s,!o),u=a.length>0?r.rerunTransactions_(t):t;r.eventQueue_.raiseEventsForChangedPath(u,a),r.callOnCompleteCallback(n,e,i)}),Ot(e,function(e){var n=r.abortTransactions_(t.child(e));r.rerunTransactions_(n)}),this.eventQueue_.raiseEventsForChangedPath(t,[])}},t.prototype.runOnDisconnectEvents_=function(){var t=this;this.log_("onDisconnectEvents");var e=this.generateServerValues(),n=[];(function(t,e){var n=new tr;return t.forEachTree(new Be(""),function(t,r){n.remember(t,nr(r,e))}),n})(this.onDisconnect_,e).forEachTree(Be.Empty,function(e,r){n=n.concat(t.serverSyncTree_.applyServerOverwrite(e,r));var i=t.abortTransactions_(e);t.rerunTransactions_(i)}),this.onDisconnect_=new tr,this.eventQueue_.raiseEventsForChangedPath(Be.Empty,n)},t.prototype.onDisconnectCancel=function(t,e){var n=this;this.server_.onDisconnectCancel(t.toString(),function(r,i){"ok"===r&&n.onDisconnect_.forget(t),n.callOnCompleteCallback(e,r,i)})},t.prototype.onDisconnectSet=function(t,e,n){var r=this,i=Vn(e);this.server_.onDisconnectPut(t.toString(),i.val(!0),function(e,o){"ok"===e&&r.onDisconnect_.remember(t,i),r.callOnCompleteCallback(n,e,o)})},t.prototype.onDisconnectSetWithPriority=function(t,e,n,r){var i=this,o=Vn(e,n);this.server_.onDisconnectPut(t.toString(),o.val(!0),function(e,n){"ok"===e&&i.onDisconnect_.remember(t,o),i.callOnCompleteCallback(r,e,n)})},t.prototype.onDisconnectUpdate=function(t,e,n){var r=this;if(Dt(e))return be("onDisconnect().update() called with empty data. Don't do anything."),void this.callOnCompleteCallback(n,"ok");this.server_.onDisconnectMerge(t.toString(),e,function(i,o){"ok"===i&&Ot(e,function(e,n){var i=Vn(n);r.onDisconnect_.remember(t.child(e),i)}),r.callOnCompleteCallback(n,i,o)})},t.prototype.addEventCallbackForQuery=function(t,e){var n;n=".info"===t.path.getFront()?this.infoSyncTree_.addEventRegistration(t,e):this.serverSyncTree_.addEventRegistration(t,e),this.eventQueue_.raiseEventsAtPath(t.path,n)},t.prototype.removeEventCallbackForQuery=function(t,e){var n;n=".info"===t.path.getFront()?this.infoSyncTree_.removeEventRegistration(t,e):this.serverSyncTree_.removeEventRegistration(t,e),this.eventQueue_.raiseEventsAtPath(t.path,n)},t.prototype.interrupt=function(){this.persistentConnection_&&this.persistentConnection_.interrupt("repo_interrupt")},t.prototype.resume=function(){this.persistentConnection_&&this.persistentConnection_.resume("repo_interrupt")},t.prototype.stats=function(t){if(void 0===t&&(t=!1),"undefined"!=typeof console){var e;t?(this.statsListener_||(this.statsListener_=new Pr(this.stats_)),e=this.statsListener_.get()):e=this.stats_.get();var n=Object.keys(e).reduce(function(t,e){return Math.max(e.length,t)},0);Ot(e,function(t,e){for(var r=t.length;r<n+2;r++)t+=" ";console.log(t+e)})}},t.prototype.statsIncrementCounter=function(t){this.stats_.incrementCounter(t),this.statsReporter_.includeStat(t)},t.prototype.log_=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n="";this.persistentConnection_&&(n=this.persistentConnection_.id+":"),be.apply(void 0,[n].concat(t))},t.prototype.callOnCompleteCallback=function(t,e,n){t&&Ue(function(){if("ok"==e)t(null);else{var r=(e||"error").toUpperCase(),i=r;n&&(i+=": "+n);var o=new Error(i);o.code=r,t(o)}})},Object.defineProperty(t.prototype,"database",{get:function(){return this.__database||(this.__database=new li(this))},enumerable:!0,configurable:!0}),t}(),ni=function(){function t(e){this.indexedFilter_=new vr(e.getIndex()),this.index_=e.getIndex(),this.startPost_=t.getStartPost_(e),this.endPost_=t.getEndPost_(e)}return t.prototype.getStartPost=function(){return this.startPost_},t.prototype.getEndPost=function(){return this.endPost_},t.prototype.matches=function(t){return this.index_.compare(this.getStartPost(),t)<=0&&this.index_.compare(t,this.getEndPost())<=0},t.prototype.updateChild=function(t,e,n,r,i,o){return this.matches(new vn(e,n))||(n=Wn.EMPTY_NODE),this.indexedFilter_.updateChild(t,e,n,r,i,o)},t.prototype.updateFullNode=function(t,e,n){e.isLeafNode()&&(e=Wn.EMPTY_NODE);var r=e.withIndex(this.index_);r=r.updatePriority(Wn.EMPTY_NODE);var i=this;return e.forEachChild(Nn,function(t,e){i.matches(new vn(t,e))||(r=r.updateImmediateChild(t,Wn.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(t,r,n)},t.prototype.updatePriority=function(t,e){return t},t.prototype.filtersNodes=function(){return!0},t.prototype.getIndexedFilter=function(){return this.indexedFilter_},t.prototype.getIndex=function(){return this.index_},t.getStartPost_=function(t){if(t.hasStart()){var e=t.getIndexStartName();return t.getIndex().makePost(t.getIndexStartValue(),e)}return t.getIndex().minPost()},t.getEndPost_=function(t){if(t.hasEnd()){var e=t.getIndexEndName();return t.getIndex().makePost(t.getIndexEndValue(),e)}return t.getIndex().maxPost()},t}(),ri=function(){function t(t){this.rangedFilter_=new ni(t),this.index_=t.getIndex(),this.limit_=t.getLimit(),this.reverse_=!t.isViewFromLeft()}return t.prototype.updateChild=function(t,e,n,r,i,o){return this.rangedFilter_.matches(new vn(e,n))||(n=Wn.EMPTY_NODE),t.getImmediateChild(e).equals(n)?t:t.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(t,e,n,r,i,o):this.fullLimitUpdateChild_(t,e,n,i,o)},t.prototype.updateFullNode=function(t,e,n){var r;if(e.isLeafNode()||e.isEmpty())r=Wn.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<e.numChildren()&&e.isIndexed(this.index_)){r=Wn.EMPTY_NODE.withIndex(this.index_);var i=void 0;i=this.reverse_?e.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):e.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);for(var o=0;i.hasNext()&&o<this.limit_;){var a=i.getNext();if(!(this.reverse_?this.index_.compare(this.rangedFilter_.getStartPost(),a)<=0:this.index_.compare(a,this.rangedFilter_.getEndPost())<=0))break;r=r.updateImmediateChild(a.name,a.node),o++}}else{r=(r=e.withIndex(this.index_)).updatePriority(Wn.EMPTY_NODE);var s=void 0,u=void 0,c=void 0;i=void 0;if(this.reverse_){i=r.getReverseIterator(this.index_),s=this.rangedFilter_.getEndPost(),u=this.rangedFilter_.getStartPost();var h=this.index_.getCompare();c=function(t,e){return h(e,t)}}else i=r.getIterator(this.index_),s=this.rangedFilter_.getStartPost(),u=this.rangedFilter_.getEndPost(),c=this.index_.getCompare();o=0;for(var l=!1;i.hasNext();){a=i.getNext();!l&&c(s,a)<=0&&(l=!0),l&&o<this.limit_&&c(a,u)<=0?o++:r=r.updateImmediateChild(a.name,Wn.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(t,r,n)},t.prototype.updatePriority=function(t,e){return t},t.prototype.filtersNodes=function(){return!0},t.prototype.getIndexedFilter=function(){return this.rangedFilter_.getIndexedFilter()},t.prototype.getIndex=function(){return this.index_},t.prototype.fullLimitUpdateChild_=function(t,e,n,r,i){var o;if(this.reverse_){var a=this.index_.getCompare();o=function(t,e){return a(e,t)}}else o=this.index_.getCompare();var s=t;lt(s.numChildren()==this.limit_,"");var u=new vn(e,n),c=this.reverse_?s.getFirstChild(this.index_):s.getLastChild(this.index_),h=this.rangedFilter_.matches(u);if(s.hasChild(e)){for(var l=s.getImmediateChild(e),p=r.getChildAfterChild(this.index_,c,this.reverse_);null!=p&&(p.name==e||s.hasChild(p.name));)p=r.getChildAfterChild(this.index_,p,this.reverse_);var f=null==p?1:o(p,u);if(h&&!n.isEmpty()&&f>=0)return null!=i&&i.trackChildChange(dr.childChangedChange(e,n,l)),s.updateImmediateChild(e,n);null!=i&&i.trackChildChange(dr.childRemovedChange(e,l));var d=s.updateImmediateChild(e,Wn.EMPTY_NODE);return null!=p&&this.rangedFilter_.matches(p)?(null!=i&&i.trackChildChange(dr.childAddedChange(p.name,p.node)),d.updateImmediateChild(p.name,p.node)):d}return n.isEmpty()?t:h&&o(c,u)>=0?(null!=i&&(i.trackChildChange(dr.childRemovedChange(c.name,c.node)),i.trackChildChange(dr.childAddedChange(e,n))),s.updateImmediateChild(e,n).updateImmediateChild(c.name,Wn.EMPTY_NODE)):t},t}(),ii=function(){function t(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=Nn}return t.prototype.hasStart=function(){return this.startSet_},t.prototype.isViewFromLeft=function(){return""===this.viewFrom_?this.startSet_:this.viewFrom_===t.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT},t.prototype.getIndexStartValue=function(){return lt(this.startSet_,"Only valid if start has been set"),this.indexStartValue_},t.prototype.getIndexStartName=function(){return lt(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:Ie},t.prototype.hasEnd=function(){return this.endSet_},t.prototype.getIndexEndValue=function(){return lt(this.endSet_,"Only valid if end has been set"),this.indexEndValue_},t.prototype.getIndexEndName=function(){return lt(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Ne},t.prototype.hasLimit=function(){return this.limitSet_},t.prototype.hasAnchoredLimit=function(){return this.limitSet_&&""!==this.viewFrom_},t.prototype.getLimit=function(){return lt(this.limitSet_,"Only valid if limit has been set"),this.limit_},t.prototype.getIndex=function(){return this.index_},t.prototype.copy_=function(){var e=new t;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e},t.prototype.limit=function(t){var e=this.copy_();return e.limitSet_=!0,e.limit_=t,e.viewFrom_="",e},t.prototype.limitToFirst=function(e){var n=this.copy_();return n.limitSet_=!0,n.limit_=e,n.viewFrom_=t.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT,n},t.prototype.limitToLast=function(e){var n=this.copy_();return n.limitSet_=!0,n.limit_=e,n.viewFrom_=t.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT,n},t.prototype.startAt=function(t,e){var n=this.copy_();return n.startSet_=!0,void 0===t&&(t=null),n.indexStartValue_=t,null!=e?(n.startNameSet_=!0,n.indexStartName_=e):(n.startNameSet_=!1,n.indexStartName_=""),n},t.prototype.endAt=function(t,e){var n=this.copy_();return n.endSet_=!0,void 0===t&&(t=null),n.indexEndValue_=t,void 0!==e?(n.endNameSet_=!0,n.indexEndName_=e):(n.endNameSet_=!1,n.indexEndName_=""),n},t.prototype.orderBy=function(t){var e=this.copy_();return e.index_=t,e},t.prototype.getQueryObject=function(){var e=t.WIRE_PROTOCOL_CONSTANTS_,n={};if(this.startSet_&&(n[e.INDEX_START_VALUE]=this.indexStartValue_,this.startNameSet_&&(n[e.INDEX_START_NAME]=this.indexStartName_)),this.endSet_&&(n[e.INDEX_END_VALUE]=this.indexEndValue_,this.endNameSet_&&(n[e.INDEX_END_NAME]=this.indexEndName_)),this.limitSet_){n[e.LIMIT]=this.limit_;var r=this.viewFrom_;""===r&&(r=this.isViewFromLeft()?e.VIEW_FROM_LEFT:e.VIEW_FROM_RIGHT),n[e.VIEW_FROM]=r}return this.index_!==Nn&&(n[e.INDEX]=this.index_.toString()),n},t.prototype.loadsAllData=function(){return!(this.startSet_||this.endSet_||this.limitSet_)},t.prototype.isDefault=function(){return this.loadsAllData()&&this.index_==Nn},t.prototype.getNodeFilter=function(){return this.loadsAllData()?new vr(this.getIndex()):this.hasLimit()?new ri(this):new ni(this)},t.prototype.toRestQueryStringParameters=function(){var e,n=t.REST_QUERY_CONSTANTS_,r={};return this.isDefault()?r:(this.index_===Nn?e=n.PRIORITY_INDEX:this.index_===Kn?e=n.VALUE_INDEX:this.index_===gn?e=n.KEY_INDEX:(lt(this.index_ instanceof Gn,"Unrecognized index type!"),e=this.index_.toString()),r[n.ORDER_BY]=Nt(e),this.startSet_&&(r[n.START_AT]=Nt(this.indexStartValue_),this.startNameSet_&&(r[n.START_AT]+=","+Nt(this.indexStartName_))),this.endSet_&&(r[n.END_AT]=Nt(this.indexEndValue_),this.endNameSet_&&(r[n.END_AT]+=","+Nt(this.indexEndName_))),this.limitSet_&&(this.isViewFromLeft()?r[n.LIMIT_TO_FIRST]=this.limit_:r[n.LIMIT_TO_LAST]=this.limit_),r)},t.WIRE_PROTOCOL_CONSTANTS_={INDEX_START_VALUE:"sp",INDEX_START_NAME:"sn",INDEX_END_VALUE:"ep",INDEX_END_NAME:"en",LIMIT:"l",VIEW_FROM:"vf",VIEW_FROM_LEFT:"l",VIEW_FROM_RIGHT:"r",INDEX:"i"},t.REST_QUERY_CONSTANTS_={ORDER_BY:"orderBy",PRIORITY_INDEX:"$priority",VALUE_INDEX:"$value",KEY_INDEX:"$key",START_AT:"startAt",END_AT:"endAt",LIMIT_TO_FIRST:"limitToFirst",LIMIT_TO_LAST:"limitToLast"},t.DEFAULT=new t,t}(),oi=function(t){function e(e,n){if(!(e instanceof ei))throw new Error("new Reference() no longer supported - use app.database().");return t.call(this,e,n,ii.DEFAULT,!1)||this}return it(e,t),e.prototype.getKey=function(){return Vt("Reference.key",0,0,arguments.length),this.path.isEmpty()?null:this.path.getBack()},e.prototype.child=function(t){return Vt("Reference.child",1,1,arguments.length),"number"==typeof t?t=String(t):t instanceof Be||(null===this.path.getFront()?function(t,e,n,r){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),cn(t,e,n,r)}("Reference.child",1,t,!1):cn("Reference.child",1,t,!1)),new e(this.repo,this.path.child(t))},e.prototype.getParent=function(){Vt("Reference.parent",0,0,arguments.length);var t=this.path.parent();return null===t?null:new e(this.repo,t)},e.prototype.getRoot=function(){Vt("Reference.root",0,0,arguments.length);for(var t=this;null!==t.getParent();)t=t.getParent();return t},e.prototype.databaseProp=function(){return this.repo.database},e.prototype.set=function(t,e){Vt("Reference.set",1,2,arguments.length),hn("Reference.set",this.path),nn("Reference.set",1,t,this.path,!1),Ht("Reference.set",2,e,!0);var n=new mt;return this.repo.setWithPriority(this.path,t,null,n.wrapCallback(e)),n.promise},e.prototype.update=function(t,e){if(Vt("Reference.update",1,2,arguments.length),hn("Reference.update",this.path),Array.isArray(t)){for(var n={},r=0;r<t.length;++r)n[""+r]=t[r];t=n,Ce("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}on("Reference.update",1,t,this.path,!1),Ht("Reference.update",2,e,!0);var i=new mt;return this.repo.update(this.path,t,i.wrapCallback(e)),i.promise},e.prototype.setWithPriority=function(t,e,n){if(Vt("Reference.setWithPriority",2,3,arguments.length),hn("Reference.setWithPriority",this.path),nn("Reference.setWithPriority",1,t,this.path,!1),an("Reference.setWithPriority",2,e,!1),Ht("Reference.setWithPriority",3,n,!0),".length"===this.getKey()||".keys"===this.getKey())throw"Reference.setWithPriority failed: "+this.getKey()+" is a read-only object.";var r=new mt;return this.repo.setWithPriority(this.path,t,e,r.wrapCallback(n)),r.promise},e.prototype.remove=function(t){return Vt("Reference.remove",0,1,arguments.length),hn("Reference.remove",this.path),Ht("Reference.remove",1,t,!0),this.set(null,t)},e.prototype.transaction=function(t,e,n){if(Vt("Reference.transaction",1,3,arguments.length),hn("Reference.transaction",this.path),Ht("Reference.transaction",1,t,!1),Ht("Reference.transaction",2,e,!0),function(t,e,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(qt(t,e,r)+"must be a boolean.")}("Reference.transaction",3,n,!0),".length"===this.getKey()||".keys"===this.getKey())throw"Reference.transaction failed: "+this.getKey()+" is a read-only object.";void 0===n&&(n=!0);var r=new mt;"function"==typeof e&&r.promise.catch(function(){});return this.repo.startTransaction(this.path,t,function(t,n,i){t?r.reject(t):r.resolve(new fn(n,i)),"function"==typeof e&&e(t,n,i)},n),r.promise},e.prototype.setPriority=function(t,e){Vt("Reference.setPriority",1,2,arguments.length),hn("Reference.setPriority",this.path),an("Reference.setPriority",1,t,!1),Ht("Reference.setPriority",2,e,!0);var n=new mt;return this.repo.setWithPriority(this.path.child(".priority"),t,null,n.wrapCallback(e)),n.promise},e.prototype.push=function(t,e){Vt("Reference.push",0,2,arguments.length),hn("Reference.push",this.path),nn("Reference.push",1,t,this.path,!0),Ht("Reference.push",2,e,!0);var n,r=this.repo.serverTime(),i=dn(r),o=this.child(i),a=this.child(i);return n=null!=t?o.set(t,e).then(function(){return a}):Promise.resolve(a),o.then=n.then.bind(n),o.catch=n.then.bind(n,void 0),"function"==typeof e&&n.catch(function(){}),o},e.prototype.onDisconnect=function(){return hn("Reference.onDisconnect",this.path),new pn(this.repo,this.path)},Object.defineProperty(e.prototype,"database",{get:function(){return this.databaseProp()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"key",{get:function(){return this.getKey()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){return this.getParent()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"root",{get:function(){return this.getRoot()},enumerable:!0,configurable:!0}),e}(Jn);Jn.__referenceConstructor=oi,Tr.__referenceConstructor=oi;var ai,si=function(){return function(){this.children={},this.childCount=0,this.value=null}}(),ui=function(){function t(t,e,n){void 0===t&&(t=""),void 0===e&&(e=null),void 0===n&&(n=new si),this.name_=t,this.parent_=e,this.node_=n}return t.prototype.subTree=function(e){for(var n,r=e instanceof Be?e:new Be(e),i=this;null!==(n=r.getFront());){i=new t(n,i,kt(i.node_.children,n)||new si),r=r.popFront()}return i},t.prototype.getValue=function(){return this.node_.value},t.prototype.setValue=function(t){lt(void 0!==t,"Cannot set value to undefined"),this.node_.value=t,this.updateParents_()},t.prototype.clear=function(){this.node_.value=null,this.node_.children={},this.node_.childCount=0,this.updateParents_()},t.prototype.hasChildren=function(){return this.node_.childCount>0},t.prototype.isEmpty=function(){return null===this.getValue()&&!this.hasChildren()},t.prototype.forEachChild=function(e){var n=this;Ot(this.node_.children,function(r,i){e(new t(r,n,i))})},t.prototype.forEachDescendant=function(t,e,n){e&&!n&&t(this),this.forEachChild(function(e){e.forEachDescendant(t,!0,n)}),e&&n&&t(this)},t.prototype.forEachAncestor=function(t,e){for(var n=e?this:this.parent();null!==n;){if(t(n))return!0;n=n.parent()}return!1},t.prototype.forEachImmediateDescendantWithValue=function(t){this.forEachChild(function(e){null!==e.getValue()?t(e):e.forEachImmediateDescendantWithValue(t)})},t.prototype.path=function(){return new Be(null===this.parent_?this.name_:this.parent_.path()+"/"+this.name_)},t.prototype.name=function(){return this.name_},t.prototype.parent=function(){return this.parent_},t.prototype.updateParents_=function(){null!==this.parent_&&this.parent_.updateChild_(this.name_,this)},t.prototype.updateChild_=function(t,e){var n=e.isEmpty(),r=At(this.node_.children,t);n&&r?(delete this.node_.children[t],this.node_.childCount--,this.updateParents_()):n||r||(this.node_.children[t]=e.node_,this.node_.childCount++,this.updateParents_())},t}();!function(t){t[t.RUN=0]="RUN",t[t.SENT=1]="SENT",t[t.COMPLETED=2]="COMPLETED",t[t.SENT_NEEDS_ABORT=3]="SENT_NEEDS_ABORT",t[t.NEEDS_ABORT=4]="NEEDS_ABORT"}(ai||(ai={})),ei.MAX_TRANSACTION_RETRIES_=25,ei.prototype.transactions_init_=function(){this.transactionQueueTree_=new ui},ei.prototype.startTransaction=function(t,e,n,r){this.log_("transaction on "+t);var i=function(){},o=new oi(this,t);o.on("value",i);var a={path:t,update:e,onComplete:n,status:null,order:de(),applyLocally:r,retryCount:0,unwatcher:function(){o.off("value",i)},abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},s=this.getLatestState_(t);a.currentInputSnapshot=s;var u=a.update(s.val());if(void 0===u){if(a.unwatcher(),a.currentOutputSnapshotRaw=null,a.currentOutputSnapshotResolved=null,a.onComplete){var c=new Qn(a.currentInputSnapshot,new oi(this,a.path),Nn);a.onComplete(null,!1,c)}}else{rn("transaction failed: Data returned ",u,a.path),a.status=ai.RUN;var h=this.transactionQueueTree_.subTree(t),l=h.getValue()||[];l.push(a),h.setValue(l);var p=void 0;if("object"==typeof u&&null!==u&&At(u,".priority"))p=kt(u,".priority"),lt(en(p),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else p=(this.serverSyncTree_.calcCompleteEventCache(t)||Wn.EMPTY_NODE).getPriority().val();p=p;var f=this.generateServerValues(),d=Vn(u,p),v=nr(d,f);a.currentOutputSnapshotRaw=d,a.currentOutputSnapshotResolved=v,a.currentWriteId=this.getNextWriteId_();var y=this.serverSyncTree_.applyUserOverwrite(t,v,a.currentWriteId,a.applyLocally);this.eventQueue_.raiseEventsForChangedPath(t,y),this.sendReadyTransactions_()}},ei.prototype.getLatestState_=function(t,e){return this.serverSyncTree_.calcCompleteEventCache(t,e)||Wn.EMPTY_NODE},ei.prototype.sendReadyTransactions_=function(t){var e=this;if(void 0===t&&(t=this.transactionQueueTree_),t||this.pruneCompletedTransactionsBelowNode_(t),null!==t.getValue()){var n=this.buildTransactionQueue_(t);lt(n.length>0,"Sending zero length transaction queue"),n.every(function(t){return t.status===ai.RUN})&&this.sendTransactionQueue_(t.path(),n)}else t.hasChildren()&&t.forEachChild(function(t){e.sendReadyTransactions_(t)})},ei.prototype.sendTransactionQueue_=function(t,e){for(var n=this,r=e.map(function(t){return t.currentWriteId}),i=this.getLatestState_(t,r),o=i,a=i.hash(),s=0;s<e.length;s++){var u=e[s];lt(u.status===ai.RUN,"tryToSendTransactionQueue_: items in queue should all be run."),u.status=ai.SENT,u.retryCount++;var c=Be.relativePath(t,u.path);o=o.updateChild(c,u.currentOutputSnapshotRaw)}var h=o.val(!0),l=t;this.server_.put(l.toString(),h,function(r){n.log_("transaction put response",{path:l.toString(),status:r});var i=[];if("ok"===r){for(var o=[],a=0;a<e.length;a++){if(e[a].status=ai.COMPLETED,i=i.concat(n.serverSyncTree_.ackUserWrite(e[a].currentWriteId)),e[a].onComplete){var s=e[a].currentOutputSnapshotResolved,u=new oi(n,e[a].path),c=new Qn(s,u,Nn);o.push(e[a].onComplete.bind(null,null,!0,c))}e[a].unwatcher()}n.pruneCompletedTransactionsBelowNode_(n.transactionQueueTree_.subTree(t)),n.sendReadyTransactions_(),n.eventQueue_.raiseEventsForChangedPath(t,i);for(a=0;a<o.length;a++)Ue(o[a])}else{if("datastale"===r)for(a=0;a<e.length;a++)e[a].status===ai.SENT_NEEDS_ABORT?e[a].status=ai.NEEDS_ABORT:e[a].status=ai.RUN;else{Ce("transaction at "+l.toString()+" failed: "+r);for(a=0;a<e.length;a++)e[a].status=ai.NEEDS_ABORT,e[a].abortReason=r}n.rerunTransactions_(t)}},a)},ei.prototype.rerunTransactions_=function(t){var e=this.getAncestorTransactionNode_(t),n=e.path(),r=this.buildTransactionQueue_(e);return this.rerunTransactionQueue_(r,n),n},ei.prototype.rerunTransactionQueue_=function(t,e){if(0!==t.length){for(var n,r=[],i=[],o=t.filter(function(t){return t.status===ai.RUN}).map(function(t){return t.currentWriteId}),a=0;a<t.length;a++){var s=t[a],u=Be.relativePath(e,s.path),c=!1,h=void 0;if(lt(null!==u,"rerunTransactionsUnderNode_: relativePath should not be null."),s.status===ai.NEEDS_ABORT)c=!0,h=s.abortReason,i=i.concat(this.serverSyncTree_.ackUserWrite(s.currentWriteId,!0));else if(s.status===ai.RUN)if(s.retryCount>=ei.MAX_TRANSACTION_RETRIES_)c=!0,h="maxretry",i=i.concat(this.serverSyncTree_.ackUserWrite(s.currentWriteId,!0));else{var l=this.getLatestState_(s.path,o);s.currentInputSnapshot=l;var p=t[a].update(l.val());if(void 0!==p){rn("transaction failed: Data returned ",p,s.path);var f=Vn(p);"object"==typeof p&&null!=p&&At(p,".priority")||(f=f.updatePriority(l.getPriority()));var d=s.currentWriteId,v=this.generateServerValues(),y=nr(f,v);s.currentOutputSnapshotRaw=f,s.currentOutputSnapshotResolved=y,s.currentWriteId=this.getNextWriteId_(),o.splice(o.indexOf(d),1),i=(i=i.concat(this.serverSyncTree_.applyUserOverwrite(s.path,y,s.currentWriteId,s.applyLocally))).concat(this.serverSyncTree_.ackUserWrite(d,!0))}else c=!0,h="nodata",i=i.concat(this.serverSyncTree_.ackUserWrite(s.currentWriteId,!0))}if(this.eventQueue_.raiseEventsForChangedPath(e,i),i=[],c&&(t[a].status=ai.COMPLETED,n=t[a].unwatcher,setTimeout(n,Math.floor(0)),t[a].onComplete))if("nodata"===h){var _=new oi(this,t[a].path),g=t[a].currentInputSnapshot,m=new Qn(g,_,Nn);r.push(t[a].onComplete.bind(null,null,!1,m))}else r.push(t[a].onComplete.bind(null,new Error(h),!1,null))}this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);for(a=0;a<r.length;a++)Ue(r[a]);this.sendReadyTransactions_()}},ei.prototype.getAncestorTransactionNode_=function(t){for(var e,n=this.transactionQueueTree_;null!==(e=t.getFront())&&null===n.getValue();)n=n.subTree(e),t=t.popFront();return n},ei.prototype.buildTransactionQueue_=function(t){var e=[];return this.aggregateTransactionQueuesForNode_(t,e),e.sort(function(t,e){return t.order-e.order}),e},ei.prototype.aggregateTransactionQueuesForNode_=function(t,e){var n=this,r=t.getValue();if(null!==r)for(var i=0;i<r.length;i++)e.push(r[i]);t.forEachChild(function(t){n.aggregateTransactionQueuesForNode_(t,e)})},ei.prototype.pruneCompletedTransactionsBelowNode_=function(t){var e=this,n=t.getValue();if(n){for(var r=0,i=0;i<n.length;i++)n[i].status!==ai.COMPLETED&&(n[r]=n[i],r++);n.length=r,t.setValue(n.length>0?n:null)}t.forEachChild(function(t){e.pruneCompletedTransactionsBelowNode_(t)})},ei.prototype.abortTransactions_=function(t){var e=this,n=this.getAncestorTransactionNode_(t).path(),r=this.transactionQueueTree_.subTree(t);return r.forEachAncestor(function(t){e.abortTransactionsOnNode_(t)}),this.abortTransactionsOnNode_(r),r.forEachDescendant(function(t){e.abortTransactionsOnNode_(t)}),n},ei.prototype.abortTransactionsOnNode_=function(t){var e=t.getValue();if(null!==e){for(var n=[],r=[],i=-1,o=0;o<e.length;o++)if(e[o].status===ai.SENT_NEEDS_ABORT);else if(e[o].status===ai.SENT)lt(i===o-1,"All SENT items should be at beginning of queue."),i=o,e[o].status=ai.SENT_NEEDS_ABORT,e[o].abortReason="set";else if(lt(e[o].status===ai.RUN,"Unexpected transaction status in abort"),e[o].unwatcher(),r=r.concat(this.serverSyncTree_.ackUserWrite(e[o].currentWriteId,!0)),e[o].onComplete){n.push(e[o].onComplete.bind(null,new Error("set"),!1,null))}-1===i?t.setValue(null):e.length=i+1,this.eventQueue_.raiseEventsForChangedPath(t.path(),r);for(o=0;o<n.length;o++)Ue(n[o])}};var ci,hi=function(){function t(){this.repos_={},this.useRestClient_=!1}return t.getInstance=function(){return ci||(ci=new t),ci},t.prototype.interrupt=function(){for(var t in this.repos_)for(var e in this.repos_[t])this.repos_[t][e].interrupt()},t.prototype.resume=function(){for(var t in this.repos_)for(var e in this.repos_[t])this.repos_[t][e].resume()},t.prototype.databaseFromApp=function(t,e){var n=e||t.options.databaseURL;void 0===n&&Te("Can't determine Firebase Database URL. Be sure to include databaseURL option when calling firebase.initializeApp().");var r=Ye(n),i=r.repoInfo;return ln("Invalid Firebase Database URL",1,r),r.path.isEmpty()||Te("Database URL must point to the root of a Firebase Database (not including a child path)."),this.createRepo(i,t).database},t.prototype.deleteRepo=function(t){var e=kt(this.repos_,t.app.name);e&&kt(e,t.repoInfo_.toURLString())===t||Te("Database "+t.app.name+"("+t.repoInfo_+") has already been deleted."),t.interrupt(),delete e[t.repoInfo_.toURLString()]},t.prototype.createRepo=function(t,e){var n=kt(this.repos_,e.name);n||(n={},this.repos_[e.name]=n);var r=kt(n,t.toURLString());return r&&Te("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),r=new ei(t,this.useRestClient_,e),n[t.toURLString()]=r,r},t.prototype.forceRestClient=function(t){this.useRestClient_=t},t}(),li=function(){function t(t){this.repo_=t,t instanceof ei||Te("Don't call new Database() directly - please use firebase.database()."),this.root_=new oi(t,Be.Empty),this.INTERNAL=new pi(this)}return Object.defineProperty(t.prototype,"app",{get:function(){return this.repo_.app},enumerable:!0,configurable:!0}),t.prototype.ref=function(t){return this.checkDeleted_("ref"),Vt("database.ref",0,1,arguments.length),t instanceof oi?this.refFromURL(t.toString()):void 0!==t?this.root_.child(t):this.root_},t.prototype.refFromURL=function(t){var e="database.refFromURL";this.checkDeleted_(e),Vt(e,1,1,arguments.length);var n=Ye(t);ln(e,1,n);var r=n.repoInfo;return r.host!==this.repo_.repoInfo_.host&&Te(e+": Host name does not match the current database: (found "+r.host+" but expected "+this.repo_.repoInfo_.host+")"),this.ref(n.path.toString())},t.prototype.checkDeleted_=function(t){null===this.repo_&&Te("Cannot call "+t+" on a deleted database.")},t.prototype.goOffline=function(){Vt("database.goOffline",0,0,arguments.length),this.checkDeleted_("goOffline"),this.repo_.interrupt()},t.prototype.goOnline=function(){Vt("database.goOnline",0,0,arguments.length),this.checkDeleted_("goOnline"),this.repo_.resume()},t.ServerValue={TIMESTAMP:{".sv":"timestamp"}},t}(),pi=function(){function t(t){this.database=t}return t.prototype.delete=function(){return at(this,void 0,void 0,function(){return st(this,function(t){return this.database.checkDeleted_("delete"),hi.getInstance().deleteRepo(this.database.repo_),this.database.repo_=null,this.database.root_=null,this.database.INTERNAL=null,this.database=null,[2]})})},t}(),fi=Object.freeze({forceLongPolling:function(){Qr.forceDisallow(),Hr.forceAllow()},forceWebSockets:function(){Hr.forceDisallow()},isWebSocketsAvailable:function(){return Qr.isAvailable()},setSecurityDebugCallback:function(t,e){t.repo.persistentConnection_.securityDebugCallback_=e},stats:function(t,e){t.repo.stats(e)},statsIncrementCounter:function(t,e){t.repo.statsIncrementCounter(e)},dataUpdateCount:function(t){return t.repo.dataUpdateCount},interceptServerData:function(t,e){return t.repo.interceptServerData_(e)}}),di=Zr;Zr.prototype.simpleListen=function(t,e){this.sendRequest("q",{p:t},e)},Zr.prototype.echo=function(t,e){this.sendRequest("echo",{d:t},e)};var vi,yi=Yr,_i=qe,gi=Object.freeze({DataConnection:di,RealTimeConnection:yi,hijackHash:function(t){var e=Zr.prototype.put;return Zr.prototype.put=function(n,r,i,o){void 0!==o&&(o=t()),e.call(this,n,r,i,o)},function(){Zr.prototype.put=e}},ConnectionTarget:_i,queryIdentifier:function(t){return t.queryIdentifier()},listens:function(t){return t.repo.persistentConnection_.listens_},forceRestClient:function(t){hi.getInstance().forceRestClient(t)}}),mi=li.ServerValue;vi=te.INTERNAL.registerService("database",function(t,e,n){return hi.getInstance().databaseFromApp(t,n)},{Reference:oi,Query:Jn,Database:li,enableLogging:me,INTERNAL:fi,ServerValue:mi,TEST_ACCESS:gi},null,!0),wt()&&(module.exports=vi);var bi,wi,Ei,Ti={AVAILABLE_IN_WINDOW:"only-available-in-window",AVAILABLE_IN_SW:"only-available-in-sw",SHOULD_BE_INHERITED:"should-be-overriden",BAD_SENDER_ID:"bad-sender-id",INCORRECT_GCM_SENDER_ID:"incorrect-gcm-sender-id",PERMISSION_DEFAULT:"permission-default",PERMISSION_BLOCKED:"permission-blocked",UNSUPPORTED_BROWSER:"unsupported-browser",NOTIFICATIONS_BLOCKED:"notifications-blocked",FAILED_DEFAULT_REGISTRATION:"failed-serviceworker-registration",SW_REGISTRATION_EXPECTED:"sw-registration-expected",GET_SUBSCRIPTION_FAILED:"get-subscription-failed",INVALID_SAVED_TOKEN:"invalid-saved-token",SW_REG_REDUNDANT:"sw-reg-redundant",TOKEN_SUBSCRIBE_FAILED:"token-subscribe-failed",TOKEN_SUBSCRIBE_NO_TOKEN:"token-subscribe-no-token",TOKEN_SUBSCRIBE_NO_PUSH_SET:"token-subscribe-no-push-set",TOKEN_UNSUBSCRIBE_FAILED:"token-unsubscribe-failed",TOKEN_UPDATE_FAILED:"token-update-failed",TOKEN_UPDATE_NO_TOKEN:"token-update-no-token",USE_SW_BEFORE_GET_TOKEN:"use-sw-before-get-token",INVALID_DELETE_TOKEN:"invalid-delete-token",DELETE_TOKEN_NOT_FOUND:"delete-token-not-found",DELETE_SCOPE_NOT_FOUND:"delete-scope-not-found",BG_HANDLER_FUNCTION_EXPECTED:"bg-handler-function-expected",NO_WINDOW_CLIENT_TO_MSG:"no-window-client-to-msg",UNABLE_TO_RESUBSCRIBE:"unable-to-resubscribe",NO_FCM_TOKEN_FOR_RESUBSCRIBE:"no-fcm-token-for-resubscribe",FAILED_TO_DELETE_TOKEN:"failed-to-delete-token",NO_SW_IN_REG:"no-sw-in-reg",BAD_SCOPE:"bad-scope",BAD_VAPID_KEY:"bad-vapid-key",BAD_SUBSCRIPTION:"bad-subscription",BAD_TOKEN:"bad-token",BAD_PUSH_SET:"bad-push-set",FAILED_DELETE_VAPID_KEY:"failed-delete-vapid-key",INVALID_PUBLIC_VAPID_KEY:"invalid-public-vapid-key",USE_PUBLIC_KEY_BEFORE_GET_TOKEN:"use-public-key-before-get-token",PUBLIC_KEY_DECRYPTION_FAILED:"public-vapid-key-decryption-failed"},Ci=((bi={})[Ti.AVAILABLE_IN_WINDOW]="This method is available in a Window context.",bi[Ti.AVAILABLE_IN_SW]="This method is available in a service worker context.",bi[Ti.SHOULD_BE_INHERITED]="This method should be overriden by extended classes.",bi[Ti.BAD_SENDER_ID]="Please ensure that 'messagingSenderId' is set correctly in the options passed into firebase.initializeApp().",bi[Ti.PERMISSION_DEFAULT]="The required permissions were not granted and dismissed instead.",bi[Ti.PERMISSION_BLOCKED]="The required permissions were not granted and blocked instead.",bi[Ti.UNSUPPORTED_BROWSER]="This browser doesn't support the API's required to use the firebase SDK.",bi[Ti.NOTIFICATIONS_BLOCKED]="Notifications have been blocked.",bi[Ti.FAILED_DEFAULT_REGISTRATION]="We are unable to register the default service worker. {$browserErrorMessage}",bi[Ti.SW_REGISTRATION_EXPECTED]="A service worker registration was the expected input.",bi[Ti.GET_SUBSCRIPTION_FAILED]="There was an error when trying to get any existing Push Subscriptions.",bi[Ti.INVALID_SAVED_TOKEN]="Unable to access details of the saved token.",bi[Ti.SW_REG_REDUNDANT]="The service worker being used for push was made redundant.",bi[Ti.TOKEN_SUBSCRIBE_FAILED]="A problem occured while subscribing the user to FCM: {$message}",bi[Ti.TOKEN_SUBSCRIBE_NO_TOKEN]="FCM returned no token when subscribing the user to push.",bi[Ti.TOKEN_SUBSCRIBE_NO_PUSH_SET]="FCM returned an invalid response when getting an FCM token.",bi[Ti.TOKEN_UNSUBSCRIBE_FAILED]="A problem occured while unsubscribing the user from FCM: {$message}",bi[Ti.TOKEN_UPDATE_FAILED]="A problem occured while updating the user from FCM: {$message}",bi[Ti.TOKEN_UPDATE_NO_TOKEN]="FCM returned no token when updating the user to push.",bi[Ti.USE_SW_BEFORE_GET_TOKEN]="The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.",bi[Ti.INVALID_DELETE_TOKEN]="You must pass a valid token into deleteToken(), i.e. the token from getToken().",bi[Ti.DELETE_TOKEN_NOT_FOUND]="The deletion attempt for token could not be performed as the token was not found.",bi[Ti.DELETE_SCOPE_NOT_FOUND]="The deletion attempt for service worker scope could not be performed as the scope was not found.",bi[Ti.BG_HANDLER_FUNCTION_EXPECTED]="The input to setBackgroundMessageHandler() must be a function.",bi[Ti.NO_WINDOW_CLIENT_TO_MSG]="An attempt was made to message a non-existant window client.",bi[Ti.UNABLE_TO_RESUBSCRIBE]="There was an error while re-subscribing the FCM token for push messaging. Will have to resubscribe the user on next visit. {$message}",bi[Ti.NO_FCM_TOKEN_FOR_RESUBSCRIBE]="Could not find an FCM token and as a result, unable to resubscribe. Will have to resubscribe the user on next visit.",bi[Ti.FAILED_TO_DELETE_TOKEN]="Unable to delete the currently saved token.",bi[Ti.NO_SW_IN_REG]="Even though the service worker registration was successful, there was a problem accessing the service worker itself.",bi[Ti.INCORRECT_GCM_SENDER_ID]="Please change your web app manifest's 'gcm_sender_id' value to '103953800507' to use Firebase messaging.",bi[Ti.BAD_SCOPE]="The service worker scope must be a string with at least one character.",bi[Ti.BAD_VAPID_KEY]="The public VAPID key is not a Uint8Array with 65 bytes.",bi[Ti.BAD_SUBSCRIPTION]="The subscription must be a valid PushSubscription.",bi[Ti.BAD_TOKEN]="The FCM Token used for storage / lookup was not a valid token string.",bi[Ti.BAD_PUSH_SET]="The FCM push set used for storage / lookup was not not a valid push set string.",bi[Ti.FAILED_DELETE_VAPID_KEY]="The VAPID key could not be deleted.",bi[Ti.INVALID_PUBLIC_VAPID_KEY]="The public VAPID key must be a string.",bi[Ti.PUBLIC_KEY_DECRYPTION_FAILED]="The public VAPID key did not equal 65 bytes when decrypted.",bi),Si=new St("messaging","Messaging",Ci),Ii=new Uint8Array([4,51,148,247,223,161,235,177,220,3,162,94,21,113,219,72,211,46,237,237,178,52,219,183,71,58,12,143,196,204,225,111,60,140,132,223,171,182,102,62,242,12,212,139,254,227,249,118,47,20,28,99,8,106,111,45,177,26,149,176,206,55,192,156,110]),Ni="https://fcm.googleapis.com";function Ri(t,e){if(null==t||null==e)return!1;if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(var n=new DataView(t),r=new DataView(e),i=0;i<t.byteLength;i++)if(n.getUint8(i)!==r.getUint8(i))return!1;return!0}function Ai(t){return function(t){var e=new Uint8Array(t);return btoa(String.fromCharCode.apply(null,e))}(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}!function(t){t.TYPE_OF_MSG="firebase-messaging-msg-type",t.DATA="firebase-messaging-msg-data"}(wi||(wi={})),function(t){t.PUSH_MSG_RECEIVED="push-msg-received",t.NOTIFICATION_CLICKED="notification-clicked"}(Ei||(Ei={}));var ki=function(){function t(){}return t.prototype.getToken=function(t,e,n){return at(this,void 0,void 0,function(){var r,i,o,a,s,u,c,h;return st(this,function(l){switch(l.label){case 0:r=Ai(e.getKey("p256dh")),i=Ai(e.getKey("auth")),o="authorized_entity="+t+"&endpoint="+e.endpoint+"&encryption_key="+r+"&encryption_auth="+i,n!==Ii&&(a=Ai(n),o+="&application_pub_key="+a),(s=new Headers).append("Content-Type","application/x-www-form-urlencoded"),u={method:"POST",headers:s,body:o},l.label=1;case 1:return l.trys.push([1,4,,5]),[4,fetch(Ni+"/fcm/connect/subscribe",u)];case 2:return[4,l.sent().json()];case 3:return c=l.sent(),[3,5];case 4:throw l.sent(),Si.create(Ti.TOKEN_SUBSCRIBE_FAILED);case 5:if(c.error)throw h=c.error.message,Si.create(Ti.TOKEN_SUBSCRIBE_FAILED,{message:h});if(!c.token)throw Si.create(Ti.TOKEN_SUBSCRIBE_NO_TOKEN);if(!c.pushSet)throw Si.create(Ti.TOKEN_SUBSCRIBE_NO_PUSH_SET);return[2,{token:c.token,pushSet:c.pushSet}]}})})},t.prototype.updateToken=function(t,e,n,r,i){return at(this,void 0,void 0,function(){var o,a,s,u,c,h,l,p;return st(this,function(f){switch(f.label){case 0:o=Ai(r.getKey("p256dh")),a=Ai(r.getKey("auth")),s="push_set="+n+"&token="+e+"&authorized_entity="+t+"&endpoint="+r.endpoint+"&encryption_key="+o+"&encryption_auth="+a,i!==Ii&&(u=Ai(i),s+="&application_pub_key="+u),(c=new Headers).append("Content-Type","application/x-www-form-urlencoded"),h={method:"POST",headers:c,body:s},f.label=1;case 1:return f.trys.push([1,4,,5]),[4,fetch(Ni+"/fcm/connect/subscribe",h)];case 2:return[4,f.sent().json()];case 3:return l=f.sent(),[3,5];case 4:throw f.sent(),Si.create(Ti.TOKEN_UPDATE_FAILED);case 5:if(l.error)throw p=l.error.message,Si.create(Ti.TOKEN_UPDATE_FAILED,{message:p});if(!l.token)throw Si.create(Ti.TOKEN_UPDATE_NO_TOKEN);return[2,l.token]}})})},t.prototype.deleteToken=function(t,e,n){return at(this,void 0,void 0,function(){var r,i,o,a,s;return st(this,function(u){switch(u.label){case 0:r="authorized_entity="+t+"&token="+e+"&pushSet="+n,(i=new Headers).append("Content-Type","application/x-www-form-urlencoded"),o={method:"POST",headers:i,body:r},u.label=1;case 1:return u.trys.push([1,4,,5]),[4,fetch(Ni+"/fcm/connect/unsubscribe",o)];case 2:return[4,u.sent().json()];case 3:if((a=u.sent()).error)throw s=a.error.message,Si.create(Ti.TOKEN_UNSUBSCRIBE_FAILED,{message:s});return[3,5];case 4:throw u.sent(),Si.create(Ti.TOKEN_UNSUBSCRIBE_FAILED);case 5:return[2]}})})},t}();function Oi(t){for(var e=(t+"=".repeat((4-t.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),n=window.atob(e),r=new Uint8Array(n.length),i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}var Pi="undefined",Di="fcm_token_object_Store";function Li(){var t=indexedDB.open(Pi);t.onerror=function(t){},t.onsuccess=function(e){!function(t){if(t.objectStoreNames.contains(Di)){var e=t.transaction(Di).objectStore(Di),n=new ki,r=e.openCursor();r.onerror=function(t){console.warn("Unable to cleanup old IDB.",t)},r.onsuccess=function(){var e=r.result;if(e){var i=e.value;n.deleteToken(i.fcmSenderId,i.fcmToken,i.fcmPushSet),e.continue()}else t.close(),indexedDB.deleteDatabase(Pi)}}}(t.result)}}var xi=function(){function t(){this.dbPromise=null}return t.prototype.get=function(t){return this.createTransaction(function(e){return e.get(t)})},t.prototype.getIndex=function(t,e){return this.createTransaction(function(n){return n.index(t).get(e)})},t.prototype.put=function(t){return this.createTransaction(function(e){return e.put(t)},"readwrite")},t.prototype.delete=function(t){return this.createTransaction(function(e){return e.delete(t)},"readwrite")},t.prototype.closeDatabase=function(){return at(this,void 0,void 0,function(){return st(this,function(t){switch(t.label){case 0:return this.dbPromise?[4,this.dbPromise]:[3,2];case 1:t.sent().close(),this.dbPromise=null,t.label=2;case 2:return[2]}})})},t.prototype.createTransaction=function(t,e){return at(this,void 0,void 0,function(){var n,r,i,o;return st(this,function(a){switch(a.label){case 0:return[4,this.getDb()];case 1:return n=a.sent(),r=n.transaction(this.objectStoreName,e),i=r.objectStore(this.objectStoreName),[4,function(t){return new Promise(function(e,n){t.onsuccess=function(){e(t.result)},t.onerror=function(){n(t.error)}})}(t(i))];case 2:return o=a.sent(),[2,new Promise(function(t,e){r.oncomplete=function(){t(o)},r.onerror=function(){e(r.error)}})]}})})},t.prototype.getDb=function(){var t=this;return this.dbPromise||(this.dbPromise=new Promise(function(e,n){var r=indexedDB.open(t.dbName,t.dbVersion);r.onsuccess=function(){e(r.result)},r.onerror=function(){t.dbPromise=null,n(r.error)},r.onupgradeneeded=function(e){return t.onDbUpgrade(r,e)}})),this.dbPromise},t}();var Fi=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.dbName="fcm_token_details_db",e.dbVersion=3,e.objectStoreName="fcm_token_object_Store",e}return it(e,t),e.prototype.onDbUpgrade=function(t,e){var n=t.result;switch(e.oldVersion){case 0:(r=n.createObjectStore(this.objectStoreName,{keyPath:"swScope"})).createIndex("fcmSenderId","fcmSenderId",{unique:!1}),r.createIndex("fcmToken","fcmToken",{unique:!0});case 1:Li();case 2:var r,i=(r=t.transaction.objectStore(this.objectStoreName)).openCursor();i.onsuccess=function(){var t=i.result;if(t){var e=t.value,n=ot({},e);e.createTime||(n.createTime=Date.now()),"string"==typeof e.vapidKey&&(n.vapidKey=Oi(e.vapidKey)),"string"==typeof e.auth&&(n.auth=Oi(e.auth).buffer),"string"==typeof e.auth&&(n.p256dh=Oi(e.p256dh).buffer),t.update(n),t.continue()}}}},e.prototype.getTokenDetailsFromToken=function(t){return at(this,void 0,void 0,function(){return st(this,function(e){if(!t)throw Si.create(Ti.BAD_TOKEN);return Ui({fcmToken:t}),[2,this.getIndex("fcmToken",t)]})})},e.prototype.getTokenDetailsFromSWScope=function(t){return at(this,void 0,void 0,function(){return st(this,function(e){if(!t)throw Si.create(Ti.BAD_SCOPE);return Ui({swScope:t}),[2,this.get(t)]})})},e.prototype.saveTokenDetails=function(t){return at(this,void 0,void 0,function(){return st(this,function(e){if(!t.swScope)throw Si.create(Ti.BAD_SCOPE);if(!t.vapidKey)throw Si.create(Ti.BAD_VAPID_KEY);if(!t.endpoint||!t.auth||!t.p256dh)throw Si.create(Ti.BAD_SUBSCRIPTION);if(!t.fcmSenderId)throw Si.create(Ti.BAD_SENDER_ID);if(!t.fcmToken)throw Si.create(Ti.BAD_TOKEN);if(!t.fcmPushSet)throw Si.create(Ti.BAD_PUSH_SET);return Ui(t),[2,this.put(t)]})})},e.prototype.deleteToken=function(t){return at(this,void 0,void 0,function(){var e;return st(this,function(n){switch(n.label){case 0:return"string"!=typeof t||0===t.length?[2,Promise.reject(Si.create(Ti.INVALID_DELETE_TOKEN))]:[4,this.getTokenDetailsFromToken(t)];case 1:if(!(e=n.sent()))throw Si.create(Ti.DELETE_TOKEN_NOT_FOUND);return[4,this.delete(e.swScope)];case 2:return n.sent(),[2,e]}})})},e}(xi);function Ui(t){if(t.fcmToken&&("string"!=typeof t.fcmToken||0===t.fcmToken.length))throw Si.create(Ti.BAD_TOKEN);if(t.swScope&&("string"!=typeof t.swScope||0===t.swScope.length))throw Si.create(Ti.BAD_SCOPE);if(t.vapidKey&&(!(t.vapidKey instanceof Uint8Array)||65!==t.vapidKey.length))throw Si.create(Ti.BAD_VAPID_KEY);if(t.endpoint&&("string"!=typeof t.endpoint||0===t.endpoint.length))throw Si.create(Ti.BAD_SUBSCRIPTION);if(t.auth&&!(t.auth instanceof ArrayBuffer))throw Si.create(Ti.BAD_SUBSCRIPTION);if(t.p256dh&&!(t.p256dh instanceof ArrayBuffer))throw Si.create(Ti.BAD_SUBSCRIPTION);if(t.fcmSenderId&&("string"!=typeof t.fcmSenderId||0===t.fcmSenderId.length))throw Si.create(Ti.BAD_SENDER_ID);if(t.fcmPushSet&&("string"!=typeof t.fcmPushSet||0===t.fcmPushSet.length))throw Si.create(Ti.BAD_PUSH_SET)}var Mi=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.dbName="fcm_vapid_details_db",e.dbVersion=1,e.objectStoreName="fcm_vapid_object_Store",e}return it(e,t),e.prototype.onDbUpgrade=function(t){t.result.createObjectStore(this.objectStoreName,{keyPath:"swScope"})},e.prototype.getVapidFromSWScope=function(t){return at(this,void 0,void 0,function(){var e;return st(this,function(n){switch(n.label){case 0:if("string"!=typeof t||0===t.length)throw Si.create(Ti.BAD_SCOPE);return[4,this.get(t)];case 1:return[2,(e=n.sent())?e.vapidKey:void 0]}})})},e.prototype.saveVapidDetails=function(t,e){return at(this,void 0,void 0,function(){var n;return st(this,function(r){if("string"!=typeof t||0===t.length)throw Si.create(Ti.BAD_SCOPE);if(null===e||65!==e.length)throw Si.create(Ti.BAD_VAPID_KEY);return n={swScope:t,vapidKey:e},[2,this.put(n)]})})},e.prototype.deleteVapidDetails=function(t){return at(this,void 0,void 0,function(){var e;return st(this,function(n){switch(n.label){case 0:return[4,this.getVapidFromSWScope(t)];case 1:if(!(e=n.sent()))throw Si.create(Ti.DELETE_SCOPE_NOT_FOUND);return[4,this.delete(t)];case 2:return n.sent(),[2,e]}})})},e}(xi),Wi="messagingSenderId",Bi=function(){function t(t){var e=this;if(!t.options[Wi]||"string"!=typeof t.options[Wi])throw Si.create(Ti.BAD_SENDER_ID);this.messagingSenderId=t.options[Wi],this.tokenDetailsModel=new Fi,this.vapidDetailsModel=new Mi,this.iidModel=new ki,this.app=t,this.INTERNAL={delete:function(){return e.delete()}}}return t.prototype.getToken=function(){return at(this,void 0,void 0,function(){var t,e,n,r,i;return st(this,function(o){switch(o.label){case 0:return"granted"!==(t=this.getNotificationPermission_())?"denied"===t?[2,Promise.reject(Si.create(Ti.NOTIFICATIONS_BLOCKED))]:[2,Promise.resolve(null)]:[4,this.getSWRegistration_()];case 1:return e=o.sent(),[4,this.getPublicVapidKey_()];case 2:return n=o.sent(),[4,this.getPushSubscription(e,n)];case 3:return r=o.sent(),[4,this.tokenDetailsModel.getTokenDetailsFromSWScope(e.scope)];case 4:return(i=o.sent())?[2,this.manageExistingToken(e,r,n,i)]:[2,this.getNewToken(e,r,n)]}})})},t.prototype.manageExistingToken=function(t,e,n,r){return at(this,void 0,void 0,function(){return st(this,function(i){switch(i.label){case 0:return function(t,e,n){if(!Ri(e.buffer,n.vapidKey.buffer))return!1;var r=t.endpoint===n.endpoint,i=Ri(t.getKey("auth"),n.auth),o=Ri(t.getKey("p256dh"),n.p256dh);return r&&i&&o}(e,n,r)?Date.now()<r.createTime+6048e5?[2,r.fcmToken]:[2,this.updateToken(t,e,n,r)]:[4,this.deleteTokenFromDB(r.fcmToken)];case 1:return i.sent(),[2,this.getNewToken(t,e,n)]}})})},t.prototype.updateToken=function(t,e,n,r){return at(this,void 0,void 0,function(){var i,o,a;return st(this,function(s){switch(s.label){case 0:return s.trys.push([0,4,,6]),[4,this.iidModel.updateToken(this.messagingSenderId,r.fcmToken,r.fcmPushSet,e,n)];case 1:return i=s.sent(),o={swScope:t.scope,vapidKey:n,fcmSenderId:this.messagingSenderId,fcmToken:i,fcmPushSet:r.fcmPushSet,createTime:Date.now(),endpoint:e.endpoint,auth:e.getKey("auth"),p256dh:e.getKey("p256dh")},[4,this.tokenDetailsModel.saveTokenDetails(o)];case 2:return s.sent(),[4,this.vapidDetailsModel.saveVapidDetails(t.scope,n)];case 3:return s.sent(),[2,i];case 4:return a=s.sent(),[4,this.deleteToken(r.fcmToken)];case 5:throw s.sent(),a;case 6:return[2]}})})},t.prototype.getNewToken=function(t,e,n){return at(this,void 0,void 0,function(){var r,i;return st(this,function(o){switch(o.label){case 0:return[4,this.iidModel.getToken(this.messagingSenderId,e,n)];case 1:return r=o.sent(),i={swScope:t.scope,vapidKey:n,fcmSenderId:this.messagingSenderId,fcmToken:r.token,fcmPushSet:r.pushSet,createTime:Date.now(),endpoint:e.endpoint,auth:e.getKey("auth"),p256dh:e.getKey("p256dh")},[4,this.tokenDetailsModel.saveTokenDetails(i)];case 2:return o.sent(),[4,this.vapidDetailsModel.saveVapidDetails(t.scope,n)];case 3:return o.sent(),[2,r.token]}})})},t.prototype.deleteToken=function(t){return at(this,void 0,void 0,function(){var e,n;return st(this,function(r){switch(r.label){case 0:return[4,this.deleteTokenFromDB(t)];case 1:return r.sent(),[4,this.getSWRegistration_()];case 2:return(e=r.sent())?[4,e.pushManager.getSubscription()]:[3,4];case 3:if(n=r.sent())return[2,n.unsubscribe()];r.label=4;case 4:return[2,!0]}})})},t.prototype.deleteTokenFromDB=function(t){return at(this,void 0,void 0,function(){var e;return st(this,function(n){switch(n.label){case 0:return[4,this.tokenDetailsModel.deleteToken(t)];case 1:return e=n.sent(),[4,this.iidModel.deleteToken(e.fcmSenderId,e.fcmToken,e.fcmPushSet)];case 2:return n.sent(),[2]}})})},t.prototype.getPushSubscription=function(t,e){return t.pushManager.getSubscription().then(function(n){return n||t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:e})})},t.prototype.requestPermission=function(){throw Si.create(Ti.AVAILABLE_IN_WINDOW)},t.prototype.useServiceWorker=function(t){throw Si.create(Ti.AVAILABLE_IN_WINDOW)},t.prototype.usePublicVapidKey=function(t){throw Si.create(Ti.AVAILABLE_IN_WINDOW)},t.prototype.onMessage=function(t,e,n){throw Si.create(Ti.AVAILABLE_IN_WINDOW)},t.prototype.onTokenRefresh=function(t,e,n){throw Si.create(Ti.AVAILABLE_IN_WINDOW)},t.prototype.setBackgroundMessageHandler=function(t){throw Si.create(Ti.AVAILABLE_IN_SW)},t.prototype.delete=function(){return at(this,void 0,void 0,function(){return st(this,function(t){switch(t.label){case 0:return[4,Promise.all([this.tokenDetailsModel.closeDatabase(),this.vapidDetailsModel.closeDatabase()])];case 1:return t.sent(),[2]}})})},t.prototype.getNotificationPermission_=function(){return Notification.permission},t.prototype.getTokenDetailsModel=function(){return this.tokenDetailsModel},t.prototype.getVapidDetailsModel=function(){return this.vapidDetailsModel},t.prototype.getIIDModel=function(){return this.iidModel},t}();var ji=function(t){function e(e){var n=t.call(this,e)||this;return n.bgMessageHandler=null,self.addEventListener("push",function(t){n.onPush(t)}),self.addEventListener("pushsubscriptionchange",function(t){n.onSubChange(t)}),self.addEventListener("notificationclick",function(t){n.onNotificationClick(t)}),n}return it(e,t),e.prototype.onPush=function(t){t.waitUntil(this.onPush_(t))},e.prototype.onSubChange=function(t){t.waitUntil(this.onSubChange_(t))},e.prototype.onNotificationClick=function(t){t.waitUntil(this.onNotificationClick_(t))},e.prototype.onPush_=function(t){return at(this,void 0,void 0,function(){var e,n,r;return st(this,function(i){switch(i.label){case 0:if(!t.data)return[2];try{e=t.data.json()}catch(t){return[2]}return[4,this.hasVisibleClients_()];case 1:return i.sent()?e.notification||this.bgMessageHandler?[2,this.sendMessageToWindowClients_(e)]:[2]:(n=this.getNotificationData_(e))?(r=n.title||"",[4,this.getSWRegistration_()]):[3,3];case 2:return[2,i.sent().showNotification(r,n)];case 3:return this.bgMessageHandler?[4,this.bgMessageHandler(e)]:[3,5];case 4:return i.sent(),[2];case 5:return[2]}})})},e.prototype.onSubChange_=function(t){return at(this,void 0,void 0,function(){var t,e,n,r;return st(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.getSWRegistration_()];case 1:return t=i.sent(),[3,3];case 2:throw e=i.sent(),Si.create(Ti.UNABLE_TO_RESUBSCRIBE,{message:e});case 3:return i.trys.push([3,5,,8]),[4,t.pushManager.getSubscription()];case 4:return i.sent(),[3,8];case 5:return n=i.sent(),[4,this.getTokenDetailsModel().getTokenDetailsFromSWScope(t.scope)];case 6:if(!(r=i.sent()))throw n;return[4,this.deleteToken(r.fcmToken)];case 7:throw i.sent(),n;case 8:return[2]}})})},e.prototype.onNotificationClick_=function(t){return at(this,void 0,void 0,function(){var e,n,r,i;return st(this,function(o){switch(o.label){case 0:return t.notification&&t.notification.data&&t.notification.data.FCM_MSG?(t.stopImmediatePropagation(),t.notification.close(),(e=t.notification.data.FCM_MSG).notification&&(n=e.notification.click_action)?[4,this.getWindowClient_(n)]:[2]):[2];case 1:return(r=o.sent())?[3,3]:[4,self.clients.openWindow(n)];case 2:return r=o.sent(),[3,5];case 3:return[4,r.focus()];case 4:r=o.sent(),o.label=5;case 5:return r?(delete e.notification,i=qi(Ei.NOTIFICATION_CLICKED,e),[2,this.attemptToMessageClient_(r,i)]):[2]}})})},e.prototype.getNotificationData_=function(t){if(t&&"object"==typeof t.notification){var e,n=ot({},t.notification);return n.data=((e={}).FCM_MSG=t,e),n}},e.prototype.setBackgroundMessageHandler=function(t){if(!t||"function"!=typeof t)throw Si.create(Ti.BG_HANDLER_FUNCTION_EXPECTED);this.bgMessageHandler=t},e.prototype.getWindowClient_=function(t){return at(this,void 0,void 0,function(){var e,n,r,i;return st(this,function(o){switch(o.label){case 0:return e=new URL(t,self.location.href).href,[4,Vi()];case 1:for(n=o.sent(),r=null,i=0;i<n.length;i++)if(new URL(n[i].url,self.location.href).href===e){r=n[i];break}return[2,r]}})})},e.prototype.attemptToMessageClient_=function(t,e){return at(this,void 0,void 0,function(){return st(this,function(n){if(!t)throw Si.create(Ti.NO_WINDOW_CLIENT_TO_MSG);return t.postMessage(e),[2]})})},e.prototype.hasVisibleClients_=function(){return at(this,void 0,void 0,function(){return st(this,function(t){switch(t.label){case 0:return[4,Vi()];case 1:return[2,t.sent().some(function(t){return"visible"===t.visibilityState})]}})})},e.prototype.sendMessageToWindowClients_=function(t){return at(this,void 0,void 0,function(){var e,n,r=this;return st(this,function(i){switch(i.label){case 0:return[4,Vi()];case 1:return e=i.sent(),n=qi(Ei.PUSH_MSG_RECEIVED,t),[4,Promise.all(e.map(function(t){return r.attemptToMessageClient_(t,n)}))];case 2:return i.sent(),[2]}})})},e.prototype.getSWRegistration_=function(){return at(this,void 0,void 0,function(){return st(this,function(t){return[2,self.registration]})})},e.prototype.getPublicVapidKey_=function(){return at(this,void 0,void 0,function(){var t,e;return st(this,function(n){switch(n.label){case 0:return[4,this.getSWRegistration_()];case 1:if(!(t=n.sent()))throw Si.create(Ti.SW_REGISTRATION_EXPECTED);return[4,this.getVapidDetailsModel().getVapidFromSWScope(t.scope)];case 2:return null==(e=n.sent())?[2,Ii]:[2,e]}})})},e}(Bi);function Vi(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function qi(t,e){return(n={})[wi.TYPE_OF_MSG]=t,n[wi.DATA]=e,n;var n}var Hi=function(t){function e(e){var n=t.call(this,e)||this;return n.registrationToUse=null,n.publicVapidKeyToUse=null,n.manifestCheckPromise=null,n.messageObserver=null,n.tokenRefreshObserver=null,n.onMessageInternal=Wt(function(t){n.messageObserver=t}),n.onTokenRefreshInternal=Wt(function(t){n.tokenRefreshObserver=t}),n.setupSWMessageListener_(),n}return it(e,t),e.prototype.getToken=function(){var e=this;return this.isSupported_()?this.manifestCheck_().then(function(){return t.prototype.getToken.call(e)}):Promise.reject(Si.create(Ti.UNSUPPORTED_BROWSER))},e.prototype.manifestCheck_=function(){if(this.manifestCheckPromise)return this.manifestCheckPromise;var t=document.querySelector('link[rel="manifest"]');return this.manifestCheckPromise=t?fetch(t.href).then(function(t){return t.json()}).catch(function(){}).then(function(t){if(t&&t.gcm_sender_id&&"103953800507"!==t.gcm_sender_id)throw Si.create(Ti.INCORRECT_GCM_SENDER_ID)}):Promise.resolve(),this.manifestCheckPromise},e.prototype.requestPermission=function(){return at(this,void 0,void 0,function(){return st(this,function(t){return"granted"===Notification.permission?[2]:[2,new Promise(function(t,e){var n=function(n){return"granted"===n?t():e("denied"===n?Si.create(Ti.PERMISSION_BLOCKED):Si.create(Ti.PERMISSION_DEFAULT))},r=Notification.requestPermission(n);r&&r.then(n)})]})})},e.prototype.useServiceWorker=function(t){if(!(t instanceof ServiceWorkerRegistration))throw Si.create(Ti.SW_REGISTRATION_EXPECTED);if(null!=this.registrationToUse)throw Si.create(Ti.USE_SW_BEFORE_GET_TOKEN);this.registrationToUse=t},e.prototype.usePublicVapidKey=function(t){if("string"!=typeof t)throw Si.create(Ti.INVALID_PUBLIC_VAPID_KEY);if(null!=this.publicVapidKeyToUse)throw Si.create(Ti.USE_PUBLIC_KEY_BEFORE_GET_TOKEN);var e=Oi(t);if(65!==e.length)throw Si.create(Ti.PUBLIC_KEY_DECRYPTION_FAILED);this.publicVapidKeyToUse=e},e.prototype.onMessage=function(t,e,n){return"function"==typeof t?this.onMessageInternal(t,e,n):this.onMessageInternal(t)},e.prototype.onTokenRefresh=function(t,e,n){return"function"==typeof t?this.onTokenRefreshInternal(t,e,n):this.onTokenRefreshInternal(t)},e.prototype.waitForRegistrationToActivate_=function(t){var e=t.installing||t.waiting||t.active;return new Promise(function(n,r){if(e)if("activated"!==e.state)if("redundant"!==e.state){var i=function(){if("activated"===e.state)n(t);else{if("redundant"!==e.state)return;r(Si.create(Ti.SW_REG_REDUNDANT))}e.removeEventListener("statechange",i)};e.addEventListener("statechange",i)}else r(Si.create(Ti.SW_REG_REDUNDANT));else n(t);else r(Si.create(Ti.NO_SW_IN_REG))})},e.prototype.getSWRegistration_=function(){var t=this;return this.registrationToUse?this.waitForRegistrationToActivate_(this.registrationToUse):(this.registrationToUse=null,navigator.serviceWorker.register("/firebase-messaging-sw.js",{scope:"/firebase-cloud-messaging-push-scope"}).catch(function(t){throw Si.create(Ti.FAILED_DEFAULT_REGISTRATION,{browserErrorMessage:t.message})}).then(function(e){return t.waitForRegistrationToActivate_(e).then(function(){return t.registrationToUse=e,e.update(),e})}))},e.prototype.getPublicVapidKey_=function(){return this.publicVapidKeyToUse?Promise.resolve(this.publicVapidKeyToUse):Promise.resolve(Ii)},e.prototype.setupSWMessageListener_=function(){var t=this;"serviceWorker"in navigator&&navigator.serviceWorker.addEventListener("message",function(e){if(e.data&&e.data[wi.TYPE_OF_MSG]){var n=e.data;switch(n[wi.TYPE_OF_MSG]){case Ei.PUSH_MSG_RECEIVED:case Ei.NOTIFICATION_CLICKED:var r=n[wi.DATA];t.messageObserver&&t.messageObserver.next(r)}}},!1)},e.prototype.isSupported_=function(){return"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")},e}(Bi);!function(t){var e={Messaging:Hi};t.INTERNAL.registerService("messaging",function(t){return self&&"ServiceWorkerGlobalScope"in self?new ji(t):new Hi(t)},e)}(te);var Ki="https://firebasestorage.googleapis.com",Gi="https://firebasestorage.googleapis.com",Qi="/v0",zi="/v0",Yi=12e4,Xi=6e4,$i=-9007199254740991,Ji=function(){function t(t,e){this.code_=to(t),this.message_="Firebase Storage: "+e,this.serverResponse_=null,this.name_="FirebaseError"}return t.prototype.codeProp=function(){return this.code},t.prototype.codeEquals=function(t){return to(t)===this.codeProp()},t.prototype.serverResponseProp=function(){return this.serverResponse_},t.prototype.setServerResponseProp=function(t){this.serverResponse_=t},Object.defineProperty(t.prototype,"name",{get:function(){return this.name_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"code",{get:function(){return this.code_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"message",{get:function(){return this.message_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"serverResponse",{get:function(){return this.serverResponse_},enumerable:!0,configurable:!0}),t}(),Zi={UNKNOWN:"unknown",OBJECT_NOT_FOUND:"object-not-found",BUCKET_NOT_FOUND:"bucket-not-found",PROJECT_NOT_FOUND:"project-not-found",QUOTA_EXCEEDED:"quota-exceeded",UNAUTHENTICATED:"unauthenticated",UNAUTHORIZED:"unauthorized",RETRY_LIMIT_EXCEEDED:"retry-limit-exceeded",INVALID_CHECKSUM:"invalid-checksum",CANCELED:"canceled",INVALID_EVENT_NAME:"invalid-event-name",INVALID_URL:"invalid-url",INVALID_DEFAULT_BUCKET:"invalid-default-bucket",NO_DEFAULT_BUCKET:"no-default-bucket",CANNOT_SLICE_BLOB:"cannot-slice-blob",SERVER_FILE_WRONG_SIZE:"server-file-wrong-size",NO_DOWNLOAD_URL:"no-download-url",INVALID_ARGUMENT:"invalid-argument",INVALID_ARGUMENT_COUNT:"invalid-argument-count",APP_DELETED:"app-deleted",INVALID_ROOT_OPERATION:"invalid-root-operation",INVALID_FORMAT:"invalid-format",INTERNAL_ERROR:"internal-error"};function to(t){return"storage/"+t}function eo(){return new Ji(Zi.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function no(){return new Ji(Zi.CANCELED,"User canceled the upload/download.")}function ro(){return new Ji(Zi.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function io(t,e,n){return new Ji(Zi.INVALID_ARGUMENT,"Invalid argument in `"+e+"` at index "+t+": "+n)}function oo(){return new Ji(Zi.APP_DELETED,"The Firebase app was deleted.")}function ao(t,e){return new Ji(Zi.INVALID_FORMAT,"String does not match format '"+t+"': "+e)}function so(t){throw new Ji(Zi.INTERNAL_ERROR,"Internal error: "+t)}var uo={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};function co(t){switch(t){case uo.RAW:case uo.BASE64:case uo.BASE64URL:case uo.DATA_URL:return;default:throw"Expected one of the event types: ["+uo.RAW+", "+uo.BASE64+", "+uo.BASE64URL+", "+uo.DATA_URL+"]."}}var ho=function(){return function(t,e){this.data=t,this.contentType=e||null}}();function lo(t,e){switch(t){case uo.RAW:return new ho(po(e));case uo.BASE64:case uo.BASE64URL:return new ho(fo(t,e));case uo.DATA_URL:return new ho(function(t){var e=new vo(t);return e.base64?fo(uo.BASE64,e.rest):function(t){var e;try{e=decodeURIComponent(t)}catch(t){throw ao(uo.DATA_URL,"Malformed data URL.")}return po(e)}(e.rest)}(e),function(t){return new vo(t).contentType}(e))}throw eo()}function po(t){for(var e=[],n=0;n<t.length;n++){var r=t.charCodeAt(n);if(r<=127)e.push(r);else if(r<=2047)e.push(192|r>>6,128|63&r);else if(55296==(64512&r))if(n<t.length-1&&56320==(64512&t.charCodeAt(n+1)))r=65536|(1023&r)<<10|1023&t.charCodeAt(++n),e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r);else e.push(239,191,189);else 56320==(64512&r)?e.push(239,191,189):e.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(e)}function fo(t,e){switch(t){case uo.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw ao(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case uo.BASE64URL:var i=-1!==e.indexOf("+"),o=-1!==e.indexOf("/");if(i||o)throw ao(t,"Invalid character '"+(i?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}var a;try{a=atob(e)}catch(e){throw ao(t,"Invalid character found")}for(var s=new Uint8Array(a.length),u=0;u<a.length;u++)s[u]=a.charCodeAt(u);return s}var vo=function(){return function(t){this.base64=!1,this.contentType=null;var e=t.match(/^data:([^,]+)?,/);if(null===e)throw ao(uo.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");var n=e[1]||null;null!=n&&(this.base64=(r=n,i=";base64",r.length>=i.length&&r.substring(r.length-i.length)===i),this.contentType=this.base64?n.substring(0,n.length-";base64".length):n),this.rest=t.substring(t.indexOf(",")+1);var r,i}}();var yo,_o={STATE_CHANGED:"state_changed"},go={RUNNING:"running",PAUSING:"pausing",PAUSED:"paused",SUCCESS:"success",CANCELING:"canceling",CANCELED:"canceled",ERROR:"error"},mo={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function bo(t){switch(t){case go.RUNNING:case go.PAUSING:case go.CANCELING:return mo.RUNNING;case go.PAUSED:return mo.PAUSED;case go.SUCCESS:return mo.SUCCESS;case go.CANCELED:return mo.CANCELED;case go.ERROR:default:return mo.ERROR}}function wo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Eo(t,e){for(var n in t)wo(t,n)&&e(n,t[n])}function To(t){if(null==t)return{};var e={};return Eo(t,function(t,n){e[t]=n}),e}function Co(t){return new Promise(t)}function So(t){return Promise.resolve(t)}function Io(t){return null!=t}function No(t){return void 0!==t}function Ro(t){return"function"==typeof t}function Ao(t){return"object"==typeof t}function ko(t){return Ao(t)&&null!==t}function Oo(t){return"string"==typeof t||t instanceof String}function Po(t){return Do()&&t instanceof Blob}function Do(){return"undefined"!=typeof Blob}!function(t){t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT"}(yo||(yo={}));var Lo=function(){function t(){var t=this;this.sent_=!1,this.xhr_=new XMLHttpRequest,this.errorCode_=yo.NO_ERROR,this.sendPromise_=Co(function(e,n){t.xhr_.addEventListener("abort",function(n){t.errorCode_=yo.ABORT,e(t)}),t.xhr_.addEventListener("error",function(n){t.errorCode_=yo.NETWORK_ERROR,e(t)}),t.xhr_.addEventListener("load",function(n){e(t)})})}return t.prototype.send=function(t,e,n,r){var i=this;if(this.sent_)throw so("cannot .send() more than once");(this.sent_=!0,this.xhr_.open(e,t,!0),Io(r))&&Eo(r,function(t,e){i.xhr_.setRequestHeader(t,e.toString())});return Io(n)?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_},t.prototype.getErrorCode=function(){if(!this.sent_)throw so("cannot .getErrorCode() before sending");return this.errorCode_},t.prototype.getStatus=function(){if(!this.sent_)throw so("cannot .getStatus() before sending");try{return this.xhr_.status}catch(t){return-1}},t.prototype.getResponseText=function(){if(!this.sent_)throw so("cannot .getResponseText() before sending");return this.xhr_.responseText},t.prototype.abort=function(){this.xhr_.abort()},t.prototype.getResponseHeader=function(t){return this.xhr_.getResponseHeader(t)},t.prototype.addUploadProgressListener=function(t){Io(this.xhr_.upload)&&this.xhr_.upload.addEventListener("progress",t)},t.prototype.removeUploadProgressListener=function(t){Io(this.xhr_.upload)&&this.xhr_.upload.removeEventListener("progress",t)},t}(),xo=function(){function t(){}return t.prototype.createXhrIo=function(){return new Lo},t}();function Fo(t){var e,n;try{e=JSON.parse(t)}catch(t){return null}return Ao(n=e)&&!Array.isArray(n)?e:null}var Uo=function(){function t(t,e){this.bucket=t,this.path_=e}return Object.defineProperty(t.prototype,"path",{get:function(){return this.path_},enumerable:!0,configurable:!0}),t.prototype.fullServerUrl=function(){var t=encodeURIComponent;return"/b/"+t(this.bucket)+"/o/"+t(this.path)},t.prototype.bucketOnlyServerUrl=function(){return"/b/"+encodeURIComponent(this.bucket)+"/o"},t.makeFromBucketSpec=function(e){var n,r;try{n=t.makeFromUrl(e)}catch(n){return new t(e,"")}if(""===n.path)return n;throw r=e,new Ji(Zi.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+r+"'.")},t.makeFromUrl=function(e){var n=null;for(var r=[{regex:new RegExp("^gs://([A-Za-z0-9.\\-]+)(/(.*))?$","i"),indices:{bucket:1,path:3},postModify:function(t){"/"===t.path.charAt(t.path.length-1)&&(t.path_=t.path_.slice(0,-1))}},{regex:new RegExp("^https?://firebasestorage\\.googleapis\\.com/v[A-Za-z0-9_]+/b/([A-Za-z0-9.\\-]+)/o(/([^?#]*).*)?$","i"),indices:{bucket:1,path:3},postModify:function(t){t.path_=decodeURIComponent(t.path)}}],i=0;i<r.length;i++){var o=r[i],a=o.regex.exec(e);if(a){var s=a[o.indices.bucket],u=a[o.indices.path];u||(u=""),n=new t(s,u),o.postModify(n);break}}if(null==n)throw function(t){return new Ji(Zi.INVALID_URL,"Invalid URL '"+t+"'.")}(e);return n},t}();function Mo(t){var e=t.lastIndexOf("/",t.length-2);return-1===e?t:t.slice(e+1)}function Wo(t){return Ki+Qi+t}function Bo(t){return Ki+zi+t}function jo(t){var e=encodeURIComponent,n="?";return Eo(t,function(t,r){var i=e(t)+"="+e(r);n=n+i+"&"}),n=n.slice(0,-1)}function Vo(t,e){return e}var qo=function(){return function(t,e,n,r){this.server=t,this.local=e||t,this.writable=!!n,this.xform=r||Vo}}(),Ho=null;function Ko(){if(Ho)return Ho;var t=[];t.push(new qo("bucket")),t.push(new qo("generation")),t.push(new qo("metageneration")),t.push(new qo("name","fullPath",!0));var e=new qo("name");e.xform=function(t,e){return function(t){return!Oo(t)||t.length<2?t:Mo(t=t)}(e)},t.push(e);var n=new qo("size");return n.xform=function(t,e){return Io(e)?+e:e},t.push(n),t.push(new qo("timeCreated")),t.push(new qo("updated")),t.push(new qo("md5Hash",null,!0)),t.push(new qo("cacheControl",null,!0)),t.push(new qo("contentDisposition",null,!0)),t.push(new qo("contentEncoding",null,!0)),t.push(new qo("contentLanguage",null,!0)),t.push(new qo("contentType",null,!0)),t.push(new qo("metadata","customMetadata",!0)),t.push(new qo("downloadTokens","downloadURLs",!1,function(t,e){if(!(Oo(e)&&e.length>0))return[];var n=encodeURIComponent;return e.split(",").map(function(e){var r=t.bucket,i=t.fullPath;return function(t){return Gi+Qi+t}("/b/"+n(r)+"/o/"+n(i))+jo({alt:"media",token:e})})})),Ho=t}function Go(t,e,n){for(var r={type:"file"},i=n.length,o=0;o<i;o++){var a=n[o];r[a.local]=a.xform(r,e[a.server])}return function(t,e){Object.defineProperty(t,"ref",{get:function(){var n=t.bucket,r=t.fullPath,i=new Uo(n,r);return e.makeStorageReference(i)}})}(r,t),r}function Qo(t,e){for(var n={},r=e.length,i=0;i<r;i++){var o=e[i];o.writable&&(n[o.server]=t[o.local])}return JSON.stringify(n)}function zo(t){if(!(t&&Ao(t)))throw"Expected Metadata object.";for(var e in t){var n=t[e];if("customMetadata"===e){if(!Ao(n))throw"Expected object for 'customMetadata' mapping."}else if(ko(n))throw"Mapping for '"+e+"' cannot be an object."}}function Yo(t,e,n){for(var r=e.length,i=e.length,o=0;o<e.length;o++)if(e[o].optional){r=o;break}var a,s,u,c,h,l;if(!(r<=n.length&&n.length<=i))throw a=r,s=i,u=t,c=n.length,a===s?(h=a,l=1===a?"argument":"arguments"):(h="between "+a+" and "+s,l="arguments"),new Ji(Zi.INVALID_ARGUMENT_COUNT,"Invalid argument count in `"+u+"`: Expected "+h+" "+l+", received "+c+".");for(o=0;o<n.length;o++)try{e[o].validator(n[o])}catch(e){throw e instanceof Error?io(o,t,e.message):io(o,t,e)}}var Xo=function(){return function(t,e){var n=this;this.validator=function(e){n.optional&&!No(e)||t(e)},this.optional=!!e}}();function $o(t,e){function n(t){if(!Oo(t))throw"Expected string."}var r,i,o;return t?(i=n,o=t,r=function(t){i(t),o(t)}):r=n,new Xo(r,e)}function Jo(t){return new Xo(zo,t)}function Zo(){return new Xo(function(t){if(!(function(t){return"number"==typeof t||t instanceof Number}(t)&&t>=0))throw"Expected a number 0 or greater."})}function ta(t,e){return new Xo(function(e){if(!(null===e||Io(e)&&e instanceof Object))throw"Expected an Object.";void 0!==t&&null!==t&&t(e)},e)}function ea(t){return new Xo(function(t){if(null!==t&&!Ro(t))throw"Expected a Function."},t)}function na(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}var ra=function(){function t(t,e){var n=0,r="";Po(t)?(this.data_=t,n=t.size,r=t.type):t instanceof ArrayBuffer?(e?this.data_=new Uint8Array(t):(this.data_=new Uint8Array(t.byteLength),this.data_.set(new Uint8Array(t))),n=this.data_.length):t instanceof Uint8Array&&(e?this.data_=t:(this.data_=new Uint8Array(t.length),this.data_.set(t)),n=t.length),this.size_=n,this.type_=r}return t.prototype.size=function(){return this.size_},t.prototype.type=function(){return this.type_},t.prototype.slice=function(e,n){if(Po(this.data_)){var r=this.data_,i=(a=e,s=n,(o=r).webkitSlice?o.webkitSlice(a,s):o.mozSlice?o.mozSlice(a,s):o.slice?o.slice(a,s):null);return null===i?null:new t(i)}var o,a,s;return new t(new Uint8Array(this.data_.buffer,e,n-e),!0)},t.getBlob=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];if(Do()){var r=e.map(function(e){return e instanceof t?e.data_:e});return new t(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=na();if(void 0!==n){for(var r=new n,i=0;i<t.length;i++)r.append(t[i]);return r.getBlob()}if(Do())return new Blob(t);throw Error("This browser doesn't seem to support creating Blobs")}.apply(null,r))}var i=e.map(function(t){return Oo(t)?lo(uo.RAW,t).data:t.data_}),o=0;i.forEach(function(t){o+=t.byteLength});var a=new Uint8Array(o),s=0;return i.forEach(function(t){for(var e=0;e<t.length;e++)a[s++]=t[e]}),new t(a,!0)},t.prototype.uploadData=function(){return this.data_},t}();function ia(t,e){return-1!==t.indexOf(e)}var oa=function(){return function(t,e,n,r){this.url=t,this.method=e,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}();function aa(t){if(!t)throw eo()}function sa(t,e){return function(n,r){var i=function(t,e,n){var r=Fo(e);return null===r?null:Go(t,r,n)}(t,r,e);return aa(null!==i),i}}function ua(t){return function(e,n){var r,i,o;return 401===e.getStatus()?r=new Ji(Zi.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(o=t.bucket,r=new Ji(Zi.QUOTA_EXCEEDED,"Quota for bucket '"+o+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(i=t.path,r=new Ji(Zi.UNAUTHORIZED,"User does not have permission to access '"+i+"'.")):r=n,r.setServerResponseProp(n.serverResponseProp()),r}}function ca(t){var e=ua(t);return function(n,r){var i,o=e(n,r);return 404===n.getStatus()&&(i=t.path,o=new Ji(Zi.OBJECT_NOT_FOUND,"Object '"+i+"' does not exist.")),o.setServerResponseProp(r.serverResponseProp()),o}}function ha(t,e,n){var r=Wo(e.fullServerUrl()),i=t.maxOperationRetryTime(),o=new oa(r,"GET",sa(t,n),i);return o.errorHandler=ca(e),o}function la(t,e,n){var r=To(n);return r.fullPath=t.path,r.size=e.size(),r.contentType||(r.contentType=function(t,e){return t&&t.contentType||e&&e.type()||"application/octet-stream"}(null,e)),r}var pa=function(){return function(t,e,n,r){this.current=t,this.total=e,this.finalized=!!n,this.metadata=r||null}}();function fa(t,e){var n;try{n=t.getResponseHeader("X-Goog-Upload-Status")}catch(t){aa(!1)}return aa(ia(e||["active"],n)),n}function da(t,e,n,r,i,o,a,s){var u=new pa(0,0);if(a?(u.current=a.current,u.total=a.total):(u.current=0,u.total=r.size()),r.size()!==u.total)throw new Ji(Zi.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");var c=u.total-u.current,h=c;i>0&&(h=Math.min(h,i));var l=u.current,p=l+h,f={"X-Goog-Upload-Command":h===c?"upload, finalize":"upload","X-Goog-Upload-Offset":u.current},d=r.slice(l,p);if(null===d)throw ro();var v=e.maxUploadRetryTime(),y=new oa(n,"POST",function(t,n){var i,a=fa(t,["active","final"]),s=u.current+h,c=r.size();return i="final"===a?sa(e,o)(t,n):null,new pa(s,c,"final"===a,i)},v);return y.headers=f,y.body=d.uploadData(),y.progressCallback=s||null,y.errorHandler=ua(t),y}var va=function(){return function(t,e,n){if(Ro(t)||Io(e)||Io(n))this.next=t,this.error=e||null,this.complete=n||null;else{var r=t;this.next=r.next||null,this.error=r.error||null,this.complete=r.complete||null}}}(),ya=function(){function t(t,e,n,r,i,o){this.bytesTransferred=t,this.totalBytes=e,this.state=n,this.metadata=r,this.task=i,this.ref=o}return Object.defineProperty(t.prototype,"downloadURL",{get:function(){if(null!==this.metadata){var t=this.metadata.downloadURLs;return null!=t&&null!=t[0]?t[0]:null}return null},enumerable:!0,configurable:!0}),t}();function _a(t){return function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];So(!0).then(function(){t.apply(null,e)})}}var ga=function(){function t(t,e,n,r,i,o){void 0===o&&(o=null);var a=this;this.transferred_=0,this.needToFetchStatus_=!1,this.needToFetchMetadata_=!1,this.observers_=[],this.error_=null,this.uploadUrl_=null,this.request_=null,this.chunkMultiplier_=1,this.resolve_=null,this.reject_=null,this.ref_=t,this.authWrapper_=e,this.location_=n,this.blob_=i,this.metadata_=o,this.mappings_=r,this.resumable_=this.shouldDoResumable_(this.blob_),this.state_=go.RUNNING,this.errorHandler_=function(t){a.request_=null,a.chunkMultiplier_=1,t.codeEquals(Zi.CANCELED)?(a.needToFetchStatus_=!0,a.completeTransitions_()):(a.error_=t,a.transition_(go.ERROR))},this.metadataErrorHandler_=function(t){a.request_=null,t.codeEquals(Zi.CANCELED)?a.completeTransitions_():(a.error_=t,a.transition_(go.ERROR))},this.promise_=Co(function(t,e){a.resolve_=t,a.reject_=e,a.start_()}),this.promise_.then(null,function(){})}return t.prototype.makeProgressCallback_=function(){var t=this,e=this.transferred_;return function(n,r){t.updateProgress_(e+n)}},t.prototype.shouldDoResumable_=function(t){return t.size()>262144},t.prototype.start_=function(){this.state_===go.RUNNING&&null===this.request_&&(this.resumable_?null===this.uploadUrl_?this.createResumable_():this.needToFetchStatus_?this.fetchStatus_():this.needToFetchMetadata_?this.fetchMetadata_():this.continueUpload_():this.oneShotUpload_())},t.prototype.resolveToken_=function(t){var e=this;this.authWrapper_.getAuthToken().then(function(n){switch(e.state_){case go.RUNNING:t(n);break;case go.CANCELING:e.transition_(go.CANCELED);break;case go.PAUSING:e.transition_(go.PAUSED)}})},t.prototype.createResumable_=function(){var t=this;this.resolveToken_(function(e){var n=function(t,e,n,r,i){var o=e.bucketOnlyServerUrl(),a=la(e,r,i),s={name:a.fullPath},u=Bo(o),c={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":r.size(),"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},h=Qo(a,n),l=t.maxUploadRetryTime(),p=new oa(u,"POST",function(t,e){var n;fa(t);try{n=t.getResponseHeader("X-Goog-Upload-URL")}catch(t){aa(!1)}return aa(Oo(n)),n},l);return p.urlParams=s,p.headers=c,p.body=h,p.errorHandler=ua(e),p}(t.authWrapper_,t.location_,t.mappings_,t.blob_,t.metadata_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then(function(e){t.request_=null,t.uploadUrl_=e,t.needToFetchStatus_=!1,t.completeTransitions_()},t.errorHandler_)})},t.prototype.fetchStatus_=function(){var t=this,e=this.uploadUrl_;this.resolveToken_(function(n){var r=function(t,e,n,r){var i=t.maxUploadRetryTime(),o=new oa(n,"POST",function(t,e){var n,i=fa(t,["active","final"]);try{n=t.getResponseHeader("X-Goog-Upload-Size-Received")}catch(t){aa(!1)}var o=parseInt(n,10);return aa(!isNaN(o)),new pa(o,r.size(),"final"===i)},i);return o.headers={"X-Goog-Upload-Command":"query"},o.errorHandler=ua(e),o}(t.authWrapper_,t.location_,e,t.blob_),i=t.authWrapper_.makeRequest(r,n);t.request_=i,i.getPromise().then(function(e){e=e,t.request_=null,t.updateProgress_(e.current),t.needToFetchStatus_=!1,e.finalized&&(t.needToFetchMetadata_=!0),t.completeTransitions_()},t.errorHandler_)})},t.prototype.continueUpload_=function(){var t=this,e=262144*this.chunkMultiplier_,n=new pa(this.transferred_,this.blob_.size()),r=this.uploadUrl_;this.resolveToken_(function(i){var o;try{o=da(t.location_,t.authWrapper_,r,t.blob_,e,t.mappings_,n,t.makeProgressCallback_())}catch(e){return t.error_=e,void t.transition_(go.ERROR)}var a=t.authWrapper_.makeRequest(o,i);t.request_=a,a.getPromise().then(function(e){t.increaseMultiplier_(),t.request_=null,t.updateProgress_(e.current),e.finalized?(t.metadata_=e.metadata,t.transition_(go.SUCCESS)):t.completeTransitions_()},t.errorHandler_)})},t.prototype.increaseMultiplier_=function(){262144*this.chunkMultiplier_<33554432&&(this.chunkMultiplier_*=2)},t.prototype.fetchMetadata_=function(){var t=this;this.resolveToken_(function(e){var n=ha(t.authWrapper_,t.location_,t.mappings_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then(function(e){t.request_=null,t.metadata_=e,t.transition_(go.SUCCESS)},t.metadataErrorHandler_)})},t.prototype.oneShotUpload_=function(){var t=this;this.resolveToken_(function(e){var n=function(t,e,n,r,i){var o=e.bucketOnlyServerUrl(),a={"X-Goog-Upload-Protocol":"multipart"},s=function(){for(var t="",e=0;e<2;e++)t+=Math.random().toString().slice(2);return t}();a["Content-Type"]="multipart/related; boundary="+s;var u=la(e,r,i),c="--"+s+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+Qo(u,n)+"\r\n--"+s+"\r\nContent-Type: "+u.contentType+"\r\n\r\n",h="\r\n--"+s+"--",l=ra.getBlob(c,r,h);if(null===l)throw ro();var p={name:u.fullPath},f=Bo(o),d=t.maxUploadRetryTime(),v=new oa(f,"POST",sa(t,n),d);return v.urlParams=p,v.headers=a,v.body=l.uploadData(),v.errorHandler=ua(e),v}(t.authWrapper_,t.location_,t.mappings_,t.blob_,t.metadata_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then(function(e){t.request_=null,t.metadata_=e,t.updateProgress_(t.blob_.size()),t.transition_(go.SUCCESS)},t.errorHandler_)})},t.prototype.updateProgress_=function(t){var e=this.transferred_;this.transferred_=t,this.transferred_!==e&&this.notifyObservers_()},t.prototype.transition_=function(t){if(this.state_!==t)switch(t){case go.CANCELING:case go.PAUSING:this.state_=t,null!==this.request_&&this.request_.cancel();break;case go.RUNNING:var e=this.state_===go.PAUSED;this.state_=t,e&&(this.notifyObservers_(),this.start_());break;case go.PAUSED:this.state_=t,this.notifyObservers_();break;case go.CANCELED:this.error_=no(),this.state_=t,this.notifyObservers_();break;case go.ERROR:case go.SUCCESS:this.state_=t,this.notifyObservers_()}},t.prototype.completeTransitions_=function(){switch(this.state_){case go.PAUSING:this.transition_(go.PAUSED);break;case go.CANCELING:this.transition_(go.CANCELED);break;case go.RUNNING:this.start_()}},Object.defineProperty(t.prototype,"snapshot",{get:function(){var t=bo(this.state_);return new ya(this.transferred_,this.blob_.size(),t,this.metadata_,this,this.ref_)},enumerable:!0,configurable:!0}),t.prototype.on=function(t,e,n,r){void 0===e&&(e=void 0),void 0===n&&(n=void 0),void 0===r&&(r=void 0);var i="Expected a function or an Object with one of `next`, `error`, `complete` properties.",o=ea(!0).validator,a=ta(null,!0).validator;function s(t){try{return void o(t)}catch(t){}try{if(a(t),!(No(t.next)||No(t.error)||No(t.complete)))throw"";return}catch(t){throw i}}Yo("on",[$o(function(e){if(t!==_o.STATE_CHANGED)throw"Expected one of the event types: ["+_o.STATE_CHANGED+"]."}),ta(s,!0),ea(!0),ea(!0)],arguments);var u=this;function c(t){return function(e,n,i){null!==t&&Yo("on",t,arguments);var o=new va(e,n,r);return u.addObserver_(o),function(){u.removeObserver_(o)}}}var h=[ta(function(t){if(null===t)throw i;s(t)}),ea(!0),ea(!0)];return!(No(e)||No(n)||No(r))?c(h):c(null)(e,n,r)},t.prototype.then=function(t,e){return this.promise_.then(t,e)},t.prototype.catch=function(t){return this.then(null,t)},t.prototype.addObserver_=function(t){this.observers_.push(t),this.notifyObserver_(t)},t.prototype.removeObserver_=function(t){var e,n,r;e=this.observers_,n=t,-1!==(r=e.indexOf(n))&&e.splice(r,1)},t.prototype.notifyObservers_=function(){var t,e=this;this.finishPromise_(),(t=this.observers_,Array.prototype.slice.call(t)).forEach(function(t){e.notifyObserver_(t)})},t.prototype.finishPromise_=function(){if(null!==this.resolve_){var t=!0;switch(bo(this.state_)){case mo.SUCCESS:_a(this.resolve_.bind(null,this.snapshot))();break;case mo.CANCELED:case mo.ERROR:_a(this.reject_.bind(null,this.error_))();break;default:t=!1}t&&(this.resolve_=null,this.reject_=null)}},t.prototype.notifyObserver_=function(t){switch(bo(this.state_)){case mo.RUNNING:case mo.PAUSED:null!==t.next&&_a(t.next.bind(t,this.snapshot))();break;case mo.SUCCESS:null!==t.complete&&_a(t.complete.bind(t))();break;case mo.CANCELED:case mo.ERROR:null!==t.error&&_a(t.error.bind(t,this.error_))();break;default:null!==t.error&&_a(t.error.bind(t,this.error_))()}},t.prototype.resume=function(){Yo("resume",[],arguments);var t=this.state_===go.PAUSED||this.state_===go.PAUSING;return t&&this.transition_(go.RUNNING),t},t.prototype.pause=function(){Yo("pause",[],arguments);var t=this.state_===go.RUNNING;return t&&this.transition_(go.PAUSING),t},t.prototype.cancel=function(){Yo("cancel",[],arguments);var t=this.state_===go.RUNNING||this.state_===go.PAUSING;return t&&this.transition_(go.CANCELING),t},t}(),ma=function(){function t(t,e){this.authWrapper=t,this.location=e instanceof Uo?e:Uo.makeFromUrl(e)}return t.prototype.toString=function(){return Yo("toString",[],arguments),"gs://"+this.location.bucket+"/"+this.location.path},t.prototype.newRef=function(e,n){return new t(e,n)},t.prototype.mappings=function(){return Ko()},t.prototype.child=function(t){Yo("child",[$o()],arguments);var e=function(t,e){var n=e.split("/").filter(function(t){return t.length>0}).join("/");return 0===t.length?n:t+"/"+n}(this.location.path,t),n=new Uo(this.location.bucket,e);return this.newRef(this.authWrapper,n)},Object.defineProperty(t.prototype,"parent",{get:function(){var t=function(t){if(0==t.length)return null;var e=t.lastIndexOf("/");return-1===e?"":t.slice(0,e)}(this.location.path);if(null===t)return null;var e=new Uo(this.location.bucket,t);return this.newRef(this.authWrapper,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){var t=new Uo(this.location.bucket,"");return this.newRef(this.authWrapper,t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bucket",{get:function(){return this.location.bucket},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullPath",{get:function(){return this.location.path},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return Mo(this.location.path)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"storage",{get:function(){return this.authWrapper.service()},enumerable:!0,configurable:!0}),t.prototype.put=function(t,e){return void 0===e&&(e=null),Yo("put",[new Xo(function(t){if(!(t instanceof Uint8Array||t instanceof ArrayBuffer||Do()&&t instanceof Blob))throw"Expected Blob or File."}),Jo(!0)],arguments),this.throwIfRoot_("put"),new ga(this,this.authWrapper,this.location,this.mappings(),new ra(t),e)},t.prototype.putString=function(t,e,n){void 0===e&&(e=uo.RAW),Yo("putString",[$o(),$o(co,!0),Jo(!0)],arguments),this.throwIfRoot_("putString");var r=lo(e,t),i=To(n);return!Io(i.contentType)&&Io(r.contentType)&&(i.contentType=r.contentType),new ga(this,this.authWrapper,this.location,this.mappings(),new ra(r.data,!0),i)},t.prototype.delete=function(){Yo("delete",[],arguments),this.throwIfRoot_("delete");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=function(t,e){var n=Wo(e.fullServerUrl()),r=t.maxOperationRetryTime(),i=new oa(n,"DELETE",function(t,e){},r);return i.successCodes=[200,204],i.errorHandler=ca(e),i}(t.authWrapper,t.location);return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.getMetadata=function(){Yo("getMetadata",[],arguments),this.throwIfRoot_("getMetadata");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=ha(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.updateMetadata=function(t){Yo("updateMetadata",[Jo()],arguments),this.throwIfRoot_("updateMetadata");var e=this;return this.authWrapper.getAuthToken().then(function(n){var r=function(t,e,n,r){var i=Wo(e.fullServerUrl()),o=Qo(n,r),a=t.maxOperationRetryTime(),s=new oa(i,"PATCH",sa(t,r),a);return s.headers={"Content-Type":"application/json; charset=utf-8"},s.body=o,s.errorHandler=ca(e),s}(e.authWrapper,e.location,t,e.mappings());return e.authWrapper.makeRequest(r,n).getPromise()})},t.prototype.getDownloadURL=function(){return Yo("getDownloadURL",[],arguments),this.throwIfRoot_("getDownloadURL"),this.getMetadata().then(function(t){var e=t.downloadURLs[0];if(Io(e))return e;throw new Ji(Zi.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")})},t.prototype.throwIfRoot_=function(t){if(""===this.location.path)throw function(t){return new Ji(Zi.INVALID_ROOT_OPERATION,"The operation '"+t+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}(t)},t}(),ba=function(){function t(t){this.promise_=function(t){return Promise.reject(t)}(t)}return t.prototype.getPromise=function(){return this.promise_},t.prototype.cancel=function(t){void 0===t&&(t=!1)},t}(),wa=function(){function t(){this.map_={},this.id_=$i}return t.prototype.addRequest=function(t){var e=this.id_;this.id_++,this.map_[e]=t;var n=this;function r(){delete n.map_[e]}t.getPromise().then(r,r)},t.prototype.clear=function(){Eo(this.map_,function(t,e){e&&e.cancel(!0)}),this.map_={}},t}(),Ea=function(){function t(e,n,r,i,o){if(this.bucket_=null,this.deleted_=!1,this.app_=e,null!==this.app_){var a=this.app_.options;Io(a)&&(this.bucket_=t.extractBucket_(a))}this.storageRefMaker_=n,this.requestMaker_=r,this.pool_=o,this.service_=i,this.maxOperationRetryTime_=Yi,this.maxUploadRetryTime_=Xi,this.requestMap_=new wa}return t.extractBucket_=function(t){var e=t.storageBucket||null;return null==e?null:Uo.makeFromBucketSpec(e).bucket},t.prototype.getAuthToken=function(){return null!==this.app_&&Io(this.app_.INTERNAL)&&Io(this.app_.INTERNAL.getToken)?this.app_.INTERNAL.getToken().then(function(t){return null!==t?t.accessToken:null},function(t){return null}):So(null)},t.prototype.bucket=function(){if(this.deleted_)throw oo();return this.bucket_},t.prototype.service=function(){return this.service_},t.prototype.makeStorageReference=function(t){return this.storageRefMaker_(this,t)},t.prototype.makeRequest=function(t,e){if(this.deleted_)return new ba(oo());var n=this.requestMaker_(t,e,this.pool_);return this.requestMap_.addRequest(n),n},t.prototype.deleteApp=function(){this.deleted_=!0,this.app_=null,this.requestMap_.clear()},t.prototype.maxUploadRetryTime=function(){return this.maxUploadRetryTime_},t.prototype.setMaxUploadRetryTime=function(t){this.maxUploadRetryTime_=t},t.prototype.maxOperationRetryTime=function(){return this.maxOperationRetryTime_},t.prototype.setMaxOperationRetryTime=function(t){this.maxOperationRetryTime_=t},t}();var Ta=function(){function t(t,e,n,r,i,o,a,s,u,c,h){this.pendingXhr_=null,this.backoffId_=null,this.resolve_=null,this.reject_=null,this.canceled_=!1,this.appDelete_=!1,this.url_=t,this.method_=e,this.headers_=n,this.body_=r,this.successCodes_=i.slice(),this.additionalRetryCodes_=o.slice(),this.callback_=a,this.errorCallback_=s,this.progressCallback_=c,this.timeout_=u,this.pool_=h;var l=this;this.promise_=Co(function(t,e){l.resolve_=t,l.reject_=e,l.start_()})}return t.prototype.start_=function(){var t=this;function e(e,n){var r,i=t.resolve_,o=t.reject_,a=n.xhr;if(n.wasSuccessCode)try{var s=t.callback_(a,a.getResponseText());No(s)?i(s):i()}catch(t){o(t)}else null!==a?((r=eo()).setServerResponseProp(a.getResponseText()),t.errorCallback_?o(t.errorCallback_(a,r)):o(r)):n.canceled?o(r=t.appDelete_?oo():no()):o(r=new Ji(Zi.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again."))}this.canceled_?e(0,new Ca(!1,null,!0)):this.backoffId_=function(t,e,n){var r=1,i=null,o=!1,a=0;function s(){return 2===a}var u=!1;function c(){u||(u=!0,e.apply(null,arguments))}function h(e){i=setTimeout(function(){i=null,t(l,s())},e)}function l(t){for(var e,n=[],i=1;i<arguments.length;i++)n[i-1]=arguments[i];u||(t?c.apply(null,arguments):s()||o?c.apply(null,arguments):(r<64&&(r*=2),1===a?(a=2,e=0):e=1e3*(r+Math.random()),h(e)))}var p=!1;function f(t){p||(p=!0,u||(null!==i?(t||(a=2),clearTimeout(i),h(0)):t||(a=1)))}return h(0),setTimeout(function(){o=!0,f(!0)},n),f}(function(e,n){if(n)e(!1,new Ca(!1,null,!0));else{var r=t.pool_.createXhrIo();t.pendingXhr_=r,null!==t.progressCallback_&&r.addUploadProgressListener(i),r.send(t.url_,t.method_,t.body_,t.headers_).then(function(n){null!==t.progressCallback_&&n.removeUploadProgressListener(i),t.pendingXhr_=null;var r=(n=n).getErrorCode()===yo.NO_ERROR,o=n.getStatus();if(r&&!t.isRetryStatusCode_(o)){var a=ia(t.successCodes_,o);e(!0,new Ca(a,n))}else{var s=n.getErrorCode()===yo.ABORT;e(!1,new Ca(!1,null,s))}})}function i(e){var n=e.loaded,r=e.lengthComputable?e.total:-1;null!==t.progressCallback_&&t.progressCallback_(n,r)}},e,this.timeout_)},t.prototype.getPromise=function(){return this.promise_},t.prototype.cancel=function(t){this.canceled_=!0,this.appDelete_=t||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingXhr_&&this.pendingXhr_.abort()},t.prototype.isRetryStatusCode_=function(t){var e=t>=500&&t<600,n=ia([408,429],t),r=ia(this.additionalRetryCodes_,t);return e||n||r},t}(),Ca=function(){return function(t,e,n){this.wasSuccessCode=t,this.xhr=e,this.canceled=!!n}}();function Sa(t,e,n){var r=jo(t.urlParams),i=t.url+r,o=To(t.headers);return function(t,e){null!==e&&e.length>0&&(t.Authorization="Firebase "+e)}(o,e),function(t){var e=void 0!==te?te.SDK_VERSION:"AppManager";t["X-Firebase-Storage-Version"]="webjs/"+e}(o),new Ta(i,t.method,o,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,n)}var Ia=function(){function t(t,e,n){if(this.bucket_=null,this.authWrapper_=new Ea(t,function(t,e){return new ma(t,e)},Sa,this,e),this.app_=t,null!=n)this.bucket_=Uo.makeFromBucketSpec(n);else{var r=this.authWrapper_.bucket();null!=r&&(this.bucket_=new Uo(r,""))}this.internals_=new Na(this)}return t.prototype.ref=function(t){if(Yo("ref",[$o(function(t){if(/^[A-Za-z]+:\/\//.test(t))throw"Expected child path but got a URL, use refFromURL instead."},!0)],arguments),null==this.bucket_)throw new Error("No Storage Bucket defined in Firebase Options.");var e=new ma(this.authWrapper_,this.bucket_);return null!=t?e.child(t):e},t.prototype.refFromURL=function(t){return Yo("refFromURL",[$o(function(t){if(!/^[A-Za-z]+:\/\//.test(t))throw"Expected full URL but got a child path, use ref instead.";try{Uo.makeFromUrl(t)}catch(t){throw"Expected valid full URL but got an invalid one."}},!1)],arguments),new ma(this.authWrapper_,t)},Object.defineProperty(t.prototype,"maxUploadRetryTime",{get:function(){return this.authWrapper_.maxUploadRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxUploadRetryTime=function(t){Yo("setMaxUploadRetryTime",[Zo()],arguments),this.authWrapper_.setMaxUploadRetryTime(t)},Object.defineProperty(t.prototype,"maxOperationRetryTime",{get:function(){return this.authWrapper_.maxOperationRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxOperationRetryTime=function(t){Yo("setMaxOperationRetryTime",[Zo()],arguments),this.authWrapper_.setMaxOperationRetryTime(t)},Object.defineProperty(t.prototype,"app",{get:function(){return this.app_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"INTERNAL",{get:function(){return this.internals_},enumerable:!0,configurable:!0}),t}(),Na=function(){function t(t){this.service_=t}return t.prototype.delete=function(){return this.service_.authWrapper_.deleteApp(),So(void 0)},t}(),Ra="storage";function Aa(t,e,n){return new Ia(t,new xo,n)}return function(t){var e={TaskState:mo,TaskEvent:_o,StringFormat:uo,Storage:Ia,Reference:ma};t.INTERNAL.registerService(Ra,Aa,e,void 0,!0)}(te),re}); //# sourceMappingURL=firebase.js.map
import time from importlib import import_module from django.apps import apps from django.core.management.base import ( BaseCommand, CommandError, no_translations, ) from django.core.management.sql import ( emit_post_migrate_signal, emit_pre_migrate_signal, ) from django.db import DEFAULT_DB_ALIAS, connections, router from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.executor import MigrationExecutor from django.db.migrations.loader import AmbiguityError from django.db.migrations.state import ModelState, ProjectState from django.utils.module_loading import module_has_submodule from django.utils.text import Truncator class Command(BaseCommand): help = "Updates database schema. Manages both apps with migrations and those without." requires_system_checks = False def add_arguments(self, parser): parser.add_argument( '--skip-checks', action='store_true', help='Skip system checks.', ) parser.add_argument( 'app_label', nargs='?', help='App label of an application to synchronize the state.', ) parser.add_argument( 'migration_name', nargs='?', help='Database state will be brought to the state after that ' 'migration. Use the name "zero" to unapply all migrations.', ) parser.add_argument( '--noinput', '--no-input', action='store_false', dest='interactive', help='Tells Django to NOT prompt the user for input of any kind.', ) parser.add_argument( '--database', default=DEFAULT_DB_ALIAS, help='Nominates a database to synchronize. Defaults to the "default" database.', ) parser.add_argument( '--fake', action='store_true', help='Mark migrations as run without actually running them.', ) parser.add_argument( '--fake-initial', action='store_true', help='Detect if tables already exist and fake-apply initial migrations if so. Make sure ' 'that the current database schema matches your initial migration before using this ' 'flag. Django will only check for an existing table name.', ) parser.add_argument( '--plan', action='store_true', help='Shows a list of the migration actions that will be performed.', ) parser.add_argument( '--run-syncdb', action='store_true', help='Creates tables for apps without migrations.', ) @no_translations def handle(self, *args, **options): database = options['database'] if not options['skip_checks']: self.check(databases=[database]) self.verbosity = options['verbosity'] self.interactive = options['interactive'] # Import the 'management' module within each installed app, to register # dispatcher events. for app_config in apps.get_app_configs(): if module_has_submodule(app_config.module, "management"): import_module('.management', app_config.name) # Get the database we're operating from connection = connections[database] # Hook for backends needing any database preparation connection.prepare_database() # Work out which apps have migrations and which do not executor = MigrationExecutor(connection, self.migration_progress_callback) # Raise an error if any migrations are applied before their dependencies. executor.loader.check_consistent_history(connection) # Before anything else, see if there's conflicting apps and drop out # hard if there are any conflicts = executor.loader.detect_conflicts() if conflicts: name_str = "; ".join( "%s in %s" % (", ".join(names), app) for app, names in conflicts.items() ) raise CommandError( "Conflicting migrations detected; multiple leaf nodes in the " "migration graph: (%s).\nTo fix them run " "'python manage.py makemigrations --merge'" % name_str ) # If they supplied command line arguments, work out what they mean. run_syncdb = options['run_syncdb'] target_app_labels_only = True if options['app_label']: # Validate app_label. app_label = options['app_label'] try: apps.get_app_config(app_label) except LookupError as err: raise CommandError(str(err)) if run_syncdb: if app_label in executor.loader.migrated_apps: raise CommandError("Can't use run_syncdb with app '%s' as it has migrations." % app_label) elif app_label not in executor.loader.migrated_apps: raise CommandError("App '%s' does not have migrations." % app_label) if options['app_label'] and options['migration_name']: migration_name = options['migration_name'] if migration_name == "zero": targets = [(app_label, None)] else: try: migration = executor.loader.get_migration_by_prefix(app_label, migration_name) except AmbiguityError: raise CommandError( "More than one migration matches '%s' in app '%s'. " "Please be more specific." % (migration_name, app_label) ) except KeyError: raise CommandError("Cannot find a migration matching '%s' from app '%s'." % ( migration_name, app_label)) targets = [(app_label, migration.name)] target_app_labels_only = False elif options['app_label']: targets = [key for key in executor.loader.graph.leaf_nodes() if key[0] == app_label] else: targets = executor.loader.graph.leaf_nodes() plan = executor.migration_plan(targets) if options['plan']: self.stdout.write('Planned operations:', self.style.MIGRATE_LABEL) if not plan: self.stdout.write(' No planned migration operations.') for migration, backwards in plan: self.stdout.write(str(migration), self.style.MIGRATE_HEADING) for operation in migration.operations: message, is_error = self.describe_operation(operation, backwards) style = self.style.WARNING if is_error else None self.stdout.write(' ' + message, style) return # At this point, ignore run_syncdb if there aren't any apps to sync. run_syncdb = options['run_syncdb'] and executor.loader.unmigrated_apps # Print some useful info if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Operations to perform:")) if run_syncdb: if options['app_label']: self.stdout.write( self.style.MIGRATE_LABEL(" Synchronize unmigrated app: %s" % app_label) ) else: self.stdout.write( self.style.MIGRATE_LABEL(" Synchronize unmigrated apps: ") + (", ".join(sorted(executor.loader.unmigrated_apps))) ) if target_app_labels_only: self.stdout.write( self.style.MIGRATE_LABEL(" Apply all migrations: ") + (", ".join(sorted({a for a, n in targets})) or "(none)") ) else: if targets[0][1] is None: self.stdout.write(self.style.MIGRATE_LABEL( " Unapply all migrations: ") + "%s" % (targets[0][0],) ) else: self.stdout.write(self.style.MIGRATE_LABEL( " Target specific migration: ") + "%s, from %s" % (targets[0][1], targets[0][0]) ) pre_migrate_state = executor._create_project_state(with_applied_migrations=True) pre_migrate_apps = pre_migrate_state.apps emit_pre_migrate_signal( self.verbosity, self.interactive, connection.alias, apps=pre_migrate_apps, plan=plan, ) # Run the syncdb phase. if run_syncdb: if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Synchronizing apps without migrations:")) if options['app_label']: self.sync_apps(connection, [app_label]) else: self.sync_apps(connection, executor.loader.unmigrated_apps) # Migrate! if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Running migrations:")) if not plan: if self.verbosity >= 1: self.stdout.write(" No migrations to apply.") # If there's changes that aren't in migrations yet, tell them how to fix it. autodetector = MigrationAutodetector( executor.loader.project_state(), ProjectState.from_apps(apps), ) changes = autodetector.changes(graph=executor.loader.graph) if changes: self.stdout.write(self.style.NOTICE( " Your models have changes that are not yet reflected " "in a migration, and so won't be applied." )) self.stdout.write(self.style.NOTICE( " Run 'manage.py makemigrations' to make new " "migrations, and then re-run 'manage.py migrate' to " "apply them." )) fake = False fake_initial = False else: fake = options['fake'] fake_initial = options['fake_initial'] post_migrate_state = executor.migrate( targets, plan=plan, state=pre_migrate_state.clone(), fake=fake, fake_initial=fake_initial, ) # post_migrate signals have access to all models. Ensure that all models # are reloaded in case any are delayed. post_migrate_state.clear_delayed_apps_cache() post_migrate_apps = post_migrate_state.apps # Re-render models of real apps to include relationships now that # we've got a final state. This wouldn't be necessary if real apps # models were rendered with relationships in the first place. with post_migrate_apps.bulk_update(): model_keys = [] for model_state in post_migrate_apps.real_models: model_key = model_state.app_label, model_state.name_lower model_keys.append(model_key) post_migrate_apps.unregister_model(*model_key) post_migrate_apps.render_multiple([ ModelState.from_model(apps.get_model(*model)) for model in model_keys ]) # Send the post_migrate signal, so individual apps can do whatever they need # to do at this point. emit_post_migrate_signal( self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, ) def migration_progress_callback(self, action, migration=None, fake=False): if self.verbosity >= 1: compute_time = self.verbosity > 1 if action == "apply_start": if compute_time: self.start = time.monotonic() self.stdout.write(" Applying %s..." % migration, ending="") self.stdout.flush() elif action == "apply_success": elapsed = " (%.3fs)" % (time.monotonic() - self.start) if compute_time else "" if fake: self.stdout.write(self.style.SUCCESS(" FAKED" + elapsed)) else: self.stdout.write(self.style.SUCCESS(" OK" + elapsed)) elif action == "unapply_start": if compute_time: self.start = time.monotonic() self.stdout.write(" Unapplying %s..." % migration, ending="") self.stdout.flush() elif action == "unapply_success": elapsed = " (%.3fs)" % (time.monotonic() - self.start) if compute_time else "" if fake: self.stdout.write(self.style.SUCCESS(" FAKED" + elapsed)) else: self.stdout.write(self.style.SUCCESS(" OK" + elapsed)) elif action == "render_start": if compute_time: self.start = time.monotonic() self.stdout.write(" Rendering model states...", ending="") self.stdout.flush() elif action == "render_success": elapsed = " (%.3fs)" % (time.monotonic() - self.start) if compute_time else "" self.stdout.write(self.style.SUCCESS(" DONE" + elapsed)) def sync_apps(self, connection, app_labels): """Run the old syncdb-style operation on a list of app_labels.""" with connection.cursor() as cursor: tables = connection.introspection.table_names(cursor) # Build the manifest of apps and models that are to be synchronized. all_models = [ ( app_config.label, router.get_migratable_models(app_config, connection.alias, include_auto_created=False), ) for app_config in apps.get_app_configs() if app_config.models_module is not None and app_config.label in app_labels ] def model_installed(model): opts = model._meta converter = connection.introspection.identifier_converter return not ( (converter(opts.db_table) in tables) or (opts.auto_created and converter(opts.auto_created._meta.db_table) in tables) ) manifest = { app_name: list(filter(model_installed, model_list)) for app_name, model_list in all_models } # Create the tables for each model if self.verbosity >= 1: self.stdout.write(" Creating tables...\n") with connection.schema_editor() as editor: for app_name, model_list in manifest.items(): for model in model_list: # Never install unmanaged models, etc. if not model._meta.can_migrate(connection): continue if self.verbosity >= 3: self.stdout.write( " Processing %s.%s model\n" % (app_name, model._meta.object_name) ) if self.verbosity >= 1: self.stdout.write(" Creating table %s\n" % model._meta.db_table) editor.create_model(model) # Deferred SQL is executed when exiting the editor's context. if self.verbosity >= 1: self.stdout.write(" Running deferred SQL...\n") @staticmethod def describe_operation(operation, backwards): """Return a string that describes a migration operation for --plan.""" prefix = '' is_error = False if hasattr(operation, 'code'): code = operation.reverse_code if backwards else operation.code action = (code.__doc__ or '') if code else None elif hasattr(operation, 'sql'): action = operation.reverse_sql if backwards else operation.sql else: action = '' if backwards: prefix = 'Undo ' if action is not None: action = str(action).replace('\n', '') elif backwards: action = 'IRREVERSIBLE' is_error = True if action: action = ' -> ' + action truncated = Truncator(action) return prefix + operation.describe() + truncated.chars(40), is_error
'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('calendar');
require(`dotenv`).config({ path: `.env` }); let ghostConfig; try { ghostConfig = require(`./.ghost`); } catch (e) { ghostConfig = { production: { apiUrl: process.env.GHOST_API_URL, contentApiKey: process.env.GHOST_CONTENT_API_KEY } }; } finally { const { apiUrl, contentApiKey } = process.env.NODE_ENV === `development` ? ghostConfig.development : ghostConfig.production; if (!apiUrl || !contentApiKey || contentApiKey.match(/<key>/)) { throw new Error( `GHOST_API_URL and GHOST_CONTENT_API_KEY are required to build. Check the README.` ); // eslint-disable-line } } module.exports = { siteMetadata: { // Used for the title template on pages other than the index site siteTitle: `Jiahao Chen`, // Default title of the page siteTitleAlt: `Jiahao Chen`, // Can be used for e.g. JSONLD siteHeadline: `Jiahao Chen`, // Will be used to generate absolute URLs for og:image etc. siteUrl: `https://jiahao-chen.web.app`, // Used for SEO` siteDescription: `Jiahao Chen Software Engineering McGill University`, // Will be set on the <html /> tag siteLanguage: `en`, // Used for og:image and must be placed inside the `static` folder siteImage: `/banner.png`, // Links displayed in the header on the right side externalLinks: [ { name: `Github`, url: `https://github.com/jhcccc` }, { name: `Linkedin`, url: `https://www.linkedin.com/in/jiahao-chen-jhcccc/` }, ], // Navigation links navigation: [ { title: `Blog`, slug: `/blog` // I want the default homepage to be /blog }, { title: `Projects`, slug: `/projects` }, { title: `About`, slug: `/about` }, ] }, plugins: [ { resolve: `gatsby-plugin-mdx`, options: { extensions: [`.mdx`, `.md`], gatsbyRemarkPlugins: [ { resolve: `gatsby-remark-images`, options: { maxWidth: 960, quality: 90, linkImagesToOriginal: false } }, { resolve: `gatsby-remark-katex`, options: { // Add any KaTeX options from https://github.com/KaTeX/KaTeX/blob/master/docs/options.md here strict: `ignore` } }, `gatsby-remark-smartypants` ], plugins: [ { resolve: `gatsby-remark-images`, options: { maxWidth: 960, quality: 90, linkImagesToOriginal: false } } ] } }, { resolve: `@lekoarts/gatsby-theme-minimal-blog`, options: { basePath: `/`, blogPath: `/blog`, mdx: false // disabling mdx from the theme and redefine it here for new plugins } }, // { // resolve: `gatsby-plugin-google-analytics`, // options: { // trackingId: process.env.GOOGLE_ANALYTICS_ID // } // }, `gatsby-plugin-sitemap`, { resolve: `gatsby-plugin-manifest`, options: { name: `Jiahao Chen`, short_name: `Jiahao`, description: `My projects and blog`, start_url: `/`, background_color: `#fff`, theme_color: `#f6ad55`, display: `standalone`, icons: [ { src: `/android-chrome-192x192.png`, sizes: `192x192`, type: `image/png` }, { src: `/android-chrome-512x512.png`, sizes: `512x512`, type: `image/png` } ] } }, `gatsby-plugin-offline`, `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-ghost`, options: process.env.NODE_ENV === `development` ? ghostConfig.development : ghostConfig.production } // `gatsby-plugin-webpack-bundle-analyser-v2`, ] };
''' Created on Nov 28, 2010 Adaboost is short for Adaptive Boosting @author: Peter ''' from numpy import * def loadSimpData(): datMat = matrix([[1., 2.1], [2., 1.1], [1.3, 1.], [1., 1.], [2., 1.]]) classLabels = [1.0, 1.0, -1.0, -1.0, 1.0] return datMat, classLabels def loadDataSet(fileName): # general function to parse tab -delimited floats numFeat = len(open(fileName).readline().split('\t')) # get number of fields dataMat = []; labelMat = [] fr = open(fileName) for line in fr.readlines(): lineArr = [] curLine = line.strip().split('\t') for i in range(numFeat - 1): lineArr.append(float(curLine[i])) dataMat.append(lineArr) labelMat.append(float(curLine[-1])) return dataMat, labelMat def stumpClassify(dataMatrix, dimen, threshVal, threshIneq): # just classify the data retArray = ones((shape(dataMatrix)[0], 1)) if threshIneq == 'lt': retArray[dataMatrix[:, dimen] <= threshVal] = -1.0 else: retArray[dataMatrix[:, dimen] > threshVal] = -1.0 return retArray def buildStump(dataArr, classLabels, D): dataMatrix = mat(dataArr); labelMat = mat(classLabels).T m, n = shape(dataMatrix) numSteps = 10.0; bestStump = {}; bestClasEst = mat(zeros((m, 1))) minError = inf # init error sum, to +infinity for i in range(n): # loop over all dimensions rangeMin = dataMatrix[:, i].min(); rangeMax = dataMatrix[:, i].max(); stepSize = (rangeMax - rangeMin) / numSteps for j in range(-1, int(numSteps) + 1): # loop over all range in current dimension for inequal in ['lt', 'gt']: # go over less than and greater than threshVal = (rangeMin + float(j) * stepSize) predictedVals = stumpClassify(dataMatrix, i, threshVal, inequal) # call stump classify with i, j, lessThan errArr = mat(ones((m, 1))) errArr[predictedVals == labelMat] = 0 weightedError = D.T * errArr # calc total error multiplied by D # print "split: dim %d, thresh %.2f, thresh ineqal: %s, the weighted error is %.3f" % (i, threshVal, inequal, weightedError) if weightedError < minError: minError = weightedError bestClasEst = predictedVals.copy() bestStump['dim'] = i bestStump['thresh'] = threshVal bestStump['ineq'] = inequal return bestStump, minError, bestClasEst def adaBoostTrainDS(dataArr, classLabels, numIt=40): weakClassArr = [] m = shape(dataArr)[0] D = mat(ones((m, 1)) / m) # init D to all equal aggClassEst = mat(zeros((m, 1))) for i in range(numIt): bestStump, error, classEst = buildStump(dataArr, classLabels, D) # build Stump # print "D:",D.T alpha = float( 0.5 * log((1.0 - error) / max(error, 1e-16))) # calc alpha, throw in max(error,eps) to account for error=0 bestStump['alpha'] = alpha weakClassArr.append(bestStump) # store Stump Params in Array # print "classEst: ",classEst.T expon = multiply(-1 * alpha * mat(classLabels).T, classEst) # exponent for D calc, getting messy D = multiply(D, exp(expon)) # Calc New D for next iteration D = D / D.sum() # calc training error of all classifiers, if this is 0 quit for loop early (use break) aggClassEst += alpha * classEst # print "aggClassEst: ",aggClassEst.T aggErrors = multiply(sign(aggClassEst) != mat(classLabels).T, ones((m, 1))) errorRate = aggErrors.sum() / m print "total error: ", errorRate if errorRate == 0.0: break return weakClassArr, aggClassEst def adaClassify(datToClass, classifierArr): dataMatrix = mat(datToClass) # do stuff similar to last aggClassEst in adaBoostTrainDS m = shape(dataMatrix)[0] aggClassEst = mat(zeros((m, 1))) for i in range(len(classifierArr)): classEst = stumpClassify(dataMatrix, classifierArr[i]['dim'], \ classifierArr[i]['thresh'], \ classifierArr[i]['ineq']) # call stump classify aggClassEst += classifierArr[i]['alpha'] * classEst print aggClassEst return sign(aggClassEst) def plotROC(predStrengths, classLabels): import matplotlib.pyplot as plt cur = (1.0, 1.0) # cursor ySum = 0.0 # variable to calculate AUC numPosClas = sum(array(classLabels) == 1.0) yStep = 1 / float(numPosClas); xStep = 1 / float(len(classLabels) - numPosClas) sortedIndicies = predStrengths.argsort() # get sorted index, it's reverse fig = plt.figure() fig.clf() ax = plt.subplot(111) # loop through all the values, drawing a line segment at each point for index in sortedIndicies.tolist()[0]: if classLabels[index] == 1.0: delX = 0; delY = yStep; else: delX = xStep; delY = 0; ySum += cur[1] # draw line from cur to (cur[0]-delX,cur[1]-delY) ax.plot([cur[0], cur[0] - delX], [cur[1], cur[1] - delY], c='b') cur = (cur[0] - delX, cur[1] - delY) # ax.plot([0, 1], [0, 1], 'b--') # plt.xlabel('False positive rate'); # plt.ylabel('True positive rate') # plt.title('ROC curve for AdaBoost horse colic detection system') ax.axis([0, 1, 0, 1]) plt.show() print "the Area Under the Curve is: ", ySum * xStep datArr, labelArr = loadDataSet('horseColicTraining2.txt') classifierArray, aggClassEst = adaBoostTrainDS(datArr, labelArr, 10) plotROC(aggClassEst.T, labelArr)
import os class Config: ''' General configuration parent class ''' SECRET_KEY = os.environ.get('SECRET_KEY') SQLALCHEMY_DATABASE_URI='postgresql+psycopg2://moringa:word@localhost/blog' UPLOADED_PHOTOS_DEST ='app/static/photos' class ProdConfig(Config): ''' Production configuration child class ''' SQLALCHEMY_DATABASE_URI=os.environ.get('DATABASE_URL') class DevConfig(Config): ''' Development configuration child class ''' DEBUG = True config_options = { 'development':DevConfig, 'production':ProdConfig }
/** * Server to share a photo */ const sgServer = require('sg-server') const endpoints = require('./endpoints/share') let shareServer = sgServer({ endpoints }) module.exports = shareServer
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from .mininode import * from .blockstore import BlockStore, TxStore from .util import p2p_port ''' This is a tool for comparing two or more bitcoinds to each other using a script provided. To use, create a class that implements get_tests(), and pass it in as the test generator to TestManager. get_tests() should be a python generator that returns TestInstance objects. See below for definition. ''' # TestNode behaves as follows: # Configure with a BlockStore and TxStore # on_inv: log the message but don't request # on_headers: log the chain tip # on_pong: update ping response map (for synchronization) # on_getheaders: provide headers via BlockStore # on_getdata: provide blocks via BlockStore global mininode_lock class RejectResult(object): ''' Outcome that expects rejection of a transaction or block. ''' def __init__(self, code, reason=b''): self.code = code self.reason = reason def match(self, other): if self.code != other.code: return False return other.reason.startswith(self.reason) def __repr__(self): return '%i:%s' % (self.code,self.reason or '*') class TestNode(NodeConnCB): def __init__(self, block_store, tx_store): NodeConnCB.__init__(self) self.conn = None self.bestblockhash = None self.block_store = block_store self.block_request_map = {} self.tx_store = tx_store self.tx_request_map = {} self.block_reject_map = {} self.tx_reject_map = {} # When the pingmap is non-empty we're waiting for # a response self.pingMap = {} self.lastInv = [] self.closed = False def on_close(self, conn): self.closed = True def add_connection(self, conn): self.conn = conn def on_headers(self, conn, message): if len(message.headers) > 0: best_header = message.headers[-1] best_header.calc_sha256() self.bestblockhash = best_header.sha256 def on_getheaders(self, conn, message): response = self.block_store.headers_for(message.locator, message.hashstop) if response is not None: conn.send_message(response) def on_getdata(self, conn, message): [conn.send_message(r) for r in self.block_store.get_blocks(message.inv)] [conn.send_message(r) for r in self.tx_store.get_transactions(message.inv)] for i in message.inv: if i.type == 1: self.tx_request_map[i.hash] = True elif i.type == 2: self.block_request_map[i.hash] = True def on_inv(self, conn, message): self.lastInv = [x.hash for x in message.inv] def on_pong(self, conn, message): try: del self.pingMap[message.nonce] except KeyError: raise AssertionError("Got pong for unknown ping [%s]" % repr(message)) def on_reject(self, conn, message): if message.message == b'tx': self.tx_reject_map[message.data] = RejectResult(message.code, message.reason) if message.message == b'block': self.block_reject_map[message.data] = RejectResult(message.code, message.reason) def send_inv(self, obj): mtype = 2 if isinstance(obj, CBlock) else 1 self.conn.send_message(msg_inv([CInv(mtype, obj.sha256)])) def send_getheaders(self): # We ask for headers from their last tip. m = msg_getheaders() m.locator = self.block_store.get_locator(self.bestblockhash) self.conn.send_message(m) def send_header(self, header): m = msg_headers() m.headers.append(header) self.conn.send_message(m) # This assumes BIP31 def send_ping(self, nonce): self.pingMap[nonce] = True self.conn.send_message(msg_ping(nonce)) def received_ping_response(self, nonce): return nonce not in self.pingMap def send_mempool(self): self.lastInv = [] self.conn.send_message(msg_mempool()) # TestInstance: # # Instances of these are generated by the test generator, and fed into the # comptool. # # "blocks_and_transactions" should be an array of # [obj, True/False/None, hash/None]: # - obj is either a CBlock, CBlockHeader, or a CTransaction, and # - the second value indicates whether the object should be accepted # into the blockchain or mempool (for tests where we expect a certain # answer), or "None" if we don't expect a certain answer and are just # comparing the behavior of the nodes being tested. # - the third value is the hash to test the tip against (if None or omitted, # use the hash of the block) # - NOTE: if a block header, no test is performed; instead the header is # just added to the block_store. This is to facilitate block delivery # when communicating with headers-first clients (when withholding an # intermediate block). # sync_every_block: if True, then each block will be inv'ed, synced, and # nodes will be tested based on the outcome for the block. If False, # then inv's accumulate until all blocks are processed (or max inv size # is reached) and then sent out in one inv message. Then the final block # will be synced across all connections, and the outcome of the final # block will be tested. # sync_every_tx: analogous to behavior for sync_every_block, except if outcome # on the final tx is None, then contents of entire mempool are compared # across all connections. (If outcome of final tx is specified as true # or false, then only the last tx is tested against outcome.) class TestInstance(object): def __init__(self, objects=None, sync_every_block=True, sync_every_tx=False): self.blocks_and_transactions = objects if objects else [] self.sync_every_block = sync_every_block self.sync_every_tx = sync_every_tx class TestManager(object): def __init__(self, testgen, datadir): self.test_generator = testgen self.connections = [] self.test_nodes = [] self.block_store = BlockStore(datadir) self.tx_store = TxStore(datadir) self.ping_counter = 1 def add_all_connections(self, nodes): for i in range(len(nodes)): # RECte a p2p connection to each node test_node = TestNode(self.block_store, self.tx_store) self.test_nodes.append(test_node) self.connections.append(NodeConn('127.0.0.1', p2p_port(i), nodes[i], test_node)) # Make sure the TestNode (callback class) has a reference to its # associated NodeConn test_node.add_connection(self.connections[-1]) def clear_all_connections(self): self.connections = [] self.test_nodes = [] def wait_for_disconnections(self): def disconnected(): return all(node.closed for node in self.test_nodes) return wait_until(disconnected, timeout=10) def wait_for_verack(self): def veracked(): return all(node.verack_received for node in self.test_nodes) return wait_until(veracked, timeout=10) def wait_for_pings(self, counter): def received_pongs(): return all(node.received_ping_response(counter) for node in self.test_nodes) return wait_until(received_pongs) # sync_blocks: Wait for all connections to request the blockhash given # then send get_headers to find out the tip of each node, and synchronize # the response by using a ping (and waiting for pong with same nonce). def sync_blocks(self, blockhash, num_blocks): def blocks_requested(): return all( blockhash in node.block_request_map and node.block_request_map[blockhash] for node in self.test_nodes ) # --> error if not requested if not wait_until(blocks_requested, attempts=20*num_blocks): # print [ c.cb.block_request_map for c in self.connections ] raise AssertionError("Not all nodes requested block") # Send getheaders message [ c.cb.send_getheaders() for c in self.connections ] # Send ping and wait for response -- synchronization hack [ c.cb.send_ping(self.ping_counter) for c in self.connections ] self.wait_for_pings(self.ping_counter) self.ping_counter += 1 # Analogous to sync_block (see above) def sync_transaction(self, txhash, num_events): # Wait for nodes to request transaction (50ms sleep * 20 tries * num_events) def transaction_requested(): return all( txhash in node.tx_request_map and node.tx_request_map[txhash] for node in self.test_nodes ) # --> error if not requested if not wait_until(transaction_requested, attempts=20*num_events): # print [ c.cb.tx_request_map for c in self.connections ] raise AssertionError("Not all nodes requested transaction") # Get the mempool [ c.cb.send_mempool() for c in self.connections ] # Send ping and wait for response -- synchronization hack [ c.cb.send_ping(self.ping_counter) for c in self.connections ] self.wait_for_pings(self.ping_counter) self.ping_counter += 1 # Sort inv responses from each node with mininode_lock: [ c.cb.lastInv.sort() for c in self.connections ] # Verify that the tip of each connection all agree with each other, and # with the expected outcome (if given) def check_results(self, blockhash, outcome): with mininode_lock: for c in self.connections: if outcome is None: if c.cb.bestblockhash != self.connections[0].cb.bestblockhash: return False elif isinstance(outcome, RejectResult): # Check that block was rejected w/ code if c.cb.bestblockhash == blockhash: return False if blockhash not in c.cb.block_reject_map: print('Block not in reject map: %064x' % (blockhash)) return False if not outcome.match(c.cb.block_reject_map[blockhash]): print('Block rejected with %s instead of expected %s: %064x' % (c.cb.block_reject_map[blockhash], outcome, blockhash)) return False elif ((c.cb.bestblockhash == blockhash) != outcome): # print c.cb.bestblockhash, blockhash, outcome return False return True # Either check that the mempools all agree with each other, or that # txhash's presence in the mempool matches the outcome specified. # This is somewhat of a strange comparison, in that we're either comparing # a particular tx to an outcome, or the entire mempools altogether; # perhaps it would be useful to add the ability to check explicitly that # a particular tx's existence in the mempool is the same across all nodes. def check_mempool(self, txhash, outcome): with mininode_lock: for c in self.connections: if outcome is None: # Make sure the mempools agree with each other if c.cb.lastInv != self.connections[0].cb.lastInv: # print c.rpc.getrawmempool() return False elif isinstance(outcome, RejectResult): # Check that tx was rejected w/ code if txhash in c.cb.lastInv: return False if txhash not in c.cb.tx_reject_map: print('Tx not in reject map: %064x' % (txhash)) return False if not outcome.match(c.cb.tx_reject_map[txhash]): print('Tx rejected with %s instead of expected %s: %064x' % (c.cb.tx_reject_map[txhash], outcome, txhash)) return False elif ((txhash in c.cb.lastInv) != outcome): # print c.rpc.getrawmempool(), c.cb.lastInv return False return True def run(self): # Wait until verack is received self.wait_for_verack() test_number = 1 for test_instance in self.test_generator.get_tests(): # We use these variables to keep track of the last block # and last transaction in the tests, which are used # if we're not syncing on every block or every tx. [ block, block_outcome, tip ] = [ None, None, None ] [ tx, tx_outcome ] = [ None, None ] invqueue = [] for test_obj in test_instance.blocks_and_transactions: b_or_t = test_obj[0] outcome = test_obj[1] # Determine if we're dealing with a block or tx if isinstance(b_or_t, CBlock): # Block test runner block = b_or_t block_outcome = outcome tip = block.sha256 # each test_obj can have an optional third argument # to specify the tip we should compare with # (default is to use the block being tested) if len(test_obj) >= 3: tip = test_obj[2] # Add to shared block_store, set as current block # If there was an open getdata request for the block # previously, and we didn't have an entry in the # block_store, then immediately deliver, because the # node wouldn't send another getdata request while # the earlier one is outstanding. first_block_with_hash = True if self.block_store.get(block.sha256) is not None: first_block_with_hash = False with mininode_lock: self.block_store.add_block(block) for c in self.connections: if first_block_with_hash and block.sha256 in c.cb.block_request_map and c.cb.block_request_map[block.sha256] == True: # There was a previous request for this block hash # Most likely, we delivered a header for this block # but never had the block to respond to the getdata c.send_message(msg_block(block)) else: c.cb.block_request_map[block.sha256] = False # Either send inv's to each node and sync, or add # to invqueue for later inv'ing. if (test_instance.sync_every_block): # if we expect success, send inv and sync every block # if we expect failure, just push the block and see what happens. if outcome == True: [ c.cb.send_inv(block) for c in self.connections ] self.sync_blocks(block.sha256, 1) else: [ c.send_message(msg_block(block)) for c in self.connections ] [ c.cb.send_ping(self.ping_counter) for c in self.connections ] self.wait_for_pings(self.ping_counter) self.ping_counter += 1 if (not self.check_results(tip, outcome)): raise AssertionError("Test failed at test %d" % test_number) else: invqueue.append(CInv(2, block.sha256)) elif isinstance(b_or_t, CBlockHeader): block_header = b_or_t self.block_store.add_header(block_header) [ c.cb.send_header(block_header) for c in self.connections ] else: # Tx test runner assert(isinstance(b_or_t, CTransaction)) tx = b_or_t tx_outcome = outcome # Add to shared tx store and clear map entry with mininode_lock: self.tx_store.add_transaction(tx) for c in self.connections: c.cb.tx_request_map[tx.sha256] = False # Again, either inv to all nodes or save for later if (test_instance.sync_every_tx): [ c.cb.send_inv(tx) for c in self.connections ] self.sync_transaction(tx.sha256, 1) if (not self.check_mempool(tx.sha256, outcome)): raise AssertionError("Test failed at test %d" % test_number) else: invqueue.append(CInv(1, tx.sha256)) # Ensure we're not overflowing the inv queue if len(invqueue) == MAX_INV_SZ: [ c.send_message(msg_inv(invqueue)) for c in self.connections ] invqueue = [] # Do final sync if we weren't syncing on every block or every tx. if (not test_instance.sync_every_block and block is not None): if len(invqueue) > 0: [ c.send_message(msg_inv(invqueue)) for c in self.connections ] invqueue = [] self.sync_blocks(block.sha256, len(test_instance.blocks_and_transactions)) if (not self.check_results(tip, block_outcome)): raise AssertionError("Block test failed at test %d" % test_number) if (not test_instance.sync_every_tx and tx is not None): if len(invqueue) > 0: [ c.send_message(msg_inv(invqueue)) for c in self.connections ] invqueue = [] self.sync_transaction(tx.sha256, len(test_instance.blocks_and_transactions)) if (not self.check_mempool(tx.sha256, tx_outcome)): raise AssertionError("Mempool test failed at test %d" % test_number) print("Test %d: PASS" % test_number, [ c.rpc.getblockcount() for c in self.connections ]) test_number += 1 [ c.disconnect_node() for c in self.connections ] self.wait_for_disconnections() self.block_store.close() self.tx_store.close()
// Copyright 2019-2020 @Premiurly/polkassembly authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. exports.up = function(knex) { return knex.schema.table('content_report', (table) => { table.enu('network', ['kusama', 'polkadot']).defaultTo('kusama'); }); }; exports.down = function(knex) { return knex.schema.table('content_report', function (table) { table.dropColumn('network'); }); };
(function(factory){if(typeof define==="function"&&define.amd)define(["jquery"],factory);else if(typeof exports=="object"&&typeof module=="object")module.exports=factory(require("jquery"));else factory(jQuery)})(function($,undefined){var defaultOpts={beforeShow:noop,move:noop,change:noop,show:noop,hide:noop,color:false,flat:false,showInput:false,allowEmpty:false,showButtons:true,clickoutFiresChange:true,showInitial:false,showPalette:false,showPaletteOnly:false,hideAfterPaletteSelect:false,togglePaletteOnly:false,showSelectionPalette:true,localStorageKey:false,appendTo:"body",maxSelectionSize:7,cancelText:"cancel",chooseText:"choose",togglePaletteMoreText:"more",togglePaletteLessText:"less",clearText:"Clear Color Selection",noColorSelectedText:"No Color Selected",preferredFormat:false,className:"",containerClassName:"",replacerClassName:"",showAlpha:false,theme:"sp-light",palette:[["#ffffff","#000000","#ff0000","#ff8000","#ffff00","#008000","#0000ff","#4b0082","#9400d3"]],selectionPalette:[],disabled:false,offset:null},spectrums=[],IE=!!/msie/i.exec(window.navigator.userAgent),rgbaSupport=function(){function contains(str,substr){return!!~(""+str).indexOf(substr)}var elem=document.createElement("div");var style=elem.style;style.cssText="background-color:rgba(0,0,0,.5)";return contains(style.backgroundColor,"rgba")||contains(style.backgroundColor,"hsla")}(),replaceInput=["<div class='sp-replacer'>","<div class='sp-preview'><div class='sp-preview-inner'></div></div>","<div class='sp-dd'></div>","</div>"].join(""),markup=function(){var gradientFix="";if(IE)for(var i=1;i<=6;i++)gradientFix+="<div class='sp-"+i+"'></div>";return["<div class='sp-container sp-hidden'>","<div class='sp-palette-container'>","<div class='sp-palette sp-thumb sp-cf'></div>","<div class='sp-palette-button-container sp-cf'>","<button type='button' class='btn btn-action sp-palette-toggle'></button>","</div>","</div>","<div class='sp-picker-container'>","<div class='sp-top sp-cf'>","<div class='sp-fill'></div>","<div class='sp-top-inner'>","<div class='sp-color'>","<div class='sp-sat'>","<div class='sp-val'>","<div class='sp-dragger'></div>","</div>","</div>","</div>","<div class='sp-clear sp-clear-display'>","</div>","<div class='sp-hue'>","<div class='sp-slider'></div>",gradientFix,"</div>","</div>","<div class='sp-alpha'><div class='sp-alpha-inner'><div class='sp-alpha-handle'></div></div></div>","</div>","<div class='sp-input-container sp-cf'>","<input class='sp-input' type='text' spellcheck='false' />","</div>","<div class='sp-initial sp-thumb sp-cf'></div>","<div class='sp-button-container sp-cf'>","<a class='btn btn-danger sp-cancel' href='#'></a>","<button type='button' class='btn btn-success sp-choose'></button>","</div>","</div>","</div>"].join("")}();function paletteTemplate(p,color,className,opts){var html=[];for(var i=0;i<p.length;i++){var current=p[i];if(current){var tiny=tinycolor(current);var c=tiny.toHsl().l<.5?"sp-thumb-el sp-thumb-dark":"sp-thumb-el sp-thumb-light";c+=tinycolor.equals(color,current)?" sp-thumb-active":"";var formattedString=tiny.toString(opts.preferredFormat||"rgb");var swatchStyle=rgbaSupport?"background-color:"+tiny.toRgbString():"filter:"+tiny.toFilter();html.push('<span title="'+formattedString+'" data-color="'+tiny.toRgbString()+'" class="'+c+'"><span class="sp-thumb-inner" style="'+swatchStyle+';"></span></span>')}else{var cls="sp-clear-display";html.push($("<div />").append($('<span data-color="" style="background-color:transparent;" class="'+cls+'"></span>').attr("title",opts.noColorSelectedText)).html())}}return"<div class='sp-cf "+className+"'>"+html.join("")+"</div>"}function hideAll(){for(var i=0;i<spectrums.length;i++)if(spectrums[i])spectrums[i].hide()}function instanceOptions(o,callbackContext){var opts=$.extend({},defaultOpts,o);opts.callbacks={"move":bind(opts.move,callbackContext),"change":bind(opts.change,callbackContext),"show":bind(opts.show,callbackContext),"hide":bind(opts.hide,callbackContext),"beforeShow":bind(opts.beforeShow,callbackContext)};return opts}function spectrum(element,o){var opts=instanceOptions(o,element),flat=opts.flat,showSelectionPalette=opts.showSelectionPalette,localStorageKey=opts.localStorageKey,theme=opts.theme,callbacks=opts.callbacks,resize=throttle(reflow,10),visible=false,isDragging=false,dragWidth=0,dragHeight=0,dragHelperHeight=0,slideHeight=0,slideWidth=0,alphaWidth=0,alphaSlideHelperWidth=0,slideHelperHeight=0,currentHue=0,currentSaturation=0,currentValue=0,currentAlpha=1,palette=[],paletteArray=[],paletteLookup={},selectionPalette=opts.selectionPalette.slice(0),maxSelectionSize=opts.maxSelectionSize,draggingClass="sp-dragging",shiftMovementDirection=null;var doc=element.ownerDocument,body=doc.body,boundElement=$(element),disabled=false,container=$(markup,doc).addClass(theme),pickerContainer=container.find(".sp-picker-container"),dragger=container.find(".sp-color"),dragHelper=container.find(".sp-dragger"),slider=container.find(".sp-hue"),slideHelper=container.find(".sp-slider"),alphaSliderInner=container.find(".sp-alpha-inner"),alphaSlider=container.find(".sp-alpha"),alphaSlideHelper=container.find(".sp-alpha-handle"),textInput=container.find(".sp-input"),paletteContainer=container.find(".sp-palette"),initialColorContainer=container.find(".sp-initial"),cancelButton=container.find(".sp-cancel"),clearButton=container.find(".sp-clear"),chooseButton=container.find(".sp-choose"),toggleButton=container.find(".sp-palette-toggle"),isInput=boundElement.is("input"),isInputTypeColor=isInput&&boundElement.attr("type")==="color"&&inputTypeColorSupport(),shouldReplace=isInput&&!flat,replacer=shouldReplace?$(replaceInput).addClass(theme).addClass(opts.className).addClass(opts.replacerClassName):$([]),offsetElement=shouldReplace?replacer:boundElement,previewElement=replacer.find(".sp-preview-inner"),initialColor=opts.color||isInput&&boundElement.val(),colorOnShow=false,currentPreferredFormat=opts.preferredFormat,clickoutFiresChange=!opts.showButtons||opts.clickoutFiresChange,isEmpty=!initialColor,allowEmpty=opts.allowEmpty&&!isInputTypeColor;function applyOptions(){if(opts.showPaletteOnly)opts.showPalette=true;toggleButton.text(opts.showPaletteOnly?opts.togglePaletteMoreText:opts.togglePaletteLessText);if(opts.palette){palette=opts.palette.slice(0);paletteArray=Array.isArray(palette[0])?palette:[palette];paletteLookup={};for(var i=0;i<paletteArray.length;i++)for(var j=0;j<paletteArray[i].length;j++){var rgb=tinycolor(paletteArray[i][j]).toRgbString();paletteLookup[rgb]=true}}container.toggleClass("sp-flat",flat);container.toggleClass("sp-input-disabled",!opts.showInput);container.toggleClass("sp-alpha-enabled",opts.showAlpha);container.toggleClass("sp-clear-enabled",allowEmpty);container.toggleClass("sp-buttons-disabled",!opts.showButtons);container.toggleClass("sp-palette-buttons-disabled",!opts.togglePaletteOnly);container.toggleClass("sp-palette-disabled",!opts.showPalette);container.toggleClass("sp-palette-only",opts.showPaletteOnly);container.toggleClass("sp-initial-disabled",!opts.showInitial);container.addClass(opts.className).addClass(opts.containerClassName);reflow()}function initialize(){if(IE)container.find("*:not(input)").attr("unselectable","on");applyOptions();if(shouldReplace)boundElement.after(replacer).hide();if(!allowEmpty)clearButton.hide();if(flat)boundElement.after(container).hide();else{var appendTo=opts.appendTo==="parent"?boundElement.parent():$(opts.appendTo);if(appendTo.length!==1)appendTo=$("body");appendTo.append(container)}updateSelectionPaletteFromStorage();offsetElement.on("click.spectrum touchstart.spectrum",function(e){if(!disabled)toggle();e.stopPropagation();if(!$(e.target).is("input"))e.preventDefault()});if(boundElement.is(":disabled")||opts.disabled===true)disable();container.on("click",stopPropagation);textInput.on("change",setFromTextInput);textInput.on("paste",function(){setTimeout(setFromTextInput,1)});textInput.on("keydown",function(e){if(e.keyCode==13)setFromTextInput()});cancelButton.text(opts.cancelText);cancelButton.on("click.spectrum",function(e){e.stopPropagation();e.preventDefault();revert();hide()});clearButton.attr("title",opts.clearText);clearButton.on("click.spectrum",function(e){e.stopPropagation();e.preventDefault();isEmpty=true;move();if(flat)updateOriginalInput(true)});chooseButton.text(opts.chooseText);chooseButton.on("click.spectrum",function(e){e.stopPropagation();e.preventDefault();if(IE&&textInput.is(":focus"))textInput.trigger("change");if(isValid()){updateOriginalInput(true);hide()}});toggleButton.text(opts.showPaletteOnly?opts.togglePaletteMoreText:opts.togglePaletteLessText);toggleButton.on("click.spectrum",function(e){e.stopPropagation();e.preventDefault();opts.showPaletteOnly=!opts.showPaletteOnly;if(!opts.showPaletteOnly&&!flat)container.css("left","-="+(pickerContainer.outerWidth(true)+5));applyOptions()});draggable(alphaSlider,function(dragX,dragY,e){currentAlpha=dragX/alphaWidth;isEmpty=false;if(e.shiftKey)currentAlpha=Math.round(currentAlpha*10)/10;move()},dragStart,dragStop);draggable(slider,function(dragX,dragY){currentHue=parseFloat(dragY/slideHeight);isEmpty=false;if(!opts.showAlpha)currentAlpha=1;move()},dragStart,dragStop);draggable(dragger,function(dragX,dragY,e){if(!e.shiftKey)shiftMovementDirection=null;else if(!shiftMovementDirection){var oldDragX=currentSaturation*dragWidth;var oldDragY=dragHeight-currentValue*dragHeight;var furtherFromX=Math.abs(dragX-oldDragX)>Math.abs(dragY-oldDragY);shiftMovementDirection=furtherFromX?"x":"y"}var setSaturation=!shiftMovementDirection||shiftMovementDirection==="x";var setValue=!shiftMovementDirection||shiftMovementDirection==="y";if(setSaturation)currentSaturation=parseFloat(dragX/dragWidth);if(setValue)currentValue=parseFloat((dragHeight-dragY)/dragHeight);isEmpty=false;if(!opts.showAlpha)currentAlpha=1;move()},dragStart,dragStop);if(!!initialColor){set(initialColor);updateUI();currentPreferredFormat=opts.preferredFormat||tinycolor(initialColor).format;addColorToSelectionPalette(initialColor)}else updateUI();if(flat)show();function paletteElementClick(e){if(e.data&&e.data.ignore){set($(e.target).closest(".sp-thumb-el").data("color"));move()}else{set($(e.target).closest(".sp-thumb-el").data("color"));move();if(opts.hideAfterPaletteSelect){updateOriginalInput(true);hide()}else updateOriginalInput()}return false}var paletteEvent=IE?"mousedown.spectrum":"click.spectrum touchstart.spectrum";paletteContainer.on(paletteEvent,".sp-thumb-el",paletteElementClick);initialColorContainer.on(paletteEvent,".sp-thumb-el:nth-child(1)",{ignore:true},paletteElementClick)}function updateSelectionPaletteFromStorage(){if(localStorageKey&&window.localStorage){try{var oldPalette=window.localStorage[localStorageKey].split(",#");if(oldPalette.length>1){delete window.localStorage[localStorageKey];$.each(oldPalette,function(i,c){addColorToSelectionPalette(c)})}}catch(e){}try{selectionPalette=window.localStorage[localStorageKey].split(";")}catch(e$0){}}}function addColorToSelectionPalette(color){if(showSelectionPalette){var rgb=tinycolor(color).toRgbString();if(!paletteLookup[rgb]&&$.inArray(rgb,selectionPalette)===-1){selectionPalette.push(rgb);while(selectionPalette.length>maxSelectionSize)selectionPalette.shift()}if(localStorageKey&&window.localStorage)try{window.localStorage[localStorageKey]=selectionPalette.join(";")}catch(e){}}}function getUniqueSelectionPalette(){var unique=[];if(opts.showPalette)for(var i=0;i<selectionPalette.length;i++){var rgb=tinycolor(selectionPalette[i]).toRgbString();if(!paletteLookup[rgb])unique.push(selectionPalette[i])}return unique.reverse().slice(0,opts.maxSelectionSize)}function drawPalette(){var currentColor=get();var html=$.map(paletteArray,function(palette,i){return paletteTemplate(palette,currentColor,"sp-palette-row sp-palette-row-"+i,opts)});updateSelectionPaletteFromStorage();if(selectionPalette)html.push(paletteTemplate(getUniqueSelectionPalette(),currentColor,"sp-palette-row sp-palette-row-selection",opts));paletteContainer.html(html.join(""))}function drawInitial(){if(opts.showInitial){var initial=colorOnShow;var current=get();initialColorContainer.html(paletteTemplate([initial,current],current,"sp-palette-row-initial",opts))}}function dragStart(){if(dragHeight<=0||dragWidth<=0||slideHeight<=0)reflow();isDragging=true;container.addClass(draggingClass);shiftMovementDirection=null;boundElement.trigger("dragstart.spectrum",[get()])}function dragStop(){isDragging=false;container.removeClass(draggingClass);boundElement.trigger("dragstop.spectrum",[get()])}function setFromTextInput(){var value=textInput.val();if((value===null||value==="")&&allowEmpty){set(null);move();updateOriginalInput()}else{var tiny=tinycolor(value);if(tiny.isValid()){set(tiny);move();updateOriginalInput()}else textInput.addClass("sp-validation-error")}}function toggle(){if(visible)hide();else show()}function show(){var event=$.Event("beforeShow.spectrum");if(visible){reflow();return}boundElement.trigger(event,[get()]);if(callbacks.beforeShow(get())===false||event.isDefaultPrevented())return;hideAll();visible=true;$(doc).on("keydown.spectrum",onkeydown);$(doc).on("click.spectrum",clickout);$(window).on("resize.spectrum",resize);replacer.addClass("sp-active");container.removeClass("sp-hidden");reflow();updateUI();colorOnShow=get();drawInitial();callbacks.show(colorOnShow);boundElement.trigger("show.spectrum",[colorOnShow])}function onkeydown(e){if(e.keyCode===27)hide()}function clickout(e){if(e.button==2)return;if(isDragging)return;if(clickoutFiresChange)updateOriginalInput(true);else revert();hide()}function hide(){if(!visible||flat)return;visible=false;$(doc).off("keydown.spectrum",onkeydown);$(doc).off("click.spectrum",clickout);$(window).off("resize.spectrum",resize);replacer.removeClass("sp-active");container.addClass("sp-hidden");callbacks.hide(get());boundElement.trigger("hide.spectrum",[get()])}function revert(){set(colorOnShow,true);updateOriginalInput(true)}function set(color,ignoreFormatChange){if(tinycolor.equals(color,get())){updateUI();return}var newColor,newHsv;if(!color&&allowEmpty)isEmpty=true;else{isEmpty=false;newColor=tinycolor(color);newHsv=newColor.toHsv();currentHue=newHsv.h%360/360;currentSaturation=newHsv.s;currentValue=newHsv.v;currentAlpha=newHsv.a}updateUI();if(newColor&&newColor.isValid()&&!ignoreFormatChange)currentPreferredFormat=opts.preferredFormat||newColor.getFormat()}function get(opts){opts=opts||{};if(allowEmpty&&isEmpty)return null;return tinycolor.fromRatio({h:currentHue,s:currentSaturation,v:currentValue,a:Math.round(currentAlpha*1E3)/1E3},{format:opts.format||currentPreferredFormat})}function isValid(){return!textInput.hasClass("sp-validation-error")}function move(){updateUI();callbacks.move(get());boundElement.trigger("move.spectrum",[get()])}function updateUI(){textInput.removeClass("sp-validation-error");updateHelperLocations();var flatColor=tinycolor.fromRatio({h:currentHue,s:1,v:1});dragger.css("background-color",flatColor.toHexString());var format=currentPreferredFormat;if(currentAlpha<1&&!(currentAlpha===0&&format==="name"))if(format==="hex"||format==="hex3"||format==="hex6"||format==="name")format="rgb";var realColor=get({format:format}),displayColor="";previewElement.removeClass("sp-clear-display");previewElement.css("background-color","transparent");if(!realColor&&allowEmpty)previewElement.addClass("sp-clear-display");else{var realHex=realColor.toHexString(),realRgb=realColor.toRgbString();if(rgbaSupport||realColor.alpha===1)previewElement.css("background-color",realRgb);else{previewElement.css("background-color","transparent");previewElement.css("filter",realColor.toFilter())}if(opts.showAlpha){var rgb=realColor.toRgb();rgb.a=0;var realAlpha=tinycolor(rgb).toRgbString();var gradient="linear-gradient(left, "+realAlpha+", "+realHex+")";if(IE)alphaSliderInner.css("filter",tinycolor(realAlpha).toFilter({gradientType:1},realHex));else{alphaSliderInner.css("background","-webkit-"+gradient);alphaSliderInner.css("background","-moz-"+gradient);alphaSliderInner.css("background","-ms-"+gradient);alphaSliderInner.css("background","linear-gradient(to right, "+realAlpha+", "+realHex+")")}}displayColor=realColor.toString(format)}if(opts.showInput)textInput.val(displayColor);if(opts.showPalette)drawPalette();drawInitial()}function updateHelperLocations(){var s=currentSaturation;var v=currentValue;if(allowEmpty&&isEmpty){alphaSlideHelper.hide();slideHelper.hide();dragHelper.hide()}else{alphaSlideHelper.show();slideHelper.show();dragHelper.show();var dragX=s*dragWidth;var dragY=dragHeight-v*dragHeight;dragX=Math.max(-dragHelperHeight,Math.min(dragWidth-dragHelperHeight,dragX-dragHelperHeight));dragY=Math.max(-dragHelperHeight,Math.min(dragHeight-dragHelperHeight,dragY-dragHelperHeight));dragHelper.css({"top":dragY+"px","left":dragX+"px"});var alphaX=currentAlpha*alphaWidth;alphaSlideHelper.css({"left":alphaX-alphaSlideHelperWidth/2-10+"px"});var slideY=currentHue*(slideHeight-3);slideHelper.css({"top":slideY-slideHelperHeight+3+"px"})}}function updateOriginalInput(fireCallback){var color=get(),displayColor="",hasChanged=!tinycolor.equals(color,colorOnShow);if(color){displayColor=color.toString(currentPreferredFormat);addColorToSelectionPalette(color)}if(isInput)boundElement.val(displayColor);if(fireCallback&&hasChanged){callbacks.change(color);boundElement.trigger("change",[color])}}function reflow(){if(!visible)return;dragWidth=dragger.width();dragHeight=dragger.height();dragHelperHeight=dragHelper.height();slideWidth=slider.width();slideHeight=slider.height();slideHelperHeight=slideHelper.height();alphaWidth=alphaSlider.width();alphaSlideHelperWidth=alphaSlideHelper.width();if(!flat){container.css("position","absolute");if(opts.offset)container.offset(opts.offset);else container.offset(getOffset(container,offsetElement))}updateHelperLocations();if(opts.showPalette)drawPalette();boundElement.trigger("reflow.spectrum")}function destroy(){boundElement.show();offsetElement.off("click.spectrum touchstart.spectrum");container.remove();replacer.remove();spectrums[spect.id]=null}function option(optionName,optionValue){if(optionName===undefined)return $.extend({},opts);if(optionValue===undefined)return opts[optionName];opts[optionName]=optionValue;if(optionName==="preferredFormat")currentPreferredFormat=opts.preferredFormat;applyOptions()}function enable(){disabled=false;boundElement.attr("disabled",false);offsetElement.removeClass("sp-disabled")}function disable(){hide();disabled=true;boundElement.attr("disabled",true);offsetElement.addClass("sp-disabled")}function setOffset(coord){opts.offset=coord;reflow()}initialize();var spect={show:show,hide:hide,toggle:toggle,reflow:reflow,option:option,enable:enable,disable:disable,offset:setOffset,set:function(c){set(c);updateOriginalInput()},get:get,destroy:destroy,container:container};spect.id=spectrums.push(spect)-1;return spect}function getOffset(picker,input){var extraY=0;var dpWidth=picker.outerWidth();var dpHeight=picker.outerHeight();var inputHeight=input.outerHeight();var doc=picker[0].ownerDocument;var docElem=doc.documentElement;var viewWidth=docElem.clientWidth+$(doc).scrollLeft();var viewHeight=docElem.clientHeight+$(doc).scrollTop();var offset=input.offset();var offsetLeft=offset.left;var offsetTop=offset.top;offsetTop+=inputHeight;offsetLeft-=Math.min(offsetLeft,offsetLeft+dpWidth>viewWidth&&viewWidth>dpWidth?Math.abs(offsetLeft+dpWidth-viewWidth):0);offsetTop-=Math.min(offsetTop,offsetTop+dpHeight>viewHeight&&viewHeight>dpHeight?Math.abs(dpHeight+inputHeight-extraY):extraY);return{top:offsetTop,bottom:offset.bottom,left:offsetLeft,right:offset.right,width:offset.width,height:offset.height}}function noop(){}function stopPropagation(e){e.stopPropagation()}function bind(func,obj){var slice=Array.prototype.slice;var args=slice.call(arguments,2);return function(){return func.apply(obj,args.concat(slice.call(arguments)))}}function draggable(element,onmove,onstart,onstop){onmove=onmove||function(){};onstart=onstart||function(){};onstop=onstop||function(){};var doc=document;var dragging=false;var offset={};var maxHeight=0;var maxWidth=0;var hasTouch="ontouchstart"in window;var duringDragEvents={};duringDragEvents["selectstart"]=prevent;duringDragEvents["dragstart"]=prevent;duringDragEvents["touchmove mousemove"]=move;duringDragEvents["touchend mouseup"]=stop;function prevent(e){if(e.stopPropagation)e.stopPropagation();if(e.preventDefault)e.preventDefault();e.returnValue=false}function move(e){if(dragging){if(IE&&doc.documentMode<9&&!e.button)return stop();var t0=e.originalEvent&&e.originalEvent.touches&&e.originalEvent.touches[0];var pageX=t0&&t0.pageX||e.pageX;var pageY=t0&&t0.pageY||e.pageY;var dragX=Math.max(0,Math.min(pageX-offset.left,maxWidth));var dragY=Math.max(0,Math.min(pageY-offset.top,maxHeight));if(hasTouch)prevent(e);onmove.apply(element,[dragX,dragY,e])}}function start(e){var rightclick=e.which?e.which==3:e.button==2;if(!rightclick&&!dragging)if(onstart.apply(element,arguments)!==false){dragging=true;maxHeight=$(element).height();maxWidth=$(element).width();offset=$(element).offset();$(doc).on(duringDragEvents);$(doc.body).addClass("sp-dragging");move(e);prevent(e)}}function stop(){if(dragging){$(doc).off(duringDragEvents);$(doc.body).removeClass("sp-dragging");setTimeout(function(){onstop.apply(element,arguments)},0)}dragging=false}$(element).on("touchstart mousedown",start)}function throttle(func,wait,debounce){var timeout;return function(){var context=this,args=arguments;var throttler=function(){timeout=null;func.apply(context,args)};if(debounce)clearTimeout(timeout);if(debounce||!timeout)timeout=setTimeout(throttler,wait)}}function inputTypeColorSupport(){return $.fn.spectrum.inputTypeColorSupport()}var dataID="spectrum.id";$.fn.spectrum=function(opts,extra){if(typeof opts=="string"){var returnValue=this;var args=Array.prototype.slice.call(arguments,1);this.each(function(){var spect=spectrums[$(this).data(dataID)];if(spect){var method=spect[opts];if(!method)throw new Error("Spectrum: no such method: '"+opts+"'");if(opts=="get")returnValue=spect.get();else if(opts=="container")returnValue=spect.container;else if(opts=="option")returnValue=spect.option.apply(spect,args);else if(opts=="destroy"){spect.destroy();$(this).removeData(dataID)}else method.apply(spect,args)}});return returnValue}return this.spectrum("destroy").each(function(){var options=$.extend({},$(this).data(),opts);var spect=spectrum(this,options);$(this).data(dataID,spect.id)})};$.fn.spectrum.load=true;$.fn.spectrum.loadOpts={};$.fn.spectrum.draggable=draggable;$.fn.spectrum.defaults=defaultOpts;$.fn.spectrum.inputTypeColorSupport=function inputTypeColorSupport(){if(typeof inputTypeColorSupport._cachedResult==="undefined"){var colorInput=$("<input type='color'/>")[0];inputTypeColorSupport._cachedResult=colorInput.type==="color"&&colorInput.value!==""}return inputTypeColorSupport._cachedResult};$.spectrum={};$.spectrum.localization={};$.spectrum.palettes={};$.fn.spectrum.processNativeColorInputs=function(){var colorInputs=$("input[type=color]");if(colorInputs.length&&!inputTypeColorSupport())colorInputs.spectrum({preferredFormat:"hex6"})};(function(){var trimLeft=/^[\s,#]+/,trimRight=/\s+$/,tinyCounter=0,math=Math,mathRound=math.round,mathMin=math.min,mathMax=math.max,mathRandom=math.random;var tinycolor=function(color,opts){color=color?color:"";opts=opts||{};if(color instanceof tinycolor)return color;if(!(this instanceof tinycolor))return new tinycolor(color,opts);var rgb=inputToRGB(color);this._originalInput=color;this._r=rgb.r;this._g=rgb.g;this._b=rgb.b;this._a=rgb.a;this._roundA=mathRound(1E3*this._a)/1E3;this._format=opts.format||rgb.format;this._gradientType=opts.gradientType;if(this._r<1)this._r=mathRound(this._r);if(this._g<1)this._g=mathRound(this._g);if(this._b<1)this._b=mathRound(this._b);this._ok=rgb.ok;this._tc_id=tinyCounter++};tinycolor.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var rgb=this.toRgb();return(rgb.r*299+rgb.g*587+rgb.b*114)/1E3},setAlpha:function(value){this._a=boundAlpha(value);this._roundA=mathRound(1E3*this._a)/1E3;return this},toHsv:function(){var hsv=rgbToHsv(this._r,this._g,this._b);return{h:hsv.h*360,s:hsv.s,v:hsv.v,a:this._a}},toHsvString:function(){var hsv=rgbToHsv(this._r,this._g,this._b);var h=mathRound(hsv.h*360),s=mathRound(hsv.s*100),v=mathRound(hsv.v*100);return this._a==1?"hsv("+h+", "+s+"%, "+v+"%)":"hsva("+h+", "+s+"%, "+v+"%, "+this._roundA+")"},toHsl:function(){var hsl=rgbToHsl(this._r,this._g,this._b);return{h:hsl.h*360,s:hsl.s,l:hsl.l,a:this._a}},toHslString:function(){var hsl=rgbToHsl(this._r,this._g,this._b);var h=mathRound(hsl.h*360),s=mathRound(hsl.s*100),l=mathRound(hsl.l*100);return this._a==1?"hsl("+h+", "+s+"%, "+l+"%)":"hsla("+h+", "+s+"%, "+l+"%, "+this._roundA+")"},toHex:function(allow3Char){return rgbToHex(this._r,this._g,this._b,allow3Char)},toHexString:function(allow3Char){return"#"+this.toHex(allow3Char)},toHex8:function(){return rgbaToHex(this._r,this._g,this._b,this._a)},toHex8String:function(){return"#"+this.toHex8()},toRgb:function(){return{r:mathRound(this._r),g:mathRound(this._g),b:mathRound(this._b),a:this._a}},toRgbString:function(){return this._a==1?"rgb("+mathRound(this._r)+", "+mathRound(this._g)+", "+mathRound(this._b)+")":"rgba("+mathRound(this._r)+", "+mathRound(this._g)+", "+mathRound(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:mathRound(bound01(this._r,255)*100)+"%",g:mathRound(bound01(this._g,255)*100)+"%",b:mathRound(bound01(this._b,255)*100)+"%",a:this._a}},toPercentageRgbString:function(){return this._a==1?"rgb("+mathRound(bound01(this._r,255)*100)+"%, "+mathRound(bound01(this._g,255)*100)+"%, "+mathRound(bound01(this._b,255)*100)+"%)":"rgba("+mathRound(bound01(this._r,255)*100)+"%, "+mathRound(bound01(this._g,255)*100)+"%, "+mathRound(bound01(this._b,255)*100)+"%, "+this._roundA+")"},toName:function(){if(this._a===0)return"transparent";if(this._a<1)return false;return hexNames[rgbToHex(this._r,this._g,this._b,true)]||false},toFilter:function(secondColor){var hex8String="#"+rgbaToHex(this._r,this._g,this._b,this._a);var secondHex8String=hex8String;var gradientType=this._gradientType?"GradientType = 1, ":"";if(secondColor){var s=tinycolor(secondColor);secondHex8String=s.toHex8String()}return"progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")"},toString:function(format){var formatSet=!!format;format=format||this._format;var formattedString=false;var hasAlpha=this._a<1&&this._a>=0;var needsAlphaFormat=!formatSet&&hasAlpha&&(format==="hex"||format==="hex6"||format==="hex3"||format==="name");if(needsAlphaFormat){if(format==="name"&&this._a===0)return this.toName();return this.toRgbString()}if(format==="rgb")formattedString=this.toRgbString();if(format==="prgb")formattedString=this.toPercentageRgbString();if(format==="hex"||format==="hex6")formattedString=this.toHexString();if(format==="hex3")formattedString=this.toHexString(true);if(format==="hex8")formattedString=this.toHex8String();if(format==="name")formattedString=this.toName();if(format==="hsl")formattedString=this.toHslString();if(format==="hsv")formattedString=this.toHsvString();return formattedString||this.toHexString()},_applyModification:function(fn,args){var color=fn.apply(null,[this].concat([].slice.call(args)));this._r=color._r;this._g=color._g;this._b=color._b;this.setAlpha(color._a);return this},lighten:function(){return this._applyModification(lighten,arguments)},brighten:function(){return this._applyModification(brighten,arguments)},darken:function(){return this._applyModification(darken,arguments)},desaturate:function(){return this._applyModification(desaturate,arguments)},saturate:function(){return this._applyModification(saturate,arguments)},greyscale:function(){return this._applyModification(greyscale,arguments)},spin:function(){return this._applyModification(spin,arguments)},_applyCombination:function(fn,args){return fn.apply(null,[this].concat([].slice.call(args)))},analogous:function(){return this._applyCombination(analogous,arguments)},complement:function(){return this._applyCombination(complement,arguments)},monochromatic:function(){return this._applyCombination(monochromatic,arguments)},splitcomplement:function(){return this._applyCombination(splitcomplement,arguments)},triad:function(){return this._applyCombination(triad,arguments)},tetrad:function(){return this._applyCombination(tetrad,arguments)}};tinycolor.fromRatio=function(color,opts){if(typeof color=="object"){var newColor={};for(var i in color)if(color.hasOwnProperty(i))if(i==="a")newColor[i]=color[i];else newColor[i]=convertToPercentage(color[i]);color=newColor}return tinycolor(color,opts)};function inputToRGB(color){var rgb={r:0,g:0,b:0};var a=1;var ok=false;var format=false;if(typeof color=="string")color=stringInputToObject(color);if(typeof color=="object"){if(color.hasOwnProperty("r")&&color.hasOwnProperty("g")&&color.hasOwnProperty("b")){rgb=rgbToRgb(color.r,color.g,color.b);ok=true;format=String(color.r).substr(-1)==="%"?"prgb":"rgb"}else if(color.hasOwnProperty("h")&&color.hasOwnProperty("s")&&color.hasOwnProperty("v")){color.s=convertToPercentage(color.s);color.v=convertToPercentage(color.v);rgb=hsvToRgb(color.h,color.s,color.v);ok=true;format="hsv"}else if(color.hasOwnProperty("h")&&color.hasOwnProperty("s")&&color.hasOwnProperty("l")){color.s=convertToPercentage(color.s);color.l=convertToPercentage(color.l);rgb=hslToRgb(color.h,color.s,color.l);ok=true;format="hsl"}if(color.hasOwnProperty("a"))a=color.a}a=boundAlpha(a);return{ok:ok,format:color.format||format,r:mathMin(255,mathMax(rgb.r,0)),g:mathMin(255,mathMax(rgb.g,0)),b:mathMin(255,mathMax(rgb.b,0)),a:a}}function rgbToRgb(r,g,b){return{r:bound01(r,255)*255,g:bound01(g,255)*255,b:bound01(b,255)*255}}function rgbToHsl(r,g,b){r=bound01(r,255);g=bound01(g,255);b=bound01(b,255);var max=mathMax(r,g,b),min=mathMin(r,g,b);var h,s,l=(max+min)/2;if(max==min)h=s=0;else{var d=max-min;s=l>.5?d/(2-max-min):d/(max+min);switch(max){case r:h=(g-b)/d+(g<b?6:0);break;case g:h=(b-r)/d+2;break;case b:h=(r-g)/d+4;break}h/=6}return{h:h,s:s,l:l}}function hslToRgb(h,s,l){var r,g,b;h=bound01(h,360);s=bound01(s,100);l=bound01(l,100);function hue2rgb(p,q,t){if(t<0)t+=1;if(t>1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*(2/3-t)*6;return p}if(s===0)r=g=b=l;else{var q=l<.5?l*(1+s):l+s-l*s;var p=2*l-q;r=hue2rgb(p,q,h+1/3);g=hue2rgb(p,q,h);b=hue2rgb(p,q,h-1/3)}return{r:r*255,g:g*255,b:b*255}}function rgbToHsv(r,g,b){r=bound01(r,255);g=bound01(g,255);b=bound01(b,255);var max=mathMax(r,g,b),min=mathMin(r,g,b);var h,s,v=max;var d=max-min;s=max===0?0:d/max;if(max==min)h=0;else{switch(max){case r:h=(g-b)/d+(g<b?6:0);break;case g:h=(b-r)/d+2;break;case b:h=(r-g)/d+4;break}h/=6}return{h:h,s:s,v:v}}function hsvToRgb(h,s,v){h=bound01(h,360)*6;s=bound01(s,100);v=bound01(v,100);var i=math.floor(h),f=h-i,p=v*(1-s),q=v*(1-f*s),t=v*(1-(1-f)*s),mod=i%6,r=[v,q,p,p,t,v][mod],g=[t,v,v,q,p,p][mod],b=[p,p,t,v,v,q][mod];return{r:r*255,g:g*255,b:b*255}}function rgbToHex(r,g,b,allow3Char){var hex=[pad2(mathRound(r).toString(16)),pad2(mathRound(g).toString(16)),pad2(mathRound(b).toString(16))];if(allow3Char&&hex[0].charAt(0)==hex[0].charAt(1)&&hex[1].charAt(0)==hex[1].charAt(1)&&hex[2].charAt(0)==hex[2].charAt(1))return hex[0].charAt(0)+hex[1].charAt(0)+hex[2].charAt(0);return hex.join("")}function rgbaToHex(r,g,b,a){var hex=[pad2(convertDecimalToHex(a)),pad2(mathRound(r).toString(16)),pad2(mathRound(g).toString(16)),pad2(mathRound(b).toString(16))];return hex.join("")}tinycolor.equals=function(color1,color2){if(!color1||!color2)return false;return tinycolor(color1).toRgbString()==tinycolor(color2).toRgbString()};tinycolor.random=function(){return tinycolor.fromRatio({r:mathRandom(),g:mathRandom(),b:mathRandom()})};function desaturate(color,amount){amount=amount===0?0:amount||10;var hsl=tinycolor(color).toHsl();hsl.s-=amount/100;hsl.s=clamp01(hsl.s);return tinycolor(hsl)}function saturate(color,amount){amount=amount===0?0:amount||10;var hsl=tinycolor(color).toHsl();hsl.s+=amount/100;hsl.s=clamp01(hsl.s);return tinycolor(hsl)}function greyscale(color){return tinycolor(color).desaturate(100)}function lighten(color,amount){amount=amount===0?0:amount||10;var hsl=tinycolor(color).toHsl();hsl.l+=amount/100;hsl.l=clamp01(hsl.l);return tinycolor(hsl)}function brighten(color,amount){amount=amount===0?0:amount||10;var rgb=tinycolor(color).toRgb();rgb.r=mathMax(0,mathMin(255,rgb.r-mathRound(255*-(amount/100))));rgb.g=mathMax(0,mathMin(255,rgb.g-mathRound(255*-(amount/100))));rgb.b=mathMax(0,mathMin(255,rgb.b-mathRound(255*-(amount/100))));return tinycolor(rgb)}function darken(color,amount){amount=amount===0?0:amount||10;var hsl=tinycolor(color).toHsl();hsl.l-=amount/100;hsl.l=clamp01(hsl.l);return tinycolor(hsl)}function spin(color,amount){var hsl=tinycolor(color).toHsl();var hue=(mathRound(hsl.h)+amount)%360;hsl.h=hue<0?360+hue:hue;return tinycolor(hsl)}function complement(color){var hsl=tinycolor(color).toHsl();hsl.h=(hsl.h+180)%360;return tinycolor(hsl)}function triad(color){var hsl=tinycolor(color).toHsl();var h=hsl.h;return[tinycolor(color),tinycolor({h:(h+120)%360,s:hsl.s,l:hsl.l}),tinycolor({h:(h+240)%360,s:hsl.s,l:hsl.l})]}function tetrad(color){var hsl=tinycolor(color).toHsl();var h=hsl.h;return[tinycolor(color),tinycolor({h:(h+90)%360,s:hsl.s,l:hsl.l}),tinycolor({h:(h+180)%360,s:hsl.s,l:hsl.l}),tinycolor({h:(h+270)%360,s:hsl.s,l:hsl.l})]}function splitcomplement(color){var hsl=tinycolor(color).toHsl();var h=hsl.h;return[tinycolor(color),tinycolor({h:(h+72)%360,s:hsl.s,l:hsl.l}),tinycolor({h:(h+216)%360,s:hsl.s,l:hsl.l})]}function analogous(color,results,slices){results=results||6;slices=slices||30;var hsl=tinycolor(color).toHsl();var part=360/slices;var ret=[tinycolor(color)];for(hsl.h=(hsl.h-(part*results>>1)+720)%360;--results;){hsl.h=(hsl.h+part)%360;ret.push(tinycolor(hsl))}return ret}function monochromatic(color,results){results=results||6;var hsv=tinycolor(color).toHsv();var h=hsv.h,s=hsv.s,v=hsv.v;var ret=[];var modification=1/results;while(results--){ret.push(tinycolor({h:h,s:s,v:v}));v=(v+modification)%1}return ret}tinycolor.mix=function(color1,color2,amount){amount=amount===0?0:amount||50;var rgb1=tinycolor(color1).toRgb();var rgb2=tinycolor(color2).toRgb();var p=amount/100;var w=p*2-1;var a=rgb2.a-rgb1.a;var w1;if(w*a==-1)w1=w;else w1=(w+a)/(1+w*a);w1=(w1+1)/2;var w2=1-w1;var rgba={r:rgb2.r*w1+rgb1.r*w2,g:rgb2.g*w1+rgb1.g*w2,b:rgb2.b*w1+rgb1.b*w2,a:rgb2.a*p+rgb1.a*(1-p)};return tinycolor(rgba)};tinycolor.readability=function(color1,color2){var c1=tinycolor(color1);var c2=tinycolor(color2);var rgb1=c1.toRgb();var rgb2=c2.toRgb();var brightnessA=c1.getBrightness();var brightnessB=c2.getBrightness();var colorDiff=Math.max(rgb1.r,rgb2.r)-Math.min(rgb1.r,rgb2.r)+Math.max(rgb1.g,rgb2.g)-Math.min(rgb1.g,rgb2.g)+Math.max(rgb1.b,rgb2.b)-Math.min(rgb1.b,rgb2.b);return{brightness:Math.abs(brightnessA-brightnessB),color:colorDiff}};tinycolor.isReadable=function(color1,color2){var readability=tinycolor.readability(color1,color2);return readability.brightness>125&&readability.color>500};tinycolor.mostReadable=function(baseColor,colorList){var bestColor=null;var bestScore=0;var bestIsReadable=false;for(var i=0;i<colorList.length;i++){var readability=tinycolor.readability(baseColor,colorList[i]);var readable=readability.brightness>125&&readability.color>500;var score=3*(readability.brightness/125)+readability.color/500;if(readable&&!bestIsReadable||readable&&bestIsReadable&&score>bestScore||!readable&&!bestIsReadable&&score>bestScore){bestIsReadable=readable;bestScore=score;bestColor=tinycolor(colorList[i])}}return bestColor};var names=tinycolor.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};var hexNames=tinycolor.hexNames=flip(names);function flip(o){var flipped={};for(var i in o)if(o.hasOwnProperty(i))flipped[o[i]]=i;return flipped}function boundAlpha(a){a=parseFloat(a);if(isNaN(a)||a<0||a>1)a=1;return a}function bound01(n,max){if(isOnePointZero(n))n="100%";var processPercent=isPercentage(n);n=mathMin(max,mathMax(0,parseFloat(n)));if(processPercent)n=parseInt(n*max,10)/100;if(math.abs(n-max)<1E-6)return 1;return n%max/parseFloat(max)}function clamp01(val){return mathMin(1,mathMax(0,val))}function parseIntFromHex(val){return parseInt(val,16)}function isOnePointZero(n){return typeof n=="string"&&n.indexOf(".")!=-1&&parseFloat(n)===1}function isPercentage(n){return typeof n==="string"&&n.indexOf("%")!=-1}function pad2(c){return c.length==1?"0"+c:""+c}function convertToPercentage(n){if(n<=1)n=n*100+"%";return n}function convertDecimalToHex(d){return Math.round(parseFloat(d)*255).toString(16)}function convertHexToDecimal(h){return parseIntFromHex(h)/255}var matchers=function(){var CSS_INTEGER="[-\\+]?\\d+%?";var CSS_NUMBER="[-\\+]?\\d*\\.\\d+%?";var CSS_UNIT="(?:"+CSS_NUMBER+")|(?:"+CSS_INTEGER+")";var PERMISSIVE_MATCH3="[\\s|\\(]+("+CSS_UNIT+")[,|\\s]+("+CSS_UNIT+")[,|\\s]+("+CSS_UNIT+")\\s*\\)?";var PERMISSIVE_MATCH4="[\\s|\\(]+("+CSS_UNIT+")[,|\\s]+("+CSS_UNIT+")[,|\\s]+("+CSS_UNIT+")[,|\\s]+("+CSS_UNIT+")\\s*\\)?";return{rgb:new RegExp("rgb"+PERMISSIVE_MATCH3),rgba:new RegExp("rgba"+PERMISSIVE_MATCH4),hsl:new RegExp("hsl"+PERMISSIVE_MATCH3),hsla:new RegExp("hsla"+PERMISSIVE_MATCH4),hsv:new RegExp("hsv"+PERMISSIVE_MATCH3),hsva:new RegExp("hsva"+PERMISSIVE_MATCH4),hex3:/^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex8:/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}}();function stringInputToObject(color){color=color.replace(trimLeft,"").replace(trimRight,"").toLowerCase();var named=false;if(names[color]){color=names[color];named=true}else if(color=="transparent")return{r:0,g:0,b:0,a:0,format:"name"};var match;if(match=matchers.rgb.exec(color))return{r:match[1],g:match[2],b:match[3]};if(match=matchers.rgba.exec(color))return{r:match[1],g:match[2],b:match[3],a:match[4]};if(match=matchers.hsl.exec(color))return{h:match[1],s:match[2],l:match[3]};if(match=matchers.hsla.exec(color))return{h:match[1],s:match[2],l:match[3],a:match[4]};if(match=matchers.hsv.exec(color))return{h:match[1],s:match[2],v:match[3]};if(match=matchers.hsva.exec(color))return{h:match[1],s:match[2],v:match[3],a:match[4]};if(match=matchers.hex8.exec(color))return{a:convertHexToDecimal(match[1]),r:parseIntFromHex(match[2]),g:parseIntFromHex(match[3]),b:parseIntFromHex(match[4]),format:named?"name":"hex8"};if(match=matchers.hex6.exec(color))return{r:parseIntFromHex(match[1]),g:parseIntFromHex(match[2]),b:parseIntFromHex(match[3]),format:named?"name":"hex"};if(match=matchers.hex3.exec(color))return{r:parseIntFromHex(match[1]+""+match[1]),g:parseIntFromHex(match[2]+""+match[2]),b:parseIntFromHex(match[3]+""+match[3]),format:named?"name":"hex"};return false}window.tinycolor=tinycolor})();$(function(){if($.fn.spectrum.load)$.fn.spectrum.processNativeColorInputs()})});
import React from 'react'; import Col from 'react-bootstrap/lib/Col'; import ControlLabel from 'react-bootstrap/lib/ControlLabel'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import HelpBlock from 'react-bootstrap/lib/HelpBlock'; import InfoPopover from 'shared/info-popover'; import SelectField from './SelectField'; import { shallowWithIntl } from 'utils/testUtils'; describe('shared/form-fields/SelectField', () => { const options = [ { id: 'option-1-id', name: { fi: 'option-1-name-fi', en: 'option-1-name-en', sv: 'option-1-name-sv', } }, { id: 'option-2-id', name: { fi: 'option-2-name-fi', en: 'option-2-name-en', sv: 'option-2-name-sv', } }, { id: 'option-3-id', name: { fi: 'option-3-name-fi', en: 'option-3-name-en', sv: 'option-3-name-sv', } }, ]; const defaultProps = { controlProps: { someProp: 'some', otherProp: 'other', options }, fieldName: 'home-municipality-name', id: 'home-municipality-id', label: 'Home municipality', labelErrorPrefix: 'Error: ', validationState: 'error', }; function getWrapper(props) { return (shallowWithIntl(<SelectField {...defaultProps} {...props} />)); } describe('FormGroup component', () => { test('is rendered', () => { const formGroup = getWrapper().find(FormGroup); expect(formGroup.length).toBe(1); }); test('gets correct props', () => { const actualProps = getWrapper().find(FormGroup).props(); expect(actualProps.controlId).toBe(defaultProps.id); expect(actualProps.validationState).toBe(defaultProps.validationState); }); }); describe('Col components', () => { test('renders 2 Col components', () => { const cols = getWrapper().find(Col); expect(cols.length).toBe(2); }); describe('the first Col', () => { function getColWrapper(props) { return getWrapper(props).find(Col).at(0); } test('gets correct props', () => { expect(getColWrapper().props().componentClass).toBe(ControlLabel); expect(getColWrapper().props().sm).toBe(3); }); test('contains the label text given in props', () => { expect( getColWrapper().props().children ).toEqual(expect.arrayContaining([defaultProps.label])); }); describe('labelErrorPrefix text', () => { test('is included in label text when field has an error', () => { expect( getColWrapper().props().children ).toEqual(expect.arrayContaining([defaultProps.labelErrorPrefix])); }); test('is not included in label text when field doesnt have an error', () => { expect( getColWrapper({ validationState: undefined }).props().children ).toEqual(expect.not.arrayContaining([defaultProps.labelErrorPrefix])); }); }); test('does not contain InfoPopover if info not given', () => { const popover = getColWrapper().find(InfoPopover); expect(popover).toHaveLength(0); }); test('contains InfoPopover if info is given', () => { const info = 'Some info'; const popover = getColWrapper({ info }).find(InfoPopover); expect(popover).toHaveLength(1); expect(popover.prop('text')).toBe(info); }); }); describe('the second Col', () => { let col; beforeAll(() => { col = getWrapper().find(Col).at(1); }); test('gets correct props', () => { expect(col.props().sm).toBe(9); }); }); }); describe('select element', () => { test('is rendered', () => { const selectElement = getWrapper().find('select'); expect(selectElement.length).toBe(1); expect(selectElement.prop('name')).toEqual(defaultProps.fieldName); expect(selectElement.prop('className')).toEqual('select-input'); expect(selectElement.prop('id')).toEqual(defaultProps.id); }); describe('when input error has occurred', () => { test('gets correct aria props', () => { const selectElement = getWrapper({ validationState: 'error' }).find('select'); expect(selectElement.length).toBe(1); expect(selectElement.prop('aria-invalid')).toBe('true'); expect(selectElement.prop('aria-describedby')).toEqual(`${defaultProps.id}-help-block`); }); }); describe('when input error has not occurred', () => { test('gets correct aria props', () => { const selectElement = getWrapper({ validationState: undefined }).find('select'); expect(selectElement.length).toBe(1); expect(selectElement.prop('aria-invalid')).toBe('false'); expect(selectElement.prop('aria-describedby')).toEqual(`${defaultProps.id}-help-block`); }); }); }); describe('HelpBlock component', () => { const help = 'some help'; test('is rendered', () => { const helpBlock = getWrapper({ help }).find(HelpBlock); expect(helpBlock.length).toBe(1); expect(helpBlock.prop('id')).toEqual(`${defaultProps.id}-help-block`); }); test('displays the help text given in props', () => { const helpBlock = getWrapper({ help }).find(HelpBlock); expect(helpBlock.props().children).toBe(help); }); }); });
# SPDX-FileCopyrightText: 2017 Google Inc. # # SPDX-License-Identifier: Apache-2.0 # Copyright (C) 2017 Google 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. """Sample that implements a gRPC client for the Google Assistant API.""" import concurrent.futures import json import logging import os import os.path import pathlib2 as pathlib import sys import time import uuid sys.path.append("env/lib/python3.7/site-packages/googlesamples/assistant/grpc") import click import grpc import google.auth.transport.grpc import google.auth.transport.requests import google.oauth2.credentials from google.assistant.embedded.v1alpha2 import ( embedded_assistant_pb2, embedded_assistant_pb2_grpc, ) from tenacity import retry, stop_after_attempt, retry_if_exception try: from . import assistant_helpers, audio_helpers, browser_helpers, device_helpers except (SystemError, ImportError): import assistant_helpers import audio_helpers import browser_helpers import device_helpers try: import board from digitalio import DigitalInOut import adafruit_dotstar except ImportError: print("Blinka not installed? Run 'pip3 install adafruit-circuitpython-dotstar'") raise ImportError( "Blinka not installed? Run 'pip3 install adafruit-circuitpython-dotstar'" ) # Setup button button = DigitalInOut(board.D17) button.switch_to_input() # Setup DotStar LEDs dots = adafruit_dotstar.DotStar( board.D6, board.D5, 3, auto_write=True, brightness=0.2, pixel_order=adafruit_dotstar.BGR, ) dots.fill(0x000000) ASSISTANT_API_ENDPOINT = "embeddedassistant.googleapis.com" END_OF_UTTERANCE = embedded_assistant_pb2.AssistResponse.END_OF_UTTERANCE DIALOG_FOLLOW_ON = embedded_assistant_pb2.DialogStateOut.DIALOG_FOLLOW_ON CLOSE_MICROPHONE = embedded_assistant_pb2.DialogStateOut.CLOSE_MICROPHONE PLAYING = embedded_assistant_pb2.ScreenOutConfig.PLAYING DEFAULT_GRPC_DEADLINE = 60 * 3 + 5 class SampleAssistant(object): """Sample Assistant that supports conversations and device actions. Args: device_model_id: identifier of the device model. device_id: identifier of the registered device instance. conversation_stream(ConversationStream): audio stream for recording query and playing back assistant answer. channel: authorized gRPC channel for connection to the Google Assistant API. deadline_sec: gRPC deadline in seconds for Google Assistant API call. device_handler: callback for device actions. """ def __init__( self, language_code, device_model_id, device_id, conversation_stream, display, channel, deadline_sec, device_handler, ): self.language_code = language_code self.device_model_id = device_model_id self.device_id = device_id self.conversation_stream = conversation_stream self.display = display # Opaque blob provided in AssistResponse that, # when provided in a follow-up AssistRequest, # gives the Assistant a context marker within the current state # of the multi-Assist()-RPC "conversation". # This value, along with MicrophoneMode, supports a more natural # "conversation" with the Assistant. self.conversation_state = None # Force reset of first conversation. self.is_new_conversation = True # Create Google Assistant API gRPC client. self.assistant = embedded_assistant_pb2_grpc.EmbeddedAssistantStub(channel) self.deadline = deadline_sec self.device_handler = device_handler def __enter__(self): return self def __exit__(self, etype, e, traceback): if e: return False self.conversation_stream.close() def is_grpc_error_unavailable(e): is_grpc_error = isinstance(e, grpc.RpcError) if is_grpc_error and (e.code() == grpc.StatusCode.UNAVAILABLE): logging.error("grpc unavailable error: %s", e) return True return False @retry( reraise=True, stop=stop_after_attempt(3), retry=retry_if_exception(is_grpc_error_unavailable), ) def assist(self): """Send a voice request to the Assistant and playback the response. Returns: True if conversation should continue. """ continue_conversation = False device_actions_futures = [] self.conversation_stream.start_recording() logging.info("Recording audio request.") def iter_log_assist_requests(): for c in self.gen_assist_requests(): assistant_helpers.log_assist_request_without_audio(c) yield c logging.debug("Reached end of AssistRequest iteration.") # This generator yields AssistResponse proto messages # received from the gRPC Google Assistant API. for resp in self.assistant.Assist(iter_log_assist_requests(), self.deadline): assistant_helpers.log_assist_response_without_audio(resp) if resp.event_type == END_OF_UTTERANCE: logging.info("End of audio request detected.") logging.info("Stopping recording.") self.conversation_stream.stop_recording() if resp.speech_results: logging.info( 'Transcript of user request: "%s".', " ".join(r.transcript for r in resp.speech_results), ) if len(resp.audio_out.audio_data) > 0: if not self.conversation_stream.playing: self.conversation_stream.stop_recording() self.conversation_stream.start_playback() logging.info("Playing assistant response.") self.conversation_stream.write(resp.audio_out.audio_data) if resp.dialog_state_out.conversation_state: conversation_state = resp.dialog_state_out.conversation_state logging.debug("Updating conversation state.") self.conversation_state = conversation_state if resp.dialog_state_out.volume_percentage != 0: volume_percentage = resp.dialog_state_out.volume_percentage logging.info("Setting volume to %s%%", volume_percentage) self.conversation_stream.volume_percentage = volume_percentage if resp.dialog_state_out.microphone_mode == DIALOG_FOLLOW_ON: continue_conversation = True logging.info("Expecting follow-on query from user.") elif resp.dialog_state_out.microphone_mode == CLOSE_MICROPHONE: continue_conversation = False if resp.device_action.device_request_json: device_request = json.loads(resp.device_action.device_request_json) fs = self.device_handler(device_request) if fs: device_actions_futures.extend(fs) if self.display and resp.screen_out.data: system_browser = browser_helpers.system_browser system_browser.display(resp.screen_out.data) if len(device_actions_futures): logging.info("Waiting for device executions to complete.") concurrent.futures.wait(device_actions_futures) logging.info("Finished playing assistant response.") self.conversation_stream.stop_playback() return continue_conversation def gen_assist_requests(self): """Yields: AssistRequest messages to send to the API.""" config = embedded_assistant_pb2.AssistConfig( audio_in_config=embedded_assistant_pb2.AudioInConfig( encoding="LINEAR16", sample_rate_hertz=self.conversation_stream.sample_rate, ), audio_out_config=embedded_assistant_pb2.AudioOutConfig( encoding="LINEAR16", sample_rate_hertz=self.conversation_stream.sample_rate, volume_percentage=self.conversation_stream.volume_percentage, ), dialog_state_in=embedded_assistant_pb2.DialogStateIn( language_code=self.language_code, conversation_state=self.conversation_state, is_new_conversation=self.is_new_conversation, ), device_config=embedded_assistant_pb2.DeviceConfig( device_id=self.device_id, device_model_id=self.device_model_id, ), ) if self.display: config.screen_out_config.screen_mode = PLAYING # Continue current conversation with later requests. self.is_new_conversation = False # The first AssistRequest must contain the AssistConfig # and no audio data. yield embedded_assistant_pb2.AssistRequest(config=config) for data in self.conversation_stream: # Subsequent requests need audio data, but not config. yield embedded_assistant_pb2.AssistRequest(audio_in=data) @click.command() @click.option( "--api-endpoint", default=ASSISTANT_API_ENDPOINT, metavar="<api endpoint>", show_default=True, help="Address of Google Assistant API service.", ) @click.option( "--credentials", metavar="<credentials>", show_default=True, default=os.path.join(click.get_app_dir("google-oauthlib-tool"), "credentials.json"), help="Path to read OAuth2 credentials.", ) @click.option( "--project-id", metavar="<project id>", help=( "Google Developer Project ID used for registration " "if --device-id is not specified" ), ) @click.option( "--device-model-id", metavar="<device model id>", help=( ( "Unique device model identifier, " "if not specifed, it is read from --device-config" ) ), ) @click.option( "--device-id", metavar="<device id>", help=( ( "Unique registered device instance identifier, " "if not specified, it is read from --device-config, " "if no device_config found: a new device is registered " "using a unique id and a new device config is saved" ) ), ) @click.option( "--device-config", show_default=True, metavar="<device config>", default=os.path.join( click.get_app_dir("googlesamples-assistant"), "device_config.json" ), help="Path to save and restore the device configuration", ) @click.option( "--lang", show_default=True, metavar="<language code>", default="en-US", help="Language code of the Assistant", ) @click.option( "--display", is_flag=True, default=False, help="Enable visual display of Assistant responses in HTML.", ) @click.option("--verbose", "-v", is_flag=True, default=False, help="Verbose logging.") @click.option( "--input-audio-file", "-i", metavar="<input file>", help="Path to input audio file. " "If missing, uses audio capture", ) @click.option( "--output-audio-file", "-o", metavar="<output file>", help="Path to output audio file. " "If missing, uses audio playback", ) @click.option( "--audio-sample-rate", default=audio_helpers.DEFAULT_AUDIO_SAMPLE_RATE, metavar="<audio sample rate>", show_default=True, help="Audio sample rate in hertz.", ) @click.option( "--audio-sample-width", default=audio_helpers.DEFAULT_AUDIO_SAMPLE_WIDTH, metavar="<audio sample width>", show_default=True, help="Audio sample width in bytes.", ) @click.option( "--audio-iter-size", default=audio_helpers.DEFAULT_AUDIO_ITER_SIZE, metavar="<audio iter size>", show_default=True, help="Size of each read during audio stream iteration in bytes.", ) @click.option( "--audio-block-size", default=audio_helpers.DEFAULT_AUDIO_DEVICE_BLOCK_SIZE, metavar="<audio block size>", show_default=True, help=("Block size in bytes for each audio device " "read and write operation."), ) @click.option( "--audio-flush-size", default=audio_helpers.DEFAULT_AUDIO_DEVICE_FLUSH_SIZE, metavar="<audio flush size>", show_default=True, help=("Size of silence data in bytes written " "during flush operation"), ) @click.option( "--grpc-deadline", default=DEFAULT_GRPC_DEADLINE, metavar="<grpc deadline>", show_default=True, help="gRPC deadline in seconds", ) @click.option( "--once", default=False, is_flag=True, help="Force termination after a single conversation.", ) def main( api_endpoint, credentials, project_id, device_model_id, device_id, device_config, lang, display, verbose, input_audio_file, output_audio_file, audio_sample_rate, audio_sample_width, audio_iter_size, audio_block_size, audio_flush_size, grpc_deadline, once, *args, **kwargs ): """Samples for the Google Assistant API. Examples: Run the sample with microphone input and speaker output: $ python -m googlesamples.assistant Run the sample with file input and speaker output: $ python -m googlesamples.assistant -i <input file> Run the sample with file input and output: $ python -m googlesamples.assistant -i <input file> -o <output file> """ # Setup logging. logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) # Load OAuth 2.0 credentials. try: with open(credentials, "r") as f: credentials = google.oauth2.credentials.Credentials( token=None, **json.load(f) ) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) except Exception as e: logging.error("Error loading credentials: %s", e) logging.error( "Run google-oauthlib-tool to initialize " "new OAuth 2.0 credentials." ) sys.exit(-1) # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, api_endpoint ) logging.info("Connecting to %s", api_endpoint) # Configure audio source and sink. audio_device = None if input_audio_file: audio_source = audio_helpers.WaveSource( open(input_audio_file, "rb"), sample_rate=audio_sample_rate, sample_width=audio_sample_width, ) else: audio_source = audio_device = audio_device or audio_helpers.SoundDeviceStream( sample_rate=audio_sample_rate, sample_width=audio_sample_width, block_size=audio_block_size, flush_size=audio_flush_size, ) if output_audio_file: audio_sink = audio_helpers.WaveSink( open(output_audio_file, "wb"), sample_rate=audio_sample_rate, sample_width=audio_sample_width, ) else: audio_sink = audio_device = audio_device or audio_helpers.SoundDeviceStream( sample_rate=audio_sample_rate, sample_width=audio_sample_width, block_size=audio_block_size, flush_size=audio_flush_size, ) # Create conversation stream with the given audio source and sink. conversation_stream = audio_helpers.ConversationStream( source=audio_source, sink=audio_sink, iter_size=audio_iter_size, sample_width=audio_sample_width, ) if not device_id or not device_model_id: try: with open(device_config) as f: device = json.load(f) device_id = device["id"] device_model_id = device["model_id"] logging.info( "Using device model %s and device id %s", device_model_id, device_id ) except Exception as e: logging.warning("Device config not found: %s" % e) logging.info("Registering device") if not device_model_id: logging.error( "Option --device-model-id required " "when registering a device instance." ) sys.exit(-1) if not project_id: logging.error( "Option --project-id required " "when registering a device instance." ) sys.exit(-1) device_base_url = "https://%s/v1alpha2/projects/%s/devices" % ( api_endpoint, project_id, ) device_id = str(uuid.uuid1()) payload = { "id": device_id, "model_id": device_model_id, "client_type": "SDK_SERVICE", } session = google.auth.transport.requests.AuthorizedSession(credentials) r = session.post(device_base_url, data=json.dumps(payload)) if r.status_code != 200: logging.error("Failed to register device: %s", r.text) sys.exit(-1) logging.info("Device registered: %s", device_id) pathlib.Path(os.path.dirname(device_config)).mkdir(exist_ok=True) with open(device_config, "w") as f: json.dump(payload, f) device_handler = device_helpers.DeviceRequestHandler(device_id) @device_handler.command("action.devices.commands.OnOff") def onoff(on): if on: logging.info("Turning device on") else: logging.info("Turning device off") @device_handler.command("com.example.commands.BlinkLight") def blink(speed, number): logging.info("Blinking device %s times." % number) delay = 1 if speed == "SLOWLY": delay = 2 elif speed == "QUICKLY": delay = 0.5 for i in range(int(number)): logging.info("Device is blinking.") time.sleep(delay) with SampleAssistant( lang, device_model_id, device_id, conversation_stream, display, grpc_channel, grpc_deadline, device_handler, ) as assistant: # If file arguments are supplied: # exit after the first turn of the conversation. if input_audio_file or output_audio_file: assistant.assist() return # If no file arguments supplied: # keep recording voice requests using the microphone # and playing back assistant response using the speaker. # When the once flag is set, don't wait for a trigger. Otherwise, wait. wait_for_user_trigger = not once while True: if wait_for_user_trigger: print("Press button to initiate a new request") dots.fill(0x00000F) # lite blue LEDs dots.show() while button.value: time.sleep(0.1) # red LEDs dots.fill(0xFF0000) dots.show() continue_conversation = assistant.assist() # LEDs off dots.fill(0x000000) dots.show() # wait for user trigger if there is no follow-up turn in # the conversation. wait_for_user_trigger = not continue_conversation # If we only want one conversation, break. if once and (not continue_conversation): break if __name__ == "__main__": main()
(function () { 'use strict'; angular .module('eligbl') .service('filteredPrograms', [filteredProgramService]); function filteredProgramService(){ function setFilteredPrograms(programs){ this.filteredPrograms = programs; } return { setFilteredPrograms: setFilteredPrograms } } })();
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M2.5 9.59c.22.34.68.42 1.01.18l.96-.7v7.15c0 .42.34.77.77.77.42 0 .77-.34.77-.77V7.81c0-.45-.36-.81-.81-.81-.17 0-.34.05-.48.15L2.68 8.63c-.31.22-.39.65-.18.96zm10.78-1.93C12.69 7.22 12 7 11.22 7s-1.47.22-2.07.66c-.59.43-1.05 1.03-1.37 1.79-.33.76-.49 1.61-.49 2.55 0 .93.16 1.78.48 2.53.32.76.78 1.36 1.38 1.8.6.44 1.28.66 2.07.66.77 0 1.46-.22 2.05-.66.6-.44 1.05-1.04 1.38-1.8.32-.76.48-1.6.48-2.53 0-.94-.16-1.79-.48-2.55-.32-.76-.78-1.36-1.37-1.79zm.01 6.15c-.19.54-.47.96-.82 1.27-.36.31-.78.47-1.25.47-.48 0-.9-.16-1.26-.47-.35-.31-.63-.74-.82-1.27s-.28-1.14-.28-1.81c0-.67.1-1.28.29-1.82.19-.54.46-.96.82-1.27.35-.31.77-.46 1.26-.46.47 0 .89.15 1.25.46s.63.73.82 1.27c.19.54.29 1.15.29 1.82-.01.67-.11 1.27-.3 1.81zm8.22-.38c-.36-.36-.89-.63-1.58-.8l-1.05-.26c-.34-.09-.61-.21-.78-.34-.18-.14-.27-.31-.27-.52 0-.22.12-.4.35-.54.23-.14.52-.21.87-.21.54 0 .95.15 1.24.46.19.21.51.24.77.13.47-.21.59-.84.21-1.18-.14-.12-.3-.23-.48-.33-.5-.27-1.08-.4-1.75-.4-.49 0-.95.09-1.37.26-.42.17-.75.42-1 .73-.25.32-.37.68-.37 1.1 0 .54.19.99.56 1.34.37.35.84.6 1.41.74l.85.21c.47.11.81.24 1.03.39.22.15.34.35.34.61 0 .27-.13.47-.39.61s-.58.2-.96.2c-.39 0-.74-.1-1.04-.29-.16-.1-.3-.23-.42-.38a.739.739 0 0 0-.88-.21c-.47.21-.6.81-.26 1.19.17.19.37.37.59.52.52.36 1.19.54 2.01.54.54 0 1.03-.09 1.48-.28.45-.19.8-.45 1.05-.79.26-.34.38-.73.38-1.18 0-.52-.18-.96-.54-1.32z" }), 'Timer10Rounded'); exports.default = _default;
/** * Kendo UI v2016.3.914 (http://www.telerik.com/kendo-ui) * Copyright 2016 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ !function(y){"function"==typeof define&&define.amd?define(["kendo.core.min"],y):y()}(function(){!function(y,n){kendo.cultures["ii-CN"]={name:"ii-CN",numberFormat:{pattern:["-n"],decimals:2,",":",",".":".",groupSize:[3],percent:{pattern:["-n%","n%"],decimals:2,",":",",".":".",groupSize:[3],symbol:"%"},currency:{name:"PRC Renminbi",abbr:"CNY",pattern:["$-n","$n"],decimals:2,",":",",".":".",groupSize:[3],symbol:"¥"}},calendars:{standard:{days:{names:["ꑭꆏꑍ","ꆏꊂ꒔","ꆏꊂꑍ","ꆏꊂꌕ","ꆏꊂꇖ","ꆏꊂꉬ","ꆏꊂꃘ"],namesAbbr:["ꑭꆏ","ꆏ꒔","ꆏꑍ","ꆏꌕ","ꆏꇖ","ꆏꉬ","ꆏꃘ"],namesShort:["ꆏ","꒔","ꑍ","ꌕ","ꇖ","ꉬ","ꃘ"]},months:{names:["ꋍꆪ","ꑍꆪ","ꌕꆪ","ꇖꆪ","ꉬꆪ","ꃘꆪ","ꏃꆪ","ꉆꆪ","ꈬꆪ","ꊰꆪ","ꊯꊪꆪ","ꊰꑋꆪ"],namesAbbr:["ꋍꆪ","ꑍꆪ","ꌕꆪ","ꇖꆪ","ꉬꆪ","ꃘꆪ","ꏃꆪ","ꉆꆪ","ꈬꆪ","ꊰꆪ","ꊯꊪꆪ","ꊰꑋꆪ"]},AM:["ꂵꆪꈌꈐ","ꂵꆪꈌꈐ","ꂵꆪꈌꈐ"],PM:["ꂵꆪꈌꉈ","ꂵꆪꈌꉈ","ꂵꆪꈌꉈ"],patterns:{d:"yyyy/M/d",D:"yyyy'ꈎ' M'ꆪ' d'ꑍ'",F:"yyyy'ꈎ' M'ꆪ' d'ꑍ' tt h:mm:ss",g:"yyyy/M/d tt h:mm",G:"yyyy/M/d tt h:mm:ss",m:"M'’ ꆪ’'d'’ ꑍ’'",M:"M'’ ꆪ’'d'’ ꑍ’'",s:"yyyy'-'MM'-'dd'T'HH':'mm':'ss",t:"tt h:mm",T:"tt h:mm:ss",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"yyyy'ꈎ' M'ꆪ'",Y:"yyyy'ꈎ' M'ꆪ'"},"/":"/",":":":",firstDay:1}}}}(this)}); //# sourceMappingURL=kendo.culture.ii-CN.min.js.map
/** * UAParser.js v0.7.17 * Lightweight JavaScript-based User-Agent string parser * https://github.com/faisalman/ua-parser-js * * Copyright © 2012-2016 Faisal Salman <[email protected]> * Dual licensed under GPLv2 & MIT */ (function(window,undefined){"use strict";var LIBVERSION="0.7.17",EMPTY="",UNKNOWN="?",FUNC_TYPE="function",UNDEF_TYPE="undefined",OBJ_TYPE="object",STR_TYPE="string",MAJOR="major",MODEL="model",NAME="name",TYPE="type",VENDOR="vendor",VERSION="version",ARCHITECTURE="architecture",CONSOLE="console",MOBILE="mobile",TABLET="tablet",SMARTTV="smarttv",WEARABLE="wearable",EMBEDDED="embedded";var util={extend:function(regexes,extensions){var margedRegexes={};for(var i in regexes){if(extensions[i]&&extensions[i].length%2===0){margedRegexes[i]=extensions[i].concat(regexes[i])}else{margedRegexes[i]=regexes[i]}}return margedRegexes},has:function(str1,str2){if(typeof str1==="string"){return str2.toLowerCase().indexOf(str1.toLowerCase())!==-1}else{return false}},lowerize:function(str){return str.toLowerCase()},major:function(version){return typeof version===STR_TYPE?version.replace(/[^\d\.]/g,"").split(".")[0]:undefined},trim:function(str){return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}};var mapper={rgx:function(ua,arrays){var i=0,j,k,p,q,matches,match;while(i<arrays.length&&!matches){var regex=arrays[i],props=arrays[i+1];j=k=0;while(j<regex.length&&!matches){matches=regex[j++].exec(ua);if(!!matches){for(p=0;p<props.length;p++){match=matches[++k];q=props[p];if(typeof q===OBJ_TYPE&&q.length>0){if(q.length==2){if(typeof q[1]==FUNC_TYPE){this[q[0]]=q[1].call(this,match)}else{this[q[0]]=q[1]}}else if(q.length==3){if(typeof q[1]===FUNC_TYPE&&!(q[1].exec&&q[1].test)){this[q[0]]=match?q[1].call(this,match,q[2]):undefined}else{this[q[0]]=match?match.replace(q[1],q[2]):undefined}}else if(q.length==4){this[q[0]]=match?q[3].call(this,match.replace(q[1],q[2])):undefined}}else{this[q]=match?match:undefined}}}}i+=2}},str:function(str,map){for(var i in map){if(typeof map[i]===OBJ_TYPE&&map[i].length>0){for(var j=0;j<map[i].length;j++){if(util.has(map[i][j],str)){return i===UNKNOWN?undefined:i}}}else if(util.has(map[i],str)){return i===UNKNOWN?undefined:i}}return str}};var maps={browser:{oldsafari:{version:{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}}},device:{amazon:{model:{"Fire Phone":["SD","KF"]}},sprint:{model:{"Evo Shift 4G":"7373KT"},vendor:{HTC:"APA",Sprint:"Sprint"}}},os:{windows:{version:{ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2000:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"}}}};var regexes={browser:[[/(opera\smini)\/([\w\.-]+)/i,/(opera\s[mobiletab]+).+version\/([\w\.-]+)/i,/(opera).+version\/([\w\.]+)/i,/(opera)[\/\s]+([\w\.]+)/i],[NAME,VERSION],[/(opios)[\/\s]+([\w\.]+)/i],[[NAME,"Opera Mini"],VERSION],[/\s(opr)\/([\w\.]+)/i],[[NAME,"Opera"],VERSION],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,/(?:ms|\()(ie)\s([\w\.]+)/i,/(rekonq)\/([\w\.]+)*/i,/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser)\/([\w\.-]+)/i],[NAME,VERSION],[/(trident).+rv[:\s]([\w\.]+).+like\sgecko/i],[[NAME,"IE"],VERSION],[/(edge)\/((\d+)?[\w\.]+)/i],[NAME,VERSION],[/(yabrowser)\/([\w\.]+)/i],[[NAME,"Yandex"],VERSION],[/(puffin)\/([\w\.]+)/i],[[NAME,"Puffin"],VERSION],[/((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i],[[NAME,"UCBrowser"],VERSION],[/(comodo_dragon)\/([\w\.]+)/i],[[NAME,/_/g," "],VERSION],[/(micromessenger)\/([\w\.]+)/i],[[NAME,"WeChat"],VERSION],[/(QQ)\/([\d\.]+)/i],[NAME,VERSION],[/m?(qqbrowser)[\/\s]?([\w\.]+)/i],[NAME,VERSION],[/xiaomi\/miuibrowser\/([\w\.]+)/i],[VERSION,[NAME,"MIUI Browser"]],[/;fbav\/([\w\.]+);/i],[VERSION,[NAME,"Facebook"]],[/headlesschrome(?:\/([\w\.]+)|\s)/i],[VERSION,[NAME,"Chrome Headless"]],[/\swv\).+(chrome)\/([\w\.]+)/i],[[NAME,/(.+)/,"$1 WebView"],VERSION],[/((?:oculus|samsung)browser)\/([\w\.]+)/i],[[NAME,/(.+(?:g|us))(.+)/,"$1 $2"],VERSION],[/android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i],[VERSION,[NAME,"Android Browser"]],[/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i],[NAME,VERSION],[/(dolfin)\/([\w\.]+)/i],[[NAME,"Dolphin"],VERSION],[/((?:android.+)crmo|crios)\/([\w\.]+)/i],[[NAME,"Chrome"],VERSION],[/(coast)\/([\w\.]+)/i],[[NAME,"Opera Coast"],VERSION],[/fxios\/([\w\.-]+)/i],[VERSION,[NAME,"Firefox"]],[/version\/([\w\.]+).+?mobile\/\w+\s(safari)/i],[VERSION,[NAME,"Mobile Safari"]],[/version\/([\w\.]+).+?(mobile\s?safari|safari)/i],[VERSION,NAME],[/webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[[NAME,"GSA"],VERSION],[/webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[NAME,[VERSION,mapper.str,maps.browser.oldsafari.version]],[/(konqueror)\/([\w\.]+)/i,/(webkit|khtml)\/([\w\.]+)/i],[NAME,VERSION],[/(navigator|netscape)\/([\w\.-]+)/i],[[NAME,"Netscape"],VERSION],[/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,/(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,/(links)\s\(([\w\.]+)/i,/(gobrowser)\/?([\w\.]+)*/i,/(ice\s?browser)\/v?([\w\._]+)/i,/(mosaic)[\/\s]([\w\.]+)/i],[NAME,VERSION]],cpu:[[/(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i],[[ARCHITECTURE,"amd64"]],[/(ia32(?=;))/i],[[ARCHITECTURE,util.lowerize]],[/((?:i[346]|x)86)[;\)]/i],[[ARCHITECTURE,"ia32"]],[/windows\s(ce|mobile);\sppc;/i],[[ARCHITECTURE,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i],[[ARCHITECTURE,/ower/,"",util.lowerize]],[/(sun4\w)[;\)]/i],[[ARCHITECTURE,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i],[[ARCHITECTURE,util.lowerize]]],device:[[/\((ipad|playbook);[\w\s\);-]+(rim|apple)/i],[MODEL,VENDOR,[TYPE,TABLET]],[/applecoremedia\/[\w\.]+ \((ipad)/],[MODEL,[VENDOR,"Apple"],[TYPE,TABLET]],[/(apple\s{0,1}tv)/i],[[MODEL,"Apple TV"],[VENDOR,"Apple"]],[/(archos)\s(gamepad2?)/i,/(hp).+(touchpad)/i,/(hp).+(tablet)/i,/(kindle)\/([\w\.]+)/i,/\s(nook)[\w\s]+build\/(\w+)/i,/(dell)\s(strea[kpr\s\d]*[\dko])/i],[VENDOR,MODEL,[TYPE,TABLET]],[/(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i],[MODEL,[VENDOR,"Amazon"],[TYPE,TABLET]],[/(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i],[[MODEL,mapper.str,maps.device.amazon.model],[VENDOR,"Amazon"],[TYPE,MOBILE]],[/\((ip[honed|\s\w*]+);.+(apple)/i],[MODEL,VENDOR,[TYPE,MOBILE]],[/\((ip[honed|\s\w*]+);/i],[MODEL,[VENDOR,"Apple"],[TYPE,MOBILE]],[/(blackberry)[\s-]?(\w+)/i,/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i,/(hp)\s([\w\s]+\w)/i,/(asus)-?(\w+)/i],[VENDOR,MODEL,[TYPE,MOBILE]],[/\(bb10;\s(\w+)/i],[MODEL,[VENDOR,"BlackBerry"],[TYPE,MOBILE]],[/android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i],[MODEL,[VENDOR,"Asus"],[TYPE,TABLET]],[/(sony)\s(tablet\s[ps])\sbuild\//i,/(sony)?(?:sgp.+)\sbuild\//i],[[VENDOR,"Sony"],[MODEL,"Xperia Tablet"],[TYPE,TABLET]],[/android.+\s([c-g]\d{4}|so[-l]\w+)\sbuild\//i],[MODEL,[VENDOR,"Sony"],[TYPE,MOBILE]],[/\s(ouya)\s/i,/(nintendo)\s([wids3u]+)/i],[VENDOR,MODEL,[TYPE,CONSOLE]],[/android.+;\s(shield)\sbuild/i],[MODEL,[VENDOR,"Nvidia"],[TYPE,CONSOLE]],[/(playstation\s[34portablevi]+)/i],[MODEL,[VENDOR,"Sony"],[TYPE,CONSOLE]],[/(sprint\s(\w+))/i],[[VENDOR,mapper.str,maps.device.sprint.vendor],[MODEL,mapper.str,maps.device.sprint.model],[TYPE,MOBILE]],[/(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i],[VENDOR,MODEL,[TYPE,TABLET]],[/(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i,/(zte)-(\w+)*/i,/(alcatel|geeksphone|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i],[VENDOR,[MODEL,/_/g," "],[TYPE,MOBILE]],[/(nexus\s9)/i],[MODEL,[VENDOR,"HTC"],[TYPE,TABLET]],[/d\/huawei([\w\s-]+)[;\)]/i,/(nexus\s6p)/i],[MODEL,[VENDOR,"Huawei"],[TYPE,MOBILE]],[/(microsoft);\s(lumia[\s\w]+)/i],[VENDOR,MODEL,[TYPE,MOBILE]],[/[\s\(;](xbox(?:\sone)?)[\s\);]/i],[MODEL,[VENDOR,"Microsoft"],[TYPE,CONSOLE]],[/(kin\.[onetw]{3})/i],[[MODEL,/\./g," "],[VENDOR,"Microsoft"],[TYPE,MOBILE]],[/\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i,/mot[\s-]?(\w+)*/i,/(XT\d{3,4}) build\//i,/(nexus\s6)/i],[MODEL,[VENDOR,"Motorola"],[TYPE,MOBILE]],[/android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i],[MODEL,[VENDOR,"Motorola"],[TYPE,TABLET]],[/hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i],[[VENDOR,util.trim],[MODEL,util.trim],[TYPE,SMARTTV]],[/hbbtv.+maple;(\d+)/i],[[MODEL,/^/,"SmartTV"],[VENDOR,"Samsung"],[TYPE,SMARTTV]],[/\(dtv[\);].+(aquos)/i],[MODEL,[VENDOR,"Sharp"],[TYPE,SMARTTV]],[/android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i,/((SM-T\w+))/i],[[VENDOR,"Samsung"],MODEL,[TYPE,TABLET]],[/smart-tv.+(samsung)/i],[VENDOR,[TYPE,SMARTTV],MODEL],[/((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i,/(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i,/sec-((sgh\w+))/i],[[VENDOR,"Samsung"],MODEL,[TYPE,MOBILE]],[/sie-(\w+)*/i],[MODEL,[VENDOR,"Siemens"],[TYPE,MOBILE]],[/(maemo|nokia).*(n900|lumia\s\d+)/i,/(nokia)[\s_-]?([\w-]+)*/i],[[VENDOR,"Nokia"],MODEL,[TYPE,MOBILE]],[/android\s3\.[\s\w;-]{10}(a\d{3})/i],[MODEL,[VENDOR,"Acer"],[TYPE,TABLET]],[/android.+([vl]k\-?\d{3})\s+build/i],[MODEL,[VENDOR,"LG"],[TYPE,TABLET]],[/android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i],[[VENDOR,"LG"],MODEL,[TYPE,TABLET]],[/(lg) netcast\.tv/i],[VENDOR,MODEL,[TYPE,SMARTTV]],[/(nexus\s[45])/i,/lg[e;\s\/-]+(\w+)*/i,/android.+lg(\-?[\d\w]+)\s+build/i],[MODEL,[VENDOR,"LG"],[TYPE,MOBILE]],[/android.+(ideatab[a-z0-9\-\s]+)/i],[MODEL,[VENDOR,"Lenovo"],[TYPE,TABLET]],[/linux;.+((jolla));/i],[VENDOR,MODEL,[TYPE,MOBILE]],[/((pebble))app\/[\d\.]+\s/i],[VENDOR,MODEL,[TYPE,WEARABLE]],[/android.+;\s(oppo)\s?([\w\s]+)\sbuild/i],[VENDOR,MODEL,[TYPE,MOBILE]],[/crkey/i],[[MODEL,"Chromecast"],[VENDOR,"Google"]],[/android.+;\s(glass)\s\d/i],[MODEL,[VENDOR,"Google"],[TYPE,WEARABLE]],[/android.+;\s(pixel c)\s/i],[MODEL,[VENDOR,"Google"],[TYPE,TABLET]],[/android.+;\s(pixel xl|pixel)\s/i],[MODEL,[VENDOR,"Google"],[TYPE,MOBILE]],[/android.+(\w+)\s+build\/hm\1/i,/android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i,/android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d\w)?)\s+build/i,/android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[MODEL,/_/g," "],[VENDOR,"Xiaomi"],[TYPE,MOBILE]],[/android.+(mi[\s\-_]*(?:pad)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[MODEL,/_/g," "],[VENDOR,"Xiaomi"],[TYPE,TABLET]],[/android.+;\s(m[1-5]\snote)\sbuild/i],[MODEL,[VENDOR,"Meizu"],[TYPE,TABLET]],[/android.+a000(1)\s+build/i],[MODEL,[VENDOR,"OnePlus"],[TYPE,MOBILE]],[/android.+[;\/]\s*(RCT[\d\w]+)\s+build/i],[MODEL,[VENDOR,"RCA"],[TYPE,TABLET]],[/android.+[;\/]\s*(Venue[\d\s]*)\s+build/i],[MODEL,[VENDOR,"Dell"],[TYPE,TABLET]],[/android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i],[MODEL,[VENDOR,"Verizon"],[TYPE,TABLET]],[/android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i],[[VENDOR,"Barnes & Noble"],MODEL,[TYPE,TABLET]],[/android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i],[MODEL,[VENDOR,"NuVision"],[TYPE,TABLET]],[/android.+[;\/]\s*(zte)?.+(k\d{2})\s+build/i],[[VENDOR,"ZTE"],MODEL,[TYPE,TABLET]],[/android.+[;\/]\s*(gen\d{3})\s+build.*49h/i],[MODEL,[VENDOR,"Swiss"],[TYPE,MOBILE]],[/android.+[;\/]\s*(zur\d{3})\s+build/i],[MODEL,[VENDOR,"Swiss"],[TYPE,TABLET]],[/android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i],[MODEL,[VENDOR,"Zeki"],[TYPE,TABLET]],[/(android).+[;\/]\s+([YR]\d{2}x?.*)\s+build/i,/android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(.+)\s+build/i],[[VENDOR,"Dragon Touch"],MODEL,[TYPE,TABLET]],[/android.+[;\/]\s*(NS-?.+)\s+build/i],[MODEL,[VENDOR,"Insignia"],[TYPE,TABLET]],[/android.+[;\/]\s*((NX|Next)-?.+)\s+build/i],[MODEL,[VENDOR,"NextBook"],[TYPE,TABLET]],[/android.+[;\/]\s*(Xtreme\_?)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i],[[VENDOR,"Voice"],MODEL,[TYPE,MOBILE]],[/android.+[;\/]\s*(LVTEL\-?)?(V1[12])\s+build/i],[[VENDOR,"LvTel"],MODEL,[TYPE,MOBILE]],[/android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i],[MODEL,[VENDOR,"Envizen"],[TYPE,TABLET]],[/android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(.*\b)\s+build/i],[VENDOR,MODEL,[TYPE,TABLET]],[/android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i],[MODEL,[VENDOR,"MachSpeed"],[TYPE,TABLET]],[/android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i],[VENDOR,MODEL,[TYPE,TABLET]],[/android.+[;\/]\s*TU_(1491)\s+build/i],[MODEL,[VENDOR,"Rotor"],[TYPE,TABLET]],[/android.+(KS(.+))\s+build/i],[MODEL,[VENDOR,"Amazon"],[TYPE,TABLET]],[/android.+(Gigaset)[\s\-]+(Q.+)\s+build/i],[VENDOR,MODEL,[TYPE,TABLET]],[/\s(tablet|tab)[;\/]/i,/\s(mobile)(?:[;\/]|\ssafari)/i],[[TYPE,util.lowerize],VENDOR,MODEL],[/(android.+)[;\/].+build/i],[MODEL,[VENDOR,"Generic"]]],engine:[[/windows.+\sedge\/([\w\.]+)/i],[VERSION,[NAME,"EdgeHTML"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i,/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,/(icab)[\/\s]([23]\.[\d\.]+)/i],[NAME,VERSION],[/rv\:([\w\.]+).*(gecko)/i],[VERSION,NAME]],os:[[/microsoft\s(windows)\s(vista|xp)/i],[NAME,VERSION],[/(windows)\snt\s6\.2;\s(arm)/i,/(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s]+\w)*/i,/(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i],[NAME,[VERSION,mapper.str,maps.os.windows.version]],[/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i],[[NAME,"Windows"],[VERSION,mapper.str,maps.os.windows.version]],[/\((bb)(10);/i],[[NAME,"BlackBerry"],VERSION],[/(blackberry)\w*\/?([\w\.]+)*/i,/(tizen)[\/\s]([\w\.]+)/i,/(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,/linux;.+(sailfish);/i],[NAME,VERSION],[/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i],[[NAME,"Symbian"],VERSION],[/\((series40);/i],[NAME],[/mozilla.+\(mobile;.+gecko.+firefox/i],[[NAME,"Firefox OS"],VERSION],[/(nintendo|playstation)\s([wids34portablevu]+)/i,/(mint)[\/\s\(]?(\w+)*/i,/(mageia|vectorlinux)[;\s]/i,/(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]+)*/i,/(hurd|linux)\s?([\w\.]+)*/i,/(gnu)\s?([\w\.]+)*/i],[NAME,VERSION],[/(cros)\s[\w]+\s([\w\.]+\w)/i],[[NAME,"Chromium OS"],VERSION],[/(sunos)\s?([\w\.]+\d)*/i],[[NAME,"Solaris"],VERSION],[/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i],[NAME,VERSION],[/(haiku)\s(\w+)/i],[NAME,VERSION],[/cfnetwork\/.+darwin/i,/ip[honead]+(?:.*os\s([\w]+)\slike\smac|;\sopera)/i],[[VERSION,/_/g,"."],[NAME,"iOS"]],[/(mac\sos\sx)\s?([\w\s\.]+\w)*/i,/(macintosh|mac(?=_powerpc)\s)/i],[[NAME,"Mac OS"],[VERSION,/_/g,"."]],[/((?:open)?solaris)[\/\s-]?([\w\.]+)*/i,/(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i,/(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,/(unix)\s?([\w\.]+)*/i],[NAME,VERSION]]};var UAParser=function(uastring,extensions){if(typeof uastring==="object"){extensions=uastring;uastring=undefined}if(!(this instanceof UAParser)){return new UAParser(uastring,extensions).getResult()}var ua=uastring||(window&&window.navigator&&window.navigator.userAgent?window.navigator.userAgent:EMPTY);var rgxmap=extensions?util.extend(regexes,extensions):regexes;this.getBrowser=function(){var browser={name:undefined,version:undefined};mapper.rgx.call(browser,ua,rgxmap.browser);browser.major=util.major(browser.version);return browser};this.getCPU=function(){var cpu={architecture:undefined};mapper.rgx.call(cpu,ua,rgxmap.cpu);return cpu};this.getDevice=function(){var device={vendor:undefined,model:undefined,type:undefined};mapper.rgx.call(device,ua,rgxmap.device);return device};this.getEngine=function(){var engine={name:undefined,version:undefined};mapper.rgx.call(engine,ua,rgxmap.engine);return engine};this.getOS=function(){var os={name:undefined,version:undefined};mapper.rgx.call(os,ua,rgxmap.os);return os};this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}};this.getUA=function(){return ua};this.setUA=function(uastring){ua=uastring;return this};return this};UAParser.VERSION=LIBVERSION;UAParser.BROWSER={NAME:NAME,MAJOR:MAJOR,VERSION:VERSION};UAParser.CPU={ARCHITECTURE:ARCHITECTURE};UAParser.DEVICE={MODEL:MODEL,VENDOR:VENDOR,TYPE:TYPE,CONSOLE:CONSOLE,MOBILE:MOBILE,SMARTTV:SMARTTV,TABLET:TABLET,WEARABLE:WEARABLE,EMBEDDED:EMBEDDED};UAParser.ENGINE={NAME:NAME,VERSION:VERSION};UAParser.OS={NAME:NAME,VERSION:VERSION};if(typeof exports!==UNDEF_TYPE){if(typeof module!==UNDEF_TYPE&&module.exports){exports=module.exports=UAParser}exports.UAParser=UAParser}else{if(typeof define===FUNC_TYPE&&define.amd){define(function(){return UAParser})}else if(window){window.UAParser=UAParser}}var $=window&&(window.jQuery||window.Zepto);if(typeof $!==UNDEF_TYPE){var parser=new UAParser;$.ua=parser.getResult();$.ua.get=function(){return parser.getUA()};$.ua.set=function(uastring){parser.setUA(uastring);var result=parser.getResult();for(var prop in result){$.ua[prop]=result[prop]}}}})(typeof window==="object"?window:this);
const path = require('path') const StyleLintPlugin = require('stylelint-webpack-plugin') module.exports = { entry: { app: './web/public/app/src/index.js' }, externals: { }, optimization: { splitChunks: { chunks: 'all' } }, module: { rules: [ { test: /\.(css)$/, use: [ { // Adds CSS to the DOM by injecting a `<style>` tag loader: 'style-loader' }, { // Interprets `@import` and `url()` like `import/require()` and will resolve them loader: 'css-loader' } ] }, { test: /\.(scss)$/, use: [ { // Adds CSS to the DOM by injecting a `<style>` tag loader: 'style-loader' }, { // Interprets `@import` and `url()` like `import/require()` and will resolve them loader: 'css-loader' }, { // Loader for webpack to process CSS with PostCSS loader: 'postcss-loader', options: { plugins: function () { return [ require('autoprefixer') ] } } }, { // Loads a SASS/SCSS file and compiles it to CSS loader: 'sass-loader' } ] } ] }, plugins: [ new StyleLintPlugin() ], output: { filename: 'js/[name].bundle.js', path: path.resolve(__dirname, '../../dist'), publicPath: '../dist/' } }
//generated code don't edit manually export class ValidationError { constructor(enErrorText, deErrorText) { this.enErrorText = enErrorText; this.deErrorText = deErrorText; } getDisplayText(locale) { if (locale === "de") { return this.deErrorText; } else { return this.enErrorText; } } }
import torch from torch.nn import functional as F # 1.初始化 input = torch.tensor( [ [1,1,1,1,1], [1,1,1,1,1], [0,0,0,1,1], [1,1,1,1,1] ]).unsqueeze(0).float() # print(input.size())#torch.Size([1, 4, 5]) # print(input) #2. avg_pool1d # m1 = F.avg_pool1d(input,kernel_size=2) # print(m1)#tensor([[[1.0000, 1.0000], # # [1.0000, 1.0000], # # [0.0000, 0.5000], # # [1.0000, 1.0000]]]) #3. avg_pool2d # m = F.avg_pool2d(input,kernel_size=2)#这里是在原矩阵中找出2*2的区域求平均,不够的舍弃,stride=(2,2) # print(m)#tensor([[[1.0000, 1.0000], # # [0.5000, 0.7500]]]) # m3= F.avg_pool2d(input,kernel_size=2,stride=1)#这里是在原矩阵中找出2*2的区域求平均,不够的舍弃,stride=(1,1),[1,1,4,5]-->[1,1,3,4] # print(m3)#tensor([[[1.0000, 1.0000, 1.0000, 1.0000], # # [0.5000, 0.5000, 0.7500, 1.0000], # # [0.5000, 0.5000, 0.7500, 1.0000]]]) c = torch.randn(256,384,4,4) print(c.size()) out = F.avg_pool2d(c, 4) print(out.size()) print("out.size(0)",out.size(0)) out = out.view(out.size(1),-1) out.size()
/*! * ui-select * http://github.com/angular-ui/ui-select * Version: 0.9.5 - 2014-12-12T16:07:20.856Z * License: MIT */ (function () { "use strict"; var KEY = { TAB: 9, ENTER: 13, ESC: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, SHIFT: 16, CTRL: 17, ALT: 18, PAGE_UP: 33, PAGE_DOWN: 34, HOME: 36, END: 35, BACKSPACE: 8, DELETE: 46, COMMAND: 91, MAP: { 91: "COMMAND", 8: "BACKSPACE", 9: "TAB", 13: "ENTER", 16: "SHIFT", 17: "CTRL", 18: "ALT", 19: "PAUSEBREAK", 20: "CAPSLOCK", 27: "ESC", 32: "SPACE", 33: "PAGE_UP", 34: "PAGE_DOWN", 35: "END", 36: "HOME", 37: "LEFT", 38: "UP", 39: "RIGHT", 40: "DOWN", 43: "+", 44: "PRINTSCREEN", 45: "INSERT", 46: "DELETE", 48: "0", 49: "1", 50: "2", 51: "3", 52: "4", 53: "5", 54: "6", 55: "7", 56: "8", 57: "9", 59: ";", 61: "=", 65: "A", 66: "B", 67: "C", 68: "D", 69: "E", 70: "F", 71: "G", 72: "H", 73: "I", 74: "J", 75: "K", 76: "L", 77: "M", 78: "N", 79: "O", 80: "P", 81: "Q", 82: "R", 83: "S", 84: "T", 85: "U", 86: "V", 87: "W", 88: "X", 89: "Y", 90: "Z", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/", 112: "F1", 113: "F2", 114: "F3", 115: "F4", 116: "F5", 117: "F6", 118: "F7", 119: "F8", 120: "F9", 121: "F10", 122: "F11", 123: "F12", 144: "NUMLOCK", 145: "SCROLLLOCK", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'" }, isControl: function (e) { var k = e.which; switch (k) { case KEY.COMMAND: case KEY.SHIFT: case KEY.CTRL: case KEY.ALT: return true; } if (e.metaKey) return true; return false; }, isFunctionKey: function (k) { k = k.which ? k.which : k; return k >= 112 && k <= 123; }, isVerticalMovement: function (k) { return ~[KEY.UP, KEY.DOWN].indexOf(k); }, isHorizontalMovement: function (k) { return ~[KEY.LEFT, KEY.RIGHT, KEY.BACKSPACE, KEY.DELETE].indexOf(k); } }; /** * Add querySelectorAll() to jqLite. * * jqLite find() is limited to lookups by tag name. * TODO This will change with future versions of AngularJS, to be removed when this happens * * See jqLite.find - why not use querySelectorAll? https://github.com/angular/angular.js/issues/3586 * See feat(jqLite): use querySelectorAll instead of getElementsByTagName in jqLite.find https://github.com/angular/angular.js/pull/3598 */ if (angular.element.prototype.querySelectorAll === undefined) { angular.element.prototype.querySelectorAll = function (selector) { return angular.element(this[0].querySelectorAll(selector)); }; } /** * Add closest() to jqLite. */ if (angular.element.prototype.closest === undefined) { angular.element.prototype.closest = function (selector) { var elem = this[0]; var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector; while (elem) { if (matchesSelector.bind(elem)(selector)) { return elem; } else { elem = elem.parentElement; } } return false; }; } angular.module('ui.select', []) .constant('uiSelectConfig', { theme: 'bootstrap', searchEnabled: true, placeholder: '', // Empty by default, like HTML tag <select> refreshDelay: 1000, // In milliseconds closeOnSelect: true }) // See Rename minErr and make it accessible from outside https://github.com/angular/angular.js/issues/6913 .service('uiSelectMinErr', function () { var minErr = angular.$$minErr('ui.select'); return function () { var error = minErr.apply(this, arguments); var message = error.message.replace(new RegExp('\nhttp://errors.angularjs.org/.*'), ''); return new Error(message); }; }) /** * Parses "repeat" attribute. * * Taken from AngularJS ngRepeat source code * See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L211 * * Original discussion about parsing "repeat" attribute instead of fully relying on ng-repeat: * https://github.com/angular-ui/ui-select/commit/5dd63ad#commitcomment-5504697 */ .service('RepeatParser', ['uiSelectMinErr', '$parse', function (uiSelectMinErr, $parse) { var self = this; /** * Example: * expression = "address in addresses | filter: {street: $select.search} track by $index" * itemName = "address", * source = "addresses | filter: {street: $select.search}", * trackByExp = "$index", */ self.parse = function (expression) { var match = expression.match(/^\s*(?:([\s\S]+?)\s+as\s+)?([\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); if (!match) { throw uiSelectMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", expression); } return { itemName: match[2], // (lhs) Left-hand side, source: $parse(match[3]), trackByExp: match[4], modelMapper: $parse(match[1] || match[2]) }; }; self.getGroupNgRepeatExpression = function () { return '$group in $select.groups'; }; self.getNgRepeatExpression = function (itemName, source, trackByExp, grouped) { var expression = itemName + ' in ' + (grouped ? '$group.items' : source); if (trackByExp) { expression += ' track by ' + trackByExp; } return expression; }; }]) /** * Contains ui-select "intelligence". * * The goal is to limit dependency on the DOM whenever possible and * put as much logic in the controller (instead of the link functions) as possible so it can be easily tested. */ .controller('uiSelectCtrl', ['$scope', '$element', '$timeout', '$filter', 'RepeatParser', 'uiSelectMinErr', 'uiSelectConfig', function ($scope, $element, $timeout, $filter, RepeatParser, uiSelectMinErr, uiSelectConfig) { var ctrl = this; var EMPTY_SEARCH = ''; ctrl.placeholder = undefined; ctrl.search = EMPTY_SEARCH; ctrl.activeIndex = 0; ctrl.activeMatchIndex = -1; ctrl.items = []; ctrl.selected = undefined; ctrl.open = false; ctrl.focus = false; ctrl.focusser = undefined; //Reference to input element used to handle focus events ctrl.disabled = undefined; // Initialized inside uiSelect directive link function ctrl.searchEnabled = undefined; // Initialized inside uiSelect directive link function ctrl.resetSearchInput = undefined; // Initialized inside uiSelect directive link function ctrl.refreshDelay = undefined; // Initialized inside uiSelectChoices directive link function ctrl.multiple = false; // Initialized inside uiSelect directive link function ctrl.disableChoiceExpression = undefined; // Initialized inside uiSelect directive link function ctrl.tagging = {isActivated: false, fct: undefined}; ctrl.taggingTokens = {isActivated: false, tokens: undefined}; ctrl.lockChoiceExpression = undefined; // Initialized inside uiSelect directive link function ctrl.closeOnSelect = true; // Initialized inside uiSelect directive link function ctrl.clickTriggeredSelect = false; ctrl.$filter = $filter; ctrl.isEmpty = function () { return angular.isUndefined(ctrl.selected) || ctrl.selected === null || ctrl.selected === ''; }; var _searchInput = $element.querySelectorAll('input.ui-select-search'); if (_searchInput.length !== 1) { throw uiSelectMinErr('searchInput', "Expected 1 input.ui-select-search but got '{0}'.", _searchInput.length); } // Most of the time the user does not want to empty the search input when in typeahead mode function _resetSearchInput() { if (ctrl.resetSearchInput || (ctrl.resetSearchInput === undefined && uiSelectConfig.resetSearchInput)) { ctrl.search = EMPTY_SEARCH; //reset activeIndex if (ctrl.selected && ctrl.items.length && !ctrl.multiple) { ctrl.activeIndex = ctrl.items.indexOf(ctrl.selected); } } } // When the user clicks on ui-select, displays the dropdown list ctrl.activate = function (initSearchValue, avoidReset) { if (!ctrl.disabled && !ctrl.open) { if (!avoidReset) _resetSearchInput(); ctrl.focusser.prop('disabled', true); //Will reactivate it on .close() ctrl.open = true; ctrl.activeMatchIndex = -1; ctrl.activeIndex = ctrl.activeIndex >= ctrl.items.length ? 0 : ctrl.activeIndex; // ensure that the index is set to zero for tagging variants // that where first option is auto-selected if (ctrl.activeIndex === -1 && ctrl.taggingLabel !== false) { ctrl.activeIndex = 0; } // Give it time to appear before focus $timeout(function () { ctrl.search = initSearchValue || ctrl.search; _searchInput[0].focus(); }); } }; ctrl.findGroupByName = function (name) { return ctrl.groups && ctrl.groups.filter(function (group) { return group.name === name; })[0]; }; ctrl.parseRepeatAttr = function (repeatAttr, groupByExp) { function updateGroups(items) { ctrl.groups = []; angular.forEach(items, function (item) { var groupFn = $scope.$eval(groupByExp); var groupName = angular.isFunction(groupFn) ? groupFn(item) : item[groupFn]; var group = ctrl.findGroupByName(groupName); if (group) { group.items.push(item); } else { ctrl.groups.push({name: groupName, items: [item]}); } }); ctrl.items = []; ctrl.groups.forEach(function (group) { ctrl.items = ctrl.items.concat(group.items); }); } function setPlainItems(items) { ctrl.items = items; } var setItemsFn = groupByExp ? updateGroups : setPlainItems; ctrl.parserResult = RepeatParser.parse(repeatAttr); ctrl.isGrouped = !!groupByExp; ctrl.itemProperty = ctrl.parserResult.itemName; // See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L259 $scope.$watchCollection(ctrl.parserResult.source, function (items) { if (items === undefined || items === null) { // If the user specifies undefined or null => reset the collection // Special case: items can be undefined if the user did not initialized the collection on the scope // i.e $scope.addresses = [] is missing ctrl.items = []; } else { if (!angular.isArray(items)) { throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items); } else { if (ctrl.multiple) { //Remove already selected items (ex: while searching) var filteredItems = items.filter(function (i) { return ctrl.selected.indexOf(i) < 0; }); setItemsFn(filteredItems); } else { setItemsFn(items); } ctrl.ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters } } }); if (ctrl.multiple) { //Remove already selected items $scope.$watchCollection('$select.selected', function (selectedItems) { var data = ctrl.parserResult.source($scope); if (!selectedItems.length) { setItemsFn(data); } else { if (data !== undefined) { var filteredItems = data.filter(function (i) { return selectedItems.indexOf(i) < 0; }); setItemsFn(filteredItems); } } ctrl.sizeSearchInput(); }); } }; var _refreshDelayPromise; /** * Typeahead mode: lets the user refresh the collection using his own function. * * See Expose $select.search for external / remote filtering https://github.com/angular-ui/ui-select/pull/31 */ ctrl.refresh = function (refreshAttr) { if (refreshAttr !== undefined) { // Debounce // See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L155 // FYI AngularStrap typeahead does not have debouncing: https://github.com/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177 if (_refreshDelayPromise) { $timeout.cancel(_refreshDelayPromise); } _refreshDelayPromise = $timeout(function () { $scope.$eval(refreshAttr); }, ctrl.refreshDelay); } }; ctrl.setActiveItem = function (item) { ctrl.activeIndex = ctrl.items.indexOf(item); }; ctrl.isActive = function (itemScope) { if (!ctrl.open) { return false; } var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]); var isActive = itemIndex === ctrl.activeIndex; if (!isActive || ( itemIndex < 0 && ctrl.taggingLabel !== false ) || ( itemIndex < 0 && ctrl.taggingLabel === false)) { return false; } if (isActive && !angular.isUndefined(ctrl.onHighlightCallback)) { itemScope.$eval(ctrl.onHighlightCallback); } return isActive; }; ctrl.isDisabled = function (itemScope) { if (!ctrl.open) return; var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]); var isDisabled = false; var item; if (itemIndex >= 0 && !angular.isUndefined(ctrl.disableChoiceExpression)) { item = ctrl.items[itemIndex]; isDisabled = !!(itemScope.$eval(ctrl.disableChoiceExpression)); // force the boolean value item._uiSelectChoiceDisabled = isDisabled; // store this for later reference } return isDisabled; }; // When the user selects an item with ENTER or clicks the dropdown ctrl.select = function (item, skipFocusser, $event) { if (item === undefined || !item._uiSelectChoiceDisabled) { if (!ctrl.items && !ctrl.search) return; if (!item || !item._uiSelectChoiceDisabled) { if (ctrl.tagging.isActivated) { // if taggingLabel is disabled, we pull from ctrl.search val if (ctrl.taggingLabel === false) { if (ctrl.activeIndex < 0) { item = ctrl.tagging.fct !== undefined ? ctrl.tagging.fct(ctrl.search) : ctrl.search; if (angular.equals(ctrl.items[0], item)) { return; } } else { // keyboard nav happened first, user selected from dropdown item = ctrl.items[ctrl.activeIndex]; } } else { // tagging always operates at index zero, taggingLabel === false pushes // the ctrl.search value without having it injected if (ctrl.activeIndex === 0) { // ctrl.tagging pushes items to ctrl.items, so we only have empty val // for `item` if it is a detected duplicate if (item === undefined) return; // create new item on the fly if we don't already have one; // use tagging function if we have one if (ctrl.tagging.fct !== undefined && typeof item === 'string') { item = ctrl.tagging.fct(ctrl.search); // if item type is 'string', apply the tagging label } else if (typeof item === 'string') { item = item.replace(ctrl.taggingLabel, ''); } } } // search ctrl.selected for dupes potentially caused by tagging and return early if found if (ctrl.selected && ctrl.selected.filter(function (selection) { return angular.equals(selection, item); }).length > 0) { ctrl.close(skipFocusser); return; } } var locals = {}; locals[ctrl.parserResult.itemName] = item; if (ctrl.multiple) { ctrl.selected.push(item); ctrl.sizeSearchInput(); } else { ctrl.selected = item; } ctrl.onSelectCallback($scope, { $item: item, $model: ctrl.parserResult.modelMapper($scope, locals) }); if (!ctrl.multiple || ctrl.closeOnSelect) { ctrl.close(skipFocusser); } if ($event && $event.type === 'click') { ctrl.clickTriggeredSelect = true; } } } }; // Closes the dropdown ctrl.close = function (skipFocusser) { if (!ctrl.open) return; _resetSearchInput(); ctrl.open = false; if (!ctrl.multiple) { $timeout(function () { ctrl.focusser.prop('disabled', false); if (!skipFocusser) ctrl.focusser[0].focus(); }, 0, false); } }; // Toggle dropdown ctrl.toggle = function (e) { if (ctrl.open) { ctrl.close(); e.preventDefault(); e.stopPropagation(); } else { ctrl.activate(); } }; ctrl.isLocked = function (itemScope, itemIndex) { var isLocked, item = ctrl.selected[itemIndex]; if (item && !angular.isUndefined(ctrl.lockChoiceExpression)) { isLocked = !!(itemScope.$eval(ctrl.lockChoiceExpression)); // force the boolean value item._uiSelectChoiceLocked = isLocked; // store this for later reference } return isLocked; }; // Remove item from multiple select ctrl.removeChoice = function (index) { var removedChoice = ctrl.selected[index]; // if the choice is locked, can't remove it if (removedChoice._uiSelectChoiceLocked) return; var locals = {}; locals[ctrl.parserResult.itemName] = removedChoice; ctrl.selected.splice(index, 1); ctrl.activeMatchIndex = -1; ctrl.sizeSearchInput(); ctrl.onRemoveCallback($scope, { $item: removedChoice, $model: ctrl.parserResult.modelMapper($scope, locals) }); }; ctrl.getPlaceholder = function () { //Refactor single? if (ctrl.multiple && ctrl.selected.length) return; return ctrl.placeholder; }; var containerSizeWatch; ctrl.sizeSearchInput = function () { var input = _searchInput[0], container = _searchInput.parent().parent()[0]; _searchInput.css('width', '10px'); var calculate = function () { var newWidth = container.clientWidth - input.offsetLeft - 10; if (newWidth < 50) newWidth = container.clientWidth; _searchInput.css('width', newWidth + 'px'); }; $timeout(function () { //Give tags time to render correctly if (container.clientWidth === 0 && !containerSizeWatch) { containerSizeWatch = $scope.$watch(function () { return container.clientWidth; }, function (newValue) { if (newValue !== 0) { calculate(); containerSizeWatch(); containerSizeWatch = null; } }); } else if (!containerSizeWatch) { calculate(); } }, 0, false); }; function _handleDropDownSelection(key) { var processed = true; switch (key) { case KEY.DOWN: if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode else if (ctrl.activeIndex < ctrl.items.length - 1) { ctrl.activeIndex++; } break; case KEY.UP: if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode else if (ctrl.activeIndex > 0 || (ctrl.search.length === 0 && ctrl.tagging.isActivated)) { ctrl.activeIndex--; } break; case KEY.TAB: if (!ctrl.multiple || ctrl.open) ctrl.select(ctrl.items[ctrl.activeIndex], true); break; case KEY.ENTER: if (ctrl.open) { ctrl.select(ctrl.items[ctrl.activeIndex]); } else { ctrl.activate(false, true); //In case its the search input in 'multiple' mode } break; case KEY.ESC: ctrl.close(); break; default: processed = false; } return processed; } // Handles selected options in "multiple" mode function _handleMatchSelection(key) { var caretPosition = _getCaretPosition(_searchInput[0]), length = ctrl.selected.length, // none = -1, first = 0, last = length - 1, curr = ctrl.activeMatchIndex, next = ctrl.activeMatchIndex + 1, prev = ctrl.activeMatchIndex - 1, newIndex = curr; if (caretPosition > 0 || (ctrl.search.length && key == KEY.RIGHT)) return false; ctrl.close(); function getNewActiveMatchIndex() { switch (key) { case KEY.LEFT: // Select previous/first item if (~ctrl.activeMatchIndex) return prev; // Select last item else return last; break; case KEY.RIGHT: // Open drop-down if (!~ctrl.activeMatchIndex || curr === last) { ctrl.activate(); return false; } // Select next/last item else return next; break; case KEY.BACKSPACE: // Remove selected item and select previous/first if (~ctrl.activeMatchIndex) { ctrl.removeChoice(curr); return prev; } // Select last item else return last; break; case KEY.DELETE: // Remove selected item and select next item if (~ctrl.activeMatchIndex) { ctrl.removeChoice(ctrl.activeMatchIndex); return curr; } else return false; } } newIndex = getNewActiveMatchIndex(); if (!ctrl.selected.length || newIndex === false) ctrl.activeMatchIndex = -1; else ctrl.activeMatchIndex = Math.min(last, Math.max(first, newIndex)); return true; } // Bind to keyboard shortcuts _searchInput.on('keydown', function (e) { var key = e.which; // if(~[KEY.ESC,KEY.TAB].indexOf(key)){ // //TODO: SEGURO? // ctrl.close(); // } $scope.$apply(function () { var processed = false; var tagged = false; if (ctrl.multiple && KEY.isHorizontalMovement(key)) { processed = _handleMatchSelection(key); } if (!processed && (ctrl.items.length > 0 || ctrl.tagging.isActivated)) { processed = _handleDropDownSelection(key); if (ctrl.taggingTokens.isActivated) { for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) { if (ctrl.taggingTokens.tokens[i] === KEY.MAP[e.keyCode]) { // make sure there is a new value to push via tagging if (ctrl.search.length > 0) { tagged = true; } } } if (tagged) { $timeout(function () { _searchInput.triggerHandler('tagged'); var newItem = ctrl.search.replace(KEY.MAP[e.keyCode], '').trim(); if (ctrl.tagging.fct) { newItem = ctrl.tagging.fct(newItem); } ctrl.select(newItem, true); }); } } } if (processed && key != KEY.TAB) { //TODO Check si el tab selecciona aun correctamente //Crear test e.preventDefault(); e.stopPropagation(); } }); if (KEY.isVerticalMovement(key) && ctrl.items.length > 0) { _ensureHighlightVisible(); } }); _searchInput.on('keyup', function (e) { if (!KEY.isVerticalMovement(e.which)) { $scope.$evalAsync(function () { ctrl.activeIndex = ctrl.taggingLabel === false ? -1 : 0; }); } // Push a "create new" item into array if there is a search string if (ctrl.tagging.isActivated && ctrl.search.length > 0) { // return early with these keys if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || KEY.isVerticalMovement(e.which)) { return; } // always reset the activeIndex to the first item when tagging ctrl.activeIndex = ctrl.taggingLabel === false ? -1 : 0; // taggingLabel === false bypasses all of this if (ctrl.taggingLabel === false) return; var items = angular.copy(ctrl.items); var stashArr = angular.copy(ctrl.items); var newItem; var item; var hasTag = false; var dupeIndex = -1; var tagItems; var tagItem; // case for object tagging via transform `ctrl.tagging.fct` function if (ctrl.tagging.fct !== undefined) { tagItems = ctrl.$filter('filter')(items, {'isTag': true}); if (tagItems.length > 0) { tagItem = tagItems[0]; } // remove the first element, if it has the `isTag` prop we generate a new one with each keyup, shaving the previous if (items.length > 0 && tagItem) { hasTag = true; items = items.slice(1, items.length); stashArr = stashArr.slice(1, stashArr.length); } newItem = ctrl.tagging.fct(ctrl.search); newItem.isTag = true; // verify the the tag doesn't match the value of an existing item if (stashArr.filter(function (origItem) { return angular.equals(origItem, ctrl.tagging.fct(ctrl.search)); }).length > 0) { return; } // handle newItem string and stripping dupes in tagging string context } else { // find any tagging items already in the ctrl.items array and store them tagItems = ctrl.$filter('filter')(items, function (item) { return item.match(ctrl.taggingLabel); }); if (tagItems.length > 0) { tagItem = tagItems[0]; } item = items[0]; // remove existing tag item if found (should only ever be one tag item) if (item !== undefined && items.length > 0 && tagItem) { hasTag = true; items = items.slice(1, items.length); stashArr = stashArr.slice(1, stashArr.length); } newItem = ctrl.search + ' ' + ctrl.taggingLabel; if (_findApproxDupe(ctrl.selected, ctrl.search) > -1) { return; } // verify the the tag doesn't match the value of an existing item from // the searched data set or the items already selected if (_findCaseInsensitiveDupe(stashArr.concat(ctrl.selected))) { // if there is a tag from prev iteration, strip it / queue the change // and return early if (hasTag) { items = stashArr; $scope.$evalAsync(function () { ctrl.activeIndex = 0; ctrl.items = items; }); } return; } if (_findCaseInsensitiveDupe(stashArr)) { // if there is a tag from prev iteration, strip it if (hasTag) { ctrl.items = stashArr.slice(1, stashArr.length); } return; } } if (hasTag) dupeIndex = _findApproxDupe(ctrl.selected, newItem); // dupe found, shave the first item if (dupeIndex > -1) { items = items.slice(dupeIndex + 1, items.length - 1); } else { items = []; items.push(newItem); items = items.concat(stashArr); } $scope.$evalAsync(function () { ctrl.activeIndex = 0; ctrl.items = items; }); } }); _searchInput.on('tagged', function () { $timeout(function () { _resetSearchInput(); }); }); _searchInput.on('blur', function () { $timeout(function () { ctrl.activeMatchIndex = -1; }); }); function _findCaseInsensitiveDupe(arr) { if (arr === undefined || ctrl.search === undefined) { return false; } var hasDupe = arr.filter(function (origItem) { if (ctrl.search.toUpperCase() === undefined) { return false; } return origItem.toUpperCase() === ctrl.search.toUpperCase(); }).length > 0; return hasDupe; } function _findApproxDupe(haystack, needle) { var tempArr = angular.copy(haystack); var dupeIndex = -1; for (var i = 0; i < tempArr.length; i++) { // handle the simple string version of tagging if (ctrl.tagging.fct === undefined) { // search the array for the match if (tempArr[i] + ' ' + ctrl.taggingLabel === needle) { dupeIndex = i; } // handle the object tagging implementation } else { var mockObj = tempArr[i]; mockObj.isTag = true; if (angular.equals(mockObj, needle)) { dupeIndex = i; } } } return dupeIndex; } function _getCaretPosition(el) { if (angular.isNumber(el.selectionStart)) return el.selectionStart; // selectionStart is not supported in IE8 and we don't want hacky workarounds so we compromise else return el.value.length; } // See https://github.com/ivaynberg/select2/blob/3.4.6/select2.js#L1431 function _ensureHighlightVisible() { var container = $element.querySelectorAll('.ui-select-choices-content'); var choices = container.querySelectorAll('.ui-select-choices-row'); if (choices.length < 1) { throw uiSelectMinErr('choices', "Expected multiple .ui-select-choices-row but got '{0}'.", choices.length); } var highlighted = choices[ctrl.activeIndex]; var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop; var height = container[0].offsetHeight; if (posY > height) { container[0].scrollTop += posY - height; } else if (posY < highlighted.clientHeight) { if (ctrl.isGrouped && ctrl.activeIndex === 0) container[0].scrollTop = 0; //To make group header visible when going all the way up else container[0].scrollTop -= highlighted.clientHeight - posY; } } $scope.$on('$destroy', function () { _searchInput.off('keyup keydown tagged blur'); }); }]) .directive('uiSelect', ['$document', 'uiSelectConfig', 'uiSelectMinErr', '$compile', '$parse', function ($document, uiSelectConfig, uiSelectMinErr, $compile, $parse) { return { restrict: 'EA', templateUrl: function (tElement, tAttrs) { var theme = tAttrs.theme || uiSelectConfig.theme; return theme + (angular.isDefined(tAttrs.multiple) ? '/select-multiple.tpl.html' : '/select.tpl.html'); }, replace: true, transclude: true, require: ['uiSelect', 'ngModel'], scope: true, controller: 'uiSelectCtrl', controllerAs: '$select', link: function (scope, element, attrs, ctrls, transcludeFn) { var $select = ctrls[0]; var ngModel = ctrls[1]; var searchInput = element.querySelectorAll('input.ui-select-search'); $select.multiple = angular.isDefined(attrs.multiple) && ( attrs.multiple === '' || attrs.multiple.toLowerCase() === 'multiple' || attrs.multiple.toLowerCase() === 'true' ); $select.closeOnSelect = function () { if (angular.isDefined(attrs.closeOnSelect)) { return $parse(attrs.closeOnSelect)(); } else { return uiSelectConfig.closeOnSelect; } }(); $select.onSelectCallback = $parse(attrs.onSelect); $select.onRemoveCallback = $parse(attrs.onRemove); //From view --> model ngModel.$parsers.unshift(function (inputValue) { var locals = {}, result; if ($select.multiple) { var resultMultiple = []; for (var j = $select.selected.length - 1; j >= 0; j--) { locals = {}; locals[$select.parserResult.itemName] = $select.selected[j]; result = $select.parserResult.modelMapper(scope, locals); resultMultiple.unshift(result); } return resultMultiple; } else { locals = {}; locals[$select.parserResult.itemName] = inputValue; result = $select.parserResult.modelMapper(scope, locals); return result; } }); //From model --> view ngModel.$formatters.unshift(function (inputValue) { var data = $select.parserResult.source(scope, {$select: {search: ''}}), //Overwrite $search locals = {}, result; if (data) { if ($select.multiple) { var resultMultiple = []; var checkFnMultiple = function (list, value) { if (!list || !list.length) return; for (var p = list.length - 1; p >= 0; p--) { locals[$select.parserResult.itemName] = list[p]; result = $select.parserResult.modelMapper(scope, locals); if (result == value) { resultMultiple.unshift(list[p]); return true; } } return false; }; if (!inputValue) return resultMultiple; //If ngModel was undefined for (var k = inputValue.length - 1; k >= 0; k--) { if (!checkFnMultiple($select.selected, inputValue[k])) { checkFnMultiple(data, inputValue[k]); } } return resultMultiple; } else { var checkFnSingle = function (d) { locals[$select.parserResult.itemName] = d; result = $select.parserResult.modelMapper(scope, locals); return result == inputValue; }; //If possible pass same object stored in $select.selected if ($select.selected && checkFnSingle($select.selected)) { return $select.selected; } for (var i = data.length - 1; i >= 0; i--) { if (checkFnSingle(data[i])) return data[i]; } } } return inputValue; }); //Set reference to ngModel from uiSelectCtrl $select.ngModel = ngModel; $select.choiceGrouped = function (group) { return $select.isGrouped && group && group.name; }; //Idea from: https://github.com/ivaynberg/select2/blob/79b5bf6db918d7560bdd959109b7bcfb47edaf43/select2.js#L1954 var focusser = angular.element("<input ng-disabled='$select.disabled' class='ui-select-focusser ui-select-offscreen' type='text' aria-haspopup='true' role='button' />"); if (attrs.tabindex) { //tabindex might be an expression, wait until it contains the actual value before we set the focusser tabindex attrs.$observe('tabindex', function (value) { //If we are using multiple, add tabindex to the search input if ($select.multiple) { searchInput.attr("tabindex", value); } else { focusser.attr("tabindex", value); } //Remove the tabindex on the parent so that it is not focusable element.removeAttr("tabindex"); }); } $compile(focusser)(scope); $select.focusser = focusser; if (!$select.multiple) { element.append(focusser); focusser.bind("focus", function () { scope.$evalAsync(function () { $select.focus = true; }); }); focusser.bind("blur", function () { scope.$evalAsync(function () { $select.focus = false; }); }); focusser.bind("keydown", function (e) { if (e.which === KEY.BACKSPACE) { e.preventDefault(); e.stopPropagation(); $select.select(undefined); scope.$apply(); return; } if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) { return; } if (e.which == KEY.DOWN || e.which == KEY.UP || e.which == KEY.ENTER || e.which == KEY.SPACE) { e.preventDefault(); e.stopPropagation(); $select.activate(); } scope.$digest(); }); focusser.bind("keyup input", function (e) { if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || e.which == KEY.ENTER || e.which === KEY.BACKSPACE) { return; } $select.activate(focusser.val()); //User pressed some regular key, so we pass it to the search input focusser.val(''); scope.$digest(); }); } scope.$watch('searchEnabled', function () { var searchEnabled = scope.$eval(attrs.searchEnabled); $select.searchEnabled = searchEnabled !== undefined ? searchEnabled : uiSelectConfig.searchEnabled; }); attrs.$observe('disabled', function () { // No need to use $eval() (thanks to ng-disabled) since we already get a boolean instead of a string $select.disabled = attrs.disabled !== undefined ? attrs.disabled : false; }); attrs.$observe('resetSearchInput', function () { // $eval() is needed otherwise we get a string instead of a boolean var resetSearchInput = scope.$eval(attrs.resetSearchInput); $select.resetSearchInput = resetSearchInput !== undefined ? resetSearchInput : true; }); attrs.$observe('tagging', function () { if (attrs.tagging !== undefined) { // $eval() is needed otherwise we get a string instead of a boolean var taggingEval = scope.$eval(attrs.tagging); $select.tagging = { isActivated: true, fct: taggingEval !== true ? taggingEval : undefined }; } else { $select.tagging = {isActivated: false, fct: undefined}; } }); attrs.$observe('taggingLabel', function () { if (attrs.tagging !== undefined) { // check eval for FALSE, in this case, we disable the labels // associated with tagging if (attrs.taggingLabel === 'false') { $select.taggingLabel = false; } else { $select.taggingLabel = attrs.taggingLabel !== undefined ? attrs.taggingLabel : '(new)'; } } }); attrs.$observe('taggingTokens', function () { if (attrs.tagging !== undefined) { var tokens = attrs.taggingTokens !== undefined ? attrs.taggingTokens.split('|') : [',', 'ENTER']; $select.taggingTokens = {isActivated: true, tokens: tokens}; } }); if ($select.multiple) { scope.$watchCollection(function () { return ngModel.$modelValue; }, function (newValue, oldValue) { if (oldValue != newValue) ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters }); scope.$watchCollection('$select.selected', function () { ngModel.$setViewValue(Date.now()); //Set timestamp as a unique string to force changes }); focusser.prop('disabled', true); //Focusser isn't needed if multiple } else { scope.$watch('$select.selected', function (newValue) { if (ngModel.$viewValue !== newValue) { ngModel.$setViewValue(newValue); } }); } ngModel.$render = function () { if ($select.multiple) { // Make sure that model value is array if (!angular.isArray(ngModel.$viewValue)) { // Have tolerance for null or undefined values if (angular.isUndefined(ngModel.$viewValue) || ngModel.$viewValue === null) { $select.selected = []; } else { throw uiSelectMinErr('multiarr', "Expected model value to be array but got '{0}'", ngModel.$viewValue); } } } $select.selected = ngModel.$viewValue; }; function onDocumentClick(e) { var contains = false; if (window.jQuery) { // Firefox 3.6 does not support element.contains() // See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains contains = window.jQuery.contains(element[0], e.target); } else { contains = element[0].contains(e.target); } if (!contains && !$select.clickTriggeredSelect) { $select.close(angular.element(e.target).closest('.ui-select-container.open').length > 0); // Skip focusser if the target is another select scope.$digest(); } $select.clickTriggeredSelect = false; } // See Click everywhere but here event http://stackoverflow.com/questions/12931369 $document.on('click', onDocumentClick); scope.$on('$destroy', function () { $document.off('click', onDocumentClick); }); // Move transcluded elements to their correct position in main template transcludeFn(scope, function (clone) { // See Transclude in AngularJS http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html // One day jqLite will be replaced by jQuery and we will be able to write: // var transcludedElement = clone.filter('.my-class') // instead of creating a hackish DOM element: var transcluded = angular.element('<div>').append(clone); var transcludedMatch = transcluded.querySelectorAll('.ui-select-match'); transcludedMatch.removeAttr('ui-select-match'); //To avoid loop in case directive as attr if (transcludedMatch.length !== 1) { throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-match but got '{0}'.", transcludedMatch.length); } element.querySelectorAll('.ui-select-match').replaceWith(transcludedMatch); var transcludedChoices = transcluded.querySelectorAll('.ui-select-choices'); transcludedChoices.removeAttr('ui-select-choices'); //To avoid loop in case directive as attr if (transcludedChoices.length !== 1) { throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-choices but got '{0}'.", transcludedChoices.length); } element.querySelectorAll('.ui-select-choices').replaceWith(transcludedChoices); }); } }; }]) .directive('uiSelectChoices', ['uiSelectConfig', 'RepeatParser', 'uiSelectMinErr', '$compile', function (uiSelectConfig, RepeatParser, uiSelectMinErr, $compile) { return { restrict: 'EA', require: '^uiSelect', replace: true, transclude: true, templateUrl: function (tElement) { // Gets theme attribute from parent (ui-select) var theme = tElement.parent().attr('theme') || uiSelectConfig.theme; return theme + '/choices.tpl.html'; }, compile: function (tElement, tAttrs) { if (!tAttrs.repeat) throw uiSelectMinErr('repeat', "Expected 'repeat' expression."); return function link(scope, element, attrs, $select, transcludeFn) { // var repeat = RepeatParser.parse(attrs.repeat); var groupByExp = attrs.groupBy; $select.parseRepeatAttr(attrs.repeat, groupByExp); //Result ready at $select.parserResult $select.disableChoiceExpression = attrs.uiDisableChoice; $select.onHighlightCallback = attrs.onHighlight; if (groupByExp) { var groups = element.querySelectorAll('.ui-select-choices-group'); if (groups.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-group but got '{0}'.", groups.length); groups.attr('ng-repeat', RepeatParser.getGroupNgRepeatExpression()); } var choices = element.querySelectorAll('.ui-select-choices-row'); if (choices.length !== 1) { throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row but got '{0}'.", choices.length); } choices.attr('ng-repeat', RepeatParser.getNgRepeatExpression($select.parserResult.itemName, '$select.items', $select.parserResult.trackByExp, groupByExp)) .attr('ng-if', '$select.open') //Prevent unnecessary watches when dropdown is closed .attr('ng-mouseenter', '$select.setActiveItem(' + $select.parserResult.itemName + ')') .attr('ng-click', '$select.select(' + $select.parserResult.itemName + ',false,$event)'); var rowsInner = element.querySelectorAll('.ui-select-choices-row-inner'); if (rowsInner.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row-inner but got '{0}'.", rowsInner.length); rowsInner.attr('uis-transclude-append', ''); //Adding uisTranscludeAppend directive to row element after choices element has ngRepeat $compile(element, transcludeFn)(scope); //Passing current transcludeFn to be able to append elements correctly from uisTranscludeAppend scope.$watch('$select.search', function (newValue) { if (newValue && !$select.open && $select.multiple) $select.activate(false, true); $select.activeIndex = $select.tagging.isActivated ? -1 : 0; $select.refresh(attrs.refresh); }); attrs.$observe('refreshDelay', function () { // $eval() is needed otherwise we get a string instead of a number var refreshDelay = scope.$eval(attrs.refreshDelay); $select.refreshDelay = refreshDelay !== undefined ? refreshDelay : uiSelectConfig.refreshDelay; }); }; } }; }]) // Recreates old behavior of ng-transclude. Used internally. .directive('uisTranscludeAppend', function () { return { link: function (scope, element, attrs, ctrl, transclude) { transclude(scope, function (clone) { element.append(clone); }); } }; }) .directive('uiSelectMatch', ['uiSelectConfig', function (uiSelectConfig) { return { restrict: 'EA', require: '^uiSelect', replace: true, transclude: true, templateUrl: function (tElement) { // Gets theme attribute from parent (ui-select) var theme = tElement.parent().attr('theme') || uiSelectConfig.theme; var multi = tElement.parent().attr('multiple'); return theme + (multi ? '/match-multiple.tpl.html' : '/match.tpl.html'); }, link: function (scope, element, attrs, $select) { $select.lockChoiceExpression = attrs.uiLockChoice; attrs.$observe('placeholder', function (placeholder) { $select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder; }); $select.allowClear = (angular.isDefined(attrs.allowClear)) ? (attrs.allowClear === '') ? true : (attrs.allowClear.toLowerCase() === 'true') : false; if ($select.multiple) { $select.sizeSearchInput(); } } }; }]) /** * Highlights text that matches $select.search. * * Taken from AngularUI Bootstrap Typeahead * See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L340 */ .filter('highlight', function () { function escapeRegexp(queryToEscape) { return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } return function (matchItem, query) { return query && matchItem ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<span class="ui-select-highlight">$&</span>') : matchItem; }; }); }()); angular.module("ui.select").run(["$templateCache", function ($templateCache) { $templateCache.put("bootstrap/choices.tpl.html", "<ul class=\"ui-select-choices ui-select-choices-content dropdown-menu\" role=\"menu\" aria-labelledby=\"dLabel\" ng-show=\"$select.items.length > 0\"><li class=\"ui-select-choices-group\"><div class=\"divider\" ng-show=\"$select.isGrouped && $index > 0\"></div><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label dropdown-header\" ng-bind-html=\"$group.name\"></div><div class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\"><a href=\"javascript:void(0)\" class=\"ui-select-choices-row-inner\"></a></div></li></ul>"); $templateCache.put("bootstrap/match-multiple.tpl.html", "<span class=\"ui-select-match\"><span ng-repeat=\"$item in $select.selected\"><span style=\"margin-right: 3px;\" class=\"ui-select-match-item btn btn-default btn-xs\" tabindex=\"-1\" type=\"button\" ng-disabled=\"$select.disabled\" ng-click=\"$select.activeMatchIndex = $index;\" ng-class=\"{\'btn-primary\':$select.activeMatchIndex === $index, \'select-locked\':$select.isLocked(this, $index)}\"><span class=\"close ui-select-match-close\" ng-hide=\"$select.disabled\" ng-click=\"$select.removeChoice($index)\">&nbsp;&times;</span> <span uis-transclude-append=\"\"></span></span></span></span>"); $templateCache.put("bootstrap/match.tpl.html", "<div class=\"btn-group ui-select-match btn-block\" ng-hide=\"$select.open\" ng-disabled=\"$select.disabled\" ng-class=\"{\'btn-default-focus\':$select.focus}\"><button type=\"button\" class=\"btn btn-default\" ng-class=\"{\'col-sm-8 col-md-10\': $select.allowClear && !$select.isEmpty(),\'col-sm-10 col-md-11\': !$select.allowClear || $select.isEmpty()}\" tabindex=\"-1\" ;=\"\" ng-click=\"$select.activate()\"><span ng-show=\"$select.isEmpty()\" class=\"text-muted\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" ng-transclude=\"\"></span></button> <button class=\"btn btn-default col-sm-2 col-md-1\" ng-if=\"$select.allowClear && !$select.isEmpty()\" ng-click=\"$select.select(undefined)\"><span class=\"glyphicon glyphicon-remove ui-select-toggle\"></span></button> <button class=\"btn btn-default col-sm-2 col-md-1\" ng-click=\"$select.activate()\"><span class=\"caret ui-select-toggle\" ng-click=\"$select.toggle($event)\"></span></button></div>"); $templateCache.put("bootstrap/select-multiple.tpl.html", "<div class=\"ui-select-container ui-select-multiple ui-select-bootstrap dropdown form-control\" ng-class=\"{open: $select.open}\"><div><div class=\"ui-select-match\"></div><input type=\"text\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" class=\"ui-select-search input-xs\" placeholder=\"{{$select.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-hide=\"$select.disabled\" ng-click=\"$select.activate()\" ng-model=\"$select.search\"></div><div class=\"ui-select-choices\"></div></div>"); $templateCache.put("bootstrap/select.tpl.html", "<div class=\"ui-select-container ui-select-bootstrap dropdown\" ng-class=\"{open: $select.open}\"><div class=\"ui-select-match\"></div><input type=\"text\" autocomplete=\"off\" tabindex=\"-1\" class=\"form-control ui-select-search\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-show=\"$select.searchEnabled && $select.open\"><div class=\"ui-select-choices\"></div></div>"); $templateCache.put("select2/choices.tpl.html", "<ul class=\"ui-select-choices ui-select-choices-content select2-results\"><li class=\"ui-select-choices-group\" ng-class=\"{\'select2-result-with-children\': $select.choiceGrouped($group) }\"><div ng-show=\"$select.choiceGrouped($group)\" class=\"ui-select-choices-group-label select2-result-label\" ng-bind-html=\"$group.name\"></div><ul ng-class=\"{\'select2-result-sub\': $select.choiceGrouped($group), \'select2-result-single\': !$select.choiceGrouped($group) }\"><li class=\"ui-select-choices-row\" ng-class=\"{\'select2-highlighted\': $select.isActive(this), \'select2-disabled\': $select.isDisabled(this)}\"><div class=\"select2-result-label ui-select-choices-row-inner\"></div></li></ul></li></ul>"); $templateCache.put("select2/match-multiple.tpl.html", "<span class=\"ui-select-match\"><li class=\"ui-select-match-item select2-search-choice\" ng-repeat=\"$item in $select.selected\" ng-class=\"{\'select2-search-choice-focus\':$select.activeMatchIndex === $index, \'select2-locked\':$select.isLocked(this, $index)}\"><span uis-transclude-append=\"\"></span> <a href=\"javascript:;\" class=\"ui-select-match-close select2-search-choice-close\" ng-click=\"$select.removeChoice($index)\" tabindex=\"-1\"></a></li></span>"); $templateCache.put("select2/match.tpl.html", "<a class=\"select2-choice ui-select-match\" ng-class=\"{\'select2-default\': $select.isEmpty()}\" ng-click=\"$select.activate()\"><span ng-show=\"$select.isEmpty()\" class=\"select2-chosen\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"select2-chosen\" ng-transclude=\"\"></span> <abbr ng-if=\"$select.allowClear && !$select.isEmpty()\" class=\"select2-search-choice-close\" ng-click=\"$select.select(undefined)\"></abbr> <span class=\"select2-arrow ui-select-toggle\" ng-click=\"$select.toggle($event)\"><b></b></span></a>"); $templateCache.put("select2/select-multiple.tpl.html", "<div class=\"ui-select-container ui-select-multiple select2 select2-container select2-container-multi\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open,\n \'select2-container-disabled\': $select.disabled}\"><ul class=\"select2-choices\"><span class=\"ui-select-match\"></span><li class=\"select2-search-field\"><input type=\"text\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" class=\"select2-input ui-select-search\" placeholder=\"{{$select.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-hide=\"$select.disabled\" ng-model=\"$select.search\" ng-click=\"$select.activate()\" style=\"width: 34px;\"></li></ul><div class=\"select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open}\"><div class=\"ui-select-choices\"></div></div></div>"); $templateCache.put("select2/select.tpl.html", "<div class=\"ui-select-container select2 select2-container\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open,\n \'select2-container-disabled\': $select.disabled,\n \'select2-container-active\': $select.focus, \n \'select2-allowclear\': $select.allowClear && !$select.isEmpty()}\"><div class=\"ui-select-match\"></div><div class=\"select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open}\"><div class=\"select2-search\" ng-show=\"$select.searchEnabled\"><input type=\"text\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" class=\"ui-select-search select2-input\" ng-model=\"$select.search\"></div><div class=\"ui-select-choices\"></div></div></div>"); $templateCache.put("selectize/choices.tpl.html", "<div ng-show=\"$select.open\" class=\"ui-select-choices selectize-dropdown single\"><div class=\"ui-select-choices-content selectize-dropdown-content\"><div class=\"ui-select-choices-group optgroup\"><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label optgroup-header\" ng-bind-html=\"$group.name\"></div><div class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\"><div class=\"option ui-select-choices-row-inner\" data-selectable=\"\"></div></div></div></div></div>"); $templateCache.put("selectize/match.tpl.html", "<div ng-hide=\"($select.open || $select.isEmpty())\" class=\"ui-select-match\" ng-transclude=\"\"></div>"); $templateCache.put("selectize/select.tpl.html", "<div class=\"ui-select-container selectize-control single\" ng-class=\"{\'open\': $select.open}\"><div class=\"selectize-input\" ng-class=\"{\'focus\': $select.open, \'disabled\': $select.disabled, \'selectize-focus\' : $select.focus}\" ng-click=\"$select.activate()\"><div class=\"ui-select-match\"></div><input type=\"text\" autocomplete=\"off\" tabindex=\"-1\" class=\"ui-select-search ui-select-toggle\" ng-click=\"$select.toggle($event)\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-hide=\"!$select.searchEnabled || ($select.selected && !$select.open)\" ng-disabled=\"$select.disabled\"></div><div class=\"ui-select-choices\"></div></div>"); }]);
import math from random import shuffle import numpy as np import yaml import rospy import dynamic_reconfigure.client from tf.transformations import euler_from_quaternion, quaternion_from_euler from geometry_msgs.msg import PoseStamped import ropod_ros_msgs.msg def send_feedback(action_req, action_server, feedback_status_code=0, sm_state=''): ''' Publishes action feedback, setting the status code to `feedback_status_code` The status codes are defined in ropod_ros_msgs.msg.Status args: action_req: ropod_ros_msgs.msg.Action -- action message action_server: ActionServer -- action server feedback_status_code: uint16 ropod_ros_msgs.msg.Status.status_code -- status code for current action sm_state: string -- state of a state machine ''' feedback = ropod_ros_msgs.msg.TaskProgressDOCK() feedback.action_id = action_req.action_id feedback.action_type = action_req.type feedback.status.domain = ropod_ros_msgs.msg.Status.ROBOT feedback.status.module_code = ropod_ros_msgs.msg.Status.MOBIDIK_COLLECTION feedback.status.status_code = feedback_status_code feedback.status.sm_state = sm_state feedback_msg = ropod_ros_msgs.msg.DockFeedback() feedback_msg.feedback = feedback action_server.publish_feedback(feedback_msg) def get_yaw_from_pose(pose): ''' Returns yaw (in radians) of the input pose args: pose: geometry_msgs.msg.PoseStamped -- input pose ''' orientation_q = pose.pose.orientation orientation_list = [orientation_q.x, orientation_q.y, orientation_q.z, orientation_q.w] _, _, yaw = euler_from_quaternion(orientation_list) return yaw def get_setpoint_in_front_of_pose(pose, distance): ''' Returns a pose offset by `distance` from the input pose args: pose: geometry_msgs.msg.PoseStamped -- input pose distance: float -- distance (in meters) to offset input pose ''' if pose is None: rospy.logerr("[cart_collector] Precondition for get_setpoint_in_front_of_pose not met: Pose not found. Aborting.") return None yaw = get_yaw_from_pose(pose) x_cart_in_world_frame = pose.pose.position.x y_cart_in_world_frame = pose.pose.position.y x = x_cart_in_world_frame + (distance * math.cos(yaw)) y = y_cart_in_world_frame + (distance * math.sin(yaw)) setpoint = PoseStamped() setpoint.header = pose.header setpoint.pose.position.x = x setpoint.pose.position.y = y setpoint.pose.position.z = pose.pose.position.z setpoint.pose.orientation = pose.pose.orientation return setpoint def set_dynamic_navigation_params(param_type): ''' Sets a list of dynamic reconfigure parameters defined by the string `param_type` args: param_type: str -- name of list of parameters specified in the `dynamic_navigation_params` file ''' node_name = '/maneuver_navigation/TebLocalPlannerROS' try: client = dynamic_reconfigure.client.Client(node_name, timeout=1.5) except Exception as e: rospy.logerr("Service {0} does not exist".format(node_name + '/set_parameters')) return False params_file = rospy.get_param('~dynamic_navigation_params', 'ros/config/dynamic_navigation_params.yaml') params = yaml.load(open(params_file)) try: client.update_configuration(params[param_type]) except Exception as e: rospy.logerr("Failed to set dynamic reconfigure params for " + node_name) rospy.logerr(e.message) def get_distance_to_line(p1, p2, tp): ''' Returns the distance of point `tp` from the line defined by `p1` and `p2` args: p1: ropod_ros_msgs.msg.Position -- point 1 of the line p2: ropod_ros_msgs.msg.Position -- point 2 of the line tp: ropod_ros_msgs.msg.Position -- test point whose distance from p1-p2 is required ''' # https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line numerator = np.abs((p2.y - p1.y) * tp.x - (p2.x - p1.x) * tp.y + p2.x*p1.y - p2.y*p1.x) denominator = np.sqrt((p2.y - p1.y)**2 + (p2.x - p1.x)**2) return numerator / denominator def does_point_intersect_segment_on_right(point, segment_p1, segment_p2): ''' Returns True if `point` intersects the line segment defined by `segment_p1` and `segment_p2` on it's right side args: point: ropod_ros_msgs.msg.Position -- test point segment_p1: ropod_ros_msgs.msg.Position -- point 1 of the line segment segment_p2: ropod_ros_msgs.msg.Position -- point 2 of the line segment ''' # find intersection point and check if t.x is to the left # t.x < p1.x + ((p1.x - p1.x)*(t.y - p1.y) / (p2.y - p1.y) return (point.x < segment_p1.x + ((segment_p2.x - segment_p1.x) * (point.y - segment_p1.y) / (segment_p2.y - segment_p1.y))) def is_point_between_points_in_y(point, segment_p1, segment_p2): ''' Returns True if the y-coordinate of `point` is between the y-coordinates of `segment_p1` and `segment_p2` args: point: ropod_ros_msgs.msg.Position -- test point segment_p1: ropod_ros_msgs.msg.Position -- point 1 of the line segment segment_p2: ropod_ros_msgs.msg.Position -- point 2 of the line segment ''' # check if the sign of the difference between the y coordinates of the points is different sign1 = math.copysign(1.0, point.y - segment_p1.y) sign2 = math.copysign(1.0, point.y - segment_p2.y) if (sign1 == sign2): return False return True def is_point_in_polygon(point, polygon): ''' Returns True if `point` is contained within the `polygon` args: point: ropod_ros_msgs.msg.Position -- test point polygon: list of ropod_ros_msgs.msg.Position -- polygon defined as a list of points; the first and last point are identical ''' # Based on algorithm here: # http://www.eecs.umich.edu/courses/eecs380/HANDOUTS/PROJ2/InsidePoly.html # https://stackoverflow.com/questions/8721406/how-to-determine-if-a-point-is-inside-a-2d-convex-polygon # # If a horizontal ray from the test point to the right intersects with # each segment of the polygon an even number of times, it is not in the polygon num_intersections = 0 for idx, p in enumerate(polygon[:-1]): if (is_point_between_points_in_y(point, p, polygon[idx+1]) and does_point_intersect_segment_on_right(point, p, polygon[idx+1])): num_intersections += 1 if num_intersections % 2 == 0: return False return True def is_pose_in_polygon(pose, polygon): ''' Returns True if `pose` is contained within the `polygon` args: pose: geometry_msgs.msg.PoseStamped -- test pose polygon: list of ropod_ros_msgs.msg.Position -- polygon defined as a list of points; the first and last point are identical ''' point = ropod_ros_msgs.msg.Position() point.x = pose.pose.position.x point.y = pose.pose.position.y return is_point_in_polygon(point, polygon) def get_pose_closest_to_normal(input_pose, edge_normal): ''' Returns a pose with the same position as `input_pose` but whose orientation best aligns with the `edge_normal` The best alignment is based on checking the angular difference between the normal and four angles spaced 90 degrees apart including the orientation of `input_pose` args: input_pose: geometry_msgs.msg.PoseStamped -- input pose edge_normal: float -- angle (in radian) of the normal of an edge / line segment ''' pose_yaw = get_yaw_from_pose(input_pose) quadrants = [pose_yaw, pose_yaw + np.pi/2.0, pose_yaw - np.pi/2.0, pose_yaw + np.pi] min_angle = 1000.0 closest_yaw = pose_yaw for quad in quadrants: angle = np.arctan2(np.sin(quad - edge_normal), np.cos(quad - edge_normal)) if np.abs(angle) < min_angle: min_angle = np.abs(angle) closest_yaw = quad closest_yaw = np.arctan2(np.sin(closest_yaw), np.cos(closest_yaw)) output_pose = PoseStamped() output_pose.header = input_pose.header output_pose.pose.position = input_pose.pose.position q = quaternion_from_euler(0.0, 0.0, closest_yaw) output_pose.pose.orientation.x = q[0] output_pose.pose.orientation.y = q[1] output_pose.pose.orientation.z = q[2] output_pose.pose.orientation.w = q[3] return output_pose def get_pose_perpendicular_to_edge(shape, input_pose): ''' Returns a pose with the same position as `input_pose` but whose orientation best aligns with the normal of the edge of `shape` which is closest to `input_pose`. The orientation of the output pose will face the inside of the polygon defined by `shape`. args: shape: ropod_ros_msgs.msg.Shape -- polygon defined by list of points input_pose: geometry_msgs.msg.PoseStamped -- input pose ''' closest_edge_idx = 0 min_dist = 1000.0 input_point = ropod_ros_msgs.msg.Position() input_point.x = input_pose.pose.position.x input_point.y = input_pose.pose.position.y for idx, v in enumerate(shape.vertices[:-1]): # last and first vertex are the same dist = get_distance_to_line(v, shape.vertices[idx+1], input_point) if dist < min_dist: min_dist = dist closest_edge_idx = idx # this is the edge closest to the input_pose v1 = shape.vertices[closest_edge_idx] v2 = shape.vertices[closest_edge_idx + 1] dx = (v2.x - v1.x) dy = (v2.y - v1.y) # normal of edge pointing inwards (assuming anticlockwise order of points) enx = -dy eny = dx # check if normal points inside the shape by testing # if we end up inside the polygon by going along the normal # This check is necessary because the assumption that the polygon # points are given in anticlockwise order is not true # The ordering is dependent on how the OSM map was created; hence # it could be either CW or CCW. If it was CW, we need to flip the normal edge_normal = np.arctan2(eny, enx) test_point = ropod_ros_msgs.msg.Position() test_point.x = (v1.x + v2.x) / 2.0 + 0.01*np.cos(edge_normal) test_point.y = (v1.y + v2.y) / 2.0 + 0.01*np.sin(edge_normal) if (not is_point_in_polygon(test_point, shape.vertices)): # the normal was pointing away from the polygon, so we need to flip it enx = -enx eny = -eny edge_normal = np.arctan2(eny, enx) # Change the direction of input_pose by increments of pi/2 until we find # the one closest to the normal of edge output_pose = get_pose_closest_to_normal(input_pose, edge_normal) return output_pose def get_edge_closest_to_wall(area_shape, sub_area_shape): ''' Returns the edge of the `sub_area_shape` (defined by two points), which is closest to an edge of `area_shape`. Effectively, this finds the edge of the sub area which is closest to a wall args: area_shape: list of ropod_ros_msgs.msg.Position -- area polygon defined by list of points sub_area_shape: list of ropod_ros_msgs.msg.Position -- sub area polygon defined by list of points ''' # find the edge of the sub-area which is closest to one of the # edges of the area. We assume this to be the edge closest to a wall min_distance = 1000.0 wall_edge_idx = 0 for idx1, area_v in enumerate(area_shape.vertices[:-1]): # last and first vertex are the same area_v2 = area_shape.vertices[idx1+1] p1 = ropod_ros_msgs.msg.Position() p1.x = (area_v.x + area_v2.x) / 2.0 p1.y = (area_v.y + area_v2.y) / 2.0 for idx2, sub_area_v in enumerate(sub_area_shape.vertices[:-1]): # last and first vertex are the same sub_area_v2 = sub_area_shape.vertices[idx2+1] p2 = ropod_ros_msgs.msg.Position() p2.x = (sub_area_v.x + sub_area_v2.x) / 2.0 p2.y = (sub_area_v.y + sub_area_v2.y) / 2.0 dist = np.sqrt((p2.y - p1.y)**2 + (p2.x - p1.x)**2) if dist < min_distance: min_distance = dist wall_edge_idx = idx2 return sub_area_shape.vertices[wall_edge_idx], sub_area_shape.vertices[wall_edge_idx + 1] def get_pose_perpendicular_to_wall(area_shape, sub_area_shape, offset_from_edge): ''' Returns a pose whose orientation best aligns with the normal of the edge of the sub area which is closest to an edge of the area, with the position offset from the edge by `offset_from_edge`. The orientation of the output pose will face the inside of the polygon defined by `sub_area_shape`. By finding the edge of the sub area closest to an edge of the area, we are effectively finding the edge closest to a wall. args: area_shape: list of ropod_ros_msgs.msg.Position -- area polygon defined by list of points sub_area_shape: list of ropod_ros_msgs.msg.Position -- sub area polygon defined by list of points offset_from_edge: float -- offset (in meters) of the pose from the selected edge of the sub area shape ''' v1, v2 = get_edge_closest_to_wall(area_shape, sub_area_shape) pose = PoseStamped() pose.pose.position.x = (v1.x + v2.x) / 2.0 pose.pose.position.y = (v1.y + v2.y) / 2.0 # we need the yaw perpendicular to the edge # hence, x and y are swapped when calculating the arctan yaw = np.arctan2((v1.x - v2.x), (v1.y - v2.y)) q = quaternion_from_euler(0.0, 0.0, yaw) pose.pose.orientation.x = q[0] pose.pose.orientation.y = q[1] pose.pose.orientation.z = q[2] pose.pose.orientation.w = q[3] output_pose = get_pose_perpendicular_to_edge(sub_area_shape, pose) yaw = get_yaw_from_pose(output_pose) output_pose.pose.position.x += (offset_from_edge * np.cos(yaw)) output_pose.pose.position.y += (offset_from_edge * np.sin(yaw)) return output_pose def generate_points_in_triangle(triangle, num_samples=100): ''' Returns a list of points which are contained inside the `triangle` args: triangle: list of ropod_ros_msgs.msg.Position -- triangle defined as a list of three points num_samples: number of samples to generate in the triangle ''' ptriangle = [] for p in triangle: ptriangle.append([p.x, p.y]) ptriangle = np.array(ptriangle) origin = ptriangle[0] ptriangle = ptriangle - origin generated_points = [] # Based on the first non-uniform example here: http://mathworld.wolfram.com/TrianglePointPicking.html for idx in range(num_samples): a1 = np.random.random() a2 = np.random.random() p = (ptriangle[1] * a1) + (ptriangle[2] * (1.0 - a1) * a2); p += origin rosp = ropod_ros_msgs.msg.Position() rosp.x = p[0] rosp.y = p[1] generated_points.append(rosp) return generated_points def generate_points_in_polygon(closed_polygon, num_samples=100): ''' Returns a list of points which are contained inside the `closed_polygon` args: closed_polygon: list of ropod_ros_msgs.msg.Position -- polygon defined as a list of points; the first and last point are identical num_samples: number of samples to generate per triangle of the polygon (i.e. for a rectangle total samples = 2xnum_samples) ''' polygon = closed_polygon[:-1] generated_points = [] for idx, p in enumerate(polygon): triangle = [p, polygon[(idx+1) % len(polygon)], polygon[(idx+2) % len(polygon)]] triangle_points = generate_points_in_triangle(triangle, num_samples) generated_points.extend(triangle_points) shuffle(generated_points) return generated_points def filter_points_close_to_polygon(polygon, input_points, distance_threshold): ''' Returns a list of points which are at least `distance_threshold` away from all edges of the `polygon` args: polygon: list of ropod_ros_msgs.msg.Position -- polygon defined as a list of points; the first and last point are identical input_points: list of ropod_ros_msgs.msg.Position distance_threshold: minimum distance (in meter) of filtered points to every edge of the polygon ''' filtered_points = [] for test_point in input_points: threshold_satisfied = True for idx, p in enumerate(polygon[:-1]): p2 = polygon[idx + 1] distance = get_distance_to_line(p, p2, test_point) if (distance < distance_threshold): threshold_satisfied = False break if threshold_satisfied: filtered_points.append(test_point) return filtered_points def filter_points_close_to_objects(objects, input_points, distance_threshold): ''' Returns a list of points which are at least `distance_threshold` away from all `objects` args: objects: list of ropod_ros_msgs.msg.Position -- polygon defined as a list of points; the first and last point are identical input_points: list of ropod_ros_msgs.msg.Position distance_threshold: minimum distance (in meter) of filtered points to every edge of the polygon ''' if (objects is None): return input_points filtered_points = [] for test_point in input_points: threshold_satisfied = True for obj in objects: for idx, p in enumerate(obj.shape.polygon.points): p2 = obj.shape.polygon.points[(idx + 1)%len(obj.shape.polygon.points)] distance = get_distance_to_line(p, p2, test_point) if (distance < distance_threshold): threshold_satisfied = False break if not threshold_satisfied: break if threshold_satisfied: filtered_points.append(test_point) return filtered_points def filter_points_in_polygon(polygon, input_points): ''' Returns a list of points which are not inside `polygon` args: polygon: list of ropod_ros_msgs.msg.Position -- polygon defined as a list of points; the first and last point are identical input_points: list of ropod_ros_msgs.msg.Position distance_threshold: minimum distance (in meter) of filtered points to every edge of the polygon ''' filtered_points = [] for test_point in input_points: if not is_point_in_polygon(test_point, polygon): filtered_points.append(test_point) return filtered_points
from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth import login,logout,get_user_model from django.views.generic import CreateView, UpdateView, DetailView from django.contrib.auth.views import LoginView from .forms import UserCreateForm, CustomDBForm from .models import UsersDB from django.contrib.auth.models import User from django.urls import reverse_lazy,reverse from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. class SignUp(CreateView): form_class = UserCreateForm success_url = reverse_lazy('login') template_name = 'users/signup.html' def post(self,request,*args,**kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() u = User.objects.filter(username=self.request.POST['username'])[0] new_user = UsersDB(user=u) new_user.save() return HttpResponseRedirect(self.success_url) return render(request, self.template_name, {'form': form}) class Login(LoginView): template_name = 'users/login.html' def get_success_url(self): url = self.get_redirect_url() u = User.objects.filter(pk=self.request.user.pk)[0] u = UsersDB.objects.filter(user=u)[0] return url or reverse_lazy('profile',kwargs={'pk':u.pk}) def profile_redirect(request): u = UsersDB.objects.filter(user = request.user)[0] return HttpResponseRedirect(reverse('profile',kwargs={'pk':u.pk})) class UserDetail(DetailView,LoginRequiredMixin): model = UsersDB class UpdateCustomFiles(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'classify/classify_spam_ham.html' form_class = CustomDBForm model = UsersDB def post(self,request,*args,**kwargs): form = self.form_class(request.POST) if form.is_valid(): u = self.model.objects.filter(user = self.request.user)[0] if request.POST['spamurl_user']: u.spamurl_user = request.POST['spamurl_user'] if request.POST['hamspamtweets_user']: u.hamspamtweets_user = request.POST['hamspamtweets_user'] if request.POST['spammywordsusers_user']: u.spammywordsusers_user = request.POST['spammywordsusers_user'] clear_su = request.POST.get('spamurl_user-clear', False) clear_hst = request.POST.get('hamspamtweets_user-clear', False) clear_swu = request.POST.get('spammywordsusers_user-clear', False) if clear_su: # print('works') u.spamurl_user = '' if clear_hst: # print('works2') u.hamspamtweets_user = '' if clear_swu: # print('works3') u.spammywordsusers_user = '' u.save() print(u.spamurl_user,'-',request.POST['spamurl_user']) print(u.hamspamtweets_user) print(u.spammywordsusers_user) return HttpResponseRedirect(reverse_lazy('classify_spam_ham')) return render(request, self.template_name, {'form': form})
const expect = require('expect'); const getMeridiemSuffixOfInteger = require('./getMeridiemSuffixOfInteger.js'); test('getMeridiemSuffixOfInteger is a Function', () => { expect(getMeridiemSuffixOfInteger).toBeInstanceOf(Function); });
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; // 高德地图 import "./plugin/aMap" Vue.config.productionTip = false; new Vue({ router, store, render: h => h(App) }).$mount("#app");
/*global angular*/ (function () { angular .module('simplAdmin.orders') .controller('OrderListCtrl', OrderListCtrl); /* @ngInject */ function OrderListCtrl(orderService, translateService) { var vm = this; vm.translate = translateService; vm.tableStateRef = {}; vm.orders = []; orderService.getOrderStatus().then(function (result) { vm.orderStatus = result.data; }); vm.getOrders = function getOrders(tableState) { vm.isLoading = true; vm.tableStateRef = tableState; orderService.getOrdersForGrid(tableState).then(function (result) { vm.orders = result.data.items; tableState.pagination.numberOfPages = result.data.numberOfPages; tableState.pagination.totalItemCount = result.data.totalRecord; vm.isLoading = false; }); }; } })();
var gulp = require( "gulp" ); var fileImports = require( "gulp-imports" ); var header = require( "gulp-header" ); var beautify = require( "gulp-beautify" ); var hintNot = require( "gulp-hint-not" ); var uglify = require( "gulp-uglify" ); var rename = require( "gulp-rename" ); var plato = require( "gulp-plato" ); var gutil = require( "gulp-util" ); var express = require( "express" ); var path = require( "path" ); var pkg = require( "./package.json" ); var open = require( "open" ); //jshint ignore:line var port = 3080; var jshint = require( "gulp-jshint" ); var jscs = require( "gulp-jscs" ); var gulpChanged = require( "gulp-changed" ); var banner = [ "/**", " * <%= pkg.name %> - <%= pkg.description %>", " * Author: <%= pkg.author %>", " * Version: v<%= pkg.version %>", " * Url: <%= pkg.homepage %>", " * License(s): <% pkg.licenses.forEach(function( license, idx ){ %><%= license.type %><% if(idx !== pkg.licenses.length-1) { %>, <% } %><% }); %>", " */", "" ].join( "\n" ); gulp.task( "combine", [ "combine.postal" ] ); gulp.task( "combine.postal", [ "format" ], function() { return gulp.src( [ "./src/postal.js" ] ) .pipe( header( banner, { pkg: pkg } ) ) .pipe( fileImports() ) .pipe( hintNot() ) .pipe( beautify( { indentSize: 4, preserveNewlines: false } ) ) .pipe( gulp.dest( "./lib/" ) ) .pipe( uglify( { compress: { negate_iife: false //jshint ignore:line } } ) ) .pipe( header( banner, { pkg: pkg } ) ) .pipe( rename( "postal.min.js" ) ) .pipe( gulp.dest( "./lib/" ) ); } ); gulp.task( "combine.postal-lodash", [ "format" ], function() { return gulp.src( [ "./src/postal.lodash.js" ] ) .pipe( header( banner, { pkg: pkg } ) ) .pipe( fileImports() ) .pipe( hintNot() ) .pipe( beautify( { indentSize: 4, preserveNewlines: false } ) ) .pipe( gulp.dest( "./lib/" ) ) .pipe( uglify( { compress: { negate_iife: false //jshint ignore:line } } ) ) .pipe( header( banner, { pkg: pkg } ) ) .pipe( rename( "postal.lodash.min.js" ) ) .pipe( gulp.dest( "./lib/" ) ); } ); gulp.task( "default", [ "combine", "combine.postal-lodash" ] ); var mocha = require( "gulp-spawn-mocha" ); gulp.task( "mocha", function() { return gulp.src( [ "spec/**/*.spec.js" ], { read: false } ) .pipe( mocha( { require: [ "spec/helpers/node-setup.js" ], reporter: "spec", colors: true, inlineDiffs: true, debug: false } ) ) .on( "error", console.warn.bind( console ) ); } ); gulp.task( "mocha-lodash", function() { return gulp.src( [ "spec/**/*.spec.js" ], { read: false } ) .pipe( mocha( { require: [ "spec/helpers/node-lodash-build-setup.js" ], reporter: "spec", colors: true, inlineDiffs: true, debug: false } ) ) .on( "error", console.warn.bind( console ) ); } ); gulp.task( "report", function() { return gulp.src( "./lib/postal.js" ) .pipe( plato( "report" ) ); } ); var createServer = function( port ) { var p = path.resolve( "./" ); var app = express(); app.use( express.static( p ) ); app.listen( port, function() { gutil.log( "Listening on", port ); } ); return { app: app }; }; var servers; gulp.task( "server", [ "combine" ], function() { if ( !servers ) { servers = createServer( port ); } open( "http://localhost:" + port + "/index.html" ); } ); gulp.task( "watch", [ "default", "mocha" ], function() { gulp.watch( "src/**/*", [ "default" ] ); gulp.watch( "{lib,spec}/**/*", [ "mocha" ] ); } ); gulp.task( "jshint", function() { return gulp.src( [ "src/**/*.js", "spec/**/*.js" ] ) .pipe( jshint() ) .pipe( jshint.reporter( "jshint-stylish" ) ) .pipe( jshint.reporter( "fail" ) ); } ); gulp.task( "format", [ "jshint" ], function() { return gulp.src( [ "./src/**/*.js", "!node_modules/**" ] ) .pipe( jscs( { configPath: ".jscsrc", fix: true } ) ) .pipe( gulpChanged( "./src", { hasChanged: gulpChanged.compareSha1Digest } ) ) .pipe( gulp.dest( "./src" ) ); } );
log_level = 'INFO' load_from = None resume_from = None dist_params = dict(backend='nccl') workflow = [('train', 1)] checkpoint_config = dict(interval=10) evaluation = dict(interval=10, metric='mAP', key_indicator='AP') optimizer = dict( type='Adam', lr=5e-4, ) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[170, 200]) total_epochs = 210 log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) channel_cfg = dict( num_output_channels=17, dataset_joints=17, dataset_channel=[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], ], inference_channel=[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]) # model settings model = dict( type='TopDown', pretrained='https://download.openmmlab.com/mmpose/' 'pretrain_models/hrnet_w48-8ef0771d.pth', backbone=dict( type='HRNet', in_channels=3, extra=dict( stage1=dict( num_modules=1, num_branches=1, block='BOTTLENECK', num_blocks=(4, ), num_channels=(64, )), stage2=dict( num_modules=1, num_branches=2, block='BASIC', num_blocks=(4, 4), num_channels=(48, 96)), stage3=dict( num_modules=4, num_branches=3, block='BASIC', num_blocks=(4, 4, 4), num_channels=(48, 96, 192)), stage4=dict( num_modules=3, num_branches=4, block='BASIC', num_blocks=(4, 4, 4, 4), num_channels=(48, 96, 192, 384))), ), keypoint_head=dict( type='TopDownSimpleHead', in_channels=48, out_channels=channel_cfg['num_output_channels'], num_deconv_layers=0, extra=dict(final_conv_kernel=1, ), loss_keypoint=dict(type='JointsMSELoss', use_target_weight=True)), train_cfg=dict(), test_cfg=dict( flip_test=True, post_process='default', shift_heatmap=True, modulate_kernel=11)) data_cfg = dict( image_size=[192, 256], heatmap_size=[48, 64], num_output_channels=channel_cfg['num_output_channels'], num_joints=channel_cfg['dataset_joints'], dataset_channel=channel_cfg['dataset_channel'], inference_channel=channel_cfg['inference_channel'], soft_nms=False, nms_thr=1.0, oks_thr=0.9, vis_thr=0.2, use_gt_bbox=False, det_bbox_thr=0.0, bbox_file='data/coco/person_detection_results/' 'COCO_val2017_detections_AP_H_56_person.json', ) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='TopDownRandomFlip', flip_prob=0.5), dict( type='TopDownHalfBodyTransform', num_joints_half_body=8, prob_half_body=0.3), dict( type='TopDownGetRandomScaleRotation', rot_factor=40, scale_factor=0.5), dict(type='TopDownAffine'), dict(type='ToTensor'), dict( type='NormalizeTensor', mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), dict(type='TopDownGenerateTarget', sigma=2), dict( type='Collect', keys=['img', 'target', 'target_weight'], meta_keys=[ 'image_file', 'joints_3d', 'joints_3d_visible', 'center', 'scale', 'rotation', 'bbox_score', 'flip_pairs' ]), ] val_pipeline = [ dict(type='LoadImageFromFile'), dict(type='TopDownAffine'), dict(type='ToTensor'), dict( type='NormalizeTensor', mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), dict( type='Collect', keys=['img'], meta_keys=[ 'image_file', 'center', 'scale', 'rotation', 'bbox_score', 'flip_pairs' ]), ] test_pipeline = val_pipeline data_root = 'data/coco' data = dict( samples_per_gpu=32, workers_per_gpu=2, train=dict( type='TopDownCocoDataset', ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', img_prefix=f'{data_root}/train2017/', data_cfg=data_cfg, pipeline=train_pipeline), val=dict( type='TopDownCocoDataset', ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', img_prefix=f'{data_root}/val2017/', data_cfg=data_cfg, pipeline=val_pipeline), test=dict( type='TopDownCocoDataset', ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', img_prefix=f'{data_root}/val2017/', data_cfg=data_cfg, pipeline=val_pipeline), )
import React from 'react'; import ReactDOM from 'react-dom' import storeManager from '../redux/storeManager' import Person from './person' class People extends HTMLElement { constructor() { // Initialize state super(); this._people = []; this.shadow = this.attachShadow({ mode: 'closed' }); // Encapsulation of elements and styles } static get observedAttributes() { // Observe state Changes return ['people']; } attributeChangedCallback(attrName, oldVal, newVal) { // Handler of state with Timeline switch(attrName){ case 'people': this._people = newVal break; default: break; } } get people(){ return this.getAttribute('people'); } set people(val){ if (val) { this.setAttribute('people', val); } else { this.removeAttribute('people'); } } connectedCallback() { this.render(); } render() { let peopleData= storeManager.getState('peopleReducer', 'componentPayload'); const {id,children} = peopleData[0]; const mountPoint = document.createElement('div'); this.shadow.appendChild(mountPoint); ReactDOM.render( <div key={id}>{children.map((personInfo)=>(<person-card key={personInfo.id} person={JSON.stringify(personInfo)}/>))}</div>, mountPoint); } } customElements.define('people-info', People); // Register your Custom web component export default People;
/* Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("a11yhelp", "hu", { title: "Kisegítő utasítások", contents: "Súgó tartalmak. A párbeszédablak bezárásához nyomjon ESC-et.", legend: [{ name: "Általános", items: [{ name: "Szerkesztő Eszköztár", legend: "Nyomjon ${toolbarFocus} hogy kijelölje az eszköztárat. A következő és előző eszköztár csoporthoz a TAB és SHIFT+TAB-al juthat el. A következő és előző eszköztár gombhoz a BAL NYÍL vagy JOBB NYÍL gombbal juthat el. Nyomjon SPACE-t vagy ENTER-t hogy aktiválja az eszköztár gombot." }, { name: "Szerkesző párbeszéd ablak", legend: "Párbeszédablakban nyomjon TAB-ot a következő párbeszédmezőhöz ugráshoz, nyomjon SHIFT + TAB-ot az előző mezőhöz ugráshoz, nyomjon ENTER-t a párbeszédablak elfogadásához, nyomjon ESC-et a párbeszédablak elvetéséhez. Azokhoz a párbeszédablakokhoz, amik több fület tartalmaznak, nyomjon ALT + F10-et vagy TAB-ot hogy a fülekre ugorjon. Ezután a TAB-al vagy a JOBB NYÍLLAL a következő fülre ugorhat." }, { name: "Szerkesztő helyi menü", legend: "Nyomjon ${contextMenu}-t vagy ALKALMAZÁS BILLENTYŰT a helyi menü megnyitásához. Ezután a következő menüpontra léphet a TAB vagy LEFELÉ NYÍLLAL. Az előző opciót a SHIFT+TAB vagy FELFELÉ NYÍLLAL érheti el. Nyomjon SPACE-t vagy ENTER-t a menüpont kiválasztásához. A jelenlegi menüpont almenüjének megnyitásához nyomjon SPACE-t vagy ENTER-t, vagy JOBB NYILAT. A főmenühöz való visszatéréshez nyomjon ESC-et vagy BAL NYILAT. A helyi menü bezárása az ESC billentyűvel lehetséges." }, { name: "Szerkesztő lista", legend: "A listán belül a következő elemre a TAB vagy LEFELÉ NYÍLLAL mozoghat. Az előző elem kiválasztásához nyomjon SHIFT+TAB-ot vagy FELFELÉ NYILAT. Nyomjon SPACE-t vagy ENTER-t az elem kiválasztásához. Az ESC billentyű megnyomásával bezárhatja a listát." }, { name: "Szerkesztő elem utak sáv", legend: "Nyomj ${elementsPathFocus} hogy kijelöld a elemek út sávját. A következő elem gombhoz a TAB-al vagy a JOBB NYÍLLAL juthatsz el. Az előző gombhoz a SHIFT+TAB vagy BAL NYÍLLAL mehetsz. A SPACE vagy ENTER billentyűvel kiválaszthatod az elemet a szerkesztőben." } ] }, { name: "Parancsok", items: [{ name: "Parancs visszavonása", legend: "Nyomj ${undo}" }, { name: "Parancs megismétlése", legend: "Nyomjon ${redo}" }, { name: "Félkövér parancs", legend: "Nyomjon ${bold}" }, { name: "Dőlt parancs", legend: "Nyomjon ${italic}" }, { name: "Aláhúzott parancs", legend: "Nyomjon ${underline}" }, { name: "Link parancs", legend: "Nyomjon ${link}" }, { name: "Szerkesztősáv összecsukása parancs", legend: "Nyomjon ${toolbarCollapse}" }, { name: "Hozzáférés az előző fókusz helyhez parancs", legend: "Nyomj ${accessNextSpace} hogy hozzáférj a legközelebbi elérhetetlen fókusz helyhez a hiányjel előtt, például: két szomszédos HR elemhez. Ismételd meg a billentyűkombinációt hogy megtaláld a távolabbi fókusz helyeket." }, { name: "Hozzáférés a következő fókusz helyhez parancs", legend: "Nyomj ${accessNextSpace} hogy hozzáférj a legközelebbi elérhetetlen fókusz helyhez a hiányjel után, például: két szomszédos HR elemhez. Ismételd meg a billentyűkombinációt hogy megtaláld a távolabbi fókusz helyeket." }, { name: "Kisegítő súgó", legend: "Nyomjon ${a11yHelp}" }, { name: "Beillesztés egyszerű szövegként", legend: "Nyomd meg: ${pastetext}", legendEdge: "Nyomj ${pastetext}, majd ${paste}" } ] } ], tab: "Tab", pause: "Pause", capslock: "Caps Lock", escape: "Escape", pageUp: "Page Up", pageDown: "Page Down", leftArrow: "balra nyíl", upArrow: "felfelé nyíl", rightArrow: "jobbra nyíl", downArrow: "lefelé nyíl", insert: "Insert", leftWindowKey: "bal Windows-billentyű", rightWindowKey: "jobb Windows-billentyű", selectKey: "Billentyű választása", numpad0: "Számbillentyűk 0", numpad1: "Számbillentyűk 1", numpad2: "Számbillentyűk 2", numpad3: "Számbillentyűk 3", numpad4: "Számbillentyűk 4", numpad5: "Számbillentyűk 5", numpad6: "Számbillentyűk 6", numpad7: "Számbillentyűk 7", numpad8: "Számbillentyűk 8", numpad9: "Számbillentyűk 9", multiply: "Szorzás", add: "Hozzáadás", subtract: "Kivonás", decimalPoint: "Tizedespont", divide: "Osztás", f1: "F1", f2: "F2", f3: "F3", f4: "F4", f5: "F5", f6: "F6", f7: "F7", f8: "F8", f9: "F9", f10: "F10", f11: "F11", f12: "F12", numLock: "Num Lock", scrollLock: "Scroll Lock", semiColon: "Pontosvessző", equalSign: "Egyenlőségjel", comma: "Vessző", dash: "Kötőjel", period: "Pont", forwardSlash: "Perjel", graveAccent: "Visszafelé dőlő ékezet", openBracket: "Nyitó szögletes zárójel", backSlash: "fordított perjel", closeBracket: "Záró szögletes zárójel", singleQuote: "szimpla idézőjel" });
exports.templateData = { sharedData: function (args, done) { return new Promise(function (resolve, reject) { setTimeout(function () { resolve({ name: 'testSharedData' }); }, 100); }); }, contextData: function (args, done) { setTimeout(function () { done(null, { name: "testContextData" }); }, 100); } };
from pineboolib import logging from pineboolib.application.utils.check_dependencies import check_dependencies from sqlalchemy import create_engine # type: ignore from PyQt5.Qt import qWarning # type: ignore from PyQt5.QtWidgets import QMessageBox, QWidget # type: ignore from pineboolib.plugins.sql.flqpsql import FLQPSQL from typing import Any, SupportsInt, Union, cast logger = logging.getLogger(__name__) class FLQPSQL2(FLQPSQL): def __init__(self): super().__init__() self.name_ = "FLQPSQL2" self.alias_ = "PostgreSQL" self.mobile_ = True self.pure_python_ = True def useThreads(self): return False def useTimer(self): return True def safe_load(self): return check_dependencies({"pg8000": "pg8000", "sqlalchemy": "sqlAlchemy"}, False) def connect( self, db_name, db_host, db_port: Union[bytes, str, SupportsInt], db_userName, db_password ) -> Any: self._dbname = db_name check_dependencies({"pg8000": "pg8000", "sqlalchemy": "sqlAlchemy"}) import pg8000 # type: ignore import traceback # conninfostr = "dbname=%s host=%s port=%s user=%s password=%s connect_timeout=5" # % (db_name, db_host, db_port, db_userName, db_password) try: self.conn_ = pg8000.connect( user=db_userName, host=db_host, port=int(db_port), database=db_name, password=db_password, timeout=5, ) self.engine_ = create_engine( "postgresql+pg8000://%s:%s@%s:%s/%s" % (db_userName, db_password, db_host, db_port, db_name) ) except Exception as e: from pineboolib.application import project if project._DGI and not project.DGI.localDesktop(): if repr(traceback.format_exc()).find("the database system is starting up") > -1: raise return False if project._splash: project._splash.hide() if repr(traceback.format_exc()).find("does not exist") > -1: ret = QMessageBox.warning( QWidget(), "Pineboo", "La base de datos %s no existe.\n¿Desea crearla?" % db_name, cast(QMessageBox, QMessageBox.Ok | QMessageBox.No), ) if ret == QMessageBox.No: return False else: try: tmpConn = pg8000.connect( user="postgres", host=db_host, port=int(db_port), password=db_password, timeout=5, ) tmpConn.autocommit = True cursor = tmpConn.cursor() try: cursor.execute("CREATE DATABASE %s" % db_name) except Exception: print("ERROR: FLPSQL.connect", traceback.format_exc()) cursor.execute("ROLLBACK") cursor.close() return False cursor.close() return self.connect(db_name, db_host, db_port, db_userName, db_password) except Exception: qWarning(traceback.format_exc()) QMessageBox.information( QWidget(), "Pineboo", "ERROR: No se ha podido crear la Base de Datos %s" % db_name, QMessageBox.Ok, ) print("ERROR: No se ha podido crear la Base de Datos %s" % db_name) return False else: QMessageBox.information( QWidget(), "Pineboo", "Error de conexión\n%s" % str(e), QMessageBox.Ok ) return False # self.conn_.autocommit = True #Posiblemente tengamos que ponerlo a # false para que las transacciones funcionen # self.conn_.set_isolation_level( # pg8000.extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.conn_.autocommit = True if self.conn_: self.open_ = True try: cursor = self.conn_.cursor() cursor.execute("SET CLIENT_ENCODING TO 'UTF8'") except Exception: qWarning(traceback.format_exc()) return self.conn_
#!/usr/bin/python ############################################################### # rsync_WxBug_data.py # ############################################################### # Python script for copying lightning files from atec-dataops # # to winter # ############################################################### import os import getopt import string import sys import time import shutil import subprocess as sub ############################################################### # Local subroutines # ############################################################### ############################################################### # print_usage(): Print the usage for this script # def print_usage(): print "Usage: ", prog_name, " [options]" print " -h | --help : Print usage and exit" print " -d | --debug : Print debug messages" print " --date : date to process (default todays date)" print " --input : default <hardt@atec-dataops:/raid/ext_obs/lightning>" print " --output : defualt </d1/data/raw/lightning/Wxbug>\n" return def get_date(): this_time = time.time() time_tuple = time.gmtime( this_time ) year = str(time_tuple[0]) month = str(time_tuple[1]) if time_tuple[1] < 10: month = "0" + month day = str(time_tuple[2]) if time_tuple[2] < 10: day = "0" + day this_date = year + month + day return this_date def get_previous_date(): this_time = time.time() - 86400 time_tuple = time.gmtime( this_time ) year = str(time_tuple[0]) month = str(time_tuple[1]) if time_tuple[1] < 10: month = "0" + month day = str(time_tuple[2]) if time_tuple[2] < 10: day = "0" + day this_date = year + month + day return this_date def get_time(): # this_time = time.time() - 86400 this_time = time.time() time_tuple = time.gmtime( this_time ) hour = str( time_tuple[3] ) if time_tuple[3] < 10: hour = "0" + hour min = str( time_tuple[4] ) if time_tuple[4] < 10: min = "0" + min this_time = hour + min return this_time ############################################################### # Main program # ############################################################### if __name__ == "__main__": # # Retrieve the program name from the command line. # prog_name = os.path.basename(sys.argv[0]) # # Initialize the command line arguments. # opt_date = "" opt_debug = 0 opt_input = "hardt@atec-dataops:/raid/ext_obs/lightning" opt_output = "/d1/data/raw/lightning/Wxbug" optlist, args = getopt.getopt(sys.argv[1:], 'dhp', \ [ 'help', \ 'date=', 'input=', 'output=' ]) for opt in optlist: if opt[0] == "-h" or opt[0] == "--help": print_usage() sys.exit() if opt[0] == "-d" or opt[0] == "--debug": opt_debug = 1 if opt[0] == "--date": opt_date = opt[1] if opt[0] == "--input": opt_input = opt[1] if opt[0] == "--output": opt_output = opt[1] if opt_date == "": process_date = get_date() else: process_date = opt_date if opt_debug: print >> sys.stderr, "Processing date ", process_date if not os.path.exists(opt_output + "/" + process_date): os.mkdir(opt_output + "/" + process_date) #--- Only want to sync current days data into #--- a subdirectory with that date rsync_command = "rsync -auv --chmod=ugo=rwX --include=\"" + process_date + "*\" --exclude=\"*\" " + opt_input + "/ " + opt_output + "/" + process_date if opt_debug: print >> sys.stderr, rsync_command #--- Rsync the requested day d = sub.Popen(rsync_command, shell=True) error_out = d.communicate()[1] if opt_debug: if error_out != " None ": print >> sys.stderr, "Error:", error_out, "-" #--- Rsync the precious day at the beginning of a new day current_time = int( get_time() ) if current_time < 10: process_date = get_previous_date() if opt_debug: print >> sys.stderr, "Processing previous date of ", process_date if not os.path.exists(opt_output + "/" + process_date): os.mkdir(opt_output + "/" + process_date) if opt_debug: print >> sys.stderr, rsync_command d = sub.Popen(rsync_command, shell=True) error_out = d.communicate()[1] if opt_debug: if error_out != " None ": print >> sys.stderr, "Error:", error_out, "-" sys.exit()
import Util from "./Util/Util" /** * ------------------------------------------------------------------------ * Class Definition ( Abstract ) * ------------------------------------------------------------------------ */ class MapElement { getLabelText(key, label) { if (!label) { return } if (Util.isFunc(label.render)) { let params = [] // Pass additional paramater (Marker config object) in case it's a Marker. if (this.config.marker) { params.push(this.config.marker) } // Becuase we need to add the key always at the end params.push(key) return label.render.apply(this, params) } return key } getLabelOffsets(key, label) { if (Util.isFunc(label.offsets)) { return label.offsets(key) } // If offsets are an array of offsets e.g offsets: [ [0, 25], [10, 15] ] if (Util.isArr(label.offsets)) { return label.offsets[key] } return [0, 0] } setStyle(property, value) { this.shape.setStyle(property, value) } remove() { this.shape.remove() if (this.label) this.label.remove() } hover(state) { this._setStatus('isHovered', state) } select(state) { this._setStatus('isSelected', state) } // Private _setStatus(property, state) { this.shape[property] = state this.shape.updateStyle() this[property] = state if (this.label) { this.label[property] = state this.label.updateStyle() } } } export default MapElement
//import { combineReducers } from "redux"; import { configureStore, getDefaultMiddleware } from "@reduxjs/toolkit"; import logger from "redux-logger"; import storage from "redux-persist/lib/storage"; import { persistStore, persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER, } from "redux-persist"; import appReducer from "./app/app-reducer"; import authReducer from "./auth/auth-reducers"; //console.log(getDefaultMiddleware()); const middleware = [ ...getDefaultMiddleware({ serializableCheck: { ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER], }, }), logger, ]; const authPersistConfig = { key: "auth", storage, whitelist: ["token"], }; const store = configureStore({ reducer: { app: appReducer, auth: persistReducer(authPersistConfig, authReducer), }, middleware, devTools: process.env.NODE_ENV === "development", }); const persistor = persistStore(store); export default { store, persistor };
import actions from "../actions"; import store from "../store"; export function isMobile() { return window.innerWidth < 768; } function initTouchDeviceTest() { window.addEventListener("touchstart", function onFirstTouch() { store.dispatch(actions.deviceState.update({ isTouchDevice: true })); window.removeEventListener("touchstart", onFirstTouch, false); }, false); } export function initVisualBehavior() { initTouchDeviceTest(); initFocusHandler(); patchSFFontIssues(); } function getFocus() { var inFocus; try { inFocus = document.hasFocus(); } catch(e){} // eslint-disable-line no-empty if (typeof inFocus !== "boolean") { // Assume we are return true; } return inFocus; } function getVisibility() { let visible = !document.hidden; if (typeof visible !== "boolean") { // Assume it is return true; } return visible; } function setFocus(inFocus) { let state = store.getState(); let changes = {}; let changed = false; let visible = getVisibility(); if (state && state.deviceState.inFocus !== inFocus) { changes.inFocus = inFocus; changed = true; } if (state && state.deviceState.visible !== visible) { changes.visible = visible; changed = true; } if (changed) { store.dispatch(actions.deviceState.update(changes)); } } function visibilityChangeHandler() { setFocus(getFocus()); } function focusHandler() { setFocus(true); } function blurHandler() { setFocus(false); } function initFocusHandler() { visibilityChangeHandler(); window.addEventListener("visibilitychange", visibilityChangeHandler); window.addEventListener("focus", focusHandler); window.addEventListener("blur", blurHandler); } export function setDarkModeStatus(status) { let list = document.body.classList; let name = "darkmode"; if (status && !list.contains(name)) { list.add(name); } else if (!status && list.contains(name)) { list.remove(name); } } function patchSFFontIssues() { let ua = navigator.userAgent; let osMatch = ua.match(/Mac OS X 10_([0-9]+)/); let osVersion = osMatch && osMatch[1] && parseInt(osMatch[1], 10); if (osVersion && osVersion >= 11) { // >= macOS 10.11, we assume SF font // General document.body.classList.add("sf-font"); // Issue with chrome if (/Chrome\//.test(ua)) { document.body.classList.add("chrome-sf-font"); } } }
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import path from 'path' import Promise from 'bluebird' import express from 'express' import proxyMiddleware from 'http-proxy-middleware' import cookieParser from 'cookie-parser' import bodyParser from 'body-parser' import expressJwt, { UnauthorizedError as Jwt401Error } from 'express-jwt' import { graphql } from 'graphql' import expressGraphQL from 'express-graphql' import jwt from 'jsonwebtoken' import nodeFetch from 'node-fetch' import React from 'react' import ReactDOM from 'react-dom/server' import { getDataFromTree } from 'react-apollo' import PrettyError from 'pretty-error' import apolloFetch from './data/graphql/apollo-fetch' import createApolloClient from './core/createApolloClient' import App from './components/App' import Html from './components/Html' import { ErrorPageWithoutStyle } from './routes/error/ErrorPage' import errorPageStyle from './routes/error/ErrorPage.css' import createFetch from './createFetch' import router from './router' import schema from './data/schema' // import assets from './asset-manifest.json'; // eslint-disable-line import/no-unresolved import chunks from './chunk-manifest.json' // eslint-disable-line import/no-unresolved import configureStore from './store/configureStore' import { setRuntimeVariable } from './actions/runtime' import config from './config' import ACCOUNT_INFO from './gql/account/ACCOUNT_INFO.gql' import { setUserInfo } from './actions/user' process.on('unhandledRejection', (reason, p) => { console.error('Unhandled Rejection at:', p, 'reason:', reason) // send entire app down. Process manager will restart it process.exit(1) }) // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {} global.navigator.userAgent = global.navigator.userAgent || 'all' const app = express() // // If you are using proxy from external machine, you can set TRUST_PROXY env // Default is to trust proxy headers only from loopback interface. // ----------------------------------------------------------------------------- app.set('trust proxy', config.trustProxy) // // Register Node.js middleware // ----------------------------------------------------------------------------- app.use(express.static(path.resolve(__dirname, 'public'))) app.use(cookieParser()) app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) // proxy-middleware app.use('/api', proxyMiddleware(config.proxy)) // // Authentication // ----------------------------------------------------------------------------- app.use( expressJwt({ secret: config.auth.jwt.secret, // set to true if front-end authenticate required credentialsRequired: false, getToken: req => req.cookies.token }).unless({ path: ['/login', '/loginapi', '/graphql'] }) ) // Error handler for express-jwt app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars if (err instanceof Jwt401Error) { console.error('[express-jwt-error]', req.cookies.token) // `clearCookie`, otherwise user can't use web-app until cookie expires res.clearCookie('token') res.redirect('/login') } next(err) }) app.post('/loginapi', (req, res) => { const payload = req.body // if (payload.userName !== 'zuomeng') { // res.clearCookie('token') // return res.json({ // errorCode: 1 // }) // } const expiresIn = 60 * 60 * 24 * 180 const token = jwt.sign( { username: payload.userName }, config.auth.jwt.secret, { expiresIn } ) res.cookie('token', token, { maxAge: 1000 * expiresIn, httpOnly: false }) return res.json({ errorCode: 0, userName: 'zuomeng' }) }) // // Register API middleware // ----------------------------------------------------------------------------- // https://github.com/graphql/express-graphql#options const graphqlMiddleware = expressGraphQL(req => ({ schema, graphiql: __DEV__, rootValue: { request: req }, pretty: __DEV__ })) app.use('/graphql', graphqlMiddleware) // // Register server-side rendering middleware // ----------------------------------------------------------------------------- app.get('*', async (req, res, next) => { try { const css = new Set() // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader const insertCss = (...styles) => { // eslint-disable-next-line no-underscore-dangle styles.forEach(style => css.add(style._getCss())) } const apolloClient = createApolloClient({ schema, rootValue: { request: req } }) // Universal HTTP client const fetch = createFetch(nodeFetch, { baseUrl: config.api.serverUrl, cookie: req.headers.cookie, apolloClient, schema, graphql }) const initialState = { user: {} } const store = configureStore(initialState, { cookie: req.headers.cookie, fetch, // I should not use `history` on server.. but how I do redirection? follow universal-router history: null }) // 提前抓去用户信息,判断登录状态 const cookie = req.cookies const pathname = req.path const whiteList = ['/login', '/register'] // 如果没有token if (!cookie.token) { // 如果不是去白名单页面,重定向到登陆页 if (whiteList.indexOf(pathname) < 0) { return res.redirect('/login') } // 如果有token并且要去注册和登陆页 } else if (pathname === '/login' || pathname === '/register') { return res.redirect('/') } const { data: accountData } = await apolloFetch({ query: ACCOUNT_INFO }) // 提取结果中的用户信息 const info = accountData.account store.dispatch(setUserInfo(info)) store.dispatch( setRuntimeVariable({ name: 'initialNow', value: new Date().toString() }) ) // Global (context) variables that can be easily accessed from any React component // https://facebook.github.io/react/docs/context.html const context = { insertCss, fetch, // The twins below are wild, be careful! pathname: req.path, query: req.query, // You can access redux through react-redux connect store, storeSubscription: null, // Apollo Client for use with react-apollo client: apolloClient, cookie: req.cookies } const route = await router.resolve(context) if (route.redirect) { return res.redirect(route.status || 302, route.redirect) } const data = { ...route } const rootComponent = <App context={context}>{route.component}</App> await getDataFromTree(rootComponent) // this is here because of Apollo redux APOLLO_QUERY_STOP action await Promise.delay(0) data.children = await ReactDOM.renderToString(rootComponent) data.styles = [{ id: 'css', cssText: [...css].join('') }] const scripts = new Set() const addChunk = chunk => { if (chunks[chunk]) { chunks[chunk].forEach(asset => scripts.add(asset)) } else if (__DEV__) { throw new Error(`Chunk with name '${chunk}' cannot be found`) } } addChunk('client') if (route.chunk) addChunk(route.chunk) if (route.chunks) route.chunks.forEach(addChunk) data.scripts = Array.from(scripts) // Furthermore invoked actions will be ignored, client will not receive them! if (__DEV__) { // eslint-disable-next-line no-console console.log('Serializing store...') } data.app = { apiUrl: config.api.clientUrl, state: context.store.getState(), apolloState: context.client.extract() } const html = ReactDOM.renderToStaticMarkup(<Html {...data} />) res.status(route.status || 200) res.send(`<!doctype html>${html}`) } catch (err) { next(err) } }) // // Error handling // ----------------------------------------------------------------------------- const pe = new PrettyError() pe.skipNodeFiles() pe.skipPackage('express') // eslint-disable-next-line no-unused-vars app.use((err, req, res, next) => { console.error(pe.render(err)) const html = ReactDOM.renderToStaticMarkup( <Html title="Internal Server Error" description={err.message} styles={[{ id: 'css', cssText: errorPageStyle._getCss() }]} // eslint-disable-line no-underscore-dangle > {ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)} </Html> ) res.status(err.status || 500) res.send(`<!doctype html>${html}`) }) // // Launch the server // ----------------------------------------------------------------------------- // const promise = models.sync().catch(err => console.error(err.stack)) if (!module.hot) { // promise.then(() => { app.listen(config.port, () => { console.info(`The server is running at http://localhost:${config.port}/`) }) // }) } // // Hot Module Replacement // ----------------------------------------------------------------------------- if (module.hot) { app.hot = module.hot module.hot.accept('./router') } export default app
import React from 'react'; import Card from './Card'; import CardRow from './CardRow'; import CardInput from './CardInput'; const RequirementCard = ({ id, saleId, productId, customerId, description, unitPrice, numberOfPieces, deliveryTime, purchaseOrderId, creationTime, loadProduct, loadCustomer, update, isSelected, setSelectedCard, }) => { const [productName, _setProductName] = React.useState('[product]'); const [customerName, _setCustomerName] = React.useState('[customer]'); // We can cache the following in a HOC React.useEffect( () => { // loadProduct(productId); // loadCustomer(customerId); }, [productName, customerName] ); // Only here we are able to edit Purchase Order ID from the card const formattedUnitPrice = `${unitPrice} MXN`; const unitPriceIconClass = 'dollar sign icon'; const numberOfPiecesIconClass = 'puzzle piece icon'; const formattedNumberOfPieces = `${numberOfPieces} `; const formattedDeliveryTime = `${deliveryTime} días`; const deliveryTimeIconClass = 'box icon'; const formattedCreationTime = `${creationTime}`; return ( <Card header={productName} subheader={customerName} content={description} isSelected={isSelected} onClick={() => setSelectedCard({ saleId })} > <CardRow leftContent={formattedUnitPrice} leftIcon={unitPriceIconClass} rightIcon={numberOfPiecesIconClass} rightContent={formattedNumberOfPieces} /> <CardInput label={'Tiempo de Entrega:'} value={formattedDeliveryTime} /> <CardInput label={'Orden de Compra:'} value={purchaseOrderId} /> </Card> ); }; export default RequirementCard;
import React from 'react' import { Progress } from 'reactstrap' class BootstrapProgressExample extends React.Component { render() { return ( <div> <h5 className="mb-4"> <strong>Default Progress</strong> </h5> <div className="mb-5"> <div className="text-center">0%</div> <Progress className="mb-4" /> <div className="text-center">25%</div> <Progress className="mb-4" value="25" /> <div className="text-center">50%</div> <Progress className="mb-4" value={50} /> <div className="text-center">75%</div> <Progress className="mb-4" value={75} /> <div className="text-center">100%</div> <Progress className="mb-4" value="100" /> <div className="text-center">Multiple bars</div> <Progress className="mb-4" multi> <Progress className="mb-4" bar value="15" /> <Progress className="mb-4" bar color="success" value="30" /> <Progress className="mb-4" bar color="info" value="25" /> <Progress className="mb-4" bar color="warning" value="20" /> <Progress className="mb-4" bar color="danger" value="5" /> </Progress> </div> <h5 className="mb-4"> <strong>Colors Variants</strong> </h5> <div className="mb-5"> <Progress className="mb-4" value={2 * 5} /> <Progress className="mb-4" color="success" value="25" /> <Progress className="mb-4" color="info" value={50} /> <Progress className="mb-4" color="warning" value={75} /> <Progress className="mb-4" color="danger" value="100" /> </div> <h5 className="mb-4"> <strong>Labels</strong> </h5> <div className="mb-5"> <Progress className="mb-4" value="25"> 25% </Progress> <Progress className="mb-4" value={50}> 1/2 </Progress> <Progress className="mb-4" value={75}> Youre almost there! </Progress> <Progress className="mb-4" color="success" value="100"> You did it! </Progress> <Progress className="mb-4" multi> <Progress className="mb-4" bar value="15"> Meh </Progress> <Progress className="mb-4" bar color="success" value="30"> Wow! </Progress> <Progress className="mb-4" bar color="info" value="25"> Cool </Progress> <Progress className="mb-4" bar color="warning" value="20"> 20% </Progress> <Progress className="mb-4" bar color="danger" value="5"> !! </Progress> </Progress> </div> <h5 className="mb-4"> <strong>Striped</strong> </h5> <div className="mb-5"> <Progress className="mb-4" striped value={2 * 5} /> <Progress className="mb-4" striped color="success" value="25" /> <Progress className="mb-4" striped color="info" value={50} /> <Progress className="mb-4" striped color="warning" value={75} /> <Progress className="mb-4" striped color="danger" value="100" /> <Progress className="mb-4" multi> <Progress className="mb-4" striped bar value="10" /> <Progress className="mb-4" striped bar color="success" value="30" /> <Progress className="mb-4" striped bar color="warning" value="20" /> <Progress className="mb-4" striped bar color="danger" value="20" /> </Progress> </div> <h5 className="mb-4"> <strong>Multiple bars / Stacked</strong> </h5> <div className="mb-5"> <Progress className="mb-4" animated value={2 * 5} /> <Progress className="mb-4" animated color="success" value="25" /> <Progress className="mb-4" animated color="info" value={50} /> <Progress className="mb-4" animated color="warning" value={75} /> <Progress className="mb-4" animated color="danger" value="100" /> <Progress className="mb-4" multi> <Progress className="mb-4" animated bar value="10" /> <Progress className="mb-4" animated bar color="success" value="30" /> <Progress className="mb-4" animated bar color="warning" value="20" /> <Progress className="mb-4" animated bar color="danger" value="20" /> </Progress> </div> <h5 className="mb-4"> <strong>Multiple bars / Stacked</strong> </h5> <div className="mb-5"> <Progress className="mb-4" multi> <Progress className="mb-4" bar value="15" /> <Progress className="mb-4" bar color="success" value="20" /> <Progress className="mb-4" bar color="info" value="25" /> <Progress className="mb-4" bar color="warning" value="20" /> <Progress className="mb-4" bar color="danger" value="15" /> </Progress> <div className="text-center">With Labels</div> <Progress className="mb-4" multi> <Progress className="mb-4" bar value="15"> Meh </Progress> <Progress className="mb-4" bar color="success" value="35"> Wow! </Progress> <Progress className="mb-4" bar color="warning" value="25"> 25% </Progress> <Progress className="mb-4" bar color="danger" value="25"> LOOK OUT!! </Progress> </Progress> <div className="text-center">Stripes and Animations</div> <Progress className="mb-4" multi> <Progress className="mb-4" bar striped value="15"> Stripes </Progress> <Progress className="mb-4" bar animated color="success" value="30"> Animated Stripes </Progress> <Progress className="mb-4" bar color="info" value="25"> Plain </Progress> </Progress> </div> </div> ) } } export default BootstrapProgressExample
import sqlite3 import sys from PyQt5.QtWidgets import QDialog, QTableWidgetItem, QHeaderView from PyQt5 import QtWidgets, uic import functions.chemistry import usefulwidgets class Chemist(QDialog): def __init__(self): super(Chemist, self).__init__() uic.loadUi('ui_dir/chemist.ui', self) self.anstext = '' self.chaintext = '' self.solveeq.clicked.connect(self.solve) self.solvec.clicked.connect(self.solvechain) self.connection = sqlite3.connect("./data_db.sqlite") header = self.chainviewer.horizontalHeader() header.setSectionResizeMode(QHeaderView.ResizeToContents) self.full.setText('<a href="https://i.ytimg.com/vi/eRnV3qBdRCI/maxresdefault.jpg">FULL IMAGE</a>') self.full.setOpenExternalLinks(True) self.select_data() self.show() def solvechain(self): """function that solves chemistry chain of reactions(need WI FI enabled)""" x = self.chain.text() try: self.chaintext = '\n'.join(functions.chemistry.chain(x)) except Exception as e: return usefulwidgets.returnalert(self, e) self.res2.setPlaceholderText(self.chaintext) self.connection.cursor().execute(f"""INSERT INTO chains (chain, res) VALUES ('{x}', '{self.chaintext}');""") self.connection.commit() self.select_data() def solve(self): """solves simple chemist reaction equation(need WI FI enabled)""" x = self.elem1.text() y = self.elem2.text() try: self.anstext = functions.chemistry.solveequation(x, y) with open('chemistsolutions.txt', 'a+', encoding="utf-16") as f: f.write('\n' + self.anstext) except Exception as e: return usefulwidgets.returnalert(self, e) self.res1.setText(self.anstext) def closeEvent(self, event): usefulwidgets.on_close(event) def select_data(self): try: query = "SELECT * FROM chains" res = self.connection.cursor().execute(query).fetchall() self.chainviewer.setColumnCount(2) self.chainviewer.setRowCount(0) for i, row in enumerate(reversed(res)): self.chainviewer.setRowCount( self.chainviewer.rowCount() + 1) for j, elem in enumerate(row): self.chainviewer.setItem( i, j, QTableWidgetItem(str(elem))) except Exception as e: print(e) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = Chemist() app.exec_()
import React from 'react'; // import { BlurView } from 'react-native-blur'; import { Modal, View } from 'react-native'; const FilterModal = ({ isVisible, bluredViewRef, view }) => ( <Modal visible={isVisible} transparent={true}> {/* bluredViewRef && ( <BlurView viewRef={bluredViewRef} style={{ position: 'absolute', left: 0, top: 0, bottom: 0, right: 0 }} blurRadius={4} blurAmount={10} blurType={'dark'} /> ) */} {view} </Modal> ); export { FilterModal };
/** * API request functions for interacting with WordPress's REST API. * * Site Kit by Google, Copyright 2020 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 * * https://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. */ /** * External dependencies */ import invariant from 'invariant'; /** * WordPress dependencies */ import apiFetch from '@wordpress/api-fetch'; import { addQueryArgs } from '@wordpress/url'; /** * Internal dependencies */ import { deleteItem, getItem, getKeys, setItem, } from './cache'; import { stringifyObject } from '../../util'; // Specific error to handle here, see below. import { STORE_NAME as CORE_USER, ERROR_MISSING_REQUIRED_SCOPE } from '../datastore/user/constants'; // Caching is enabled by default. let cachingEnabled = true; const KEY_SEPARATOR = '::'; /** * Create a cache key for a set of type/identifier/datapoint values. * * @since 1.5.0 * @private * * @param {string} type The data to access. One of 'core' or 'modules'. * @param {string} identifier The data identifier, eg. a module slug like `'search-console'`. * @param {string} datapoint The endpoint to request data from. * @param {Object} queryParams Query params to send with the request. * @return {string} The cache key to use for this set of values. */ export const createCacheKey = ( type, identifier, datapoint, queryParams = {} ) => { const keySections = [ type, identifier, datapoint ].filter( ( keySection ) => { return !! keySection && keySection.length; } ); if ( keySections.length === 3 && ( !! queryParams ) && ( queryParams.constructor === Object ) && Object.keys( queryParams ).length ) { keySections.push( stringifyObject( queryParams ) ); } return keySections.join( KEY_SEPARATOR ); }; /** * Make a request to a WP REST API Site Kit endpoint. * * @since 1.5.0 * @private * * @param {string} type The data to access. One of 'core' or 'modules'. * @param {string} identifier The data identifier, eg. a module slug like `'search-console'`. * @param {string} datapoint The endpoint to request data from. * @param {Object} options Optional. Options to pass to the request. * @param {number} options.cacheTTL The oldest cache data to use, in seconds. * @param {Object} options.bodyParams Request body data to send. (Eg. used for `POST`/`PUT` request variables.) * @param {number} options.method HTTP method to use for this request. * @param {Object} options.queryParams Query params to send with the request. * @param {boolean} options.useCache Enable or disable caching for this request only. (Caching is only used for `GET` requests.) * @return {Promise} Response of HTTP request. */ export const siteKitRequest = async ( type, identifier, datapoint, { bodyParams, cacheTTL = 3600, method = 'GET', queryParams, useCache = undefined, } = {} ) => { invariant( type, '`type` argument for requests is required.' ); invariant( identifier, '`identifier` argument for requests is required.' ); invariant( datapoint, '`datapoint` argument for requests is required.' ); // Don't check for a `false`-y `useCache` value to ensure we don't fallback // to the `usingCache()` behaviour when caching is manually disabled on a // per-request basis. const useCacheForRequest = method === 'GET' && ( useCache !== undefined ? useCache : usingCache() ); const cacheKey = createCacheKey( type, identifier, datapoint, queryParams ); if ( useCacheForRequest ) { const { cacheHit, value } = await getItem( cacheKey, cacheTTL ); if ( cacheHit ) { return value; } } // Make an API request to retrieve the results. try { const response = await apiFetch( { data: bodyParams, method, path: addQueryArgs( `/google-site-kit/v1/${ type }/${ identifier }/data/${ datapoint }`, queryParams ), } ); if ( useCacheForRequest ) { await setItem( cacheKey, response ); } return response; } catch ( error ) { // Check to see if this error was a `ERROR_MISSING_REQUIRED_SCOPE` error; // if so and there is a data store available to dispatch on, dispatch a // `setPermissionScopeError()` action. // Kind of a hack, but scales to all components. if ( error.code === ERROR_MISSING_REQUIRED_SCOPE && global.googlesitekit?.data?.dispatch?.( CORE_USER ) ) { global.googlesitekit.data.dispatch( CORE_USER ).setPermissionScopeError( error ); } global.console.error( 'Google Site Kit API Error', error ); throw error; } }; /** * Get Google Site Kit data. * * Makes a request to this site's WordPress REST API, which will in * turn make GET requests to the relevant Google services' APIs. * * This method automatically handles authentication, so no credentials * are required to use this method. * * @since 1.5.0 * * @param {string} type The data to access. One of 'core' or 'modules'. * @param {string} identifier The data identifier, eg. a module slug like `'search-console'`. * @param {string} datapoint The endpoint to request data from. * @param {Object} data Data (query params) to send with the request. * @param {Object} options Extra options for this request. * @param {number} options.cacheTTL The oldest cache data to use, in seconds. * @param {boolean} options.useCache Enable or disable caching for this request only. * @return {Promise} A promise for the `fetch` request. */ export const get = async ( type, identifier, datapoint, data, { cacheTTL = 3600, useCache = undefined } = {} ) => { return siteKitRequest( type, identifier, datapoint, { cacheTTL, queryParams: data, useCache, } ); }; /** * Set Google Site Kit data. * * Makes a request to this site's WordPress REST API, which will in * turn make requests to the relevant Google services' APIs to save * the data sent in the request. * * This method automatically handles authentication, so no credentials * are required to use this method. * * @since 1.5.0 * * @param {string} type The data to access. One of 'core' or 'modules'. * @param {string} identifier The data identifier, eg. a module slug like `'adsense'`. * @param {string} datapoint The endpoint to send data to. * @param {Object} data Request body data (eg. post data) to send with the request. * @param {Object} options Extra options for this request. * @param {number} options.method HTTP method to use for this request. * @param {boolean} options.queryParams Query params to send with the request. * @return {Promise} A promise for the `fetch` request. */ export const set = async ( type, identifier, datapoint, data, { method = 'POST', queryParams = {} } = {} ) => { const response = await siteKitRequest( type, identifier, datapoint, { bodyParams: { data }, method, queryParams, useCache: false, } ); await invalidateCache( type, identifier, datapoint ); return response; }; /** * Enable/disable caching. * * Set the caching to on/off for the entire API library. * * Individual requests can still be overridden to _disable_ caching, * but if caching is turned off it cannot be turned on for a specific request. * * @since 1.5.0 * * @param {boolean} shouldUseCache Set to `true` to use this cache across requests; set to `false` to disable caching. * @return {boolean} The new caching state (`true` for on, `false` for off). */ export const setUsingCache = ( shouldUseCache ) => { cachingEnabled = !! shouldUseCache; return cachingEnabled; }; /** * Get current caching state for the API. * * @since 1.5.0 * * @return {boolean} The current caching state (`true` for on, `false` for off). */ export const usingCache = () => { return cachingEnabled; }; /** * Invalidate the cache for a specific datapoint or all data. * * Invalidate cache data for either a specific datapoint, identifier, type, or * all data. The more specificity supplied the more granularly cache data will * be invalidated. * * Calling `invalidateCache()` will invalidate _all_ cached data, while calling * `invalidateCache( 'modules', 'adsense' )` will invalidate all AdSense data only. * * @since 1.5.0 * * @param {string} type The data type to operate on. One of 'core' or 'modules'. * @param {string} identifier The data identifier, eg. a module slug like `'adsense'`. * @param {string} datapoint The endpoint to invalidate cache data for. */ export const invalidateCache = async ( type, identifier, datapoint ) => { const groupPrefix = createCacheKey( type, identifier, datapoint ); const allKeys = await getKeys(); allKeys.forEach( ( key ) => { if ( key.indexOf( groupPrefix ) === 0 ) { deleteItem( key ); } } ); }; const API = { invalidateCache, get, set, setUsingCache, usingCache, }; export default API;
module.exports = { // github username: required github: 'jdwilkin4', // // everything below here is optional. by default, we pull most profile data from your github profile. // you can override that data here, as well as provide some additional account links below // // name - if not defined here, will default to your Name on github if defined, if not, then your username // name: 'Your Name', // // mainUrl: the url your name links to on the members page. defaults to your github profile // mainUrl: 'https://virtualcoffee.io', // // bio - accepts markdown. // bio: `This is _my_ **bio** and [here is a link](https://virtualcoffee.io)`, // // can take one of each type except website - you can add as many `website` accounts as you wish accounts: [ { type: 'linkedin', username: 'jessica-wilkins-developer' }, // { type: 'dev', username: 'yourUserName' }, // { type: 'codenewbie', username: 'yourUserName' }, { type: 'twitter', username: 'codergirl1991' }, // { type: 'twitch', username: 'yourUserName' }, // { type: 'youtube', channelId: 'yourChannelId' }, // or { type: 'youtube', customUrl: 'https://www.youtube.com/c/yourCustomUrl' } // { type: 'polywork', username: 'yourUserName' }, // { type: 'medium', username: 'yourUserName' }, // { type: 'hashnode', username: 'yourUserName' }, { type: 'website', url: 'https://www.freecodecamp.org/news/author/jessica-wilkins/', title: 'freeCodeCamp News Author Profile', }, ], };
/* eslint-disable flowtype/require-valid-file-annotation */ const path = require('path') const webpack = require('webpack') // Run `yarn start.dev` to enable debug mode. // This mode will serve the plugin bundle via a local dev-server. const debug = process.env.WEBPACK_SERVE module.exports = { devtool: debug ? 'source-map' : undefined, devServer: { allowedHosts: 'all', hot: false, static: false, port: 8101 }, entry: './src/util/corePluginBundle.js', mode: debug ? 'development' : 'production', module: { rules: [ { test: /\.js$/, exclude: /(@babel\/runtime|babel-runtime)/, use: debug ? { loader: '@sucrase/webpack-loader', options: { transforms: [] } } : { loader: 'babel-loader', options: { babelrc: false, presets: ['@babel/preset-env'], plugins: [ ['@babel/plugin-transform-for-of', { assumeArray: true }], // Work around metro-react-native-babel-preset issue: ['@babel/plugin-proposal-class-properties', { loose: false }] ], cacheDirectory: true } } } ] }, output: { filename: 'plugin-bundle.js', path: path.join(path.resolve(__dirname), 'android/app/src/main/assets/edge-core') }, performance: { hints: false }, node: { fs: 'empty' }, plugins: [new webpack.IgnorePlugin(/^(https-proxy-agent)$/)], resolve: { aliasFields: ['browser'], mainFields: ['browser', 'module', 'main'] } }
'use strict';var G="function"==typeof Object.defineProperties?Object.defineProperty:function(p,r,t){p!=Array.prototype&&p!=Object.prototype&&(p[r]=t.value)};function L(p){p=["object"==typeof globalThis&&globalThis,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global,p];for(var r=0;r<p.length;++r){var t=p[r];if(t&&t.Math==Math)return t}throw Error("Cannot find global object");}var M=L(this);function O(){O=function(){};M.Symbol||(M.Symbol=P)} function Q(p,r){this.a=p;G(this,"description",{configurable:!0,writable:!0,value:r})}Q.prototype.toString=function(){return this.a};var P=function(){function p(t){if(this instanceof p)throw new TypeError("Symbol is not a constructor");return new Q("jscomp_symbol_"+(t||"")+"_"+r++,t)}var r=0;return p}(); (function(p){function r(e){e()}function t(e){e(this)}function H(){if(y){do u=!1,D.shift()();while(--y)}u=!1}function B(e,l,c){this.then=e;this["catch"]=l;this["finally"]=c}function v(e){function l(a){0===g&&(F(a)?a.then(l,c):(f=a,g=2,null!==d&&("function"===typeof d?d(a):d.forEach(t,a),d=null),b=null,null!==k&&("function"===typeof k?k():k.forEach(r),k=null)))}function c(a){0===g&&(f=a,g=1,null!==b&&("function"===typeof b?b(a):b.forEach(t,a),b=null),d=null,null!==k&&("function"===typeof k?k():k.forEach(r), k=null))}var f,g=0,d=null,b=null,k=null,h=new B(function(a,m){if(0===g)return I(function(w,C){var z="function"===typeof a?function(){w(a(f))}:w,J="function"===typeof m?function(){C(m(f))}:C;null!==d?"function"===typeof d?d=[d,z]:d.push(z):d=z;null!==b?"function"===typeof b?b=[b,J]:b.push(J):b=J});try{return 2===g?"function"===typeof a?E(a(f)):x:"function"===typeof m?q(m(f)):x}catch(w){return q(w)}},function(a){if(0===g)return I(function(m){null!==b?"function"===typeof b?b=[b,function(){m(a(f))}]: b.push(function(){m(a(f))}):b=function(){m(a(f))};null!==d?"function"===typeof d?d=[d,m]:d.push(m):d=m});if(2===g)return E(f);try{return"function"===typeof a?E(a(f)):x}catch(m){return q(m)}},function(a){if(0===g)null!==k?"function"===typeof k?k=[k,a]:k.push(a):k=a;else try{a()}catch(m){return q(m)}return h});if(!0===u)D.push(function(){try{e(l,c)}catch(a){c(a)}}),y=y+1|0;else{n=n+1|0;if(u=128===n)try{e(l,c)}catch(a){c(a)}else{try{e(l,c)}catch(a){c(a)}!0===u&&1===n&&H()}n=n-1|0}return h}function I(e){function l(h){0=== f&&(c=h,f=1,null!==d&&("function"===typeof d?d(h):d.forEach(t,h),d=null),g=null,null!==b&&("function"===typeof b?b():b.forEach(r),b=null))}var c,f=0,g=null,d=null,b=null,k=new B(function(h,a){if(0===f)return v(function(m,w){var C="function"===typeof h?function(){m(h(c))}:m,z="function"===typeof a?function(){w(a(c))}:w;null!==g?"function"===typeof g?g=[g,C]:g.push(C):g=C;null!==d?"function"===typeof d?d=[d,z]:d.push(z):d=z});try{return 2===f?"function"===typeof h?A(h(c)):x:"function"===typeof a?q(a(c)): x}catch(m){return q(m)}},function(h){if(0===f)return v(function(a){null!==d?"function"===typeof d?d=[d,function(){a(h(c))}]:d.push(function(){a(h(c))}):d=function(){a(h(c))};null!==g?"function"===typeof g?g=[g,a]:g.push(a):g=a});if(2===f)return A(c);try{return"function"===typeof h?A(h(c)):x}catch(a){return q(a)}},function(h){0===f?null!==b?"function"===typeof b?b=[b,h]:b.push(h):b=h:h();return k});try{e(function m(a){0===f&&(F(a)?a.then(m,l):(c=a,f=2,null!==g&&("function"===typeof g?g(a):g.forEach(t, a),g=null),null!==b&&("function"===typeof b?b():b.forEach(r),b=null),d=null))},l)}catch(h){l(h)}return k}function A(e){if("object"===typeof e&&null!==e&&"function"===typeof e.then)return e;var l=new B(function(c){if("function"!==typeof c)return l;if(!0===u)return I(function(g,d){D.push(function(){try{g(c(e))}catch(b){d(b)}});y=y+1|0});n=n+1|0;var f=null;try{(u=128===n)?D.push(function(){c(e)}):(f=c(e),!0===u&&1===n&&H())}catch(g){return q(g)}finally{n=n-1|0}return E(f)},function(){return l},function(c){if("function"=== typeof c)if(!0===u)D.push(c),y=y+1|0;else{n=n+1|0;try{(u=128===n)?(c(),u=!1):(c(),!0===u&&1===n&&H())}catch(f){return q(f)}finally{n=n-1|0}}return l});return l}function E(e){if("object"===typeof e&&null!==e&&"function"===typeof e.then)return e;var l=new B(function(c){try{return"function"===typeof c?A(c(e)):x}catch(f){return q(f)}},function(){return l},function(c){try{"function"===typeof c&&c()}catch(f){return q(f)}return l});return l}function q(e){if("object"===typeof e&&null!==e&&"function"===typeof e.then)return e; var l=new B(function(c,f){try{return"function"===typeof f?A(f(e)):x}catch(g){return q(g)}},function(c){try{return"function"===typeof c?A(c(e)):x}catch(f){return q(f)}},function(c){try{"function"===typeof c&&c()}catch(f){return q(f)}return l});return l}function K(e){return e===p?e.b=v:v}var D=[],F=v.isPromise=function(e){return"object"===typeof e&&null!==e&&"function"===typeof e.then},n=0,u=!1,y=0;O();O();var N=""+void 0!==typeof Symbol&&Symbol.toStringTag,x=A(void 0);"symbol"===typeof N&&(B.prototype[N]= "Promise");v.resolve=E;v.reject=q;v.race=function(e){return v(function(l,c){function f(h){d&&(d=0,l(h))}function g(h){d&&(d=0,c(h))}for(var d=1,b=0,k;b<e.length&&d;b=b+1|0)F(k=e[b])?k.then(f,g):f(k)})};v.all=function(e){return v(function(l,c){function f(m){a.then(function(w){k[m|0]=w;b=b-1|0;0===b&&l(k)},function(w){0<b&&(b=-1,c(w))})}for(var g=null,d=e.length|0,b=d,k=[],h=0,a;h<d;h=h+1|0)F(a=e[h])?(k[h]=g,f(h)):(b=b-1|0,k[h]=g=a);0===b&&l(k)})};"object"===typeof exports&&""+void 0!==typeof module? module.exports=v:typeof define==typeof K&&"function"===typeof define&&define.amd?define(K):K(p)})("object"==typeof self?self:"object"==typeof global?global:this);//AnonyCo //# sourceMappingURL=https://cdn.jsdelivr.net/gh/AnonyCo/SPromiseMeSpeed/dist/dist/SPromiseMeSpeed.min.js.map
module.exports={title:"Gitee",slug:"gitee",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Gitee</title><path d="M11.984 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.016 0zm6.09 5.333c.328 0 .593.266.592.593v1.482a.594.594 0 0 1-.593.592H9.777c-.982 0-1.778.796-1.778 1.778v5.63c0 .327.266.592.593.592h5.63c.982 0 1.778-.796 1.778-1.778v-.296a.593.593 0 0 0-.592-.593h-4.15a.592.592 0 0 1-.592-.592v-1.482a.593.593 0 0 1 .593-.592h6.815c.327 0 .593.265.593.592v3.408a4 4 0 0 1-4 4H5.926a.593.593 0 0 1-.593-.593V9.778a4.444 4.444 0 0 1 4.445-4.444h8.296Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://gitee.com/about_us",hex:"C71D23",guidelines:void 0,license:void 0};
const variables = [ 'PROCESS_ENV_KEY', 'ENV_FILE_KEY', 'LOCAL_ENV_FILE_KEY', 'ENV_FILE_LOCAL_OVERRIDE_TEST', 'PRODUCTION_ENV_FILE_KEY', 'LOCAL_PRODUCTION_ENV_FILE_KEY', 'DEVELOPMENT_ENV_FILE_KEY', 'LOCAL_DEVELOPMENT_ENV_FILE_KEY', 'ENV_FILE_DEVELOPMENT_OVERRIDE_TEST', 'ENV_FILE_DEVELOPMENT_LOCAL_OVERRIDEOVERRIDE_TEST', 'ENV_FILE_PRODUCTION_OVERRIDEOVERRIDE_TEST', 'ENV_FILE_PRODUCTION_LOCAL_OVERRIDEOVERRIDE_TEST', 'TEST_ENV_FILE_KEY', 'LOCAL_TEST_ENV_FILE_KEY', 'ENV_FILE_TEST_OVERRIDE_TEST', 'ENV_FILE_TEST_LOCAL_OVERRIDEOVERRIDE_TEST', ] export async function getServerSideProps() { const items = {} variables.forEach(variable => { if (process.env[variable]) { items[variable] = process.env[variable] } }) return { // Do not pass any sensitive values here as they will // be made PUBLICLY available in `pageProps` props: { env: items }, } } export default ({ env }) => <p>{JSON.stringify(env)}</p>
// Karma configuration module.exports = config => { config.set({ frameworks: [ // Reference: https://github.com/karma-runner/karma-jasmine // Set framework to jasmine 'jasmine' ], browsers: [ // Run tests using PhantomJS 'PhantomJS' ], files: [ 'src/scripts/tests.webpack.js' ], preprocessors: { // add webpack as preprocessor 'src/scripts/tests.webpack.js': ['webpack', 'sourcemap'] }, // TODO: Using 2.0.6 karma-webpack due to bug: // https://github.com/webpack-contrib/karma-webpack/issues/291 webpack: require('./webpack.config'), webpackMiddleware: { // webpack-dev-middleware configuration // i. e. stats: 'errors-only' }, singleRun: true }); };
import React from "react" import Header from "../components/Header" import Hero from "../components/Hero" import BlogComponent from "../components/BlogComponent" import FeedbackMail from "../components/FeedbackMail" import Footer from "../components/Footer" const blog = () => { return ( <> <Header /> <Hero title={"Blog"} buttons={[]} /> <BlogComponent /> <FeedbackMail /> <Footer /> </> ) } export default blog
Proj4js.defs["EPSG:32630"] = "+proj=utm +zone=30 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";
from __future__ import division, print_function import argparse import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import os import random def init_centroids(num_clusters, image): """ Initialize a `num_clusters` x image_shape[-1] nparray to RGB values of randomly chosen pixels of`image` Parameters ---------- num_clusters : int Number of centroids/clusters image : nparray (H, W, C) image represented as an nparray Returns ------- centroids_init : nparray Randomly initialized centroids """ # *** START YOUR CODE *** H, W, C = image.shape idx = np.random.randint(H * W, size=num_clusters) centroids_init = image[(idx / W).astype(int), idx % W].astype('float64') # *** END YOUR CODE *** return centroids_init def update_centroids(centroids, image, max_iter=30, print_every=10): """ Carry out k-means centroid update step `max_iter` times Parameters ---------- centroids : nparray The centroids stored as an nparray image : nparray (H, W, C) image represented as an nparray max_iter : int Number of iterations to run print_every : int Frequency of status update Returns ------- new_centroids : nparray Updated centroids """ # *** START YOUR CODE *** # raise NotImplementedError('update_centroids function not implemented') # Usually expected to converge long before `max_iter` iterations # Initialize `dist` vector to keep track of distance to every centroid # Loop over all centroids and store distances in `dist` # Find closest centroid and update `new_centroids` # Update `new_centroids` H, W, C = image.shape idx = np.zeros((H, W)) it = 0 while it < max_iter: it += 1 if it % print_every == 0: print(f'Update centroids for {it} iterations') for i in range(H): for j in range(W): idx[i, j] = np.argmin(np.linalg.norm(centroids - image[i, j], axis=1)) ''' # Print loss which should be monotonically decreasing loss = 0 for i in range(H): for j in range(W): loss += np.linalg.norm(centroids[int(idx[i,j])] - image[i, j]) print(loss / (H*W)) ''' for k in range(centroids.shape[0]): pixel_group = image[idx==k] if pixel_group.shape[0] > 0: centroids[k] = pixel_group.mean(axis=0) new_centroids = centroids.astype(int) # *** END YOUR CODE *** return new_centroids def update_image(image, centroids): """ Update RGB values of pixels in `image` by finding the closest among the `centroids` Parameters ---------- image : nparray (H, W, C) image represented as an nparray centroids : int The centroids stored as an nparray Returns ------- image : nparray Updated image """ # *** START YOUR CODE *** # raise NotImplementedError('update_image function not implemented') # Initialize `dist` vector to keep track of distance to every centroid # Loop over all centroids and store distances in `dist` # Find closest centroid and update pixel value in `image` H, W, C = image.shape for i in range(H): for j in range(W): image[i, j] = centroids[np.argmin(np.linalg.norm(centroids - image[i, j], axis=1))] # *** END YOUR CODE *** return image def main(args): # Setup max_iter = args.max_iter print_every = args.print_every image_path_small = args.small_path image_path_large = args.large_path num_clusters = args.num_clusters figure_idx = 0 # Load small image image = np.copy(mpimg.imread(image_path_small)) print('[INFO] Loaded small image with shape: {}'.format(np.shape(image))) plt.figure(figure_idx) figure_idx += 1 plt.imshow(image) plt.title('Original small image') plt.axis('off') savepath = os.path.join('.', 'orig_small.png') plt.savefig(savepath, transparent=True, format='png', bbox_inches='tight') # Initialize centroids print('[INFO] Centroids initialized') centroids_init = init_centroids(num_clusters, image) # Update centroids print(25 * '=') print('Updating centroids ...') print(25 * '=') centroids = update_centroids(centroids_init, image, max_iter, print_every) # Load large image image = np.copy(mpimg.imread(image_path_large)) image.setflags(write=1) print('[INFO] Loaded large image with shape: {}'.format(np.shape(image))) plt.figure(figure_idx) figure_idx += 1 plt.imshow(image) plt.title('Original large image') plt.axis('off') savepath = os.path.join('.', 'orig_large.png') plt.savefig(fname=savepath, transparent=True, format='png', bbox_inches='tight') # Update large image with centroids calculated on small image print(25 * '=') print('Updating large image ...') print(25 * '=') image_clustered = update_image(image, centroids) plt.figure(figure_idx) figure_idx += 1 plt.imshow(image_clustered) plt.title('Updated large image') plt.axis('off') savepath = os.path.join('.', 'updated_large.png') plt.savefig(fname=savepath, transparent=True, format='png', bbox_inches='tight') print('\nCOMPLETE') plt.show() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--small_path', default='./peppers-small.tiff', help='Path to small image') parser.add_argument('--large_path', default='./peppers-large.tiff', help='Path to large image') parser.add_argument('--max_iter', type=int, default=150, help='Maximum number of iterations') parser.add_argument('--num_clusters', type=int, default=16, help='Number of centroids/clusters') parser.add_argument('--print_every', type=int, default=10, help='Iteration print frequency') args = parser.parse_args() main(args)
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. */ import angular from 'angular'; import _ from 'lodash'; import expect from 'expect.js'; import ngMock from 'ng_mock'; import $ from 'jquery'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; import LineVisTypeProvider from '../../line'; import { VisProvider } from 'ui/vis'; import { AggConfig } from 'ui/vis/agg_config'; describe('point series editor', function () { let $parentScope; let $container; let $elem; let lineVisType; let Vis; let indexPattern; function makeConfig() { return { type: 'line', params: lineVisType.visConfig.defaults, aggs: [ { type: 'count', schema: 'metric', params: { field: 'bytes' } }, { type: 'terms', schema: 'segment', params: { field: 'machine.os' } }, ], listeners: { click: _.noop } }; } beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function ($rootScope, $compile, Private) { lineVisType = Private(LineVisTypeProvider); Vis = Private(VisProvider); indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); $parentScope = $rootScope; $parentScope.vis = new Vis(indexPattern, makeConfig()); $parentScope.editorState = { params: $parentScope.vis.params, aggs: $parentScope.vis.aggs, }; $parentScope.savedVis = {}; // share the scope //_.defaults($parentScope, $rootScope, Object.getPrototypeOf($rootScope)); $container = $(document.createElement('div')) .appendTo('body'); // make the element $elem = angular.element('<div><vislib-series></vislib-series><vislib-value-axes>' + '</vislib-value-axes><vislib-category-axis></vislib-category-axis></div>'); $container.append($elem); // compile the html $compile($elem)($parentScope); // Digest everything $elem.scope().$digest(); })); afterEach(function () { $container.remove(); }); it('should show correct series', function () { expect($parentScope.editorState.params.seriesParams.length).to.be(1); expect($parentScope.editorState.params.seriesParams[0].data.label).to.be('Count'); }); it('should update series when new agg is added', function () { const aggConfig = new AggConfig($parentScope.vis.aggs, { type: 'avg', schema: 'metric', params: { field: 'bytes' } }); $parentScope.vis.aggs.push(aggConfig); $parentScope.$digest(); expect($parentScope.editorState.params.seriesParams.length).to.be(2); }); it('should only allow left and right value axis position when category axis is horizontal', function () { expect($parentScope.isPositionDisabled('top')).to.be(true); expect($parentScope.isPositionDisabled('bottom')).to.be(true); expect($parentScope.isPositionDisabled('left')).to.be(false); expect($parentScope.isPositionDisabled('right')).to.be(false); }); it('should only allow top and bottom value axis position when category axis is vertical', function () { $parentScope.editorState.params.categoryAxes[0].position = 'left'; $parentScope.$digest(); expect($parentScope.editorState.params.valueAxes[0].position).to.be('bottom'); expect($parentScope.isPositionDisabled('top')).to.be(false); expect($parentScope.isPositionDisabled('bottom')).to.be(false); expect($parentScope.isPositionDisabled('left')).to.be(true); expect($parentScope.isPositionDisabled('right')).to.be(true); }); it('should add value axis', function () { $parentScope.addValueAxis(); expect($parentScope.editorState.params.valueAxes.length).to.be(2); }); it('should remove value axis', function () { $parentScope.addValueAxis(); $parentScope.removeValueAxis({ id: 'ValueAxis-2' }); expect($parentScope.editorState.params.valueAxes.length).to.be(1); }); it('should not allow to remove the last value axis', function () { $parentScope.removeValueAxis({ id: 'ValueAxis-1' }); expect($parentScope.editorState.params.valueAxes.length).to.be(1); }); it('should set the value axis title if its not set', function () { $parentScope.updateAxisTitle(); expect($parentScope.editorState.params.valueAxes[0].title.text).to.equal('Count'); }); it('should not update the value axis title if custom title was set', function () { $parentScope.editorState.params.valueAxes[0].title.text = 'Custom Title'; $parentScope.updateAxisTitle(); expect($parentScope.editorState.params.valueAxes[0].title.text).to.equal('Custom Title'); }); it('should set the custom title to match the value axis label when only one agg exists for that axis', function () { $parentScope.editorState.aggs[0].params.customLabel = 'Custom Label'; $parentScope.updateAxisTitle(); expect($parentScope.editorState.params.valueAxes[0].title.text).to.equal('Custom Label'); }); it('should not set the custom title to match the value axis label when more than one agg exists for that axis', function () { const aggConfig = new AggConfig($parentScope.vis.aggs, { type: 'avg', schema: 'metric', params: { field: 'bytes' } }); $parentScope.vis.aggs.push(aggConfig); $parentScope.$digest(); $parentScope.editorState.aggs[0].params.customLabel = 'Custom Label'; $parentScope.updateAxisTitle(); expect($parentScope.editorState.params.valueAxes[0].title.text).to.equal('Count'); }); it('should not overwrite the custom title with the value axis label if the custom title has been changed', function () { $parentScope.editorState.params.valueAxes[0].title.text = 'Custom Title'; $parentScope.editorState.aggs[0].params.customLabel = 'Custom Label'; $parentScope.updateAxisTitle(); expect($parentScope.editorState.params.valueAxes[0].title.text).to.equal('Custom Title'); }); it('should overwrite the custom title when the agg type changes', function () { const aggConfig = new AggConfig($parentScope.vis.aggs, { type: 'avg', schema: 'metric', params: { field: 'bytes' } }); $parentScope.editorState.params.valueAxes[0].title.text = 'Custom Title'; $parentScope.editorState.aggs[0].params.customLabel = 'Custom Label'; $parentScope.updateAxisTitle(); $parentScope.vis.aggs.push(aggConfig); $parentScope.vis.aggs.shift(); $parentScope.$digest(); $parentScope.updateAxisTitle(); expect($parentScope.editorState.params.valueAxes[0].title.text).to.equal('Average bytes'); }); });
/* jQWidgets v13.2.0 (2022-Jan) Copyright (c) 2011-2022 jQWidgets. License: https://jqwidgets.com/license/ */ /* eslint-disable */ (function(a){a.jqx.jqxWidget("jqxDocking","",{});a.extend(a.jqx._jqxDocking.prototype,{defineInstance:function(){var b={orientation:"horizontal",mode:"default",floatingWindowOpacity:0.3,panelsRoundedCorners:true,disabled:false,width:"auto",height:"auto",windowsMode:null,cookies:false,cookieOptions:{},windowsOffset:5,rtl:false,keyboardNavigation:false,_windowOptions:{},_draggedFired:false,_dragging:false,_draggingItem:null,_panels:[],_windows:[],_indicator:null,_events:["dragEnd","dragStart"]};if(this===a.jqx._jqxDocking.prototype){return b}a.extend(true,this,b);return b},createInstance:function(){if(!this.host.jqxWindow){throw new Error("jqxDocking: Missing reference to jqxwindow.js.")}this._refresh(true);if(this.disabled){this.disabled=false;this.disable()}},refresh:function(b){if(b==true){return}this._performLayout()},_refresh:function(c){this._render();this._removeClasses();this._addClasses();this._setWindowsOptions(true);this._performLayout();this._cookieHandler();this._cookieExporter();this._removeEventListeners();this._addEventListeners();var b=a.Event("resize");this.host.trigger(b)},resize:function(){this._refresh()},_addClasses:function(){this.host.addClass("jqx-docking");for(var b=0;b<this._panels.length;b+=1){this._panels[b].addClass(this.toThemeProperty("jqx-docking-panel"));if(this.panelsRoundedCorners){this._panels[b].addClass(this.toThemeProperty("jqx-rc-all"))}}for(var b=0;b<this._windows.length;b+=1){this._windows[b].addClass(this.toThemeProperty("jqx-docking-window"))}},_removeClasses:function(){this.host.removeClass("jqx-docking");for(var b=0;b<this._panels.length;b+=1){this._panels[b].removeClass(this.toThemeProperty("jqx-docking-panel"));this._panels[b].removeClass(this.toThemeProperty("jqx-rc-all"))}for(var b=0;b<this._windows.length;b+=1){this._windows[b].removeClass(this.toThemeProperty("jqx-docking-window"))}},_render:function(){var b=this.host.children("div"),d;for(var c=0;c<b.length;c+=1){this._panels.push(a(b[c]));this._renderWindows(a(b[c]))}},focus:function(b){if(this.focusedWindow){a(this.focusedWindow).removeClass(this.toThemeProperty("jqx-fill-state-focus"))}if(!a.isEmptyObject(b)&&a.type(b)==="string"&&a("#"+b).length>0){this.focusedWindow=a("#"+b)[0]}else{this.focusedWindow=this._windows[0][0]}a(this.focusedWindow).addClass(this.toThemeProperty("jqx-fill-state-focus"));this.host.focus()},_renderWindows:function(b){var f=b.children("div");for(var d=0;d<f.length;d+=1){this._windows.push(a(f[d]));a(f[d]).jqxWindow({keyboardNavigation:false,rtl:this.rtl,theme:this.theme,enableResize:false,width:a(f[d]).css("width"),maxWidth:Number.MAX_VALUE});a(f[d]).detach();b.append(a(f[d]))}b.append('<div class="spacer" style="clear: both;"></div>');var e=this;if(this.keyboardNavigation){var c=function(i){if(i.keyCode===13){if(e.focusedWindow&&a(e.focusedWindow).jqxWindow("showCollapseButton")){a(e.focusedWindow).jqxWindow("_collapseButton").trigger("click")}}else{if((e.focusedWindow&&i.keyCode===27&&a(e.focusedWindow).jqxWindow("keyboardCloseKey")==="esc")||(e.focusedWindow&&a(e.focusedWindow).jqxWindow("keyboardCloseKey")==i.keyCode)){a(e.focusedWindow).jqxWindow("closeWindow",i)}}if(i.keyCode===9){if(e.focusedWindow==null){e.focusedWindow=e._windows[0];a(e.focusedWindow).focus();i.stopPropagation()}else{var g=-1;a.each(e._windows,function(j,k){if(this[0]==e.focusedWindow){g=j}});if(i.shiftKey){g--}else{g++}if(g>=e._windows.length||g<0){a(e.focusedWindow).removeClass(e.toThemeProperty("jqx-fill-state-focus"));e.focusedWindow=null;i.stopPropagation();return true}var h=e._windows[g];if(!h){h=e._windows[0]}a(e.focusedWindow).removeClass(e.toThemeProperty("jqx-fill-state-focus"));e.focusedWindow=h[0];a(e.focusedWindow).focus()}a(e.focusedWindow).addClass(e.toThemeProperty("jqx-fill-state-focus"));if(i.preventDefault){i.preventDefault();i.stopPropagation()}}};a.each(e._windows,function(h,i){var g=a(this);e.removeHandler(g,"focus");e.removeHandler(g,"blur");e.removeHandler(g,"mousedown");e.addHandler(g,"mousedown",function(j){if(e.focusedWindow){a(e.focusedWindow).removeClass(e.toThemeProperty("jqx-fill-state-focus"))}e.focusedWindow=g[0];a(e.focusedWindow).addClass(e.toThemeProperty("jqx-fill-state-focus"));a(e.focusedWindow).focus()});e.addHandler(g,"focus",function(j){if(e.focusedWindow){a(e.focusedWindow).removeClass(e.toThemeProperty("jqx-fill-state-focus"))}e.focusedWindow=g[0];a(e.focusedWindow).addClass(e.toThemeProperty("jqx-fill-state-focus"))});e.addHandler(g,"blur",function(j){if(a(document.activeElement).ischildof(a(g))){return true}a(g).removeClass(e.toThemeProperty("jqx-fill-state-focus"))});e.removeHandler(g,"keydown");e.addHandler(g,"keydown",function(j){c(j)})});this.removeHandler(this.host,"keydown");this.addHandler(this.host,"keydown",function(g){c(g)});this.removeHandler(this.host,"blur");this.addHandler(this.host,"blur",function(g){if(e.focusedWindow){a(e.focusedWindow).removeClass(e.toThemeProperty("jqx-fill-state-focus"));e.focusedWindow=null}})}},_performLayout:function(){this.host.css("width",this.width);this.host.css("height",this.height);this._performWindowsLayout();this._performPanelsLayout();this._performWindowsLayout()},_performPanelsLayout:function(){this.host.css("overflow","hidden");var b,e=this.host.width(),c=0;for(var d=0;d<this._panels.length;d+=1){b=this._panels[d];b.css("height","auto");b.css("min-width","auto");b[0].style.width="auto";if(this.orientation==="vertical"){b.css("width","auto");b.css("float","none")}else{c+=this._handleHorizontalSize(b,c,e);if(d>0){b.css("margin-left",-this.windowsOffset)}}}if(this.orientation==="horizontal"){if(c<e){this._fillContainer(e,c)}}},_handleHorizontalSize:function(c,d,i){var f=i/this._panels.length,e,h=(c.outerWidth()-c.width());c.css("float","left");if(c[0].style.width==="auto"||parseInt(c.css("width"),10)===0){var g=h/i*100;var b=99.99/this._panels.length;c[0].style.width=b+"%";return c.outerWidth()}if(d+c.outerWidth()>=i){if(d+f<i){e=f-h;c.css("min-width",e);c.width(e)}else{e=c.width()-((d+c.outerWidth())-i);c.css("min-width",e);c.width(e)}}return c.outerWidth()},_fillContainer:function(f,b){var d=this._panels.length,e=this._panels[d-1],c=f-b+e.width();if(a.jqx.browser.msie&&a.jqx.browser.version<9){c-=this._panels.length}return;e.width(c)},_performWindowsLayout:function(){var b;for(var c=0;c<this._windows.length;c+=1){b=this._getWindowOptions(this._windows[c]);if(this._windows[c].ischildof(this.host)){if(b){if(b.mode!=="floating"){this._windows[c].css("margin",this.windowsOffset);this._windows[c].css("position","static")}}else{if(this.mode!=="floating"){this._windows[c].css("position","static");this._windows[c].css("margin",this.windowsOffset)}}}this._setWindowSize(this._windows[c],b)}},_setWindowSize:function(d,c){if(c.mode!=="floating"){if(d.ischildof(this.host)){var b=d.parent().width()-(d.outerWidth()-d.width())-2*this.windowsOffset;if(this.orientation==="vertical"){d.jqxWindow("width",b)}else{d.jqxWindow("width",b)}}}this._setWindowOption(d,"size",{width:d.width(),height:d.height()})},_setWindowsOptions:function(b){for(var f=0;f<this._windows.length;f+=1){var g,c=this._windows[f].attr("id"),d=this._getWindowOptions(c);if(!b){var e="TEDX"}g=null;if(this.windowsMode&&this.windowsMode.hasOwnProperty(c)){g=this.windowsMode[c];this._setWindowOption(this._windows[f],"mode",g)}else{if(typeof d!=="undefined"&&typeof d.mode==="undefined"){g=this.mode;this._setWindowOption(this._windows[f],"mode",g)}}if(b){this._setWindowOption(this._windows[f],"resizable",true);if(g=="floating"){this._windows[f].jqxWindow({enableResize:true})}else{this._windows[f].jqxWindow({enableResize:false})}this._setWindowOption(this._windows[f],"size",{height:this._windows[f].height(),width:this._windows[f].width()})}}},_removeEventListeners:function(){for(var b=0;b<this._windows.length;b+=1){this.removeHandler(this._windows[b],"moving",this._itemDragging);this.removeHandler(this._windows[b],"moved",this._itemDrop);this.removeHandler(this._windows[b],"resized",this._itemResized);this.removeHandler(this._windows[b],"collapse",this._collapsed);this.removeHandler(this._windows[b],"expand",this._expanded)}},_addEventListeners:function(){for(var b=0;b<this._windows.length;b+=1){this._addEventListenersTo(this._windows[b])}var c=this;a.jqx.utilities.resize(this.host,function(){c._performLayout()})},_addEventListenersTo:function(b){this.addHandler(b,"moving",this._itemDragging,{self:this});this.addHandler(b,"moved",this._itemDrop,{self:this});this.addHandler(b,"resized",this._itemResized,{self:this});this.addHandler(b,"collapse",this._collapsed,{self:this});this.addHandler(b,"expand",this._expanded,{self:this})},_itemDragging:function(g){var d=g.data.self,f=a(g.target),e=d._getWindowOptions(f);f.removeClass(d.toThemeProperty("jqx-docking-window"));f.css("margin","0px");if(!d._dragging){d._prepareForDragging(f)}if(e.mode==="floating"){return}var b={x:g.args.pageX,y:g.args.pageY},c=d._getMouseOverPanel(b);if(c){d._mouseOverPanel(c,b)}else{d._mouseLeavePanel()}if(!d._draggedFired){d._raiseEvent(1,{window:a(f).attr("id")});d._draggedFired=true}return true},_prepareForDragging:function(c){this._dragging=true;var b={parent:c.parent(),next:c.next(),prev:c.prev()};this._setWindowOption(c,"lastPosition",b);c.detach();a(document.body).append(c);this._setDraggingStyles(c);this._draggingItem=c},_setDraggingStyles:function(b){b.css({position:"absolute",left:b.offset().left,top:b.offset().top});b.fadeTo(0,this.floatingWindowOpacity)},_getMouseOverPanel:function(c){var e,b,g,f;for(var d=0;d<this._panels.length;d+=1){if(this._isMouseOverItem(this._panels[d],c,false)){return this._panels[d]}}return null},_mouseOverPanel:function(c,b){if(this._dragging){var e=c.children("div"),d=this._getHoverWindow(b,e);if(d==="indicator"){return}var f=this._centerOffset(d,b);this._handleIndicator(c,d,f)}},_getHoverWindow:function(c,f){var e,b,h,g;if(this._isMouseOverItem(this._indicator,c,true)){return"indicator"}for(var d=0;d<f.length;d+=1){if(this._isMouseOverItem(a(f[d]),c,true)){return a(f[d])}}return null},_centerOffset:function(f,b){if(f){var e={x:f.offset().left,y:f.offset().top},g=f.height(),d=f.width(),c;c=e.y+g/2;if(b.y>c){return"next"}return"prev"}return"all"},_handleIndicator:function(c,d,e){var b=this._getIndicator(d);if(e==="all"){if(this.orientation==="vertical"){b.insertBefore(c.children(".spacer"))}else{c.append(b)}}else{if(e==="prev"){b.insertBefore(d)}else{b.insertAfter(d)}}this._resizeIndicator(b,c)},_getIndicator:function(){var b=this._indicator;if(!b){b=a('<div class="'+this.toThemeProperty("jqx-docking-drop-indicator")+'"></div>')}this._indicator=b;this._indicator.css("margin",this.windowsOffset);if(this.orientation==="vertical"){this._indicator.css("float","left")}return b},_resizeIndicator:function(c,b){if(this.orientation==="horizontal"){c.width(b.width()-(c.outerWidth(true)-c.width()));c.height(this._draggingItem.height())}else{c.width(this._draggingItem.width());c.height(this._draggingItem.height())}},_mouseLeavePanel:function(b){if(this._indicator){this._indicator.remove();this._indicator=null}},_itemDrop:function(d){var b=d.data.self,c=a(d.currentTarget);b._dragging=false;if(b._indicator){c.detach();c.insertAfter(b._indicator);b._indicator.remove();b._dropFixer(c)}else{b._dropHandler(c)}c.fadeTo(0,1);c.focus();b._indicator=null;b._cookieExporter();b._draggedFired=false;b._raiseEvent(0,{window:c.attr("id")})},_dropFixer:function(b){b.css("position","static");b.addClass(this.toThemeProperty("jqx-docking-window"));b.css("margin",this.windowsOffset);b.jqxWindow("enableResize",false);if(this.orientation==="horizontal"){this._fixWindowSize(b)}},_dropHandler:function(c){var b=this._getWindowOptions(c);if(this.mode==="docked"){this._dropDocked(c)}else{this._dropFloating(c)}},_dropDocked:function(d){var c=this._getWindowOptions(d),b=c.lastPosition;d.detach();if(b.next[0]){d.insertBefore(b.next)}else{if(b.prev[0]){d.insertAfter(b.prev)}else{b.parent.append(d)}}this._dropFixer(d)},_fixWindowSize:function(b){a(b).jqxWindow({width:b.parent().width()-(b.outerWidth()-b.width())-2*parseInt(this.windowsOffset,10)})},_itemResized:function(d){var b=d.data.self,c=a(d.currentTarget);b._setWindowOption(c,"size",{width:d.args.width,height:d.args.height});b._cookieExporter()},_dropFloating:function(c){var b;if(!a(c).jqxWindow("collapsed")){b=this._getWindowOptions(c);a(c).jqxWindow("enableResize",b.resizable)}a(document.body).append(c);this._restoreWindowSize(c)},_restoreWindowSize:function(c){var b=this._getWindowOptions(c);a(c).jqxWindow({width:b.size.width})},_isMouseOverItem:function(i,e,d){if(!i){return false}var j=i.outerWidth(true),g=i.outerHeight(true),b=i.width(),h=i.height(),f=i.offset().top,c=i.offset().left;if(d){f-=(g-h)/2;c-=(j-b)/2;b=j;h=g}if((c<=e.x&&c+b>=e.x)&&(f<=e.y&&f+h+2*this._draggingItem.height()/3>=e.y)){return true}return false},_cookieHandler:function(){if(this.cookies){var b=a.jqx.cookie.cookie("jqxDocking"+this.element.id);if(b!==null){this.importLayout(b);this.layoutImported=true}}},_cookieExporter:function(){if(this.cookies){a.jqx.cookie.cookie("jqxDocking"+this.element.id,this.exportLayout(),this.cookieOptions)}},_indexOf:function(c,d){for(var b=0;b<d.length;b+=1){if(c[0]===d[b][0]){return b}}return -1},_exportFixed:function(){var e=[],g="",b,f;for(var d=0;d<this._panels.length;d+=1){g+='"panel'+d+'": {';b=this._panels[d].children();for(var c=0;c<b.length;c+=1){f=a(b[c]);if(f.attr("id")){e.push(f);g+='"'+f.attr("id")+'":{"collapsed":'+f.jqxWindow("collapsed")+"},"}}if(b.length>1){g=g.substring(0,g.length-1)}g+="},"}g=g.substring(0,g.length-1);return{JSON:g,children:e}},_exportFloating:function(c){var e="",d;e+='"floating":{';for(var b=0;b<this._windows.length;b+=1){d=a(this._windows[b]);if(this._indexOf(d,c)===-1){e+='"'+d.attr("id")+'":{"x":"'+d.css("left")+'","y":"'+d.css("top")+'","width":"'+d.jqxWindow("width")+'","height":"'+d.jqxWindow("height")+'","collapsed":'+d.jqxWindow("collapsed")+"},"}}if(e.substring(e.length-1,e.length)===","){e=e.substring(0,e.length-1)}e+="}";return e},_importFixed:function(d){for(var e in d){if(e!=="orientation"&&e!=="floating"&&d.hasOwnProperty(e)){var b=e.substring(e.length-1,e.length);b=parseInt(b,10);var c=d[e];for(var e in c){a("#"+e).css("position","static");if(c[e].collapsed){(function(f){setTimeout(function(){a("#"+f).jqxWindow("collapsed",true)},0)}(e))}this._panels[b].append(a("#"+e));if(this.orientation==="horizontal"){this._fixWindowSize(a("#"+e))}}}}},_importFloating:function(d){var f=d.floating,c,b;for(var e in f){if(f.hasOwnProperty(e)){a("#"+e).css("position","absolute");a(document.body).append(a("#"+e));b=this._dragging;a("#"+e).jqxWindow("move",f[e].x,f[e].y);this._dragging=b;a("#"+e).jqxWindow("width",f[e].width);a("#"+e).jqxWindow("height",f[e].height);a("#"+e).jqxWindow("enableResize",true);this._setWindowsOptions(true);(function(g){setTimeout(function(){a("#"+g).jqxWindow("collapsed",f[g].collapsed)},0)}(e));a("#"+e).fadeTo(0,1)}}},_getWindowOptions:function(b){if(typeof b==="object"&&b!==null){if(b.length>0){b=b.attr("id")}else{b=b.id}}return this._windowOptions[b]},_setWindowOption:function(c,b,d){if(typeof c==="object"&&c!==null){if(c.length>0){c=c.attr("id")}else{c=c.id}}if(typeof this._windowOptions[c]==="undefined"){this._windowOptions[c]={}}this._windowOptions[c][b]=d;if(b==="mode"){this.setWindowMode(c,d)}},_expanded:function(c){var b=c.data.self;b._cookieExporter()},_collapsed:function(c){var b=c.data.self;b._cookieExporter()},_raiseEvent:function(b){var c=a.Event(this._events[b]);c.args=arguments[1];return this.host.trigger(c)},_moveWindow:function(e,c,b){var d=c.children();var g=null;var f=0;a.each(d,function(h){if(a(this).css("position")=="static"){if(f==b&&this!=e[0]){g=this}f++}});if(f<=b){e.appendTo(c)}else{if(g!=null){e.insertBefore(g)}}e.css("position","static")},propertyChangedHandler:function(b,c,e,d){switch(c){case"rtl":a.each(b._windows,function(){this.jqxWindow({rtl:d})});break;case"theme":a.each(b._windows,function(){this.jqxWindow({theme:d})});break;case"orientation":case"height":case"width":b._performLayout();b._cookieExporter();break;case"panelsRoundedCorners":b._removeClasses();b._addClasses();break;case"disabled":if(d){b.disabled=false;b.disable()}else{b.disabled=true;b.enable()}break;case"windowsMode":case"mode":b._setWindowsOptions(false);break;case"cookies":b._cookieExporter();break;case"windowsOffset":b._performLayout();break}},destroy:function(){this._removeEventListeners();this.host.remove();this.windowsMode=null;this.cookieOptions=null;this._windowOptions=null;this._panels=null;this._windows=null;this._events=null},disable:function(){if(!this.disabled){this.disabled=true;this._removeEventListeners();for(var b=0;b<this._windows.length;b+=1){this._windows[b][0].style.opacity="";a(this._windows[b]).jqxWindow("disable")}}},enable:function(){if(this.disabled){this.disabled=false;this._addEventListeners();for(var b=0;b<this._windows.length;b+=1){a(this._windows[b]).jqxWindow("enable")}}},move:function(f,c,b){var c=this._panels[c];if(!c){return}var e=a(c.children(".spacer")),d;e.detach();f=a("#"+f);d=this._getWindowOptions(f);if(d.mode==="floating"){return}else{this._moveWindow(f,c,b)}c.append(e);this._cookieExporter();this._dropFixer(f)},exportLayout:function(){var c="{",b=this._exportFixed();c+=b.JSON+","+this._exportFloating(b.children)+',"orientation": "'+this.orientation+'"';c+="}";return c},importLayout:function(g){try{var f=a.parseJSON(g),b,c;this.orientation=f.orientation;this._performLayout();this._importFixed(f);this._importFloating(f)}catch(d){alert("Invalid JSON string.")}},setWindowMode:function(c,d){var c=a("#"+c),b=this._getWindowOptions(c);if(d==="floating"){c.css("position","absolute");this._windowOptions[c.attr("id")]["mode"]=d}else{if(b.mode==="floating"&&c.css("position")==="absolute"){if(b.lastPosition){this._dropDocked(c)}else{this._panels[0].append(c);this._dropFixer(c)}}}this._windowOptions[c.attr("id")]["mode"]=d},hideCloseButton:function(b){a("#"+b).jqxWindow("showCloseButton",false)},showCloseButton:function(b){a("#"+b).jqxWindow("showCloseButton",true)},hideCollapseButton:function(b){a("#"+b).jqxWindow("showCollapseButton",false)},showCollapseButton:function(b){a("#"+b).jqxWindow("showCollapseButton",true)},expandWindow:function(b,c){a("#"+b).jqxWindow("expand",c)},collapseWindow:function(b,c){a("#"+b).jqxWindow("collapse",c)},setWindowProperty:function(c,b,d){a("#"+c).jqxWindow(b,d)},getWindowProperty:function(c,b){return a("#"+c).jqxWindow(b)},setWindowPosition:function(d,b,e){var d=a("#"+d),c=this._getWindowOptions(d);if(c.mode==="floating"){d.css("position","absolute");a(d).jqxWindow("move",b,e,null,false)}},hideAllCloseButtons:function(){for(var b=0;b<this._windows.length;b+=1){this._windows[b].jqxWindow("showCloseButton",false)}},hideAllCollapseButtons:function(){for(var b=0;b<this._windows.length;b+=1){this._windows[b].jqxWindow("showCollapseButton",false)}},showAllCloseButtons:function(){for(var b=0;b<this._windows.length;b+=1){this._windows[b].jqxWindow("showCloseButton",true)}},showAllCollapseButtons:function(){for(var b=0;b<this._windows.length;b+=1){this._windows[b].jqxWindow("showCollapseButton",true)}},pinWindow:function(b){a("#"+b).jqxWindow("draggable",false)},unpinWindow:function(b){a("#"+b).jqxWindow("draggable",true)},setDraggingMode:function(c){var b=a("#"+c);this._prepareForDragging(b);b.fadeTo(0,1)},enableWindowResize:function(b){b=a("#"+b);if(b.css("position")==="absolute"){this._setWindowOption(b,"resizable",true);b.jqxWindow("enableResize",true)}},disableWindowResize:function(b){b=a("#"+b);this._setWindowOption(b,"resizable",false);b.jqxWindow("enableResize",false)},addWindow:function(e,f,d,c){var b="#"+e;a(b).jqxWindow({keyboardNavigation:false,rtl:this.rtl,theme:this.theme,enableResize:false,width:a(b).css("width"),maxWidth:Number.MAX_VALUE});this._panels[0].append(a(b));this._windows.push(a(b));if(f){this._setWindowOption(a(b),"mode",f)}else{this._setWindowOption(a(b),"mode",this.mode)}this._setWindowOption(a(b),"resizable",true);this._setWindowOption(a(b),"size",{width:a(b).width(),height:a(b).height()});if(f=="floating"){a(b).jqxWindow({enableResize:true})}else{a(b).jqxWindow({enableResize:false})}if(this._panels[d]!=null){this._setWindowOption(a(b),"size",{width:this._panels[d].width(),height:this._panels[d].height()})}this._addEventListenersTo(a(b));if(typeof d!=="undefined"&&typeof c!=="undefined"){this.move(e,d,c)}this._dropFixer(a(b))},closeWindow:function(b){a("#"+b).jqxWindow("closeWindow")}})})(jqxBaseFramework);
import sys from psutil import virtual_memory import numpy as np import tensorflow as tf import pandas as pd from tensorflow.keras.losses import categorical_crossentropy from tensorflow.keras.models import Model from sklearn.model_selection import train_test_split class LCAWrap(Model): def __init__(self, *args, **kwargs): try: self.layer_names = kwargs['layer_names'] del kwargs['layer_names'] except: self.layer_names = None try: self.lca_type = kwargs['lca_type'] del kwargs['lca_type'] except: self.lca_type = 'Mean' super(LCAWrap, self).__init__(**kwargs) self.LCA_vals = {} self.last_LCA = None self.memory_threshold = .9 self.lca_save = False self.df = None self.max_occurence = None self.variable_names = None self.Weights = False self.OldWeights = False if not self.layer_names: self.get_layer_names() self.get_variable_names() else: self.get_variable_names() self.variable_index() def setup_lca_save(self, path, basename, occurence): self.path = path self.basename = basename self.max_occurence = occurence self.lca_save = True def Fit(self, new_fitting=None, **kwargs): self.check_memory() epochs = kwargs['epochs'] del kwargs['epochs'] self.OldWeights = self.get_weights() if 'validation_data' not in kwargs.keys(): X_train, x_test, Y_train, y_test = train_test_split(kwargs['x'], kwargs['y'], test_size=kwargs['validation_split']) kwargs['x'] = X_train kwargs['y'] = Y_train kwargs['validation_data'] = (x_test, y_test) del kwargs['validation_split'] else: x_test = kwargs['validation_data'][0] y_test = kwargs['validation_data'][1] self.x_test = np.asarray(x_test).astype('float32') self.y_test = y_test # print('Y_test shape:',y_test.shape) self.epochs = epochs for j in range(0, epochs): self.current_epoch = j assert self.single_epoch_size < virtual_memory()[1], "LCA will fill into swap this epoch" if not new_fitting: self.fit(**kwargs, epochs=1) else: new_fitting(**kwargs, epoch=1) self.get_grads() self.Weights = self.get_weights() self.last_LCA = self.get_LCA() self.OldWeights = self.Weights def lca_stream(self, path='', basename='', save_occurence=None, lca=None): # temp_df = pd.DataFrame(lca,index=[self.current_epoch]) temp_df = pd.DataFrame(columns=lca.keys(), dtype=object) for item in lca.keys(): temp_df.loc[self.current_epoch, item] = lca[item] if self.df is not None: self.df = pd.concat([self.df, temp_df]) else: self.df = temp_df if ( self.current_epoch % save_occurence == 0 and self.current_epoch != 0) or self.current_epoch == self.epochs - 1: self.df.to_hdf(path + basename + str(int(self.current_epoch - save_occurence)) + '.h5', key=(str(self.current_epoch - save_occurence))) self.df = None def get_grads(self): with tf.GradientTape() as tape: pred = self(self.x_test) loss = categorical_crossentropy(self.y_test, pred) return tape.gradient(loss, self.trainable_variables) def variable_index(self): listOfVariableTensors = self.trainable_weights self.trainable_numbers = {} for l in range(0, len(listOfVariableTensors)): if listOfVariableTensors[l].name in self.variable_names: self.trainable_numbers[l] = listOfVariableTensors[l].name def get_weights(self): listOfVariableTensors = self.trainable_weights Weights = {} for l in range(0, len(listOfVariableTensors)): if listOfVariableTensors[l].name in self.variable_names: Weights[listOfVariableTensors[l].name] = listOfVariableTensors[l].value() return Weights def calculate_mean_LCA(self): if not self.OldWeights: return 'Model hasnt been run or oldweights have been lost' grads = self.get_grads() LCA = {} for j, name in enumerate(self.variable_names): lca = grads[list(self.trainable_numbers.keys())[j]] * (self.Weights[name] - self.OldWeights[name]) LCA[name] = np.array(np.mean(lca)) if self.lca_save: self.lca_stream(path=self.path, basename=self.basename, save_occurence=self.max_occurence, lca=LCA) return LCA def calculate_LCA(self): if not self.OldWeights: return 'Model hasnt been run or oldweights have been lost' grads = self.get_grads() LCA = {} for j, name in enumerate(self.variable_names): lca = grads[list(self.trainable_numbers.keys())[j]] * (self.Weights[name] - self.OldWeights[name]) LCA[name] = np.array(lca) if self.lca_save: self.lca_stream(path=self.path, basename=self.basename, save_occurence=self.max_occurence, lca=LCA) return LCA def calculate_per_node_LCA(self): if not self.OldWeights: return 'Model hasnt been run or oldweights have been lost' grads = self.get_grads() LCA = {} for j, name in enumerate(self.variable_names): lca = grads[list(self.trainable_numbers.keys())[j]] * (self.Weights[name] - self.OldWeights[name]) LCA[name] = np.mean(lca, axis=0) if self.lca_save: self.lca_stream(path=self.path, basename=self.basename, save_occurence=self.max_occurence, lca=LCA) return LCA def get_LCA(self): if self.lca_type == 'Mean': return self.calculate_mean_LCA() elif self.lca_type == 'Raw': return self.calculate_LCA() elif self.lca_type == 'Node': return self.calculate_per_node_LCA() def get_layer_names(self): self.layer_names = [] for layer in self.layers: if layer.trainable: self.layer_names.append(layer.name) self.variable_names = [item.name for item in self.trainable_weights] def get_variable_names(self): variable_names = [item.name for item in self.trainable_weights] self.variable_names = [] for item in variable_names: if item.split('/')[0] in self.layer_names: self.variable_names.append(item) def check_memory(self, epochs=1): tempArray = self.get_weights() if self.lca_type == 'Mean': templist = [] for j in tempArray: templist.append(np.mean(tempArray[j])) size = sys.getsizeof(templist) elif self.lca_type == 'Raw': size = sys.getsizeof(tempArray) elif self.lca_type == 'Node': templist = [] for j in tempArray: templist.append(np.mean(tempArray[j], axis=0)) size = sys.getsizeof(templist) self.single_epoch_size = size * 3 total_size = size * (epochs + 3) available_space = virtual_memory()[1] try: self.max_occurence = min(available_space // (size * 3), self.max_occurence) except: self.max_occurence = available_space // (size * 3) if self.max_occurence == 0: raise Exception(" Single Epoch LCA will fill memory") if total_size > self.memory_threshold * available_space: raise Exception("LCA will fill memory before completing epochs")
import React from "react" const Videoembed = (props) =>{ const url= props.src return( <iframe width="800" height="450" src={"https://www.youtube.com/embed/"+url+"?rel=0"} frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""> </iframe> ) } export default Videoembed
function SvgBorderClearOutlined(props) { return ( <svg xmlns='http://www.w3.org/2000/svg' height='1em' viewBox='0 0 24 24' width='1em' className='svg-icon' {...props}> <path d='M0 0h24v24H0V0z' fill='none' /> <path d='M7 5h2V3H7v2zm0 8h2v-2H7v2zm0 8h2v-2H7v2zm4-4h2v-2h-2v2zm0 4h2v-2h-2v2zm-8 0h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2V7H3v2zm0-4h2V3H3v2zm8 8h2v-2h-2v2zm8 4h2v-2h-2v2zm0-4h2v-2h-2v2zm0 8h2v-2h-2v2zm0-12h2V7h-2v2zm-8 0h2V7h-2v2zm8-6v2h2V3h-2zm-8 2h2V3h-2v2zm4 16h2v-2h-2v2zm0-8h2v-2h-2v2zm0-8h2V3h-2v2z' /> </svg> ); } export default SvgBorderClearOutlined;
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _capitalize = _interopRequireDefault(require("../utils/capitalize")); var _withStyles = _interopRequireDefault(require("../styles/withStyles")); var _useTheme = _interopRequireDefault(require("../styles/useTheme")); var styles = function styles(theme) { var hidden = { display: 'none' }; return theme.breakpoints.keys.reduce(function (acc, key) { acc["only".concat((0, _capitalize.default)(key))] = (0, _defineProperty2.default)({}, theme.breakpoints.only(key), hidden); acc["".concat(key, "Up")] = (0, _defineProperty2.default)({}, theme.breakpoints.up(key), hidden); acc["".concat(key, "Down")] = (0, _defineProperty2.default)({}, theme.breakpoints.down(key), hidden); return acc; }, {}); }; /** * @ignore - internal component. */ function HiddenCss(props) { var children = props.children, classes = props.classes, className = props.className, only = props.only, other = (0, _objectWithoutProperties2.default)(props, ["children", "classes", "className", "only"]); var theme = (0, _useTheme.default)(); if (process.env.NODE_ENV !== 'production') { var unknownProps = Object.keys(other).filter(function (propName) { var isUndeclaredBreakpoint = !theme.breakpoints.keys.some(function (breakpoint) { return "".concat(breakpoint, "Up") === propName || "".concat(breakpoint, "Down") === propName; }); return isUndeclaredBreakpoint; }); if (unknownProps.length > 0) { console.error("Material-UI: unsupported props received by `<Hidden implementation=\"css\" />`: ".concat(unknownProps.join(', '), ". Did you forget to wrap this component in a ThemeProvider declaring these breakpoints?")); } } var clsx = []; if (className) { clsx.push(className); } for (var i = 0; i < theme.breakpoints.keys.length; i += 1) { var breakpoint = theme.breakpoints.keys[i]; var breakpointUp = props["".concat(breakpoint, "Up")]; var breakpointDown = props["".concat(breakpoint, "Down")]; if (breakpointUp) { clsx.push(classes["".concat(breakpoint, "Up")]); } if (breakpointDown) { clsx.push(classes["".concat(breakpoint, "Down")]); } } if (only) { var onlyBreakpoints = Array.isArray(only) ? only : [only]; onlyBreakpoints.forEach(function (breakpoint) { clsx.push(classes["only".concat((0, _capitalize.default)(breakpoint))]); }); } return React.createElement("div", { className: clsx.join(' ') }, children); } process.env.NODE_ENV !== "production" ? HiddenCss.propTypes = { /** * The content of the component. */ children: _propTypes.default.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: _propTypes.default.object.isRequired, /** * @ignore */ className: _propTypes.default.string, /** * Specify which implementation to use. 'js' is the default, 'css' works better for * server-side rendering. */ implementation: _propTypes.default.oneOf(['js', 'css']), /** * If `true`, screens this size and down will be hidden. */ lgDown: _propTypes.default.bool, /** * If `true`, screens this size and up will be hidden. */ lgUp: _propTypes.default.bool, /** * If `true`, screens this size and down will be hidden. */ mdDown: _propTypes.default.bool, /** * If `true`, screens this size and up will be hidden. */ mdUp: _propTypes.default.bool, /** * Hide the given breakpoint(s). */ only: _propTypes.default.oneOfType([_propTypes.default.oneOf(['xs', 'sm', 'md', 'lg', 'xl']), _propTypes.default.arrayOf(_propTypes.default.oneOf(['xs', 'sm', 'md', 'lg', 'xl']))]), /** * If `true`, screens this size and down will be hidden. */ smDown: _propTypes.default.bool, /** * If `true`, screens this size and up will be hidden. */ smUp: _propTypes.default.bool, /** * If `true`, screens this size and down will be hidden. */ xlDown: _propTypes.default.bool, /** * If `true`, screens this size and up will be hidden. */ xlUp: _propTypes.default.bool, /** * If `true`, screens this size and down will be hidden. */ xsDown: _propTypes.default.bool, /** * If `true`, screens this size and up will be hidden. */ xsUp: _propTypes.default.bool } : void 0; var _default = (0, _withStyles.default)(styles, { name: 'PrivateHiddenCss' })(HiddenCss); exports.default = _default;
// moment.js language configuration // language : Tagalog/Filipino (tl-ph) // author : Dan Hagman (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('tl-ph', { months : "Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre".split("_"), monthsShort : "Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis".split("_"), weekdays : "Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado".split("_"), weekdaysShort : "Lin_Lun_Mar_Miy_Huw_Biy_Sab".split("_"), weekdaysMin : "Li_Lu_Ma_Mi_Hu_Bi_Sab".split("_"), longDateFormat : { LT : "HH:mm", L : "MM/D/YYYY", LL : "MMMM D, YYYY", LLL : "MMMM D, YYYY LT", LLLL : "dddd, MMMM DD, YYYY LT" }, calendar : { sameDay: "[Ngayon sa] LT", nextDay: '[Bukas sa] LT', nextWeek: 'dddd [sa] LT', lastDay: '[Kahapon sa] LT', lastWeek: 'dddd [huling linggo] LT', sameElse: 'L' }, relativeTime : { future : "sa loob ng %s", past : "%s ang nakalipas", s : "ilang segundo", m : "isang minuto", mm : "%d minuto", h : "isang oras", hh : "%d oras", d : "isang araw", dd : "%d araw", M : "isang buwan", MM : "%d buwan", y : "isang taon", yy : "%d taon" }, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); }));
'use strict'; const fetch = require("node-fetch") class Request { /* * @param {string} url - The URL to request */ constructor(url, body=null, j, headers={ "Content-Type": "application/json", "Authorization": "Bot " + process.env.TOKEN }) { if (!j) j = false this.url = url this.body = JSON.stringify(body) this.headers = headers this.json = j } async test_request(method, reason=null) { if (reason) this.headers["X-Audit-Log-Reason"] = reason let request = await fetch(`https://discord.com/api/v9/${this.url}`, { method: method, body: this.body, headers: this.headers }) let response = { code: await request.status, text: await request.statusText, data: await request.json() } console.log(response.text) return response } async test_get() { let request = await fetch(`https://discord.com/api/v9${this.url}`, { method: "GET", headers: this.headers }) let response = { code: await request.statusCode, text: await request.statusText, data: await request.json() } return response } async request(method, reason=null) { if (reason) this.headers["X-Audit-Log-Reason"] = reason let request = await fetch(`https://discord.com/api/v9/${this.url}`, { method: method, body: this.body, headers: this.headers }) let response = { code: await request.status, text: await request.statusText, } if (this.json) { response.data = await request.json() } return response } async get() { let request = await fetch(`https://discord.com/api/v9${this.url}`, { method: "GET", headers: this.headers }) let response = { code: await request.status, text: await request.statusText, } response.data = await request.json() return response } } module.exports = {Request}
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // Copyright (c) 2015 Uber Technologies, Inc. // 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 browser from 'bowser'; var PREFIX = '-webkit'; // browser.webkit || browser.blink ? '-webkit-' : // browser.gecko ? '-moz-' : // ''; exports.default = { DEFAULTS: {}, CURSOR: { GRABBING: PREFIX + 'grabbing', GRAB: PREFIX + 'grab', POINTER: 'pointer' } }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb250cm9sbGVycy9jb25maWcuanMiXSwibmFtZXMiOlsiUFJFRklYIiwiREVGQVVMVFMiLCJDVVJTT1IiLCJHUkFCQklORyIsIkdSQUIiLCJQT0lOVEVSIl0sIm1hcHBpbmdzIjoiOzs7OztBQUFBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBLElBQU1BLFNBQVMsU0FBZjtBQUNFO0FBQ0E7QUFDQTs7a0JBRWE7QUFDYkMsWUFBVSxFQURHO0FBRWJDLFVBQVE7QUFDTkMsY0FBYUgsTUFBYixhQURNO0FBRU5JLFVBQVNKLE1BQVQsU0FGTTtBQUdOSyxhQUFTO0FBSEg7QUFGSyxDIiwiZmlsZSI6ImNvbmZpZy5qcyIsInNvdXJjZXNDb250ZW50IjpbIi8vIENvcHlyaWdodCAoYykgMjAxNSBVYmVyIFRlY2hub2xvZ2llcywgSW5jLlxuXG4vLyBQZXJtaXNzaW9uIGlzIGhlcmVieSBncmFudGVkLCBmcmVlIG9mIGNoYXJnZSwgdG8gYW55IHBlcnNvbiBvYnRhaW5pbmcgYSBjb3B5XG4vLyBvZiB0aGlzIHNvZnR3YXJlIGFuZCBhc3NvY2lhdGVkIGRvY3VtZW50YXRpb24gZmlsZXMgKHRoZSBcIlNvZnR3YXJlXCIpLCB0byBkZWFsXG4vLyBpbiB0aGUgU29mdHdhcmUgd2l0aG91dCByZXN0cmljdGlvbiwgaW5jbHVkaW5nIHdpdGhvdXQgbGltaXRhdGlvbiB0aGUgcmlnaHRzXG4vLyB0byB1c2UsIGNvcHksIG1vZGlmeSwgbWVyZ2UsIHB1Ymxpc2gsIGRpc3RyaWJ1dGUsIHN1YmxpY2Vuc2UsIGFuZC9vciBzZWxsXG4vLyBjb3BpZXMgb2YgdGhlIFNvZnR3YXJlLCBhbmQgdG8gcGVybWl0IHBlcnNvbnMgdG8gd2hvbSB0aGUgU29mdHdhcmUgaXNcbi8vIGZ1cm5pc2hlZCB0byBkbyBzbywgc3ViamVjdCB0byB0aGUgZm9sbG93aW5nIGNvbmRpdGlvbnM6XG5cbi8vIFRoZSBhYm92ZSBjb3B5cmlnaHQgbm90aWNlIGFuZCB0aGlzIHBlcm1pc3Npb24gbm90aWNlIHNoYWxsIGJlIGluY2x1ZGVkIGluXG4vLyBhbGwgY29waWVzIG9yIHN1YnN0YW50aWFsIHBvcnRpb25zIG9mIHRoZSBTb2Z0d2FyZS5cblxuLy8gVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEIFwiQVMgSVNcIiwgV0lUSE9VVCBXQVJSQU5UWSBPRiBBTlkgS0lORCwgRVhQUkVTUyBPUlxuLy8gSU1QTElFRCwgSU5DTFVESU5HIEJVVCBOT1QgTElNSVRFRCBUTyBUSEUgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFksXG4vLyBGSVRORVNTIEZPUiBBIFBBUlRJQ1VMQVIgUFVSUE9TRSBBTkQgTk9OSU5GUklOR0VNRU5ULiBJTiBOTyBFVkVOVCBTSEFMTCBUSEVcbi8vIEFVVEhPUlMgT1IgQ09QWVJJR0hUIEhPTERFUlMgQkUgTElBQkxFIEZPUiBBTlkgQ0xBSU0sIERBTUFHRVMgT1IgT1RIRVJcbi8vIExJQUJJTElUWSwgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIFRPUlQgT1IgT1RIRVJXSVNFLCBBUklTSU5HIEZST00sXG4vLyBPVVQgT0YgT1IgSU4gQ09OTkVDVElPTiBXSVRIIFRIRSBTT0ZUV0FSRSBPUiBUSEUgVVNFIE9SIE9USEVSIERFQUxJTkdTIElOXG4vLyBUSEUgU09GVFdBUkUuXG5cbi8vIGltcG9ydCBicm93c2VyIGZyb20gJ2Jvd3Nlcic7XG5cbmNvbnN0IFBSRUZJWCA9ICctd2Via2l0JztcbiAgLy8gYnJvd3Nlci53ZWJraXQgfHwgYnJvd3Nlci5ibGluayA/ICctd2Via2l0LScgOlxuICAvLyBicm93c2VyLmdlY2tvID8gJy1tb3otJyA6XG4gIC8vICcnO1xuXG5leHBvcnQgZGVmYXVsdCB7XG4gIERFRkFVTFRTOiB7fSxcbiAgQ1VSU09SOiB7XG4gICAgR1JBQkJJTkc6IGAke1BSRUZJWH1ncmFiYmluZ2AsXG4gICAgR1JBQjogYCR7UFJFRklYfWdyYWJgLFxuICAgIFBPSU5URVI6ICdwb2ludGVyJ1xuICB9XG59O1xuIl19
const satsolver = require('satsolver') satsolver.solve("hole4.cnf")
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class RadioButtonGroup(Component): """A RadioButtonGroup component. Keyword arguments: - id (string; required): the element's ID. - className (string; default ''): the css class name of the root element. - classes (dict; optional): The classes to be applied to each radio button. This keys in this object must be valid CSS rule names, and the values must be strings for the classnames to be assigned to each rule name Valid rule names are: root checked disabled colorPrimary colorSecondary. `classes` is a dict with keys: - root (string; optional) - checked (string; optional) - disabled (string; optional) - colorPrimary (string; optional) - colorSecondary (string; optional) - name (string; required): the name that will be applied to the group of radio buttons. - options (list; optional): used to create the RadioButtons to populate the RadioButtonGroup with. A Dash user passes in a list of dict items, each one having at least a `value` and `label`. If that value is selected, valueSelected will be updated. - row (boolean; default False): If True, Radio Buttons appear as a row\". - valueSelected (string; required): Initial value selected.""" @_explicitize_args def __init__(self, classes=Component.UNDEFINED, className=Component.UNDEFINED, fireEvent=Component.UNDEFINED, id=Component.REQUIRED, name=Component.REQUIRED, options=Component.UNDEFINED, row=Component.UNDEFINED, valueSelected=Component.REQUIRED, **kwargs): self._prop_names = ['id', 'className', 'classes', 'name', 'options', 'row', 'valueSelected'] self._type = 'RadioButtonGroup' self._namespace = 'sd_material_ui' self._valid_wildcard_attributes = [] self.available_properties = ['id', 'className', 'classes', 'name', 'options', 'row', 'valueSelected'] self.available_wildcard_properties = [] _explicit_args = kwargs.pop('_explicit_args') _locals = locals() _locals.update(kwargs) # For wildcard attrs args = {k: _locals[k] for k in _explicit_args if k != 'children'} for k in ['id', 'name', 'valueSelected']: if k not in args: raise TypeError( 'Required argument `' + k + '` was not specified.') super(RadioButtonGroup, self).__init__(**args)
function initJWPageFactoryAMap(t){var e={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",decode:function(t){var a,r,o,n,d,i,s="",c=0;for(t=t.replace(/[^A-Za-z0-9+/=]/g,"");c<t.length;)a=this._keyStr.indexOf(t.charAt(c++))<<2|(n=this._keyStr.indexOf(t.charAt(c++)))>>4,r=(15&n)<<4|(d=this._keyStr.indexOf(t.charAt(c++)))>>2,o=(3&d)<<6|(i=this._keyStr.indexOf(t.charAt(c++))),s+=String.fromCharCode(a),64!=d&&(s+=String.fromCharCode(r)),64!=i&&(s+=String.fromCharCode(o));return s=e._utf8_decode(s)},_utf8_decode:function(t){for(var e="",a=0,r=c1=c2=0;a<t.length;)(r=t.charCodeAt(a))<128?(e+=String.fromCharCode(r),a++):r>191&&r<224?(c2=t.charCodeAt(a+1),e+=String.fromCharCode((31&r)<<6|63&c2),a+=2):(c2=t.charCodeAt(a+1),c3=t.charCodeAt(a+2),e+=String.fromCharCode((15&r)<<12|(63&c2)<<6|63&c3),a+=3);return e}};jQuery(".jwpf-addon-amap-canvas",t).each(function(a){var r=jQuery(this).attr("id"),l=jQuery(this).attr("data-maplang"),s=jQuery(this).attr("data-mapstyle"),i=jQuery(this).attr("data-maptype"),u=jQuery(this).attr("data-lat"),g=jQuery(this).attr("data-lng"),m=jQuery(this).attr("data-marker"),n=jQuery(this).attr("data-infowindow"),z=Number(jQuery(this).attr("data-mapzoom")),d="true"===jQuery(this).attr("data-mousescroll"),c=new AMap.Map(t.getElementById(r),{center:new AMap.LngLat(Number(g),Number(u)),mapStyle:'amap://styles/'+s,zoom:z,lang:l,scrollWheel:d,resizeEnable:true}),x=jQuery(this).attr("data-location"),a=[];switch(i){case'roadnet':a.push(new AMap.TileLayer.RoadNet());break;case'satellite':a.push(new AMap.TileLayer.Satellite());break;case'hybrid':a.push(new AMap.TileLayer.Satellite());a.push(new AMap.TileLayer.RoadNet());break;case'traffic':a.push(new AMap.TileLayer.Traffic());a.push(new AMap.TileLayer());break;default:a.push(new AMap.TileLayer());break}c.setLayers(a);if(void 0!==x){var h=e.decode(n),l=JSON.stringify([{address:h,latitude:u,longitude:g,icon:m}]),f=e.decode(x),p=JSON.parse(l),b=JSON.parse(f),o=p.concat(b),C=o.length;if(C>0){var n=new AMap.InfoWindow({offset:new AMap.Pixel(5,-30)});for(var S=0;S<C;S++){q=new AMap.LngLat(o[S].longitude,o[S].latitude);w=new AMap.Marker({position:q,map:c});if(o[S].icon){var icon=new AMap.Icon({image:o[S].icon});w.setIcon(icon)}if(o[S].address){w.content=o[S].address;w.on('click',function(e){n.setContent('<div class="amap-info-window-content">'+e.target.content+'</div>');n.open(c,e.target.getPosition())})}}if(C>1)c.setFitView()}}})}jQuery(window).on("load",function(){initJWPageFactoryAMap(document)});
import time import os import subprocess import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from nw_util import * from selenium import webdriver from selenium.webdriver.chrome.options import Options def click_and_assert(driver, id, expect): driver.find_element_by_id(id).click() wait_window_handles(driver, 2) print 'switch to opened window' driver.switch_to_window(driver.window_handles[-1]) driver.find_element_by_id('getwinsize').click() result = driver.find_element_by_id('result').get_attribute('innerHTML') print 'window size: %s' % result assert (expect in result) driver.close() wait_window_handles(driver, 1) driver.switch_to_window(driver.window_handles[0]) chrome_options = Options() chrome_options.add_argument("nwapp=" + os.path.dirname(os.path.abspath(__file__))) driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_options=chrome_options, service_log_path="log", service_args=["--verbose"]) time.sleep(1) try: print driver.current_url driver.implicitly_wait(10) print 'open new window with `window.open()`' click_and_assert(driver, 'winopen', '400,300') print 'open new window with <a target="_blank">' click_and_assert(driver, 'winopen', '400,300') print 'bind new-win-policy and newly opened window should have size of 388,300' driver.find_element_by_id('bindnewwinpolicy').click() print 'open new window with `window.open()` after new-win-policy' click_and_assert(driver, 'winopen', '388,300') print 'open new window with <a target="_blank"> after new-win-policy' click_and_assert(driver, 'winopen', '388,300') finally: driver.quit()
var zipextractor={};zipextractor.config={};zipextractor.state={};zipextractor.config.DRIVE_API_CONFIG_DATA={clientId:"824911851129-6d64j0e08s86ih74l0lu386tqqfv71t9.apps.googleusercontent.com",appId:"824911851129",scopes:["https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive.install"],apiKey:"AIzaSyBW4IYnFZLyPFFKtZ2qWJYTlURyyE-Vt_4"};zipextractor.App=function(){var e=new driveapi.AppConfig(zipextractor.config.DRIVE_API_CONFIG_DATA);this.presenter_=new zipextractor.Presenter(e);this.presenter_.init()};zipextractor.App.prototype.onHtmlBodyLoaded=function(){this.presenter_.onHtmlBodyLoaded()};zipextractor.App.prototype.onGapiClientLoaded=function(){this.presenter_.onGapiClientLoaded()};zipextractor.Model=function(){this.filename_=null;this.entryTree_=null};zipextractor.Model.EXTRACTED_FOLDER_SUFFIX_="(Unzipped Files)";zipextractor.Model.prototype.getFilename=function(){return this.filename_};zipextractor.Model.prototype.setFilename=function(e){if(this.filename_){throw"Existing model must be cleared before existing filename can be updated."}this.filename_=e};zipextractor.Model.prototype.getEntryTree=function(){return this.entryTree_};zipextractor.Model.prototype.clear=function(){if(!(this.entryTree_||this.filename_)){throw"No exisitng model to clear."}this.filename_=null;delete this.entryTree_};zipextractor.Model.prototype.build=function(e,t){zipextractor.util.execLater(zipextractor.util.bindFn(this.buildInternal_,this,e),t)};zipextractor.Model.prototype.buildInternal_=function(e){if(this.entryTree_){throw"Existing model must be cleared before being built."}var t=this.getFolderName_(this.filename_);this.entryTree_={directory:true,root:true,name:t,path:t,children:{},state:zipextractor.state.SessionState.DEFAULT};for(var n=0;n<e.length;n++){this.insertEntry_(this.entryTree_,e[n])}};zipextractor.Model.prototype.insertEntry_=function(e,t){var n=t.filename;if(zipextractor.util.endsWith(n,"/")){n=n.substring(0,n.length-1)}var r=n.split("/");var i=e;var s=null;for(var o=0;o<r.length;o++){var u=r[o];if(s===null){s=u}else{s=s+"/"+u}var a=i.children[u];if(!a){if(o<r.length-1||t.directory){a={};a.directory=true;a.children={}}else{a=t}a.state=zipextractor.state.EntryState.DEFAULT;a.path=s;a.name=u;a.parentEntry=i;i.children[u]=a}else{}i=a}};zipextractor.Model.prototype.getFolderName_=function(e){return zipextractor.util.trimFileExtension(e)+" "+zipextractor.Model.EXTRACTED_FOLDER_SUFFIX_};zipextractor.Presenter=function(e){this.appConfig_=e;this.model_=new zipextractor.Model;this.urlStateParser_=new driveapi.UrlStateParser;this.zipReader_=new zipextractor.ZipReader;this.authManager_=new driveapi.AuthManager(e);this.fileManager_=new driveapi.FileManager(this.authManager_);var t=new zipextractor.util.PickerManager(e,this.authManager_);this.view_=new zipextractor.View(this,t);this.state_=zipextractor.state.SessionState.DEFAULT;this.htmlBodyLoaded_=false;this.apiLoaded_=false;this.sharingLoaded_=false;this.currentSession_=null;this.hasDownloadBeenAutoRetried_=false;this.lastDownloadId_=null};zipextractor.Presenter.IS_DEBUG_=false;zipextractor.Presenter.prototype.onHtmlBodyLoaded=function(){this.htmlBodyLoaded_=true;this.view_.init();if(!this.checkBrowser_()){this.setState_(zipextractor.state.SessionState.UNSUPPORTED_BROWSER);return}this.parseUrlState_();if(this.apiLoaded_){this.authorize_(true)}if(zipextractor.Presenter.IS_DEBUG_){this.processRequestFromState_()}};zipextractor.Presenter.prototype.onGapiClientLoaded=function(){if(!this.checkBrowser_()){this.setState_(zipextractor.state.SessionState.UNSUPPORTED_BROWSER);return}this.apiLoaded_=true;this.setState_(zipextractor.state.SessionState.API_LOADED);this.parseUrlState_();if(this.htmlBodyLoaded_){this.authorize_(true)}gapi.load("drive-share",zipextractor.util.bindFn(this.sharingLoadComplete_,this))};zipextractor.Presenter.prototype.parseUrlState_=function(){if(!this.urlStateParser_.isParsed()){this.setState_(zipextractor.state.SessionState.READ_URL_STATE);this.urlStateParser_.parseState()}};zipextractor.Presenter.prototype.sharingLoadComplete_=function(){this.sharingLoaded_=true};zipextractor.Presenter.prototype.showSharingDialog_=function(e){var t=new gapi.drive.share.ShareClient(this.appConfig_.getAppId());t.setItemIds([e]);t.showSettingsDialog()};zipextractor.Presenter.prototype.checkBrowser_=function(){var e=zipextractor.util.isIE();return!e||e&&!(e<=9)};zipextractor.Presenter.prototype.init=function(){this.setState_(zipextractor.state.SessionState.INIT)};zipextractor.Presenter.prototype.updateEntryState=function(e,t){var n=e.state;e.state=t;this.view_.updateEntryState(e,t,n)};zipextractor.Presenter.prototype.setState_=function(e,t){var n=this.state_;this.state_=e;this.view_.updateState(e,n,t)};zipextractor.Presenter.prototype.authorize_=function(e){if(zipextractor.Presenter.IS_DEBUG_){return}var t=e?zipextractor.state.SessionState.AUTH_PENDING_AUTO:zipextractor.state.SessionState.AUTH_PENDING_USER;this.setState_(t);this.authManager_.authorize(e,zipextractor.util.bindFn(this.handleAuthResult_,this),this.urlStateParser_.getUserId())};zipextractor.Presenter.prototype.handleAuthResult_=function(e){if(e){if(e.error){this.setState_(zipextractor.state.SessionState.AUTH_ERROR,e.error)}else{this.setState_(zipextractor.state.SessionState.AUTH_SUCCESS);this.processRequestFromState_()}}else{this.setState_(zipextractor.state.SessionState.AUTH_REQUIRED)}};zipextractor.Presenter.prototype.processRequestFromState_=function(){this.setState_(zipextractor.state.SessionState.READ_URL_STATE);this.urlStateParser_.parseState();if(this.urlStateParser_.isForOpen()){this.downloadFileById_(this.urlStateParser_.getFileId())}else{this.startNewSession_()}};zipextractor.Presenter.prototype.startNewSession_=function(){this.view_.updatePageTitle();this.setState_(zipextractor.state.SessionState.NEW_SESSION)};zipextractor.Presenter.prototype.downloadFileById_=function(e){this.lastDownloadId_=e;this.setState_(zipextractor.state.SessionState.DOWNLOADING_METADATA);var t=this.fileManager_.generateCallbacks(zipextractor.util.bindFn(this.downloadFile_,this),zipextractor.util.bindFn(this.onDownloadError_,this),undefined,zipextractor.util.bindFn(this.onDownloadAborted_,this));this.fileManager_.get(e,t)};zipextractor.Presenter.prototype.downloadFile_=function(e){this.setState_(zipextractor.state.SessionState.DOWNLOADING,e);var fileSize = e.fileSize ? parseInt(e.fileSize, 10) : -1;var t=this.fileManager_.generateCallbacks(zipextractor.util.bindFn(this.onDownloadSuccess_,this),zipextractor.util.bindFn(this.onDownloadError_,this),zipextractor.util.bindFn(this.onDownloadProgress_,this,fileSize),zipextractor.util.bindFn(this.onDownloadAborted_,this));this.fileManager_.downloadFile(e,t)};zipextractor.Presenter.prototype.onDownloadSuccess_=function(e,t){this.setState_(zipextractor.state.SessionState.DOWNLOADED);this.createSession_(e);this.initModel_(e.title,t)};zipextractor.Presenter.prototype.onDownloadError_=function(e,t){if(!this.hasDownloadBeenAutoRetried_){this.hasDownloadBeenAutoRetried_=true;if(e==driveapi.FileManager.ErrorType.AUTH_ERROR){this.setState_(zipextractor.state.SessionState.AUTH_PENDING_AUTO);this.authManager_.authorize(true,zipextractor.util.bindFn(this.downloadFileById_,this,this.lastDownloadId_))}else{this.downloadFileById_(this.lastDownloadId_)}}else{this.setState_(zipextractor.state.SessionState.DOWNLOAD_ERROR,t)}};zipextractor.Presenter.prototype.onDownloadProgress_=function(fileSize,e,total){if(this.state_==zipextractor.state.SessionState.DOWNLOAD_CANCELED){return}if (fileSize != -1) {this.view_.handleDownloadProgress(e,fileSize);if(e===fileSize){this.setState_(zipextractor.state.SessionState.DOWNLOAD_ALL_BYTES_TRANSFERRED)}}};zipextractor.Presenter.prototype.onDownloadAborted_=function(){this.handleDownloadCanceled_()};zipextractor.Presenter.prototype.handleDownloadCanceled_=function(){this.setState_(zipextractor.state.SessionState.DOWNLOAD_CANCELED)};zipextractor.Presenter.prototype.initModel_=function(e,t){this.view_.updatePageTitle(e);this.setState_(zipextractor.state.SessionState.ZIP_READING);this.model_.setFilename(e);this.zipReader_.read(t,zipextractor.util.bindFn(this.zipReadSuccess_,this),zipextractor.util.bindFn(this.zipReadError_,this))};zipextractor.Presenter.prototype.zipReadError_=function(e){this.setState_(zipextractor.state.SessionState.ZIP_READ_ERROR,e)};zipextractor.Presenter.prototype.zipReadSuccess_=function(e){this.setState_(zipextractor.state.SessionState.MODEL_BUILDING);this.model_.build(e,zipextractor.util.bindFn(this.modelBuildComplete_,this))};zipextractor.Presenter.prototype.modelBuildComplete_=function(){this.setState_(zipextractor.state.SessionState.MODEL_BUILT,this.model_);this.setState_(zipextractor.state.SessionState.RENDER_ZIP_UI,zipextractor.util.bindFn(this.zipUiRenderComplete_,this))};zipextractor.Presenter.prototype.zipUiRenderComplete_=function(){this.setState_(zipextractor.state.SessionState.PENDING_USER_INPUT)};zipextractor.Presenter.prototype.createSession_=function(e){this.currentSession_=new zipextractor.Session(this.urlStateParser_.getFolderId(),this,this.model_,this.view_,this.fileManager_);if(e){this.currentSession_.updateParentIdByFile(e)}};zipextractor.Presenter.prototype.extract_=function(e){this.setState_(zipextractor.state.SessionState.EXTRACTING,this.model_.getEntryTree());this.currentSession_.execute(e)};zipextractor.Presenter.prototype.reset_=function(){if(this.currentSession_){this.currentSession_.close();this.currentSession_=null;this.model_.clear()}this.lastDownloadId_=null;this.hasDownloadBeenAutoRetried_=false};zipextractor.Presenter.prototype.VIEW__authRequested=function(){this.authorize_(false)};zipextractor.Presenter.prototype.VIEW__driveFileChosen=function(e){this.downloadFileById_(e.id)};zipextractor.Presenter.prototype.VIEW__driveFolderChosen=function(e){this.currentSession_.setParentId(e.id);this.view_.updateDestinationFolderUi(e)};zipextractor.Presenter.prototype.VIEW__localBlobChosen=function(e,t){this.createSession_(undefined);this.initModel_(e,t)};zipextractor.Presenter.prototype.VIEW__extractNow=function(){this.extract_(false)};zipextractor.Presenter.prototype.VIEW__cancelSession=function(){this.setState_(zipextractor.state.SessionState.SESSION_CANCELED);this.reset_();this.startNewSession_()};zipextractor.Presenter.prototype.VIEW__reset=function(){this.reset_();this.startNewSession_()};zipextractor.Presenter.prototype.VIEW__rateApp=function(){var e="https://chrome.google.com/webstore/detail/zip-extractor/mmfcakoljjhncfphlflcedhgogfhpbcd/reviews?hl=en-US";window.open(e,"_blank").focus()};zipextractor.Presenter.prototype.VIEW__cancelExtraction=function(){this.setState_(zipextractor.state.SessionState.EXTRACTION_CANCEL_REQUESTED);this.currentSession_.abort()};zipextractor.Presenter.prototype.SESSION__extractionComplete=function(){var e=this.currentSession_.hasErrors();if(e&&!this.currentSession_.hasBeenRetried()){if(this.currentSession_.hasAuthErrors()){this.setState_(zipextractor.state.SessionState.AUTH_PENDING_AUTO);this.authManager_.authorize(true,zipextractor.util.bindFn(this.extract_,this,true))}else{this.extract_(true)}}else{this.setState_(zipextractor.state.SessionState.EXTRACTION_COMPLETE,e)}};zipextractor.Presenter.prototype.SESSION__extractionCanceled=function(){this.setState_(zipextractor.state.SessionState.EXTRACTION_CANCELED)};zipextractor.Presenter.prototype.VIEW__shareExtractedFiles=function(){var e=this.getNewParentId_();if(e){if(this.sharingLoaded_){this.showSharingDialog_(this.getNewParentId_())}}};zipextractor.Presenter.prototype.VIEW__viewExtractedFiles=function(){var e=zipextractor.util.createDriveFolderLink(this.getNewParentId_());var t=window.open(e,"_blank");t.focus()};zipextractor.Presenter.prototype.VIEW__retryErrors=function(){this.extract_(true)};zipextractor.Presenter.prototype.VIEW__retryDownload=function(){this.hasDownloadBeenAutoRetried_=false;this.downloadFileById_(this.lastDownloadId_)};zipextractor.Presenter.prototype.VIEW__downloadBrowser=function(e){var t=null;switch(e){case"chrome":t="http://www.google.com/chrome";break;case"firefox":t="http://www.mozilla.org/en-US/firefox/new/";break;case"ie":t="http://windows.microsoft.com/en-us/internet-explorer/download-ie";break}if(t){var n=window.open(t,"_blank");n.focus()}};zipextractor.Presenter.prototype.VIEW__cancelDownload=function(){this.setState_(zipextractor.state.SessionState.CANCEL_DOWNLOAD_REQUESTED);this.fileManager_.abortDownload()};zipextractor.Presenter.prototype.getNewParentId_=function(){var e=this.model_.getEntryTree();if(e&&e.folder){return e.folder.id}else if(this.currentSession_&&this.currentSession_.getParentId()){return this.currentSession_.getParentId()}else{return null}};zipextractor.Session=function(e,t,n,r,i){this.parentId_=e;this.presenter_=t;this.model_=n;this.view_=r;this.workQueue_=new zipextractor.util.AsyncWorkQueue(zipextractor.Session.MAX_WORKQUEUE_WORKERS_);this.fileManager_=i;this.entryStateMap_={};this.entriesInProcessMap_={};this.totalSessionSize_=0;this.currentSessionProgress_=0;this.isClosed_=false;this.isAborted_=false;this.hasBeenRetried_=false};zipextractor.Session.MAX_WORKQUEUE_WORKERS_=2;zipextractor.Session.TRANSFER_DECOMPRESS_MULTIPLIER_=3;zipextractor.Session.ENTRY_OVERHEAD_BYTES_=2e4;zipextractor.Session.prototype.updateParentIdByFile=function(e){var t=e.parents;if(t&&t.length>0){var n=t[0];if(n&&n.id){this.parentId_=n.id}}};zipextractor.Session.prototype.getParentId=function(){return this.parentId_};zipextractor.Session.prototype.setParentId=function(e){this.parentId_=e};zipextractor.Session.prototype.abort=function(){this.isAborted_=true;this.workQueue_.stop();this.fileManager_.abortAllRequests();this.cancelAllUnstartedEntries_();this.checkForExtractionComplete_()};zipextractor.Session.prototype.close=function(){if(this.isClosed_){throw"Error: Cannot close an already closed session."}this.model_=null;this.parentId_=null;delete this.workQueue_;this.entryStateMap_={};this.entriesInProcessMap_={};this.fileManager_=null;this.totalSessionSize_=0;this.currentSessionProgress_=0;this.isClosed_=true};zipextractor.Session.prototype.hasBeenRetried=function(){return this.hasBeenRetried_};zipextractor.Session.prototype.hasErrors=function(){var e=this.model_.getEntryTree();if(this.isErrorState_(e.state)){return true}else{return this.childEntriesHaveErrors_(e)}};zipextractor.Session.prototype.childEntriesHaveErrors_=function(e){for(var t in e.children){var n=e.children[t];if(this.isErrorState_(n.state)){return true}else if(n.directory&&this.childEntriesHaveErrors_(n)){return true}}return false};zipextractor.Session.prototype.hasAuthErrors=function(){var e=this.model_.getEntryTree();if(this.entryHasAuthError_(e)){return true}else{return this.childEntriesHaveAuthErrors_(e)}};zipextractor.Session.prototype.childEntriesHaveAuthErrors_=function(e){for(var t in e.children){var n=e.children[t];if(this.entryHasAuthError_(n)){return true}else if(n.directory&&this.childEntriesHaveAuthErrors_(n)){return true}}return false};zipextractor.Session.prototype.entryHasAuthError_=function(e){return e.uploadError==driveapi.FileManager.ErrorType.AUTH_ERROR&&e.state==zipextractor.state.EntryState.UPLOAD_ERROR};zipextractor.Session.prototype.execute=function(e){if(this.isClosed_){throw"Error: Cannot execute a closed session."}if(e){this.hasBeenRetried_=true}var t=this.model_.getEntryTree();this.queueEntry_(t);this.queueEntryChildren_(t);this.currentSessionProgress_=0;this.totalSessionSize_=this.computeSessionSize_(t);if(this.isUploadableState_(t.state)){this.workQueue_.enqueue(this.generateWorkItem_(t,this.parentId_));this.updateEntryState_(t,zipextractor.state.EntryState.PENDING);this.runWorkQueue_()}else{this.processEntryTreeChildren_(t,this.parentId_,e)}};zipextractor.Session.prototype.processEntryTreeChildren_=function(e,t,n){for(var r in e.children){var i=e.children[r];if(this.isAborted_){this.updateEntryState_(i,zipextractor.state.EntryState.CANCELED)}else{if(this.isUploadableState_(i.state)){this.workQueue_.enqueue(this.generateWorkItem_(i,t));this.updateEntryState_(i,zipextractor.state.EntryState.PENDING)}else if(!!n&&i.directory&&i.state==zipextractor.state.EntryState.UPLOAD_COMPLETE){this.processEntryTreeChildren_(i,i.folder.id,n)}}}if(!this.isAborted_){this.runWorkQueue_()}};zipextractor.Session.prototype.computeSessionSize_=function(e){return this.getEntrySize_(e)+this.computeChildEntrySize_(e)};zipextractor.Session.prototype.computeChildEntrySize_=function(e){var t=0;for(var n in e.children){var r=e.children[n];var i=this.getEntrySize_(r);var s=r.directory?this.computeChildEntrySize_(r):0;t+=i+s}return t};zipextractor.Session.prototype.getEntrySize_=function(e){if(!this.isUploadableState_(e.state)){return 0}else{var t=e.directory?0:e.compressedSize+zipextractor.Session.TRANSFER_DECOMPRESS_MULTIPLIER_*e.uncompressedSize;return t+zipextractor.Session.ENTRY_OVERHEAD_BYTES_}};zipextractor.Session.prototype.queueEntry_=function(e){if(e.state==zipextractor.state.EntryState.DEFAULT){var t=this.view_.isSelected(e)?zipextractor.state.EntryState.QUEUED:zipextractor.state.EntryState.SKIPPED;this.updateEntryState_(e,t)}};zipextractor.Session.prototype.queueEntryChildren_=function(e){for(var t in e.children){var n=e.children[t];this.queueEntry_(n);if(n.directory){this.queueEntryChildren_(n)}}};zipextractor.Session.prototype.cancelAllUnstartedEntries_=function(){var e=this.model_.getEntryTree();this.cancelUnstartedEntry_(e);this.cancelUnstartedChildEntries_(e)};zipextractor.Session.prototype.cancelUnstartedEntry_=function(e){if(!this.isTerminalState_(e.state)&&!this.isInProgressState_(e.state)){this.updateEntryState_(e,zipextractor.state.EntryState.CANCELED)}};zipextractor.Session.prototype.cancelUnstartedChildEntries_=function(e){for(var t in e.children){var n=e.children[t];this.cancelUnstartedEntry_(n);if(n.directory){this.cancelUnstartedChildEntries_(n)}}};zipextractor.Session.prototype.runWorkQueue_=function(){this.workQueue_.run(zipextractor.util.bindFn(this.workQueueExecutionComplete_,this))};zipextractor.Session.prototype.updateEntryState_=function(e,t){this.updateEntryStateMap_(e,t);this.presenter_.updateEntryState(e,t)};zipextractor.Session.prototype.incrementSessionProgress_=function(e,t){if(this.isAborted_){return}this.currentSessionProgress_+=t;this.view_.handleSessionProgress(this.currentSessionProgress_,this.totalSessionSize_)};zipextractor.Session.prototype.updateEntryStateMap_=function(e,t){var n=e.state;var r=e.path;var i=this.entryStateMap_[t];if(!i){i={};this.entryStateMap_[t]=i}i[r]=e;var s=this.entryStateMap_[n];if(s){if(s.hasOwnProperty(r)){delete s[r]}}if(this.isTerminalState_(t)){delete this.entriesInProcessMap_[r]}else{this.entriesInProcessMap_[r]=e}};zipextractor.Session.prototype.areAllStatesTerminal_=function(){return Object.keys(this.entriesInProcessMap_).length===0};zipextractor.Session.prototype.isTerminalState_=function(e){return e==zipextractor.state.EntryState.UPLOAD_COMPLETE||e==zipextractor.state.EntryState.UPLOAD_ERROR||e==zipextractor.state.EntryState.SKIPPED||e==zipextractor.state.EntryState.CANCELED||e==zipextractor.state.EntryState.QUEUED_PENDING_RETRY||e==zipextractor.state.EntryState.UPLOAD_ABORTED};zipextractor.Session.prototype.isUploadableState_=function(e){return e==zipextractor.state.EntryState.QUEUED||e==zipextractor.state.EntryState.QUEUED_PENDING_RETRY||e==zipextractor.state.EntryState.UPLOAD_ERROR};zipextractor.Session.prototype.isErrorState_=function(e){return e==zipextractor.state.EntryState.UPLOAD_ERROR||e==zipextractor.state.EntryState.DECOMPRESSION_ERROR};zipextractor.Session.prototype.isInProgressState_=function(e){return e==zipextractor.state.EntryState.BEGIN_UPLOAD||e==zipextractor.state.EntryState.UPLOAD_PROGRESS||e==zipextractor.state.EntryState.UPLOAD_ALL_BYTES_TRANSFERRED};zipextractor.Session.prototype.generateWorkItem_=function(e,t){e.parentId=t;var n=e.directory?this.processFolder_:this.processFile_;return zipextractor.util.bindFn(n,this,e,t)};zipextractor.Session.prototype.processFolder_=function(e,t,n){if(this.isAborted_){this.updateEntryState_(e,zipextractor.state.EntryState.CANCELED);return}e.uploadPrev=0;e.uploadCurrent=0;e.uploadTotal=0;this.updateEntryState_(e,zipextractor.state.EntryState.BEGIN_UPLOAD);var r=this.fileManager_.generateCallbacks(zipextractor.util.bindFn(this.folderInsertComplete_,this,e,n,zipextractor.util.bindFn(this.processEntryTreeChildren_,this,e)),zipextractor.util.bindFn(this.folderInsertError_,this,e,n),undefined,zipextractor.util.bindFn(this.folderInsertAborted_,this,e,n));this.fileManager_.insertFolder(e.name,t,r)};zipextractor.Session.prototype.processFile_=function(e,t,n){if(this.isAborted_){this.updateEntryState_(e,zipextractor.state.EntryState.CANCELED);return}e.decompressionPrev=0;e.decompressionCurrent=0;e.decompressionTotal=0;e.uploadPrev=0;e.uploadCurrent=0;e.uploadTotal=0;this.updateEntryState_(e,zipextractor.state.EntryState.BEGIN_DECOMPRESSION);e.getData(new zip.BlobWriter,zipextractor.util.bindFn(this.decompressionComplete_,this,e,t,n),zipextractor.util.bindFn(this.handleDecompressionProgress_,this,e),true)};zipextractor.Session.prototype.handleDecompressionProgress_=function(e,t,n){if(this.isAborted_){return}e.decompressionPrev=e.decompressionCurrent?e.decompressionCurrent:0;e.decompressionCurrent=t;e.decompressionTotal=n;this.updateEntryState_(e,zipextractor.state.EntryState.DECOMPRESSION_PROGRESS);var r=e.decompressionCurrent-e.decompressionPrev;this.incrementSessionProgress_(e,r)};zipextractor.Session.prototype.decompressionComplete_=function(e,t,n,r){if(this.isAborted_){this.updateEntryState_(e,zipextractor.state.EntryState.CANCELED);this.checkForExtractionComplete_();return}this.updateEntryState_(e,zipextractor.state.EntryState.DECOMPRESSION_COMPLETE);this.uploadFile_(e,t,r,n)};zipextractor.Session.prototype.uploadFile_=function(e,t,n,r){if(this.isAborted_){this.updateEntryState_(e,zipextractor.state.EntryState.CANCELED);this.checkForExtractionComplete_();return}this.updateEntryState_(e,zipextractor.state.EntryState.BEGIN_UPLOAD);var i=this.fileManager_.generateCallbacks(zipextractor.util.bindFn(this.fileUploadComplete_,this,e,r),zipextractor.util.bindFn(this.fileUploadError_,this,e,r),zipextractor.util.bindFn(this.fileUploadProgress_,this,e),zipextractor.util.bindFn(this.fileUploadAborted_,this,e,r));this.fileManager_.insertBlob(n,e.name,t,i)};zipextractor.Session.prototype.fileUploadComplete_=function(e,t,n){e.file=n;this.updateEntryState_(e,zipextractor.state.EntryState.UPLOAD_COMPLETE);this.view_.updateUiForFileComplete(e,n.alternateLink,n.iconLink);this.incrementSessionProgress_(e,zipextractor.Session.ENTRY_OVERHEAD_BYTES_);t();if(this.isAborted_){this.checkForExtractionComplete_()}};zipextractor.Session.prototype.fileUploadError_=function(e,t,n,r){this.incrementSessionProgress_(e,zipextractor.Session.ENTRY_OVERHEAD_BYTES_);e.uploadError=n;e.message=r;this.updateEntryState_(e,zipextractor.state.EntryState.UPLOAD_ERROR,n);t();this.checkForExtractionComplete_()};zipextractor.Session.prototype.fileUploadAborted_=function(e,t,n){this.incrementSessionProgress_(e,zipextractor.Session.ENTRY_OVERHEAD_BYTES_);e.aborted=true;e.message=n;this.updateEntryState_(e,zipextractor.state.EntryState.UPLOAD_ABORTED,n);t();this.checkForExtractionComplete_()};zipextractor.Session.prototype.fileUploadProgress_=function(e,t,n){if(this.isAborted_){return}e.uploadPrev=e.uploadCurrent?e.uploadCurrent:0;e.uploadCurrent=t;e.uploadTotal=n;this.updateEntryState_(e,zipextractor.state.EntryState.UPLOAD_PROGRESS);if(t===n){this.updateEntryState_(e,zipextractor.state.EntryState.UPLOAD_ALL_BYTES_TRANSFERRED)}var r=e.uploadCurrent-e.uploadPrev;var i=e.uncompressedSize/n*r;this.incrementSessionProgress_(e,zipextractor.Session.TRANSFER_DECOMPRESS_MULTIPLIER_*i)};zipextractor.Session.prototype.folderInsertComplete_=function(e,t,n,r){e.folder=r;this.updateEntryState_(e,zipextractor.state.EntryState.UPLOAD_COMPLETE);this.view_.updateUiForFileComplete(e,zipextractor.util.createDriveFolderLink(r.id));this.incrementSessionProgress_(e,zipextractor.Session.ENTRY_OVERHEAD_BYTES_);n(r.id);t();if(this.isAborted_){this.checkForExtractionComplete_()}};zipextractor.Session.prototype.folderInsertError_=function(e,t,n,r){this.incrementSessionProgress_(e,zipextractor.Session.ENTRY_OVERHEAD_BYTES_);e.uploadError=n;e.message=r;this.updateEntryState_(e,zipextractor.state.EntryState.UPLOAD_ERROR,r);this.setAllChildEntriesQueuedPendingRetry_(e);t();this.checkForExtractionComplete_()};zipextractor.Session.prototype.folderInsertAborted_=function(e,t,n){this.incrementSessionProgress_(e,zipextractor.Session.ENTRY_OVERHEAD_BYTES_);e.aborted=true;e.message=n;this.updateEntryState_(e,zipextractor.state.EntryState.UPLOAD_ABORTED,n);this.cancelAllChildEntries_(e);t();this.checkForExtractionComplete_()};zipextractor.Session.prototype.cancelAllChildEntries_=function(e){for(var t in e.children){var n=e.children[t];this.updateEntryState_(n,zipextractor.state.EntryState.CANCELED);if(n.directory){this.cancelAllChildEntries_(n)}}};zipextractor.Session.prototype.setAllChildEntriesQueuedPendingRetry_=function(e){for(var t in e.children){var n=e.children[t];if(n.state!=zipextractor.state.EntryState.SKIPPED){this.updateEntryState_(n,zipextractor.state.EntryState.QUEUED_PENDING_RETRY);this.incrementSessionProgress_(n,zipextractor.Session.ENTRY_OVERHEAD_BYTES_);if(n.directory){this.setAllChildEntriesQueuedPendingRetry_(n)}}}};zipextractor.Session.prototype.workQueueExecutionComplete_=function(){this.checkForExtractionComplete_()};zipextractor.Session.prototype.checkForExtractionComplete_=function(){if(this.areAllStatesTerminal_()){if(this.isAborted_){this.presenter_.SESSION__extractionCanceled()}else{this.presenter_.SESSION__extractionComplete()}}};zipextractor.state.SessionState={DEFAULT:"default",INIT:"init",UNSUPPORTED_BROWSER:"unsupportedBrowser",NEW_SESSION:"newSession",APP_CREATE:"appCreate",APP_CREATED:"appCreated",APP_INIT:"appInit",AUTH_PENDING_AUTO:"authPendingAuto",AUTH_PENDING_USER:"authPendingUser",AUTH_REQUIRED:"authRequired",AUTH_SUCCESS:"authSuccess",AUTH_ERROR:"authError",DOWNLOADING:"downloading",DOWNLOADING_METADATA:"downloadingMetadata",CANCEL_DOWNLOAD_REQUESTED:"cancelDownloadRequested",DOWNLOAD_CANCELED:"downloadCanceled",DOWNLOAD_ALL_BYTES_TRANSFERRED:"downloadAllBytesTransferred",DOWNLOADED:"downloaded",DOWNLOAD_ERROR:"downloadError",ZIP_READING:"zipReading",ZIP_READ_ERROR:"zipReadError",MODEL_BUILDING:"modelBuilding",MODEL_BUILT:"modelBuilt",EXTRACTING:"extracting",EXTRACTION_COMPLETE:"extractionComplete",READ_URL_STATE:"readUrlState",API_LOADED:"apiLoaded",PENDING_USER_INPUT:"pendingUserInput",SESSION_CANCELED:"sessionCanceled",EXTRACTION_CANCEL_REQUESTED:"extractionCancelRequested",EXTRACTION_CANCELED:"extractionCanceled",RENDER_ZIP_UI:"renderZipUi",COMPLETE_WITH_ERRORS:"completeWithErrors"};zipextractor.state.EntryState={DEFAULT:"default",QUEUED:"queued",QUEUED_PENDING_RETRY:"queuedPendingRetry",SKIPPED:"skipped",PENDING:"pending",WAITING:"waiting",CANCELED:"canceled",BEGIN_DECOMPRESSION:"beginDecompression",DECOMPRESSION_PROGRESS:"decompressionProgress",DECOMPRESSION_COMPLETE:"decompressionComplete",DECOMPRESSION_ERROR:"decompressionError",BEGIN_UPLOAD:"beginUpload",UPLOAD_PROGRESS:"uploadProgress",UPLOAD_ERROR:"uploadError",UPLOAD_ALL_BYTES_TRANSFERRED:"uploadAllBytesTransferred",UPLOAD_COMPLETE:"uploadComplete",UPLOAD_ABORTED:"uploadAborted"};zipextractor.Table=function(e){this.tableEl_=e;this.rootEntry_=null};zipextractor.Table.INDENT_PX_=24;zipextractor.Table.BASE_INDENT_PX_=5;zipextractor.Table.UNCHECKED_COLOR_="#888";zipextractor.Table.IMAGES_PATH_="images/";zipextractor.Table.Icon_={CONTAINER:"folder.png",FOLDER:"folder.png",FILE:"file.png",SPINNER:"spinner.gif"};zipextractor.Table.prototype.clear=function(){while(this.tableEl_.rows.length>1){this.tableEl_.deleteRow(1)}this.rootEntry_=null};zipextractor.Table.prototype.lockForSession=function(e){this.getCheckboxForEntry_(e).disabled=true;this.disableCheckboxesForChildren_(e)};zipextractor.Table.prototype.updateChildEntryIndents_=function(e,t){for(var n in e.children){var r=e.children[n];this.shiftEntryPadding_(r,t);if(r.directory){this.updateChildEntryIndents_(r,t)}}};zipextractor.Table.prototype.shiftEntryPadding_=function(e,t){var n=e.tableRow.cells[0];var r=parseInt(n.style.paddingLeft,10);this.setCellPaddingLeft_(n,r+t)};zipextractor.Table.prototype.setCellPaddingLeft_=function(e,t){e.style.paddingLeft=t+"px"};zipextractor.Table.prototype.disableCheckboxesForChildren_=function(e){for(var t in e.children){var n=e.children[t];this.getCheckboxForEntry_(n).disabled=true;if(n.directory){this.disableCheckboxesForChildren_(n)}}};zipextractor.Table.prototype.isRootEntryFolderCreated=function(){return this.getCheckboxForEntry_(this.rootEntry_).checked};zipextractor.Table.prototype.generate=function(e,t){zipextractor.util.execLater(zipextractor.util.bindFn(this.generateInternal_,this,e),t)};zipextractor.Table.prototype.generateInternal_=function(e){this.clear();this.rootEntry_=e;e.tableRow=this.generateFileTableRow_(e,0);this.generateChildren_(e,1)};zipextractor.Table.prototype.generateChildren_=function(e,t){for(var n in e.children){var r=e.children[n];r.tableRow=this.generateFileTableRow_(r,t);if(r.directory){this.generateChildren_(r,t+1)}}};zipextractor.Table.prototype.generateFileTableRow_=function(e,t){var n=this.tableEl_.insertRow(-1);var r=n.insertCell(0);var i=n.insertCell(1);var s=n.insertCell(2);r.className="filenameCell";i.className="sizeCell";s.className="statusCell";r.style.paddingLeft=zipextractor.Table.BASE_INDENT_PX_+zipextractor.Table.INDENT_PX_*t+"px";var o=document.createElement("input");o.type="checkbox";o.checked="true";r.appendChild(o);var u=this;o.onclick=function(t){u.handleCheckboxClick_(e,t.target.checked)};var a=document.createElement("span");a.className="tableRowNameSpan";a.innerHTML=e.name;var f=this.getDefaultIconForEntry_(e);var l=this.getDefaultAltTextForEntry_(e);var c=document.createElement("img");c.className="tableRowIcon";c.setAttribute("src",f);c.setAttribute("alt",l);r.appendChild(c);r.appendChild(a);if(!e.directory&&e.uncompressedSize){i.innerHTML=zipextractor.util.formatSize(e.uncompressedSize)}else{i.innerHTML="——"}return n};zipextractor.Table.prototype.getDefaultIconForEntry_=function(e){return zipextractor.Table.IMAGES_PATH_+(e.directory?e.root?zipextractor.Table.Icon_.CONTAINER:zipextractor.Table.Icon_.FOLDER:zipextractor.Table.Icon_.FILE)};zipextractor.Table.prototype.getDefaultAltTextForEntry_=function(e){return e.directory?e.root?"Container icon":"Folder icon":"File icon"};zipextractor.Table.prototype.handleSelectAllCheckboxClick=function(e){var t=this.rootEntry_;var n=this.getCheckboxForEntry_(t).checked;this.setEntryChecked_(t,e);this.setChildEntriesCheckState_(t,e);if(n!==e){this.updateChildEntryIndents_(t,zipextractor.Table.INDENT_PX_*(e?1:-1))}};zipextractor.Table.prototype.setEntryChecked_=function(e,t){this.getCheckboxForEntry_(e).checked=t;this.updateEntryRowStyle_(e,t)};zipextractor.Table.prototype.updateEntryRowStyle_=function(e,t){e.tableRow.style.color=t?"inherit":zipextractor.Table.UNCHECKED_COLOR_};zipextractor.Table.prototype.handleCheckboxClick_=function(e,t){this.updateEntryRowStyle_(e,t);if(e.root){this.updateChildEntryIndents_(e,zipextractor.Table.INDENT_PX_*(t?1:-1));return}if(t){this.setParentEntriesCheckState_(e,true)}if(!t&&e.directory){this.setChildEntriesCheckState_(e,false)}};zipextractor.Table.prototype.setChildEntriesCheckState_=function(e,t){for(var n in e.children){var r=e.children[n];this.setEntryChecked_(r,t);if(r.directory){this.setChildEntriesCheckState_(r,t)}}};zipextractor.Table.prototype.setParentEntriesCheckState_=function(e,t){var n=e.parentEntry;if(n&&!n.root){this.setEntryChecked_(n,t);this.setParentEntriesCheckState_(n,t)}};zipextractor.Table.prototype.getCheckboxForEntry_=function(e){return e.tableRow.cells[0].firstChild};zipextractor.Table.prototype.isChecked=function(e){return this.getCheckboxForEntry_(e).checked};zipextractor.Table.prototype.updateEntryState=function(e,t,n){var r="";if(t!==null){r=this.translateEntryState_(t,e)}if(n!==null&&n!==-1){r+=" ("+n+")"}e.tableRow.cells[2].innerHTML=r};zipextractor.Table.prototype.updateEntryIcon=function(e,t,n){var r=t?t:n?zipextractor.Table.IMAGES_PATH_+zipextractor.Table.Icon_.SPINNER:this.getDefaultIconForEntry_(e);var i=t?this.getDefaultAltTextForEntry_(e):n?"Processing...":this.getDefaultAltTextForEntry_(e);var s=e.tableRow.cells[0].children[1];s.src=r;s.alt=i};zipextractor.Table.prototype.updateEntryLink=function(e,t){var n=this.getFilenameCell_(e);n.innerHTML='<a target="_blank" href="'+t+'">'+n.innerHTML+"</a>"};zipextractor.Table.prototype.translateEntryState_=function(e,t){switch(e){case zipextractor.state.EntryState.QUEUED:return"Queued";case zipextractor.state.EntryState.QUEUED_PENDING_RETRY:return"Queued (Pending resolution of error on parent folder)";case zipextractor.state.EntryState.SKIPPED:return"Skipped";case zipextractor.state.EntryState.PENDING:return"Pending";case zipextractor.state.EntryState.WAITING:return"Waiting";case zipextractor.state.EntryState.BEGIN_DECOMPRESSION:return"Decompressing...";case zipextractor.state.EntryState.DECOMPRESSION_PROGRESS:return"Decompressing...";case zipextractor.state.EntryState.DECOMPRESSION_COMPLETE:return"Decompressed";case zipextractor.state.EntryState.BEGIN_UPLOAD:return"Uploading...";case zipextractor.state.EntryState.UPLOAD_PROGRESS:return"Uploading...";case zipextractor.state.EntryState.UPLOAD_ERROR:return"Upload Error ("+t.message+")";case zipextractor.state.EntryState.UPLOAD_ALL_BYTES_TRANSFERRED:return"Finishing...";case zipextractor.state.EntryState.UPLOAD_COMPLETE:return"Uploaded";case zipextractor.state.EntryState.CANCELED:return"Canceled";case zipextractor.state.EntryState.UPLOAD_ABORTED:return"Aborted";default:return""}};zipextractor.Table.prototype.getFilenameCell_=function(e){return e.tableRow.cells[0].children[2]};zipextractor.View=function(e,t){this.model_=null;this.presenter_=e;this.table_=null;this.pickerManager_=t;this.isInitialized_=false;this.localFileInputEl=null;this.zipDropAreaDiv=null;this.chooseFileFromDriveButton=null;this.chooseLocalFileButton=null;this.resetButton=null;this.rateAppButton=null;this.viewFilesButton=null;this.retryErrorsButton=null;this.retryDownloadButton=null;this.shareFilesButton=null;this.cancelDownloadButton=null;this.downloadChromeButton=null;this.downloadFirefoxButton=null;this.downloadIeButton=null;this.destinationEl=null;this.fileTableDiv=null;this.fileTableHeaderEl=null;this.fileTable=null;this.primaryStatus=null;this.primaryStatusSpinner=null;this.primaryStatusProgress=null;this.primaryStatusText=null;this.primaryStatusProgressBar=null;this.selectAllCheckbox=null;this.extractNowButton=null;this.changeDestinationFolderButton=null;this.cancelSessionButton=null;this.cancelExtractionButton=null};zipextractor.View.APP_NAME_="ZIP Extractor";zipextractor.View.prototype.init=function(){if(this.isInitialized_){throw"Error: View already initialized."}this.attachDom_();this.attachListeners_();this.table_=new zipextractor.Table(this.fileTable);this.isInitialized_=true};zipextractor.View.prototype.attachDom_=function(){this.authButton=document.getElementById("authorizeButton");this.localFileInputEl=document.getElementById("filePicker");this.zipDropAreaDiv=document.getElementById("zipDropArea");this.chooseFileFromDriveButton=document.getElementById("chooseFromDriveButton");this.chooseLocalFileButton=document.getElementById("chooseLocalFileButton");this.resetButton=document.getElementById("resetButton");this.rateAppButton=document.getElementById("rateAppButton");this.viewFilesButton=document.getElementById("viewFilesButton");this.retryErrorsButton=document.getElementById("retryErrorsButton");this.retryDownloadButton=document.getElementById("retryDownloadButton");this.shareFilesButton=document.getElementById("shareFilesButton");this.cancelDownloadButton=document.getElementById("cancelDownloadButton");this.downloadChromeButton=document.getElementById("downloadChromeButton");this.downloadFirefoxButton=document.getElementById("downloadFirefoxButton");this.downloadIeButton=document.getElementById("downloadIeButton");this.destinationEl=document.getElementById("destinationFolderName");this.fileTableDiv=document.getElementById("fileTableDiv");this.primaryStatus=document.getElementById("primaryStatus");this.primaryStatusSpinner=document.getElementById("primaryStatusSpinner");this.primaryStatusProgress=document.getElementById("primaryStatusProgress");this.primaryStatusText=document.getElementById("primaryStatusText");this.primaryStatusProgressBar=document.getElementById("primaryStatusProgressBar");this.selectAllCheckbox=document.getElementById("selectAllCheckbox");this.extractNowButton=document.getElementById("extractNowButton");this.changeDestinationFolderButton=document.getElementById("changeDestinationFolderButton");this.cancelSessionButton=document.getElementById("cancelSessionButton");this.cancelExtractionButton=document.getElementById("cancelExtractionButton");this.fileTable=document.getElementById("fileTable");this.fileTableHeaderEl=document.getElementById("fileTableHeaderCaption")};zipextractor.View.prototype.attachListeners_=function(){this.chooseLocalFileButton.onclick=zipextractor.util.bindFn(this.handleChooseLocalFile_,this);this.localFileInputEl.onchange=zipextractor.util.bindFn(this.handleLocalFileInputElChange_,this);this.chooseFileFromDriveButton.onclick=zipextractor.util.bindFn(this.chooseFileFromDriveButtonClick_,this);this.changeDestinationFolderButton.onclick=zipextractor.util.bindFn(this.changeDestinationFolderButtonClick_,this);this.resetButton.onclick=zipextractor.util.bindFn(this.handleResetButtonClick_,this);this.rateAppButton.onclick=zipextractor.util.bindFn(this.handleRateAppButtonClick_,this);this.authButton.onclick=zipextractor.util.bindFn(this.handleAuthButtonClick_,this);this.cancelSessionButton.onclick=zipextractor.util.bindFn(this.handleCancelSessionButtonClick_,this);this.extractNowButton.onclick=zipextractor.util.bindFn(this.handleExtractNowButtonClick_,this);this.cancelExtractionButton.onclick=zipextractor.util.bindFn(this.handleCancelExtractionButtonClick_,this);this.shareFilesButton.onclick=zipextractor.util.bindFn(this.handleShareFilesButtonClick_,this);this.viewFilesButton.onclick=zipextractor.util.bindFn(this.handleViewFilesButtonClick_,this);this.retryErrorsButton.onclick=zipextractor.util.bindFn(this.handleRetryErrorsButtonClick_,this);this.retryDownloadButton.onclick=zipextractor.util.bindFn(this.handleRetryDownloadButtonClick_,this);this.cancelDownloadButton.onclick=zipextractor.util.bindFn(this.handleCancelDownloadButtonClick_,this);this.downloadChromeButton.onclick=zipextractor.util.bindFn(this.handleDownloadChromeButtonClick_,this);this.downloadFirefoxButton.onclick=zipextractor.util.bindFn(this.handleDownloadFirefoxButtonClick_,this);this.downloadIeButton.onclick=zipextractor.util.bindFn(this.handleDownloadIeButtonClick_,this);this.selectAllCheckbox.onclick=zipextractor.util.bindFn(this.handleSelectAllCheckboxClick_,this);this.zipDropAreaDiv.ondragenter=zipextractor.util.bindFn(this.handleZipDropAreaDragEnter_,this);this.zipDropAreaDiv.ondragleave=zipextractor.util.bindFn(this.handleZipDropAreaDragLeave_,this);this.zipDropAreaDiv.ondragover=zipextractor.util.bindFn(this.handleZipDropAreaDragOver_,this);this.zipDropAreaDiv.ondrop=zipextractor.util.bindFn(this.handleZipDropAreaDrop_,this)};zipextractor.View.prototype.isSelected=function(e){return this.table_.isChecked(e)};zipextractor.View.prototype.updateState=function(e,t,n){if(!this.isInitialized_){return}switch(e){case zipextractor.state.SessionState.API_LOADED:break;case zipextractor.state.SessionState.UNSUPPORTED_BROWSER:this.updatePrimaryStatus_(true,false,"Your browser version is not supported by ZIP Extractor. Please upgrade your browser.");this.showEl_(this.downloadChromeButton,true);this.showEl_(this.downloadFirefoxButton,true);this.showEl_(this.downloadIeButton,true);break;case zipextractor.state.SessionState.READ_URL_STATE:break;case zipextractor.state.SessionState.AUTH_PENDING_AUTO:this.updatePrimaryStatus_(true,true,"Checking authorization...");break;case zipextractor.state.SessionState.AUTH_PENDING_USER:this.authButton.disabled=true;this.updatePrimaryStatus_(true,true,'Authorization pending... (Click "Accept" in '+"the popup window to authorize ZIP Extractor to use Google Drive.)");break;case zipextractor.state.SessionState.AUTH_SUCCESS:this.authButton.disabled=true;this.showEl_(this.authButton,false);break;case zipextractor.state.SessionState.AUTH_ERROR:case zipextractor.state.SessionState.AUTH_REQUIRED:this.updatePrimaryStatus_(true,false,"Please authorize ZIP Extractor to access to Google Drive. "+'(Click "Authorize" below.)');this.authButton.disabled=false;this.showEl_(this.authButton,true);break;case zipextractor.state.SessionState.CANCEL_DOWNLOAD_REQUESTED:this.enableEl_(this.cancelDownloadButton,false);break;case zipextractor.state.SessionState.DOWNLOAD_CANCELED:this.showEl_(this.cancelDownloadButton,false);this.enableEl_(this.cancelDownloadButton,true);this.showEl_(this.retryDownloadButton,true);this.showEl_(this.resetButton,true);this.updatePrimaryStatus_(true,false,"Download canceled.");break;case zipextractor.state.SessionState.DOWNLOADING_METADATA:this.showEl_(this.chooseFileFromDriveButton,false);this.showEl_(this.chooseLocalFileButton,false);this.zipDropAreaDiv.style.visibility="hidden";this.showEl_(this.cancelDownloadButton,true);this.enableEl_(this.cancelDownloadButton,true);this.showEl_(this.retryDownloadButton,false);this.showEl_(this.resetButton,false);this.updatePrimaryStatus_(true,true,"Preparing to download file...");break;case zipextractor.state.SessionState.DOWNLOADING:var r=n;var i='Downloading "'+r.title+'" from Google Drive...';this.updatePrimaryStatus_(true,true,i);this.handleDownloadProgress(0,100);break;case zipextractor.state.SessionState.DOWNLOAD_ALL_BYTES_TRANSFERRED:this.updatePrimaryStatus_(true,false,"Finishing download...");break;case zipextractor.state.SessionState.DOWNLOADED:this.showEl_(this.cancelDownloadButton,false);this.updatePrimaryStatus_(true,false,"File downloaded.");break;case zipextractor.state.SessionState.DOWNLOAD_ERROR:this.updateUiForDownloadError_(n);break;case zipextractor.state.SessionState.INIT:break;case zipextractor.state.SessionState.ZIP_READ_ERROR:this.updatePrimaryStatus_(true,false,"Error reading ZIP file: "+n);this.enableEl_(this.chooseFileFromDriveButton,true);this.enableEl_(this.chooseLocalFileButton,true);this.showEl_(this.chooseFileFromDriveButton,false);this.showEl_(this.chooseLocalFileButton,false);this.showEl_(this.resetButton,true);this.showEl_(this.cancelExtractionButton,false);break;case zipextractor.state.SessionState.MODEL_BUILDING:this.updatePrimaryStatus_(true,true,"Processing ZIP file...");break;case zipextractor.state.SessionState.MODEL_BUILT:this.model_=n;break;case zipextractor.state.SessionState.SESSION_CANCELED:break;case zipextractor.state.SessionState.EXTRACTION_CANCEL_REQUESTED:this.updateUiForExtractionCancelRequested_();break;case zipextractor.state.SessionState.EXTRACTION_CANCELED:this.updateUiForExtractionCanceled_();break;case zipextractor.state.SessionState.RENDER_ZIP_UI:this.renderZipTableUi_(n);break;case zipextractor.state.SessionState.PENDING_USER_INPUT:this.promptToExtract_();break;case zipextractor.state.SessionState.ZIP_READING:this.updatePrimaryStatus_(true,true,"Reading ZIP file...");this.enableEl_(this.chooseFileFromDriveButton,false);this.enableEl_(this.chooseLocalFileButton,false);this.zipDropAreaDiv.style.visibility="hidden";break;case zipextractor.state.SessionState.EXTRACTING:this.updateUiForExtractionStart_(n);this.handleSessionProgress(0,100);break;case zipextractor.state.SessionState.NEW_SESSION:this.setupForNewSession_();break;case zipextractor.state.SessionState.EXTRACTION_COMPLETE:this.updateUiForExtractionComplete_(n);break;default:throw"Unexpected state: "+e}};zipextractor.View.prototype.updateEntryState=function(e,t,n){var r=null;switch(t){case zipextractor.state.EntryState.QUEUED:break;case zipextractor.state.EntryState.QUEUED_PENDING_RETRY:break;case zipextractor.state.EntryState.SKIPPED:break;case zipextractor.state.EntryState.PENDING:break;case zipextractor.state.EntryState.CANCELED:this.updateEntryIconForState_(e,true);break;case zipextractor.state.EntryState.BEGIN_UPLOAD:this.updateEntryIconForState_(e,false);break;case zipextractor.state.EntryState.UPLOAD_PROGRESS:r=Math.round(100*e.uploadCurrent/e.uploadTotal)+"%";break;case zipextractor.state.EntryState.UPLOAD_ALL_BYTES_TRANSFERRED:break;case zipextractor.state.EntryState.UPLOAD_COMPLETE:break;case zipextractor.state.EntryState.UPLOAD_ERROR:this.updateEntryIconForState_(e,true);break;case zipextractor.state.EntryState.UPLOAD_ABORTED:this.updateEntryIconForState_(e,true);break;case zipextractor.state.EntryState.BEGIN_DECOMPRESSION:this.updateEntryIconForState_(e,false);break;case zipextractor.state.EntryState.DECOMPRESSION_PROGRESS:r=Math.round(100*e.decompressionCurrent/e.decompressionTotal)+"%";break;case zipextractor.state.EntryState.DECOMPRESSION_COMPLETE:break;default:throw"Unexpected state: "+t}this.table_.updateEntryState(e,t,r)};zipextractor.View.prototype.updateEntryIconForState_=function(e,t){this.table_.updateEntryIcon(e,undefined,!t)};zipextractor.View.prototype.handleDownloadProgress=function(e,t){var n=5+95*(e/t);this.updatePrimaryStatus_(true,false,"",true,true,Math.round(n))};zipextractor.View.prototype.handleSessionProgress=function(e,t){var n=100*(e/t);this.updatePrimaryStatus_(true,false,"",true,true,Math.round(n))};zipextractor.View.prototype.updatePageTitle=function(e){document.title=e?e+" - "+zipextractor.View.APP_NAME_:zipextractor.View.APP_NAME_};zipextractor.View.prototype.updateUiForFileComplete=function(e,t,n){if(t){this.table_.updateEntryLink(e,t)}if(n){this.table_.updateEntryIcon(e,n)}else{this.updateEntryIconForState_(e,true)}};zipextractor.View.prototype.handleSelectAllCheckboxClick_=function(e){this.table_.handleSelectAllCheckboxClick(e.target.checked)};zipextractor.View.prototype.updatePrimaryStatus_=function(e,t,n,r,i,s){if(!r){this.primaryStatusText.innerHTML=n||""}this.showEl_(this.primaryStatusProgress,e);this.showEl_(this.primaryStatusSpinner,t);if(i){this.primaryStatusProgressBar.style.width=""+s+"%"}this.showEl_(this.primaryStatusProgress,!!i)};zipextractor.View.prototype.renderZipTableUi_=function(e){this.fileTableHeaderEl.innerHTML=this.model_.getFilename();this.table_.generate(this.model_.getEntryTree(),zipextractor.util.bindFn(this.zipTableUiRendered_,this,e))};zipextractor.View.prototype.zipTableUiRendered_=function(e){this.showEl_(this.fileTableDiv,true);e()};zipextractor.View.prototype.updateUiForExtractionComplete_=function(e){this.showEl_(this.extractNowButton,false);this.showEl_(this.cancelExtractionButton,false);this.showEl_(this.viewFilesButton,true);this.showEl_(this.retryErrorsButton,e);this.showEl_(this.resetButton,true);this.showEl_(this.rateAppButton,!e);if(!e){this.showEl_(this.shareFilesButton,this.table_.isRootEntryFolderCreated())}var t=e?"Extraction complete, but with one or more errors.":"Extraction complete.";this.updatePrimaryStatus_(true,false,t)};zipextractor.View.prototype.updateUiForExtractionStart_=function(e){this.showEl_(this.extractNowButton,false);this.showEl_(this.cancelSessionButton,false);this.showEl_(this.changeDestinationFolderButton,false);this.showEl_(this.cancelExtractionButton,true);this.enableEl_(this.cancelExtractionButton,true);this.showEl_(this.retryErrorsButton,false);this.showEl_(this.viewFilesButton,false);this.showEl_(this.resetButton,false);this.showEl_(this.rateAppButton,false);this.enableEl_(this.selectAllCheckbox,false);this.table_.lockForSession(e);this.updatePrimaryStatus_(true,false,"Extracting ZIP file to Drive...")};zipextractor.View.prototype.setupForNewSession_=function(){this.showEl_(this.extractNowButton,false);this.showEl_(this.cancelSessionButton,false);this.showEl_(this.changeDestinationFolderButton,false);this.showEl_(this.viewFilesButton,false);this.showEl_(this.retryErrorsButton,false);this.showEl_(this.retryDownloadButton,false);this.showEl_(this.shareFilesButton,false);this.showEl_(this.resetButton,false);this.showEl_(this.rateAppButton,false);this.showEl_(this.cancelDownloadButton,false);this.showEl_(this.fileTableDiv,false);this.showEl_(this.chooseFileFromDriveButton,true);this.showEl_(this.chooseLocalFileButton,true);this.enableEl_(this.chooseFileFromDriveButton,true);this.enableEl_(this.chooseLocalFileButton,true);this.showEl_(this.zipDropAreaDiv,true);this.zipDropAreaDiv.style.visibility="";this.table_.clear();this.enableEl_(this.selectAllCheckbox,true);this.updatePrimaryStatus_(true,false,"Choose a ZIP file to extract.")};zipextractor.View.prototype.promptToExtract_=function(){this.updatePrimaryStatus_(true,false,"Ready to extract ZIP file.");this.showEl_(this.extractNowButton,true);this.showEl_(this.cancelSessionButton,true);this.showEl_(this.changeDestinationFolderButton,true);this.showEl_(this.chooseFileFromDriveButton,false);this.showEl_(this.chooseLocalFileButton,false);this.showEl_(this.zipDropAreaDiv,false);this.showEl_(this.cancelDownloadButton,false)};zipextractor.View.prototype.updateUiForExtractionCancelRequested_=function(){this.enableEl_(this.cancelExtractionButton,false);this.updatePrimaryStatus_(true,false,"Canceling extraction...")};zipextractor.View.prototype.updateUiForExtractionCanceled_=function(){this.showEl_(this.cancelExtractionButton,false);this.showEl_(this.viewFilesButton,true);this.showEl_(this.retryErrorsButton,false);this.showEl_(this.resetButton,true);this.updatePrimaryStatus_(true,false,"Extraction canceled.")};zipextractor.View.prototype.updateUiForDownloadError_=function(e){this.showEl_(this.cancelDownloadButton,false);this.showEl_(this.retryDownloadButton,true);this.showEl_(this.resetButton,true);this.updatePrimaryStatus_(true,false,"Unable to download file. ("+e+")")};zipextractor.View.prototype.updateDestinationFolderUi=function(e){var t=zipextractor.util.createDriveFolderLink(e.id);var n='Ready to extract ZIP file to "<a target="_blank" href="'+t+'">'+e.name+'</a>".';this.updatePrimaryStatus_(true,false,n)};zipextractor.View.prototype.handleChooseLocalFile_=function(e){this.localFileInputEl.click()};zipextractor.View.prototype.chooseFileFromDriveButtonClick_=function(e){this.pickerManager_.show(zipextractor.util.PickerManager.PickerMode.FILE,zipextractor.util.bindFn(this.handlePickerFileSelected_,this))};zipextractor.View.prototype.changeDestinationFolderButtonClick_=function(e){this.pickerManager_.show(zipextractor.util.PickerManager.PickerMode.FOLDER,zipextractor.util.bindFn(this.handlePickerFolderSelected_,this))};zipextractor.View.prototype.handlePickerFileSelected_=function(e){this.presenter_.VIEW__driveFileChosen(e)};zipextractor.View.prototype.handlePickerFolderSelected_=function(e){this.presenter_.VIEW__driveFolderChosen(e)};zipextractor.View.prototype.handleLocalFileInputElChange_=function(e){var t=e.target.files[0];if(t){this.presenter_.VIEW__localBlobChosen(t.name,t)}};zipextractor.View.prototype.handleZipDropAreaDragEnter_=function(e){e.stopPropagation();e.preventDefault();e.dataTransfer.allowedEffect="copyMove";this.zipDropAreaDiv.classList.add("zipDropAreaHover")};zipextractor.View.prototype.handleZipDropAreaDragLeave_=function(e){e.stopPropagation();e.preventDefault();this.zipDropAreaDiv.classList.remove("zipDropAreaHover")};zipextractor.View.prototype.handleZipDropAreaDragOver_=function(e){e.stopPropagation();e.preventDefault();e.dataTransfer.dropEffect="move"};zipextractor.View.prototype.handleZipDropAreaDrop_=function(e){e.stopPropagation();e.preventDefault();this.zipDropAreaDiv.classList.remove("zipDropAreaHover");var t=e.dataTransfer.files;if(t&&t.length==1){var n=t[0];var r=n.name;var i=".zip";if(r.indexOf(i,r.length-i.length)!==-1){this.presenter_.VIEW__localBlobChosen(n.name,n)}}};zipextractor.View.prototype.handleAuthButtonClick_=function(e){this.presenter_.VIEW__authRequested()};zipextractor.View.prototype.handleExtractNowButtonClick_=function(e){this.presenter_.VIEW__extractNow()};zipextractor.View.prototype.handleCancelSessionButtonClick_=function(){this.presenter_.VIEW__cancelSession()};zipextractor.View.prototype.handleResetButtonClick_=function(){this.presenter_.VIEW__reset()};zipextractor.View.prototype.handleRateAppButtonClick_=function(){this.presenter_.VIEW__rateApp()};zipextractor.View.prototype.showEl_=function(e,t){e.style.display=t?"":"none"};zipextractor.View.prototype.enableEl_=function(e,t){e.disabled=!t};zipextractor.View.prototype.handleCancelExtractionButtonClick_=function(e){this.presenter_.VIEW__cancelExtraction()};zipextractor.View.prototype.handleViewFilesButtonClick_=function(e){this.presenter_.VIEW__viewExtractedFiles()};zipextractor.View.prototype.handleRetryErrorsButtonClick_=function(e){this.presenter_.VIEW__retryErrors()};zipextractor.View.prototype.handleRetryDownloadButtonClick_=function(e){this.presenter_.VIEW__retryDownload()};zipextractor.View.prototype.handleShareFilesButtonClick_=function(e){this.presenter_.VIEW__shareExtractedFiles()};zipextractor.View.prototype.handleCancelDownloadButtonClick_=function(e){this.presenter_.VIEW__cancelDownload()};zipextractor.View.prototype.handleDownloadChromeButtonClick_=function(e){this.presenter_.VIEW__downloadBrowser("chrome")};zipextractor.View.prototype.handleDownloadFirefoxButtonClick_=function(e){this.presenter_.VIEW__downloadBrowser("firefox")};zipextractor.View.prototype.handleDownloadIeButtonClick_=function(e){this.presenter_.VIEW__downloadBrowser("ie")};zipextractor.ZipReader=function(){};zipextractor.ZipReader.prototype.read=function(e,t,n){zip.createReader(new zip.BlobReader(e),zipextractor.util.bindFn(this.readZipManifest_,this,t),zipextractor.util.bindFn(this.handleError_,this,n))};zipextractor.ZipReader.prototype.readZipManifest_=function(e,t){t.getEntries(zipextractor.util.bindFn(this.zipManifestReadComplete_,this,t,e))};zipextractor.ZipReader.prototype.zipManifestReadComplete_=function(e,t,n){e.close(zipextractor.util.bindFn(this.readerClosed_,this,n,t))};zipextractor.ZipReader.prototype.readerClosed_=function(e,t){t(e)};zipextractor.ZipReader.prototype.handleError_=function(e,t){e(t)}
from typing import cast, List, Dict, Set, Optional from abc import ABC, abstractmethod from enum import Enum from spec_random import SPEC_RANDOM from spec_basis import Rand, Kobj, KindSend, KindRecv, Lego, Syscall, Program, \ Executable from spec_pack import pack_int from util_bean import Bean class RandInt(Rand): data: int class KobjInt(Kobj): pass class KindSendInt(KindSend[RandInt], ABC): bits: int signed: bool def __init__(self) -> None: super().__init__() self.int_min = 0 self.int_max = 0 # bean def validate(self) -> None: assert self.bits in {8, 16, 32, 64} self.int_min = -(2 ** (self.bits - 1)) if self.signed else 0 self.int_max = (2 ** (self.bits - (1 if self.signed else 0))) - 1 # chain def link(self, ctxt: Syscall) -> None: pass # memory def length(self) -> Optional[int]: return self.bits // 8 # builder def mk_rand(self) -> RandInt: return RandInt() # utils def sanitize(self, data: int) -> int: if data < self.int_min: return self.int_min if data > self.int_max: return self.int_max return data @abstractmethod def toss(self) -> int: raise RuntimeError('Method not implemented') def drag(self, data: int) -> int: p = SPEC_RANDOM.random() if p < 0.45: # [DRAG] inc/dec based on the existing value step = abs(data // 10) retv = data + SPEC_RANDOM.choice([ 1, step, data, -1, -step, -2 * data, ]) elif p < 0.9: # [DRAG] choose from an extreme value (integer range-wise) retv = SPEC_RANDOM.choice([ 0, 1, 4096, -1, -4096, self.int_min, self.int_min + 1, self.int_min + 4096, self.int_max, self.int_max - 1, self.int_max - 4096, ]) else: # [DRAG] choose a random number within the integer range retv = SPEC_RANDOM.randint(self.int_min, self.int_max) # sanitize return self.sanitize(retv) # operations: engage and remove def engage_rand(self, rand: RandInt, prog: Program) -> None: # init rand.data = self.toss() def remove_rand(self, rand: RandInt, prog: Program) -> None: pass # operations: mutate and puzzle def mutate_rand(self, rand: RandInt, prog: Program) -> None: rand.data = self.toss() def puzzle_rand(self, rand: RandInt, prog: Program) -> None: rand.data = self.drag(rand.data) # operations: update def update_rand(self, rand: RandInt, prog: Program) -> None: pass # operations: migrate def migrate_rand( self, rand: RandInt, orig: RandInt, ctxt: Dict[Bean, Bean], hist: Set[Lego] ) -> None: rand.data = orig.data # show def expo_rand(self, rand: RandInt) -> str: return str(rand.data) # blob def blob_size_rand(self, rand: RandInt) -> int: return cast(int, self.length()) def blob_hole_rand(self, rand: RandInt, inst: Executable) -> None: pass def blob_data_rand(self, rand: RandInt, inst: Executable) -> bytes: return pack_int(rand.data, self.bits, self.signed) def blob_fill_rand(self, rand: RandInt, inst: Executable) -> None: pass # relationship def rely_on_rand(self, rand: RandInt, prog: Program) -> Set[int]: return set() class KindSendIntConst(KindSendInt): val_const: int # bean def validate(self) -> None: assert self.int_min <= self.val_const <= self.int_max # debug def note(self) -> str: return str(self.val_const) # utils def toss(self) -> int: return self.val_const def drag(self, data: int) -> int: p = SPEC_RANDOM.random() if p < 0.5: # [DRAG] inc/dec based on the given constant value step = abs(self.val_const // 10) retv = SPEC_RANDOM.choice([ self.val_const + 1, self.val_const + step, self.val_const, self.val_const - 1, self.val_const - step, -2 * self.val_const, ]) return self.sanitize(retv) else: # [DRAG] use parent strategy return super().drag(data) class IntFlagOperation(Enum): AND = '&' OR = '|' XOR = '^' class KindSendIntFlag(KindSendInt): name: str vals: Set[int] elem_min: int elem_max: int use_ops: List[IntFlagOperation] use_neg: bool def __init__(self) -> None: super().__init__() self.elem_set = [] # type: List[int] # defaults def default_elem_min(self) -> int: return 0 def default_elem_max(self) -> int: return len(self.vals) def default_use_ops(self) -> List[IntFlagOperation]: return [IntFlagOperation.OR] def default_use_neg(self) -> bool: return False # bean def validate(self) -> None: elem_set = set(self.vals) if self.use_neg: elem_set.update({(~i) for i in self.vals}) assert self.elem_min <= self.elem_max <= len(elem_set) self.elem_set.extend(sorted(elem_set)) # debug def note(self) -> str: return self.name # utils def toss(self) -> int: num = SPEC_RANDOM.randint(self.elem_min, self.elem_max) if num == 0: return 0 vas = SPEC_RANDOM.sample(self.elem_set, num) ops = [SPEC_RANDOM.choice(self.use_ops) for _ in range(num - 1)] res = vas[0] for i in range(1, num): if ops[i - 1] == IntFlagOperation.OR: res = res | vas[i] elif ops[i - 1] == IntFlagOperation.AND: res = res & vas[i] elif ops[i - 1] == IntFlagOperation.XOR: res = res ^ vas[i] else: raise RuntimeError('Invalid flag operation') return res def drag(self, data: int) -> int: p = SPEC_RANDOM.random() if p < 0.1: # [DRAG] use 0 return 0 elif p < 0.5: # [DRAG] use | with all flags res = 0 for i in self.elem_set: res = res | i return res else: # [DRAG] use parent strategy return super().drag(data) class KindSendIntRange(KindSendInt): val_min: int val_max: int # defaults def default_val_min(self) -> int: return cast(int, -(2 ** (self.bits - 1)) if self.signed else 0) def default_val_max(self) -> int: return cast(int, (2 ** (self.bits - (1 if self.signed else 0))) - 1) # bean def validate(self) -> None: assert self.int_min <= self.val_min <= self.val_max <= self.int_max # debug def note(self) -> str: min_repr = 'MIN' if self.val_min == self.int_min else str(self.val_min) max_repr = 'MAX' if self.val_max == self.int_max else str(self.val_max) return min_repr + '-' + max_repr # utils def toss(self) -> int: return SPEC_RANDOM.randint(self.val_min, self.val_max) def drag(self, data: int) -> int: p = SPEC_RANDOM.random() if p < 0.5: # [DRAG] choose from an extreme value (given range-wise) val_mid = (self.val_min + self.val_max) // 2 step_min = abs(self.val_min // 10) step_max = abs(self.val_max // 10) retv = SPEC_RANDOM.choice([ self.val_min, self.val_max, val_mid, self.val_min - 1, self.val_min - step_min, self.val_max - 1, self.val_max - step_max, self.val_min + 1, self.val_min + step_min, self.val_max + 1, self.val_max + step_max, ]) return self.sanitize(retv) else: # [DRAG] use parent strategy return super().drag(data) class KindRecvInt(KindRecv[KobjInt], ABC): bits: int signed: bool # bean def validate(self) -> None: assert self.bits in {8, 16, 32, 64} # memory def length(self) -> Optional[int]: return self.bits // 8 # builder def mk_kobj(self) -> KobjInt: return KobjInt() # operations: engage and remove def engage_kobj(self, kobj: KobjInt, prog: Program) -> None: pass def remove_kobj(self, kobj: KobjInt, prog: Program) -> None: pass # show def expo_kobj(self, kobj: KobjInt) -> str: return str('-X-') # blob def blob_size_kobj(self, kobj: KobjInt) -> int: return cast(int, self.length()) def blob_hole_kobj(self, kobj: KobjInt, inst: Executable) -> None: pass def blob_data_kobj(self, kobj: KobjInt, inst: Executable) -> bytes: return pack_int(0, self.bits, self.signed) def blob_fill_kobj(self, kobj: KobjInt, inst: Executable) -> None: pass # relationship def rely_on_kobj(self, kobj: KobjInt, prog: Program) -> Set[int]: return set() class KindRecvIntData(KindRecvInt): # debug def note(self) -> str: return '' # chain def link(self, ctxt: Syscall) -> None: pass
/* * The copyright in this software is being made available under the BSD License, included below. This software may be subject to other third party and contributor rights, including patent rights, and no such rights are granted under this license. * * Copyright (c) 2013, Digital Primates * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * • Neither the name of the Digital Primates 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. */ MediaPlayer.dependencies.BufferExtensions = function () { "use strict"; var minBufferTarget, currentBufferTarget, topAudioQualityIndex = 0, topVideoQualityIndex = 0, audioData = null, videoData = null, getCurrentHttpRequestLatency = function(metrics) { var httpRequest = this.metricsExt.getCurrentHttpRequest(metrics); if (httpRequest !== null) { return (httpRequest.tresponse.getTime() - httpRequest.trequest.getTime()) / 1000; } return 0; }, isPlayingAtTopQuality = function() { var self = this, audioQuality, videoQuality, isAtTop; audioQuality = audioData ? self.abrController.getQualityFor("audio") : topAudioQualityIndex; videoQuality = videoData ? self.abrController.getQualityFor("video") : topVideoQualityIndex; isAtTop = (audioQuality === topAudioQualityIndex) && (videoQuality === topVideoQualityIndex); return isAtTop; }; return { system:undefined, videoModel: undefined, metricsExt: undefined, metricsModel: undefined, abrController: undefined, bufferMax: undefined, updateData: function(data, type) { if (data) { var topIndex = data.Representation_asArray.length - 1; if (type === "audio") { topAudioQualityIndex = topIndex; audioData = data; } else if (type === "video") { topVideoQualityIndex = topIndex; videoData = data; } } }, getTopQualityIndex: function(type) { var topQualityIndex = null; if (type === "audio") { topQualityIndex = topAudioQualityIndex; } else if (type === "video") { topQualityIndex = topVideoQualityIndex; } return topQualityIndex; }, decideBufferLength: function (minBufferTime, duration/*, waitingForBuffer*/) { if (isNaN(duration) || MediaPlayer.dependencies.BufferExtensions.DEFAULT_MIN_BUFFER_TIME < duration && minBufferTime < duration) { minBufferTarget = Math.max(MediaPlayer.dependencies.BufferExtensions.DEFAULT_MIN_BUFFER_TIME, minBufferTime); } else if (minBufferTime >= duration) { minBufferTarget = Math.min(duration, MediaPlayer.dependencies.BufferExtensions.DEFAULT_MIN_BUFFER_TIME); } else { minBufferTarget = Math.min(duration, minBufferTime); } return minBufferTarget; }, getLeastBufferLevel: function() { var videoMetrics = this.metricsModel.getReadOnlyMetricsFor("video"), videoBufferLevel = this.metricsExt.getCurrentBufferLevel(videoMetrics), audioMetrics = this.metricsModel.getReadOnlyMetricsFor("audio"), audioBufferLevel = this.metricsExt.getCurrentBufferLevel(audioMetrics), leastLevel = null; if (videoBufferLevel === null || audioBufferLevel === null) { leastLevel = (audioBufferLevel !== null) ? audioBufferLevel.level : ((videoBufferLevel !== null) ? videoBufferLevel.level : null); } else { leastLevel = Math.min(audioBufferLevel.level, videoBufferLevel.level); } return leastLevel; }, getRequiredBufferLength: function (waitingForBuffer, delay, isDynamic, duration) { var self = this, vmetrics = self.metricsModel.getReadOnlyMetricsFor("video"), ametrics = self.metricsModel.getReadOnlyMetricsFor("audio"), isLongFormContent = (duration >= MediaPlayer.dependencies.BufferExtensions.LONG_FORM_CONTENT_DURATION_THRESHOLD), deferred = Q.defer(), isAtTop = false, requiredBufferLength; if (self.bufferMax === MediaPlayer.dependencies.BufferExtensions.BUFFER_SIZE_MIN) { requiredBufferLength = minBufferTarget; deferred.resolve(requiredBufferLength); } else if (self.bufferMax === MediaPlayer.dependencies.BufferExtensions.BUFFER_SIZE_INFINITY) { requiredBufferLength = duration; deferred.resolve(requiredBufferLength); } else if (self.bufferMax === MediaPlayer.dependencies.BufferExtensions.BUFFER_SIZE_REQUIRED) { currentBufferTarget = minBufferTarget; if (!isDynamic) { if (!waitingForBuffer) { isAtTop = isPlayingAtTopQuality.call(self); } } if (isAtTop) { currentBufferTarget = isLongFormContent ? MediaPlayer.dependencies.BufferExtensions.BUFFER_TIME_AT_TOP_QUALITY_LONG_FORM : MediaPlayer.dependencies.BufferExtensions.BUFFER_TIME_AT_TOP_QUALITY; } requiredBufferLength = currentBufferTarget + delay + Math.max(getCurrentHttpRequestLatency.call(self, vmetrics), getCurrentHttpRequestLatency.call(self, ametrics)); deferred.resolve(requiredBufferLength); } else { deferred.reject("invalid bufferMax value: " + self.bufferMax); } return deferred.promise; }, //TODO: need to add this info to MediaPlayer.vo.metrics.BufferLevel or create new metric? getBufferTarget: function() { return currentBufferTarget === undefined ? minBufferTarget : currentBufferTarget; } }; }; MediaPlayer.dependencies.BufferExtensions.BUFFER_SIZE_REQUIRED = "required"; MediaPlayer.dependencies.BufferExtensions.BUFFER_SIZE_MIN = "min"; MediaPlayer.dependencies.BufferExtensions.BUFFER_SIZE_INFINITY = "infinity"; MediaPlayer.dependencies.BufferExtensions.BUFFER_TIME_AT_STARTUP = 1; MediaPlayer.dependencies.BufferExtensions.DEFAULT_MIN_BUFFER_TIME = 16; MediaPlayer.dependencies.BufferExtensions.DEFAULT_BUFFER_TO_KEEP = 30; MediaPlayer.dependencies.BufferExtensions.DEFAULT_LIVE_DELAY = 16; MediaPlayer.dependencies.BufferExtensions.BUFFER_TIME_AT_TOP_QUALITY = 30; MediaPlayer.dependencies.BufferExtensions.BUFFER_TIME_AT_TOP_QUALITY_LONG_FORM = 300; MediaPlayer.dependencies.BufferExtensions.LONG_FORM_CONTENT_DURATION_THRESHOLD = 600; MediaPlayer.dependencies.BufferExtensions.prototype.constructor = MediaPlayer.dependencies.BufferExtensions;
import alt from '../alt' import FormActions from '../actions/FormActions' import UserActions from '../actions/UserActions' class FormStore { constructor () { this.bindActions(FormActions) this.bindListeners({ onRegisterUserFail: UserActions.registerUserFail, onRegisterUserSuccess: UserActions.registerUserSuccess, onLoginUserSuccess: UserActions.loginUserSuccess, onLoginUserFail: UserActions.loginUserFail }) this.username = '' this.password = '' this.confirmedPassword = '' this.firstName = '' this.lastName = '' this.age = '' this.picture = '' this.gender = '' this.formSubmitState = '' this.usernameValidationState = '' this.passwordValidationState = '' this.message = '' this.relocate = '' } onUnauthorizedAccessAttempt () { this.formSubmitState = 'has-error' this.usernameValidationState = '' this.passwordValidationState = '' this.message = 'Please login.' } onLoginUserSuccess () { this.formSubmitState = 'has-success' this.usernameValidationState = '' this.passwordValidationState = '' this.message = 'User login successful' this.relocate = '/' } onLoginUserFail (err) { this.formSubmitState = 'has-error' this.usernameValidationState = 'has-error' this.passwordValidationState = 'has-error' this.message = err.message } onRegisterUserSuccess (data) { console.log('FormStore register success') this.formSubmitState = 'has-success' this.usernameValidationState = '' this.passwordValidationState = '' this.message = 'User register successful' this.relocate = '/user/login' } onRegisterUserFail (err) { console.log('FormStore register error', err) if (err.code === 11000) { this.usernameValidationState = 'has-error' this.message = 'Username already in use' return } this.formSubmitState = 'has-error' this.message = err.errmsg } onUsernameValidationFail () { this.usernameValidationState = 'has-error' this.passwordValidationState = '' this.formSubmitState = '' this.message = 'Enter username' } onPasswordValidationFail () { this.passwordValidationState = 'has-error' this.usernameValidationState = '' this.formSubmitState = '' this.message = 'Invalid password, or passwords do not match' } onHandleUsernameChange (e) { this.username = e.target.value } onHandlePasswordChange (e) { this.password = e.target.value } onHandleConfirmedPasswordChange (e) { this.confirmedPassword = e.target.value } onHandleFirstNameChange (e) { this.firstName = e.target.value } onHandleLastNameChange (e) { this.lastName = e.target.value } handleLastPictureChange (e) { this.picture = e.target.value } onHandleAgeChange (e) { this.age = e.target.value } onHandleGenderChange (e) { this.gender = e.target.value } onAddCommentFail (err) { this.commentValidationState = 'has-error' this.message = err.message } onCommentValidationFail () { this.commentValidationState = 'has-error' this.message = 'Please enter comment text.' } onHandleCommentChange (e) { this.comment = e.target.value } onHandleScoreChange (e) { this.score = e.target.value } onScoreValidationFail () { this.scoreValidationState = 'has-error' this.message = 'Valid score is between 0 - 10' } onAddVoteSuccess () { this.scoreValidationState = '' this.message = '' } onAddVoteFail (err) { this.scoreValidationState = 'has-error' this.message = err.message } } export default alt.createStore(FormStore)
import 'core-js/stable' import 'regenerator-runtime/runtime' import 'whatwg-fetch' import 'assets/styles/base.sass' import React from 'react' import ReactDOM from 'react-dom' import MainContainer from 'components/Main' import scroll from 'utils/scroll' scroll.resetScroll() ReactDOM.render(( <article> <MainContainer /> </article> ), document.getElementById('wrapper'))
import { Directive, ElementRef, forwardRef } from '@angular/core'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; /** * @element ons-checkbox * @directive OnsCheckbox * @selector ons-checkbox * @description * [en]Angular directive for `<ons-checkbox>` component. You can use `[(ngModel)]` to synchronize the value of `[(ngModel)]` with the array of the selected values.[/en] * [ja]`<ons-checkbox>`要素のAngularディレクティブです。 `[(ngModel)]` を使用すると、 `[(ngModel)]` の値を選択された値の配列と同期することができます。[/ja] * @example * <ons-checkbox value="Item A" [(ngModel)]="selectedValues"></ons-checkbox> * <ons-checkbox value="Item B" [(ngModel)]="selectedValues"></ons-checkbox> * <ons-checkbox value="Item C" [(ngModel)]="selectedValues"></ons-checkbox> */ var OnsCheckbox = (function () { function OnsCheckbox(_elementRef) { this._elementRef = _elementRef; this._propagateChange = function (_) { }; this._boundOnChange = this._onChange.bind(this); this._element = _elementRef.nativeElement; this._element.addEventListener('change', this._boundOnChange); } OnsCheckbox.prototype._onChange = function (event) { var _a = event.target, value = _a.value, checked = _a.checked; var newValue; if (this._state instanceof Array) { // Is Array var index = this._state.indexOf(value); var included = index >= 0; if (included && !checked) { newValue = this._state.slice(0, index).concat(this._state.slice(index + 1, this._state.length)); } if (!included && checked) { newValue = this._state.concat([value]); } } else { // Is Boolean newValue = checked; } // Emit if value changed if (newValue !== undefined) { this._state = newValue; this._propagateChange(this._state); } }; Object.defineProperty(OnsCheckbox.prototype, "element", { get: function () { return this._element; }, enumerable: true, configurable: true }); Object.defineProperty(OnsCheckbox.prototype, "nativeElement", { get: function () { return this._element; }, enumerable: true, configurable: true }); OnsCheckbox.prototype.ngOnDestroy = function () { this._element.removeEventListener('change', this._boundOnChange); this._element = null; }; OnsCheckbox.prototype.writeValue = function (obj) { this._state = obj; if (obj instanceof Array) { this._element.checked = obj.indexOf(this._element.value) >= 0; } else { this._element.checked = obj; } }; OnsCheckbox.prototype.registerOnChange = function (fn) { this._propagateChange = fn; }; OnsCheckbox.prototype.registerOnTouched = function () { }; return OnsCheckbox; }()); export { OnsCheckbox }; OnsCheckbox.decorators = [ { type: Directive, args: [{ selector: 'ons-checkbox', providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(function () { return OnsCheckbox; }), multi: true, } ] },] }, ]; /** @nocollapse */ OnsCheckbox.ctorParameters = function () { return [ { type: ElementRef, }, ]; }; //# sourceMappingURL=ons-checkbox.js.map
import pytest import taichi as ti @ti.test(arch=ti.get_host_arch_list()) def test_struct_for_mismatch(): x = ti.field(ti.f32, (3, 4)) @ti.kernel def func(): for i in x: print(i) with pytest.raises(ti.TaichiCompilationError): func() @ti.test(arch=ti.get_host_arch_list()) def test_struct_for_mismatch2(): x = ti.field(ti.f32, (3, 4)) @ti.kernel def func(): for i, j, k in x: print(i, j, k) with pytest.raises(ti.TaichiCompilationError): func() @ti.test(arch=ti.get_host_arch_list()) def _test_grouped_struct_for_mismatch(): # doesn't work for now # need grouped refactor # for now, it just throw a unfriendly message: # AssertionError: __getitem__ cannot be called in Python-scope x = ti.field(ti.f32, (3, 4)) @ti.kernel def func(): for i, j in ti.grouped(x): print(i, j) with pytest.raises(ti.TaichiCompilationError): func() @ti.test(arch=ti.get_host_arch_list()) def _test_ndrange_for_mismatch(): # doesn't work for now # need ndrange refactor @ti.kernel def func(): for i in ti.ndrange(3, 4): print(i) with pytest.raises(ti.TaichiCompilationError): func() @ti.test(arch=ti.get_host_arch_list()) def _test_ndrange_for_mismatch2(): # doesn't work for now # need ndrange and grouped refactor @ti.kernel def func(): for i, j, k in ti.ndrange(3, 4): print(i, j, k) with pytest.raises(ti.TaichiCompilationError): func() @ti.test(arch=ti.get_host_arch_list()) def _test_grouped_ndrange_for_mismatch(): # doesn't work for now # need ndrange and grouped refactor @ti.kernel def func(): for i in ti.grouped(ti.ndrange(3, 4)): print(i) with pytest.raises(ti.TaichiCompilationError): func() @ti.test(arch=ti.get_host_arch_list()) def _test_static_ndrange_for_mismatch(): # doesn't work for now # need ndrange and static refactor @ti.kernel def func(): for i in ti.static(ti.ndrange(3, 4)): print(i) with pytest.raises(ti.TaichiCompilationError): func()
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var xml_json_1 = __importDefault(require("../maps/xml.json")); var inverseXML = getInverseObj(xml_json_1.default); var xmlReplacer = getInverseReplacer(inverseXML); exports.encodeXML = getInverse(inverseXML, xmlReplacer); var entities_json_1 = __importDefault(require("../maps/entities.json")); var inverseHTML = getInverseObj(entities_json_1.default); var htmlReplacer = getInverseReplacer(inverseHTML); exports.encodeHTML = getInverse(inverseHTML, htmlReplacer); function getInverseObj(obj) { return Object.keys(obj) .sort() .reduce(function (inverse, name) { inverse[obj[name]] = "&" + name + ";"; return inverse; }, {}); } function getInverseReplacer(inverse) { var single = []; var multiple = []; Object.keys(inverse).forEach(function (k) { return k.length === 1 ? // Add value to single array single.push("\\" + k) : // Add value to multiple array multiple.push(k); }); //TODO add ranges multiple.unshift("[" + single.join("") + "]"); return new RegExp(multiple.join("|"), "g"); } var reNonASCII = /[^\0-\x7F]/g; var reAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; function singleCharReplacer(c) { return "&#x" + c .charCodeAt(0) .toString(16) .toUpperCase() + ";"; } // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any function astralReplacer(c, _) { // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae var high = c.charCodeAt(0); var low = c.charCodeAt(1); var codePoint = (high - 0xd800) * 0x400 + low - 0xdc00 + 0x10000; return "&#x" + codePoint.toString(16).toUpperCase() + ";"; } function getInverse(inverse, re) { return function (data) { return data .replace(re, function (name) { return inverse[name]; }) .replace(reAstralSymbols, astralReplacer) .replace(reNonASCII, singleCharReplacer); }; } var reXmlChars = getInverseReplacer(inverseXML); function escape(data) { return data .replace(reXmlChars, singleCharReplacer) .replace(reAstralSymbols, astralReplacer) .replace(reNonASCII, singleCharReplacer); } exports.escape = escape;